From 1e3c8edc401ffa6a19ea09ef500c2c11f41b996a Mon Sep 17 00:00:00 2001 From: hultonha <82228511+hultonha@users.noreply.github.com> Date: Mon, 13 Sep 2021 18:04:20 +0100 Subject: [PATCH 01/26] Remove viewport freeze request bus (#4089) Signed-off-by: hultonha --- Code/Editor/CryEditPy.cpp | 4 ---- Code/Editor/EditorViewportWidget.cpp | 22 ------------------- Code/Editor/EditorViewportWidget.h | 8 ------- .../Viewport/ViewportMessages.h | 18 --------------- 4 files changed, 52 deletions(-) diff --git a/Code/Editor/CryEditPy.cpp b/Code/Editor/CryEditPy.cpp index 7a407aac37..1b38fe23b8 100644 --- a/Code/Editor/CryEditPy.cpp +++ b/Code/Editor/CryEditPy.cpp @@ -77,10 +77,6 @@ namespace // This closes the current document (level) currentLevel->OnNewDocument(); - // Then we freeze the viewport's input - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Broadcast( - &AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Events::FreezeViewportInput, true); - // Then we need to tell the game engine there is no level to render anymore if (GetIEditor()->GetGameEngine()) { diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 851d2c5b6f..7631ac6237 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -669,16 +669,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) case eNotify_OnEndSceneSave: PopDisableRendering(); break; - - case eNotify_OnBeginLoad: // disables viewport input when starting to load an existing level - case eNotify_OnBeginCreate: // disables viewport input when starting to create a new level - m_freezeViewportInput = true; - break; - - case eNotify_OnEndLoad: // enables viewport input when finished loading an existing level - case eNotify_OnEndCreate: // enables viewport input when finished creating a new level - m_freezeViewportInput = false; - break; } } @@ -962,16 +952,6 @@ AzFramework::ScreenPoint EditorViewportWidget::ViewportWorldToScreen(const AZ::V return m_renderViewport->ViewportWorldToScreen(worldPosition); } -bool EditorViewportWidget::IsViewportInputFrozen() -{ - return m_freezeViewportInput; -} - -void EditorViewportWidget::FreezeViewportInput(bool freeze) -{ - m_freezeViewportInput = freeze; -} - QWidget* EditorViewportWidget::GetWidgetForViewportContextMenu() { return this; @@ -1057,7 +1037,6 @@ void EditorViewportWidget::SetViewportId(int id) void EditorViewportWidget::ConnectViewportInteractionRequestBus() { - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler::BusConnect(GetViewportId()); AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); m_viewportUi.ConnectViewportUiBus(GetViewportId()); @@ -1072,7 +1051,6 @@ void EditorViewportWidget::DisconnectViewportInteractionRequestBus() m_viewportUi.DisconnectViewportUiBus(); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusDisconnect(); AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusDisconnect(); - AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler::BusDisconnect(); } namespace AZ::ViewportHelpers diff --git a/Code/Editor/EditorViewportWidget.h b/Code/Editor/EditorViewportWidget.h index 825d21a034..c4a8e9fcca 100644 --- a/Code/Editor/EditorViewportWidget.h +++ b/Code/Editor/EditorViewportWidget.h @@ -89,7 +89,6 @@ class SANDBOX_API EditorViewportWidget final , private Camera::EditorCameraRequestBus::Handler , private Camera::CameraNotificationBus::Handler , private AzFramework::InputSystemCursorConstraintRequestBus::Handler - , private AzToolsFramework::ViewportInteraction::ViewportFreezeRequestBus::Handler , private AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler , private AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler , private AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler @@ -202,10 +201,6 @@ private: // AzFramework::InputSystemCursorConstraintRequestBus overrides ... void* GetSystemCursorConstraintWindow() const override; - // AzToolsFramework::ViewportFreezeRequestBus overrides ... - bool IsViewportInputFrozen() override; - void FreezeViewportInput(bool freeze) override; - // AzToolsFramework::MainEditorViewportInteractionRequestBus overrides ... AZ::EntityId PickEntity(const AzFramework::ScreenPoint& point) override; AZ::Vector3 PickTerrain(const AzFramework::ScreenPoint& point) override; @@ -387,9 +382,6 @@ private: // Unclear if it's still necessary. QSet m_keyDown; - // State for ViewportFreezeRequestBus, currently does nothing - bool m_freezeViewportInput = false; - // This widget holds a reference to the manipulator manage because its responsible for drawing manipulators AZStd::shared_ptr m_manipulatorManager; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h index c90c506a05..8bddeb7a44 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/Viewport/ViewportMessages.h @@ -221,24 +221,6 @@ namespace AzToolsFramework using ViewportSettingsNotificationBus = AZ::EBus; - //! Requests to freeze the Viewport Input - //! Added to prevent a bug with the legacy CryEngine Viewport code that would - //! keep doing raycast tests even when no level is loaded, causing a crash. - class ViewportFreezeRequests - { - public: - //! Return if Viewport Input is frozen - virtual bool IsViewportInputFrozen() = 0; - //! Sets the Viewport Input freeze state - virtual void FreezeViewportInput(bool freeze) = 0; - - protected: - ~ViewportFreezeRequests() = default; - }; - - //! Type to inherit to implement ViewportFreezeRequests. - using ViewportFreezeRequestBus = AZ::EBus; - //! Viewport requests that are only guaranteed to be serviced by the Main Editor viewport. class MainEditorViewportInteractionRequests { From 32e6473de2d6db4b7c4725a86baeaff5ee068752 Mon Sep 17 00:00:00 2001 From: Scott Romero <24445312+AMZN-ScottR@users.noreply.github.com> Date: Mon, 13 Sep 2021 10:41:53 -0700 Subject: [PATCH 02/26] [development] Update RapidXML package info (#4057) Signed-off-by: AMZN-ScottR <24445312+AMZN-ScottR@users.noreply.github.com> --- cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake | 2 +- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 2 +- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake index 0d9be5bb49..119fc324c6 100644 --- a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake +++ b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake @@ -9,7 +9,7 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) -ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) +ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index 2f0669f635..f66f762f7a 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -12,7 +12,7 @@ ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) -ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) +ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index 1799fde7b9..ebc5de729a 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -12,7 +12,7 @@ ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) -ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) +ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index e0b77fb0fa..05368d1f6a 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -12,7 +12,7 @@ ly_associate_package(PACKAGE_NAME assimp-5.0.1-rev11-multiplatform ly_associate_package(PACKAGE_NAME ASTCEncoder-2017_11_14-rev2-multiplatform TARGETS ASTCEncoder PACKAGE_HASH c240ffc12083ee39a5ce9dc241de44d116e513e1e3e4cc1d05305e7aa3bdc326) ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) -ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) +ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) ly_associate_package(PACKAGE_NAME pybind11-2.4.3-rev2-multiplatform TARGETS pybind11 PACKAGE_HASH d8012f907b6c54ac990b899a0788280857e7c93a9595405a28114b48c354eb1b) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) diff --git a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake index ea51158f4a..2f12d7f81e 100644 --- a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake +++ b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake @@ -9,7 +9,7 @@ # shared by other platforms: ly_associate_package(PACKAGE_NAME md5-2.0-multiplatform TARGETS md5 PACKAGE_HASH 29e52ad22c78051551f78a40c2709594f0378762ae03b417adca3f4b700affdf) ly_associate_package(PACKAGE_NAME RapidJSON-1.1.0-rev1-multiplatform TARGETS RapidJSON PACKAGE_HASH 2f5e26ecf86c3b7a262753e7da69ac59928e78e9534361f3d00c1ad5879e4023) -ly_associate_package(PACKAGE_NAME RapidXML-1.13-multiplatform TARGETS RapidXML PACKAGE_HASH 510b3c12f8872c54b34733e34f2f69dd21837feafa55bfefa445c98318d96ebf) +ly_associate_package(PACKAGE_NAME RapidXML-1.13-rev1-multiplatform TARGETS RapidXML PACKAGE_HASH 4b7b5651e47cfd019b6b295cc17bb147b65e53073eaab4a0c0d20a37ab74a246) ly_associate_package(PACKAGE_NAME cityhash-1.1-multiplatform TARGETS cityhash PACKAGE_HASH 0ace9e6f0b2438c5837510032d2d4109125845c0efd7d807f4561ec905512dd2) ly_associate_package(PACKAGE_NAME expat-2.1.0-multiplatform TARGETS expat PACKAGE_HASH 452256acd1fd699cef24162575b3524fccfb712f5321c83f1df1ce878de5b418) ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zstd PACKAGE_HASH 45d466c435f1095898578eedde85acf1fd27190e7ea99aeaa9acfd2f09e12665) From de3d2a2b693be2d9f1769fb7247282b4281e3ab3 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Mon, 13 Sep 2021 11:15:23 -0700 Subject: [PATCH 03/26] Detects that binary dir and install prefix are not the same (#4091) Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- cmake/OutputDirectory.cmake | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/cmake/OutputDirectory.cmake b/cmake/OutputDirectory.cmake index a75b47e818..6906f76de5 100644 --- a/cmake/OutputDirectory.cmake +++ b/cmake/OutputDirectory.cmake @@ -14,6 +14,16 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin CACHE PATH "Build dir # We install outside of the binary dir because our install support muliple platforms to # be installed together. We also have an exclusion rule in the AP that filters out the # "install" folder to avoid the AP picking it up +unset(define_with_force) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) - set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/install CACHE PATH "Install directory" FORCE) + set(define_with_force FORCE) +endif() +set(CMAKE_INSTALL_PREFIX ${CMAKE_SOURCE_DIR}/install CACHE PATH "Install directory" ${define_with_force}) + +cmake_path(ABSOLUTE_PATH CMAKE_BINARY_DIR NORMALIZE OUTPUT_VARIABLE cmake_binary_dir_normalized) +cmake_path(ABSOLUTE_PATH CMAKE_INSTALL_PREFIX NORMALIZE OUTPUT_VARIABLE cmake_install_prefix_normalized) +cmake_path(COMPARE ${cmake_binary_dir_normalized} EQUAL ${cmake_install_prefix_normalized} are_paths_equal) +if(are_paths_equal) + message(FATAL_ERROR "Binary dir is the same path as install prefix, indicate a different install prefix with " + "CMAKE_INSTALL_PREFIX or a different binary dir with -B ") endif() From 6103c9c63cca0889243b8e49729bfbbfc304cfa4 Mon Sep 17 00:00:00 2001 From: Nicholas Lawson <70027408+lawsonamzn@users.noreply.github.com> Date: Mon, 13 Sep 2021 12:35:29 -0700 Subject: [PATCH 04/26] Updates libtiff for all platforms (#4068) The new libtiff is uniform, and static, across all platforms. It includes zlib support and uses our own zlib. Signed-off-by: lawsonamzn <70027408+lawsonamzn@users.noreply.github.com> --- cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake | 2 +- cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake | 2 +- cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake | 2 +- cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake | 2 +- cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake index 119fc324c6..47c3c66463 100644 --- a/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake +++ b/cmake/3rdParty/Platform/Android/BuiltInPackages_android.cmake @@ -16,8 +16,8 @@ ly_associate_package(PACKAGE_NAME zstd-1.35-multiplatform TARGETS zst ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS glad PACKAGE_HASH ff97ee9664e97d0854b52a3734c2289329d9f2b4cd69478df6d0ca1f1c9392ee) ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) # platform-specific: +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-rev2-android TARGETS tiff PACKAGE_HASH 252b99e5886ec59fdccf38603c1399dd3fc02d878641aba35a7f8d2504065a06) ly_associate_package(PACKAGE_NAME freetype-2.10.4.16-android TARGETS freetype PACKAGE_HASH df9e4d559ea0f03b0666b48c79813b1cd4d9624429148a249865de9f5c2c11cd) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.14-android TARGETS tiff PACKAGE_HASH a9b30a1980946390c2fad0ed94562476a1d7ba8c1f36934ae140a89c54a8efd0) ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev6-android TARGETS AWSNativeSDK PACKAGE_HASH 1624ba9aaf03d001ed0ffc57d2f945ff82590e75a7ea868de35043cf673e82fb) ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-android TARGETS Lua PACKAGE_HASH 1f638e94a17a87fe9e588ea456d5893876094b4db191234380e4c4eb9e06c300) ly_associate_package(PACKAGE_NAME PhysX-4.1.2.29882248-rev3-android TARGETS PhysX PACKAGE_HASH b8cb6aa46b2a21671f6cb1f6a78713a3ba88824d0447560ff5ce6c01014b9f43) diff --git a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake index f66f762f7a..429665f04a 100644 --- a/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake +++ b/cmake/3rdParty/Platform/Linux/BuiltInPackages_linux.cmake @@ -25,8 +25,8 @@ ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform # platform-specific: ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-linux TARGETS AWSGameLiftServerSDK PACKAGE_HASH a8149a95bd100384af6ade97e2b21a56173740d921e6c3da8188cd51554d39af) +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-rev2-linux TARGETS tiff PACKAGE_HASH 19791da0a370470a6c187199f97c2c46efcc2d89146e2013775fb3600fd7317d) ly_associate_package(PACKAGE_NAME freetype-2.10.4.16-linux TARGETS freetype PACKAGE_HASH 3f10c703d9001ecd2bb51a3bd003d3237c02d8f947ad0161c0252fdc54cbcf97) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-linux TARGETS tiff PACKAGE_HASH ae92b4d3b189c42ef644abc5cac865d1fb2eb7cb5622ec17e35642b00d1a0a76) ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev6-linux TARGETS AWSNativeSDK PACKAGE_HASH 490291e4c8057975c3ab86feb971b8a38871c58bac5e5d86abdd1aeb7141eec4) ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-linux TARGETS Lua PACKAGE_HASH 1adc812abe3dd0dbb2ca9756f81d8f0e0ba45779ac85bf1d8455b25c531a38b0) ly_associate_package(PACKAGE_NAME PhysX-4.1.2.29882248-rev3-linux TARGETS PhysX PACKAGE_HASH a110249cbef4f266b0002c4ee9a71f59f373040cefbe6b82f1e1510c811edde6) diff --git a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake index ebc5de729a..4900a9d77e 100644 --- a/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake +++ b/cmake/3rdParty/Platform/Mac/BuiltInPackages_mac.cmake @@ -27,8 +27,8 @@ ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform # platform-specific: ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev3-mac TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 3f77367dbb0342136ec4ebbd44bc1fedf7198089a0f83c5631248530769b2be6) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-mac TARGETS SPIRVCross PACKAGE_HASH 78c6376ed2fd195b9b1f5fb2b56e5267a32c3aa21fb399e905308de470eb4515) +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-rev2-mac TARGETS tiff PACKAGE_HASH b6f3040319f5bfe465d7e3f9b12ceed0dc951e66e05562beaac1c8da3b1b5d3f) ly_associate_package(PACKAGE_NAME freetype-2.10.4.16-mac TARGETS freetype PACKAGE_HASH f159b346ac3251fb29cb8dd5f805c99b0015ed7fdb3887f656945ca701a61d0d) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-mac-ios TARGETS tiff PACKAGE_HASH a23ae1f8991a29f8e5df09d6d5b00d7768a740f90752cef465558c1768343709) ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev5-mac TARGETS AWSNativeSDK PACKAGE_HASH ffb890bd9cf23afb429b9214ad9bac1bf04696f07a0ebb93c42058c482ab2f01) ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev6-mac TARGETS Lua PACKAGE_HASH b9079fd35634774c9269028447562c6b712dbc83b9c64975c095fd423ff04c08) ly_associate_package(PACKAGE_NAME PhysX-4.1.2.29882248-rev3-mac TARGETS PhysX PACKAGE_HASH 5e092a11d5c0a50c4dd99bb681a04b566a4f6f29aa08443d9bffc8dc12c27c8e) diff --git a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake index 05368d1f6a..3855b7d712 100644 --- a/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake +++ b/cmake/3rdParty/Platform/Windows/BuiltInPackages_windows.cmake @@ -28,8 +28,8 @@ ly_associate_package(PACKAGE_NAME PVRTexTool-4.24.0-rev4-multiplatform ly_associate_package(PACKAGE_NAME AWSGameLiftServerSDK-3.4.1-rev1-windows TARGETS AWSGameLiftServerSDK PACKAGE_HASH a0586b006e4def65cc25f388de17dc475e417dc1e6f9d96749777c88aa8271b0) ly_associate_package(PACKAGE_NAME DirectXShaderCompilerDxc-1.6.2104-o3de-rev3-windows TARGETS DirectXShaderCompilerDxc PACKAGE_HASH 803e10b94006b834cbbdd30f562a8ddf04174c2cb6956c8399ec164ef8418d1f) ly_associate_package(PACKAGE_NAME SPIRVCross-2021.04.29-rev1-windows TARGETS SPIRVCross PACKAGE_HASH 7d601ea9d625b1d509d38bd132a1f433d7e895b16adab76bac6103567a7a6817) +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-rev2-windows TARGETS tiff PACKAGE_HASH ff03464ca460fc34a8406b2a0c548ad221b10e40480b0abb954f1e649c20bad0) ly_associate_package(PACKAGE_NAME freetype-2.10.4.16-windows TARGETS freetype PACKAGE_HASH 9809255f1c59b07875097aa8d8c6c21c97c47a31fb35e30f2bb93188e99a85ff) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.14-windows TARGETS tiff PACKAGE_HASH ab60d1398e4e1e375ec0f1a00cdb1d812a07c0096d827db575ce52dd6d714207) ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev4-windows TARGETS AWSNativeSDK PACKAGE_HASH a900e80f7259e43aed5c847afee2599ada37f29db70505481397675bcbb6c76c) ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-windows TARGETS Lua PACKAGE_HASH 136faccf1f73891e3fa3b95f908523187792e56f5b92c63c6a6d7e72d1158d40) ly_associate_package(PACKAGE_NAME PhysX-4.1.2.29882248-rev3-windows TARGETS PhysX PACKAGE_HASH 0c5ffbd9fa588e5cf7643721a7cfe74d0fe448bf82252d39b3a96d06dfca2298) diff --git a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake index 2f12d7f81e..25fbaf830f 100644 --- a/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake +++ b/cmake/3rdParty/Platform/iOS/BuiltInPackages_ios.cmake @@ -17,8 +17,8 @@ ly_associate_package(PACKAGE_NAME glad-2.0.0-beta-rev2-multiplatform TARGETS gla ly_associate_package(PACKAGE_NAME lux_core-2.2-rev5-multiplatform TARGETS lux_core PACKAGE_HASH c8c13cf7bc351643e1abd294d0841b24dee60e51647dff13db7aec396ad1e0b5) # platform-specific: +ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-rev2-ios TARGETS tiff PACKAGE_HASH d864beb0c955a55f28c2a993843afb2ecf6e01519ddfc857cedf34fc5db68d49) ly_associate_package(PACKAGE_NAME freetype-2.10.4.16-ios TARGETS freetype PACKAGE_HASH 3ac3c35e056ae4baec2e40caa023d76a7a3320895ef172b6655e9261b0dc2e29) -ly_associate_package(PACKAGE_NAME tiff-4.2.0.15-mac-ios TARGETS tiff PACKAGE_HASH a23ae1f8991a29f8e5df09d6d5b00d7768a740f90752cef465558c1768343709) ly_associate_package(PACKAGE_NAME AWSNativeSDK-1.7.167-rev3-ios TARGETS AWSNativeSDK PACKAGE_HASH 1246219a213ccfff76b526011febf521586d44dbc1753e474f8fb5fd861654a4) ly_associate_package(PACKAGE_NAME Lua-5.3.5-rev5-ios TARGETS Lua PACKAGE_HASH c2d3c4e67046c293049292317a7d60fdb8f23effeea7136aefaef667163e5ffe) ly_associate_package(PACKAGE_NAME PhysX-4.1.2.29882248-rev3-ios TARGETS PhysX PACKAGE_HASH b1bbc1fc068d2c6e1eb18eecd4e8b776adc516833e8da3dcb1970cef2a8f0cbd) From 2b7caa685b8989f6772bca93ad3d6e5eb99aa5cd Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Mon, 13 Sep 2021 14:23:00 -0700 Subject: [PATCH 05/26] Introduce default font size. This fixes sizing and spacing for text rendered via a painter with not font specified. (#4069) Also removed some qss for windows that have been removed. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- Code/Editor/Style/Editor.qss | 90 ------------------- .../Components/StyleManager.cpp | 4 + 2 files changed, 4 insertions(+), 90 deletions(-) diff --git a/Code/Editor/Style/Editor.qss b/Code/Editor/Style/Editor.qss index 302b7703a5..5eb280260e 100644 --- a/Code/Editor/Style/Editor.qss +++ b/Code/Editor/Style/Editor.qss @@ -191,94 +191,4 @@ ConsoleTextEdit:focus, border-width: 0px; border-color: #e9e9e9; border-style: solid; -} - -/* Welcome Screen styling */ - -WelcomeScreenDialog QLabel -{ - font-size: 12px; - color: #FFFFFF; - line-height: 20px; - background-color: transparent; - margin: 0; -} - -WelcomeScreenDialog QLabel#currentProjectLabel -{ - margin-top: 10px; -} - -WelcomeScreenDialog QPushButton -{ - font-size: 14px; - line-height: 16px; -} - -WelcomeScreenDialog QWidget#articleViewContainerRoot -{ - background: #444444; -} - -WelcomeScreenDialog QWidget#levelViewFTUEContainer -{ - background: #282828; -} - -QTableWidget#recentLevelTable::item { - background-color: rgb(64,64,64); - margin-bottom: 4px; - margin-top: 4px; -} - -/* Particle Editor */ - -#NumParticlesLabel -{ - margin-top: 6px; -} - -#LibrarySearchIcon -{ - max-width: 16px; - max-height: 16px; - qproperty-iconSize: 16px 16px; -} - - -#ClosePrefabDialog, #SavePrefabDialog -{ - min-width : 640px; -} - -#SaveDependentPrefabsCard -{ - margin: 0px 15px 10px 15px; -} - -#PrefabSavedMessageFrame{ - border: 1px solid green; - margin: 10px 15px 10px 15px; - border-radius: 2px; - padding: 5px 2px 5px 2px; -} - -#ClosePrefabDialog #PrefabSaveWarningFrame -{ - border: 1px solid orange; - margin: 10px 15px 10px 15px; - border-radius: 2px; - padding: 5px 2px 5px 2px; - color : white; -} - -#SavePrefabDialog #FooterSeparatorLine -{ - color: gray; -} - -#SavePrefabDialog #PrefabSavePreferenceHint -{ - font: italic; - color: #999999; } \ No newline at end of file diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/StyleManager.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/StyleManager.cpp index c7ec4d4c7a..8f659afb7e 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/StyleManager.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/StyleManager.cpp @@ -169,6 +169,10 @@ namespace AzQtComponents initializeSearchPaths(application, engineRootPath); initializeFonts(); + QFont defaultFont("Open Sans"); + defaultFont.setPixelSize(12); + QApplication::setFont(defaultFont); + m_titleBarOverdrawHandler = TitleBarOverdrawHandler::createHandler(application, this); // The window decoration wrappers require the titlebar overdraw handler From 850d401bb3de889a9bd2e4337abef4d7156f6175 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Mon, 13 Sep 2021 14:55:55 -0700 Subject: [PATCH 06/26] PerScreenDpi | Moving windows between screens with different scale changes the window size (#4064) * Fix window size when dropped on a screen with a different scale setting compared to the one it was dragged from. Note that this fixes a bug that could only be reproduced with the PerScreenDpiAware setting activated - current editor uses SystemDpiAware. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> * Fix loss of precision warning. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- .../AzQtComponents/Components/FancyDocking.cpp | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp index d73ebbec28..f60a98f392 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp +++ b/Code/Framework/AzQtComponents/AzQtComponents/Components/FancyDocking.cpp @@ -2461,6 +2461,18 @@ namespace AzQtComponents placeholderRect.translate(0, -margins.bottom()); } + // Also adjust the placeholderRect by the relative dpi change from the original screen, since setGeometry uses the screen's + // virtualGeometry! + QScreen* fromScreen = dock->screen(); + QScreen* toScreen = Utilities::ScreenAtPoint(placeholderRect.topLeft()); + + if (fromScreen != toScreen) + { + qreal factorRatio = QHighDpiScaling::factor(fromScreen) / QHighDpiScaling::factor(toScreen); + placeholderRect.setWidth(aznumeric_cast(aznumeric_cast(placeholderRect.width()) * factorRatio)); + placeholderRect.setHeight(aznumeric_cast(aznumeric_cast(placeholderRect.height()) * factorRatio)); + } + // Place the floating dock widget makeDockWidgetFloating(dock, placeholderRect); clearDraggingState(); From b2963f2bc1018e3bf0be54b2a31e9582a81d36c0 Mon Sep 17 00:00:00 2001 From: srikappa-amzn <82230713+srikappa-amzn@users.noreply.github.com> Date: Mon, 13 Sep 2021 15:55:28 -0700 Subject: [PATCH 07/26] Renamed AtomMaxFileSize to DefaultMaxFileSize (#4067) Signed-off-by: srikappa-amzn --- .../Asset/Shader/Code/Source/Editor/AzslCompiler.cpp | 4 ++-- .../Shader/Code/Source/Editor/ShaderAssetBuilder.cpp | 2 +- .../Shader/Code/Source/Editor/ShaderBuilderUtility.cpp | 8 ++++---- .../Code/Source/Editor/ShaderVariantAssetBuilder.cpp | 10 +++++----- .../RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h | 4 ++-- .../Source/RPI.Builders/Material/MaterialBuilder.cpp | 4 ++-- .../RPI.Edit/Material/MaterialSourceDataSerializer.cpp | 2 +- .../Code/Source/RPI.Edit/Material/MaterialUtils.cpp | 2 +- .../Editor/AssetCollectionAsyncLoaderTestComponent.cpp | 2 +- 9 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp index a82c731d7b..79a39ff793 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/AzslCompiler.cpp @@ -1150,7 +1150,7 @@ namespace AZ return BuildResult::CompilationFailed; } - auto readJsonResult = JsonSerializationUtils::ReadJsonFile(outputFile, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto readJsonResult = JsonSerializationUtils::ReadJsonFile(outputFile, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (readJsonResult.IsSuccess()) { @@ -1171,7 +1171,7 @@ namespace AZ AZStd::string outputFile = m_inputFilePath; AzFramework::StringFunc::Path::ReplaceExtension(outputFile, outputExtension); - auto readJsonResult = JsonSerializationUtils::ReadJsonFile(outputFile, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto readJsonResult = JsonSerializationUtils::ReadJsonFile(outputFile, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (readJsonResult.IsSuccess()) { diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp index 6b673759cf..6673da2be3 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp @@ -556,7 +556,7 @@ namespace AZ shaderAssetCreator.SetRenderStates(renderStates); } - Outcome hlslSourceCodeOutcome = Utils::ReadFile(hlslFullPath, AZ::RPI::JsonUtils::AtomMaxFileSize); + Outcome hlslSourceCodeOutcome = Utils::ReadFile(hlslFullPath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!hlslSourceCodeOutcome.IsSuccess()) { AZ_Error( diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp index 9c616569bd..e47dd55a97 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp @@ -52,7 +52,7 @@ namespace AZ { RPI::ShaderSourceData shaderSourceData; - auto document = JsonSerializationUtils::ReadJsonFile(fullPathToJsonFile, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto document = JsonSerializationUtils::ReadJsonFile(fullPathToJsonFile, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!document.IsSuccess()) { @@ -128,7 +128,7 @@ namespace AZ AZStd::unordered_map> outcomes; for (int i : indicesOfInterest) { - outcomes[i] = JsonSerializationUtils::ReadJsonFile(pathOfJsonFiles[i], AZ::RPI::JsonUtils::AtomMaxFileSize); + outcomes[i] = JsonSerializationUtils::ReadJsonFile(pathOfJsonFiles[i], AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!outcomes[i].IsSuccess()) { AZ_Error(builderName, false, "%s", outcomes[i].GetError().c_str()); @@ -623,7 +623,7 @@ namespace AZ StructData inputStruct; inputStruct.m_id = ""; - auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(pathToIaJson, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(pathToIaJson, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!jsonOutcome.IsSuccess()) { AZ_Error(ShaderBuilderUtilityName, false, "%s", jsonOutcome.GetError().c_str()); @@ -716,7 +716,7 @@ namespace AZ StructData outputStruct; outputStruct.m_id = ""; - auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(pathToOmJson, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(pathToOmJson, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!jsonOutcome.IsSuccess()) { AZ_Error(ShaderBuilderUtilityName, false, "%s", jsonOutcome.GetError().c_str()); diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp index 5a552a2702..7c5be89508 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderVariantAssetBuilder.cpp @@ -478,7 +478,7 @@ namespace AZ RPI::Ptr shaderOptionGroupLayout = RPI::ShaderOptionGroupLayout::Create(); // The shader options define what options are available, what are the allowed values/range // for each option and what is its default value. - auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(optionsGroupJsonPath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(optionsGroupJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!jsonOutcome.IsSuccess()) { AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str()); @@ -509,7 +509,7 @@ namespace AZ } auto functionsJsonPath = functionsJsonPathOutcome.TakeValue(); - auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(functionsJsonPath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(functionsJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!jsonOutcome.IsSuccess()) { AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str()); @@ -541,7 +541,7 @@ namespace AZ } auto srgJsonPath = srgJsonPathOutcome.TakeValue(); - auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(srgJsonPath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(srgJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!jsonOutcome.IsSuccess()) { AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str()); @@ -598,7 +598,7 @@ namespace AZ } auto bindingsJsonPath = bindingsJsonPathOutcome.TakeValue(); - auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(bindingsJsonPath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto jsonOutcome = JsonSerializationUtils::ReadJsonFile(bindingsJsonPath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!jsonOutcome.IsSuccess()) { AZ_Error(ShaderVariantAssetBuilderName, false, "%s", jsonOutcome.GetError().c_str()); @@ -630,7 +630,7 @@ namespace AZ } hlslSourcePath = hlslSourcePathOutcome.TakeValue(); - Outcome hlslSourceOutcome = Utils::ReadFile(hlslSourcePath, AZ::RPI::JsonUtils::AtomMaxFileSize); + Outcome hlslSourceOutcome = Utils::ReadFile(hlslSourcePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!hlslSourceOutcome.IsSuccess()) { AZ_Error( diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h index 913a9702b1..4715acd64c 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Edit/Common/JsonUtils.h @@ -22,7 +22,7 @@ namespace AZ { //! Protects from allocating too much memory. The choice of a 1MB threshold is arbitrary. //! If you need to work with larger files, please use AZ::IO directly instead of these utility functions. - inline constexpr size_t AtomMaxFileSize = 1024 * 1024; + inline constexpr size_t DefaultMaxFileSize = 1024 * 1024; // Declarations... @@ -43,7 +43,7 @@ namespace AZ { objectData = ObjectType(); - auto loadOutcome = AZ::JsonSerializationUtils::ReadJsonFile(path, AtomMaxFileSize); + auto loadOutcome = AZ::JsonSerializationUtils::ReadJsonFile(path, DefaultMaxFileSize); if (!loadOutcome.IsSuccess()) { AZ_Error("AZ::RPI::JsonUtils", false, "%s", loadOutcome.GetError().c_str()); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp index 62e078c628..5ddeb08ef8 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Builders/Material/MaterialBuilder.cpp @@ -152,7 +152,7 @@ namespace AZ AZStd::string fullSourcePath; AzFramework::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), fullSourcePath, true); - auto loadOutcome = JsonSerializationUtils::ReadJsonFile(fullSourcePath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto loadOutcome = JsonSerializationUtils::ReadJsonFile(fullSourcePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!loadOutcome.IsSuccess()) { AZ_Error(MaterialBuilderName, false, "%s", loadOutcome.GetError().c_str()); @@ -299,7 +299,7 @@ namespace AZ AZStd::string fullSourcePath; AzFramework::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), fullSourcePath, true); - auto loadOutcome = JsonSerializationUtils::ReadJsonFile(fullSourcePath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto loadOutcome = JsonSerializationUtils::ReadJsonFile(fullSourcePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!loadOutcome.IsSuccess()) { AZ_Error(MaterialBuilderName, false, "Failed to load material file: %s", loadOutcome.GetError().c_str()); diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceDataSerializer.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceDataSerializer.cpp index 6f68115ccb..5e4af07aae 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceDataSerializer.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialSourceDataSerializer.cpp @@ -68,7 +68,7 @@ namespace AZ { AZStd::string materialTypePath = AssetUtils::ResolvePathReference(jsonFileLoadContext->GetFilePath(), materialSourceData->m_materialType); - auto materialTypeJson = JsonSerializationUtils::ReadJsonFile(materialTypePath, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto materialTypeJson = JsonSerializationUtils::ReadJsonFile(materialTypePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!materialTypeJson.IsSuccess()) { AZStd::string failureMessage; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp index 80b292ea9b..62f4f02e3c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Edit/Material/MaterialUtils.cpp @@ -65,7 +65,7 @@ namespace AZ AZ::Outcome loadOutcome; if (document == nullptr) { - loadOutcome = AZ::JsonSerializationUtils::ReadJsonFile(filePath, AZ::RPI::JsonUtils::AtomMaxFileSize); + loadOutcome = AZ::JsonSerializationUtils::ReadJsonFile(filePath, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!loadOutcome.IsSuccess()) { AZ_Error("AZ::RPI::JsonUtils", false, "%s", loadOutcome.GetError().c_str()); diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Editor/AssetCollectionAsyncLoaderTestComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Editor/AssetCollectionAsyncLoaderTestComponent.cpp index 8270901b6b..92e09bf4b1 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/Editor/AssetCollectionAsyncLoaderTestComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/Editor/AssetCollectionAsyncLoaderTestComponent.cpp @@ -115,7 +115,7 @@ namespace AZ { rapidjson::Document jsonDoc; - auto readJsonResult = JsonSerializationUtils::ReadJsonFile(pathToAssetListJson, AZ::RPI::JsonUtils::AtomMaxFileSize); + auto readJsonResult = JsonSerializationUtils::ReadJsonFile(pathToAssetListJson, AZ::RPI::JsonUtils::DefaultMaxFileSize); if (!readJsonResult.IsSuccess()) { From 0d0b6c80330d2804d494d1944713db596c584f14 Mon Sep 17 00:00:00 2001 From: brianherrera Date: Mon, 13 Sep 2021 17:04:47 -0700 Subject: [PATCH 08/26] Add support for nvme volumes Signed-off-by: brianherrera --- scripts/build/bootstrap/incremental_build_util.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/scripts/build/bootstrap/incremental_build_util.py b/scripts/build/bootstrap/incremental_build_util.py index 10543d5951..101e31b5db 100644 --- a/scripts/build/bootstrap/incremental_build_util.py +++ b/scripts/build/bootstrap/incremental_build_util.py @@ -320,10 +320,14 @@ def mount_volume_to_device(created): time.sleep(1) else: - subprocess.call(['file', '-s', '/dev/xvdf']) + device_name = '/dev/xvdf' + nvme_device_name = '/dev/nvme1n1' + if os.path.exists(nvme_device_name): + device_name = nvme_device_name + subprocess.call(['file', '-s', device_name]) if created: - subprocess.call(['mkfs', '-t', 'ext4', '/dev/xvdf']) - subprocess.call(['mount', '/dev/xvdf', MOUNT_PATH]) + subprocess.call(['mkfs', '-t', 'ext4', device_name]) + subprocess.call(['mount', device_name, MOUNT_PATH]) def attach_volume_to_ec2_instance(volume, volume_id, instance_id, timeout_duration=DEFAULT_TIMEOUT): @@ -515,4 +519,4 @@ def main(action, snapshot_hint, repository_name, project, pipeline, branch, plat if __name__ == "__main__": args = parse_args() ret = main(args.action, args.snapshot_hint, args.repository_name, args.project, args.pipeline, args.branch, args.platform, args.build_type, args.disk_size, args.disk_type) - sys.exit(ret) \ No newline at end of file + sys.exit(ret) From db63dcbcd9c6b1758870ed20f91e869394e06ae8 Mon Sep 17 00:00:00 2001 From: Nicholas Van Sickle Date: Mon, 13 Sep 2021 17:57:42 -0700 Subject: [PATCH 09/26] Refresh rate driven rendering tick logic (#3375) * Implement sync interval and refresh rate API for RenderViewportWidget Signed-off-by: nvsickle * Measure actual frame timings in the viewport info overlay. Takes the median of the sum of (frame end - frame begin) to provide more a more representative view of when frames begin and end. Note: Until VSync is internally supported by the event loop, this will produce nearly identical frame timings as the frame will spend as much time as needed synchronously waiting on a vblank. Signed-off-by: nvsickle * Make frame timing per-pipeline, wire up refresh rate info to ViewportContext Signed-off-by: nvsickle * POC: Frame limit pipeline rendering Signed-off-by: nvsickle * Switch Editor tick to every 0ms to allow better tick accumulation behavior Signed-off-by: nvsickle * Move RPISystemComponent to the tick bus, remove tick accumulation logic Signed-off-by: nvsickle * Add `AddToRenderTickAtInterval` to RenderPipeline API This allows a pipeline to update at a set cadence, instead of rendering every frame or being directly told when to tick. Signed-off-by: nvsickle * Make ViewportContext enforce a target framerate -Adds GetFpsLimit/SetFpsLimit for actively limiting FPS -Calculates a render tick interval based on vsync and the vps limit and updates the current pipeline Signed-off-by: nvsickle * Add r_fps_limit and ed_inactive_viewport_fps_limit cvars Signed-off-by: nvsickle * Quick null check from a crash I bumped into Signed-off-by: nvsickle * Fix off-by-one on FPS calculation (shouldn't include the not-yet-rendered frame) Signed-off-by: nvsickle * Clarify frame time begin initialization Signed-off-by: nvsickle * Fix TrackView export. Signed-off-by: nvsickle * Address some reviewer feedback, revert RPISystem API change, fix CPU profiler. Signed-off-by: nvsickle * Add g_simulation_tick_rate Signed-off-by: nvsickle * Address review feedback, make frame limit updates event driven Signed-off-by: nvsickle * Remove timestamp update from ComponentApplication::Tick Signed-off-by: nvsickle --- Code/Editor/Core/QtEditorApplication.cpp | 2 +- .../TrackView/SequenceBatchRenderDialog.cpp | 10 + .../AzCore/Component/ComponentApplication.cpp | 19 ++ .../AzCore/AzCore/Component/TickBus.h | 2 + .../Atom/Bootstrap/BootstrapNotificationBus.h | 3 +- .../Atom/Bootstrap/BootstrapRequestBus.h | 2 + .../Code/Source/BootstrapSystemComponent.cpp | 39 +-- .../Code/Source/BootstrapSystemComponent.h | 2 + .../RHI/Code/Source/RHI/CpuProfilerImpl.cpp | 2 +- .../Include/Atom/RPI.Public/RenderPipeline.h | 43 +++- .../Code/Include/Atom/RPI.Public/SceneBus.h | 3 + .../Include/Atom/RPI.Public/ViewportContext.h | 49 +++- .../Atom/RPI.Public/ViewportContextBus.h | 8 +- .../Source/RPI.Private/RPISystemComponent.cpp | 18 +- .../Source/RPI.Private/RPISystemComponent.h | 7 +- .../RPI/Code/Source/RPI.Public/Pass/Pass.cpp | 7 +- .../Code/Source/RPI.Public/RenderPipeline.cpp | 44 +++- .../Atom/RPI/Code/Source/RPI.Public/Scene.cpp | 21 +- Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp | 5 +- .../Source/RPI.Public/ViewportContext.cpp | 142 +++++++++-- .../Viewport/RenderViewportWidget.h | 24 ++ .../RenderViewportWidgetNotificationBus.h | 35 +++ .../Source/Viewport/RenderViewportWidget.cpp | 223 ++++++++++++++---- .../Code/atomtoolsframework_files.cmake | 1 + ...AtomViewportDisplayInfoSystemComponent.cpp | 31 ++- .../AtomViewportDisplayInfoSystemComponent.h | 15 +- 26 files changed, 633 insertions(+), 124 deletions(-) create mode 100644 Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidgetNotificationBus.h diff --git a/Code/Editor/Core/QtEditorApplication.cpp b/Code/Editor/Core/QtEditorApplication.cpp index a4aab24be4..66ed42af8f 100644 --- a/Code/Editor/Core/QtEditorApplication.cpp +++ b/Code/Editor/Core/QtEditorApplication.cpp @@ -44,7 +44,7 @@ enum { // in milliseconds GameModeIdleFrequency = 0, - EditorModeIdleFrequency = 1, + EditorModeIdleFrequency = 0, InactiveModeFrequency = 10, UninitializedFrequency = 9999, }; diff --git a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp index b510315995..6b3f1c2633 100644 --- a/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp +++ b/Code/Editor/TrackView/SequenceBatchRenderDialog.cpp @@ -36,6 +36,9 @@ #include "CryEdit.h" #include "Viewport.h" +// Atom Renderer +#include + AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING @@ -1234,6 +1237,13 @@ void CSequenceBatchRenderDialog::OnKickIdleTimout() { componentApplication->TickSystem(); } + + // Directly tick the renderer, as it's no longer part of the system tick + if (auto rpiSystem = AZ::RPI::RPISystemInterface::Get()) + { + rpiSystem->SimulationTick(); + rpiSystem->RenderTick(); + } } } diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index c76156c006..04a76b0f8e 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -74,6 +74,8 @@ #include #include +AZ_CVAR(float, g_simulation_tick_rate, 0, nullptr, AZ::ConsoleFunctorFlags::Null, "The rate at which the game simulation tick loop runs, or 0 for as fast as possible"); + static void PrintEntityName(const AZ::ConsoleCommandContainer& arguments) { if (arguments.empty()) @@ -1392,6 +1394,23 @@ namespace AZ AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick"); EBUS_EVENT(TickBus, OnTick, m_deltaTime, ScriptTimePoint(now)); } + + // If tick rate limiting is on, ensure (1 / g_simulation_tick_rate) ms has elapsed since the last frame, + // sleeping if there's still time remaining. + if (g_simulation_tick_rate > 0.f) + { + now = AZStd::chrono::system_clock::now(); + + // Work in microsecond durations here as that's the native measurement time for time_point + constexpr float microsecondsPerSecond = 1000.f * 1000.f; + const AZStd::chrono::microseconds timeBudgetPerTick(static_cast(microsecondsPerSecond / g_simulation_tick_rate)); + AZStd::chrono::microseconds timeUntilNextTick = m_currentTime + timeBudgetPerTick - now; + + if (timeUntilNextTick.count() > 0) + { + AZStd::this_thread::sleep_for(timeUntilNextTick); + } + } } } diff --git a/Code/Framework/AzCore/AzCore/Component/TickBus.h b/Code/Framework/AzCore/AzCore/Component/TickBus.h index e65efb93f2..966a3c303e 100644 --- a/Code/Framework/AzCore/AzCore/Component/TickBus.h +++ b/Code/Framework/AzCore/AzCore/Component/TickBus.h @@ -46,6 +46,8 @@ namespace AZ TICK_PRE_RENDER = 750, ///< Suggested tick handler position to update render-related data. + TICK_RENDER = 800, ///< Suggested tick handler position for rendering. + TICK_DEFAULT = 1000, ///< Default tick handler position when the handler is constructed. TICK_UI = 2000, ///< Suggested tick handler position for UI components. diff --git a/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapNotificationBus.h b/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapNotificationBus.h index e40bf39923..f4ce51fc02 100644 --- a/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapNotificationBus.h +++ b/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapNotificationBus.h @@ -56,7 +56,8 @@ namespace AZ ////////////////////////////////////////////////////////////////////////// - virtual void OnBootstrapSceneReady(AZ::RPI::Scene* bootstrapScene) = 0; + virtual void OnBootstrapSceneReady([[maybe_unused]]AZ::RPI::Scene* bootstrapScene){} + virtual void OnFrameRateLimitChanged([[maybe_unused]]float fpsLimit){} }; using NotificationBus = AZ::EBus; } // namespace Bootstrap diff --git a/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapRequestBus.h b/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapRequestBus.h index 21cc91420b..fbf3bad935 100644 --- a/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapRequestBus.h +++ b/Gems/Atom/Bootstrap/Code/Include/Atom/Bootstrap/BootstrapRequestBus.h @@ -23,6 +23,8 @@ namespace AZ::Render::Bootstrap virtual AZ::RPI::ScenePtr GetOrCreateAtomSceneFromAzScene(AzFramework::Scene* scene) = 0; virtual bool EnsureDefaultRenderPipelineInstalledForScene(AZ::RPI::ScenePtr scene, AZ::RPI::ViewportContextPtr viewportContext) = 0; + virtual float GetFrameRateLimit() const = 0; + virtual void SetFrameRateLimit(float fpsLimit) = 0; protected: ~Request() = default; diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp index d837988cfb..97faa7380f 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp @@ -41,7 +41,14 @@ #include #include +static void OnFrameRateLimitChanged(const float& fpsLimit) +{ + AZ::Render::Bootstrap::RequestBus::Broadcast( + &AZ::Render::Bootstrap::RequestBus::Events::SetFrameRateLimit, fpsLimit); +} + AZ_CVAR(AZ::CVarFixedString, r_default_pipeline_name, AZ_TRAIT_BOOTSTRAPSYSTEMCOMPONENT_PIPELINE_NAME, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Default Render pipeline name"); +AZ_CVAR(float, r_fps_limit, 0, OnFrameRateLimitChanged, AZ::ConsoleFunctorFlags::Null, "The maximum framerate to render at, or 0 for unlimited"); namespace AZ { @@ -342,6 +349,22 @@ namespace AZ return true; } + float BootstrapSystemComponent::GetFrameRateLimit() const + { + return r_fps_limit; + } + + void BootstrapSystemComponent::SetFrameRateLimit(float fpsLimit) + { + r_fps_limit = fpsLimit; + if (m_viewportContext) + { + m_viewportContext->SetFpsLimit(r_fps_limit); + } + Render::Bootstrap::NotificationBus::Broadcast( + &Render::Bootstrap::NotificationBus::Events::OnFrameRateLimitChanged, fpsLimit); + } + void BootstrapSystemComponent::CreateDefaultRenderPipeline() { EnsureDefaultRenderPipelineInstalledForScene(m_defaultScene, m_viewportContext); @@ -381,23 +404,11 @@ namespace AZ } void BootstrapSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] ScriptTimePoint time) - { - // Temp: When running in the launcher without the legacy renderer - // we need to call RenderTick on the viewport context each frame. - if (m_viewportContext) - { - AZ::ApplicationTypeQuery appType; - ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationBus::Events::QueryApplicationType, appType); - if (appType.IsGame()) - { - m_viewportContext->RenderTick(); - } - } - } + { } int BootstrapSystemComponent::GetTickOrder() { - return TICK_LAST; + return TICK_PRE_RENDER; } void BootstrapSystemComponent::OnWindowClosed() diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h index 566d19b1a4..438c6cb236 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.h @@ -69,6 +69,8 @@ namespace AZ // Render::Bootstrap::RequestBus::Handler overrides ... AZ::RPI::ScenePtr GetOrCreateAtomSceneFromAzScene(AzFramework::Scene* scene) override; bool EnsureDefaultRenderPipelineInstalledForScene(AZ::RPI::ScenePtr scene, AZ::RPI::ViewportContextPtr viewportContext) override; + float GetFrameRateLimit() const override; + void SetFrameRateLimit(float fpsLimit) override; protected: // Component overrides ... diff --git a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp index 8099fc3a32..e16b89b5cd 100644 --- a/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp +++ b/Gems/Atom/RHI/Code/Source/RHI/CpuProfilerImpl.cpp @@ -144,7 +144,7 @@ namespace AZ // Try to lock here, the shutdownMutex will only be contested when the CpuProfiler is shutting down. if (m_shutdownMutex.try_lock_shared()) { - if (m_enabled) + if (m_enabled && ms_threadLocalStorage != nullptr) { ms_threadLocalStorage->RegionStackPopBack(); } diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RenderPipeline.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RenderPipeline.h index 90389687de..cc25aa17c4 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RenderPipeline.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/RenderPipeline.h @@ -161,19 +161,25 @@ namespace AZ //! Add this RenderPipeline to RPI system's RenderTick and it will be rendered whenever //! the RPI system's RenderTick is called. - //! The RenderPipeline is rendered per RenderTick by default unless AddToRenderTickOnce() was called. + //! The RenderPipeline is rendered per RenderTick by default. void AddToRenderTick(); + //! Add this RenderPipeline to RPI system's RenderTick and it will be rendered every RenderTick + //! after the specified interval has elapsed since the last rendered frame. + //! @param renderInterval The desired time between rendered frames, in seconds. + void AddToRenderTickAtInterval(AZStd::chrono::duration renderInterval); + //! Disable render for this RenderPipeline void RemoveFromRenderTick(); ~RenderPipeline(); - + enum class RenderMode : uint8_t { - RenderEveryTick, // Render at each RPI system render tick - RenderOnce, // Render once in next RPI system render tick - NoRender // Render disabled. + RenderEveryTick, //!< Render at each RPI system render tick. + RenderAtTargetRate, //!< Render on RPI system render tick after a target refresh rate interval has passed. + RenderOnce, //!< Render once in next RPI system render tick. + NoRender //!< Render disabled. }; //! Get current render mode @@ -185,6 +191,12 @@ namespace AZ //! Get draw filter mask RHI::DrawFilterMask GetDrawFilterMask() const; + using FrameNotificationEvent = AZ::Event<>; + //! Notifies a listener when a frame is about to be prepared for render, before SRGs are bound. + void ConnectPrepareFrameHandler(FrameNotificationEvent::Handler& handler); + //! Notifies a listener when the rendering of a frame has finished + void ConnectEndFrameHandler(FrameNotificationEvent::Handler& handler); + private: RenderPipeline() = default; @@ -202,8 +214,11 @@ namespace AZ void OnAddedToScene(Scene* scene); void OnRemovedFromScene(Scene* scene); + // Called before this pipeline is about to be rendered and before SRGs are bound. + void OnPrepareFrame(); + // Called when this pipeline is about to be rendered - void OnStartFrame(const TickTimeInfo& tick); + void OnStartFrame(); // Called when the rendering of current frame is finished. void OnFrameEnd(); @@ -228,8 +243,14 @@ namespace AZ PipelineViewMap m_pipelineViewsByTag; - /// The system time when the last time this pipeline render was started - float m_lastRenderStartTime = 0; + // The system time when the last time this pipeline render was started + AZStd::chrono::system_clock::time_point m_lastRenderStartTime; + + // The current system time, as of OnPrepareFrame's execution. + AZStd::chrono::system_clock::time_point m_lastRenderRequestTime; + + // The target time between renders when m_renderMode is RenderMode::RenderAtTargetRate + AZStd::chrono::duration m_targetRefreshRate; // RenderPipeline's name id, it will be used to identify the render pipeline when it's added to a Scene RenderPipelineId m_nameId; @@ -259,7 +280,11 @@ namespace AZ RHI::DrawFilterTag m_drawFilterTag; // A mask to filter draw items submitted by passes of this render pipeline. // This mask is created from the value of m_drawFilterTag. - RHI::DrawFilterMask m_drawFilterMask = 0; + RHI::DrawFilterMask m_drawFilterMask = 0; + + // Events for notification on render state + FrameNotificationEvent m_prepareFrameEvent; + FrameNotificationEvent m_endFrameEvent; }; } // namespace RPI diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/SceneBus.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/SceneBus.h index ca531d2de6..748c470edf 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/SceneBus.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/SceneBus.h @@ -67,6 +67,9 @@ namespace AZ //! Notifies when the PrepareRender phase is ending virtual void OnEndPrepareRender() {} + + //! Notifies when the render tick for a given frame has finished. + virtual void OnFrameEnd() {} }; using SceneNotificationBus = AZ::EBus; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h index 966e6b3016..feed24a80d 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContext.h @@ -51,9 +51,21 @@ namespace AZ //! Sets the root scene associated with this viewport. //! This does not provide a default render pipeline, one must be provided to enable rendering. void SetRenderScene(ScenePtr scene); - //! Runs one simulation and render tick and renders a frame to this viewport's window. - //! @note This is likely to be replaced by a tick management system in the RPI. - void RenderTick(); + + //! Gets the maximum frame rate this viewport context's pipeline can render at, 0 for unlimited. + //! The target framerate for the pipeline will be determined by this frame limit and the + //! vsync settings for the current window. + float GetFpsLimit() const; + + //! Sets the maximum frame rate this viewport context's pipeline can render at, 0 for unlimited. + //! The target framerate for the pipeline will be determined by this frame limit and the + //! vsync settings for the current window. + void SetFpsLimit(float fpsLimit); + + //! Gets the target frame rate for this viewport context. + //! This returns the lowest of either the current VSync refresh rate + //! or 0 for an unlimited frame rate (if there's no FPS limit and vsync is off). + float GetTargetFrameRate() const; //! Gets the current name of this ViewportContext. //! This name is used to tie this ViewportContext to its View stack, and ViewportContexts may be @@ -74,19 +86,28 @@ namespace AZ //! \see AzFramework::WindowRequests::GetDpiScaleFactor float GetDpiScalingFactor() const; + //! Gets the current vsync interval, as a divisor of the current refresh rate. + //! A value of 0 indicates that vsync is disabled. + uint32_t GetVsyncInterval() const; + + //! Gets the current display refresh rate, in frames per second. + uint32_t GetRefreshRate() const; + // SceneNotificationBus interface overrides... //! Ensures our default view remains set when our scene's render pipelines are modified. void OnRenderPipelineAdded(RenderPipelinePtr pipeline) override; //! Ensures our default view remains set when our scene's render pipelines are modified. void OnRenderPipelineRemoved(RenderPipeline* pipeline) override; - //! OnBeginPrepareRender is forwarded to our RenderTick notification to allow subscribers to do rendering. - void OnBeginPrepareRender() override; // WindowNotificationBus interface overrides... //! Used to fire a notification when our window resizes. void OnWindowResized(uint32_t width, uint32_t height) override; //! Used to fire a notification when our window DPI changes. void OnDpiScaleFactorChanged(float dpiScaleFactor) override; + //! Used to fire a notification when our vsync interval changes. + void OnVsyncIntervalChanged(uint32_t interval) override; + //! Used to fire a notification when our refresh rate changes. + void OnRefreshRateChanged(uint32_t refreshRate) override; using SizeChangedEvent = AZ::Event; //! Notifies consumers when the viewport size has changed. @@ -98,6 +119,12 @@ namespace AZ //! Alternatively, connect to ViewportContextNotificationsBus and listen to ViewportContextNotifications::OnViewportDpiScalingChanged. void ConnectDpiScalingFactorChangedHandler(ScalarChangedEvent::Handler& handler); + using UintChangedEvent = AZ::Event; + //! Notifies consumers when the vsync interval has changed. + void ConnectVsyncIntervalChangedHandler(UintChangedEvent::Handler& handler); + //! Notifies consumers when the refresh rate has changed. + void ConnectRefreshRateChangedHandler(UintChangedEvent::Handler& handler); + using MatrixChangedEvent = AZ::Event; //! Notifies consumers when the view matrix has changed. void ConnectViewMatrixChangedHandler(MatrixChangedEvent::Handler& handler); @@ -139,15 +166,24 @@ namespace AZ void SetDefaultView(ViewPtr view); // Ensures our render pipeline's default camera matches ours. void UpdatePipelineView(); + // Ensures our render pipeline refresh rate matches our refresh rate. + void UpdatePipelineRefreshRate(); + // Resets the current pipeline reference and ensures pipeline events are disconnected. + void ResetCurrentPipeline(); ScenePtr m_rootScene; WindowContextSharedPtr m_windowContext; ViewPtr m_defaultView; AzFramework::WindowSize m_viewportSize; float m_viewportDpiScaleFactor = 1.0f; + uint32_t m_vsyncInterval = 1; + uint32_t m_refreshRate = 60; + float m_fpsLimit = 0.f; SizeChangedEvent m_sizeChangedEvent; ScalarChangedEvent m_dpiScalingFactorChangedEvent; + UintChangedEvent m_vsyncIntervalChangedEvent; + UintChangedEvent m_refreshRateChangedEvent; MatrixChangedEvent m_viewMatrixChangedEvent; MatrixChangedEvent::Handler m_onViewMatrixChangedHandler; MatrixChangedEvent m_projectionMatrixChangedEvent; @@ -157,6 +193,9 @@ namespace AZ ViewChangedEvent m_defaultViewChangedEvent; ViewportIdEvent m_aboutToBeDestroyedEvent; + AZ::Event<>::Handler m_prepareFrameHandler; + AZ::Event<>::Handler m_endFrameHandler; + ViewportContextManager* m_manager; RenderPipelinePtr m_currentPipeline; Name m_name; diff --git a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h index 0b53172ba2..fa13a3987a 100644 --- a/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h +++ b/Gems/Atom/RPI/Code/Include/Atom/RPI.Public/ViewportContextBus.h @@ -110,11 +110,13 @@ namespace AZ virtual void OnViewportSizeChanged(AzFramework::WindowSize size){AZ_UNUSED(size);} //! Called when the window DPI scaling changes for a given viewport context. virtual void OnViewportDpiScalingChanged(float dpiScale){AZ_UNUSED(dpiScale);} - //! Called when the active view for a given viewport context name changes. + //! Called when the active view changes for a given viewport context. virtual void OnViewportDefaultViewChanged(AZ::RPI::ViewPtr view){AZ_UNUSED(view);} //! Called when the viewport is to be rendered. - //! Add draws to this functions if they only need to be rendered to this viewport. - virtual void OnRenderTick(){}; + //! Add draws to this function if they only need to be rendered to this viewport. + virtual void OnRenderTick(){} + //! Called when the viewport finishes rendering a frame. + virtual void OnFrameEnd(){} protected: ~ViewportContextNotifications() = default; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.cpp b/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.cpp index 2567d221e5..789d43712e 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.cpp @@ -14,6 +14,9 @@ #include #include +#include +#include +#include #include #include @@ -93,20 +96,29 @@ namespace AZ } m_rpiSystem.Initialize(m_rpiDescriptor); - AZ::SystemTickBus::Handler::BusConnect(); + AZ::TickBus::Handler::BusConnect(); } void RPISystemComponent::Deactivate() { - AZ::SystemTickBus::Handler::BusDisconnect(); + AZ::TickBus::Handler::BusDisconnect(); m_rpiSystem.Shutdown(); } - void RPISystemComponent::OnSystemTick() + void RPISystemComponent::OnTick([[maybe_unused]]float deltaTime, [[maybe_unused]]ScriptTimePoint time) { + if (deltaTime == 0.f) + { + return; + } + m_rpiSystem.SimulationTick(); m_rpiSystem.RenderTick(); } + int RPISystemComponent::GetTickOrder() + { + return AZ::ComponentTickBus::TICK_RENDER; + } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.h b/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.h index e0a128c3f1..7933e1581c 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.h +++ b/Gems/Atom/RPI/Code/Source/RPI.Private/RPISystemComponent.h @@ -32,7 +32,7 @@ namespace AZ */ class RPISystemComponent final : public AZ::Component - , public AZ::SystemTickBus::Handler + , private AZ::TickBus::Handler { public: AZ_COMPONENT(RPISystemComponent, "{83E301F3-7A0C-4099-B530-9342B91B1BC0}"); @@ -50,8 +50,9 @@ namespace AZ private: RPISystemComponent(const RPISystemComponent&) = delete; - // SystemTickBus overrides... - void OnSystemTick() override; + // TickBus overrides... + void OnTick(float deltaTime, ScriptTimePoint time) override; + int GetTickOrder() override; RPISystem m_rpiSystem; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp index a8d94e9a91..c5e871697b 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Pass/Pass.cpp @@ -93,8 +93,11 @@ namespace AZ void Pass::SetEnabled(bool enabled) { - m_flags.m_enabled = enabled; - OnHierarchyChange(); + if (m_flags.m_enabled != enabled) + { + m_flags.m_enabled = enabled; + OnHierarchyChange(); + } } bool Pass::IsEnabled() const diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp index 6d974a074f..7f0ab9c8aa 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/RenderPipeline.cpp @@ -301,6 +301,26 @@ namespace AZ m_drawFilterMask = 0; } + void RenderPipeline::OnPrepareFrame() + { + m_lastRenderRequestTime = AZStd::chrono::system_clock::now(); + + // If we're attempting to render at a target interval, check to see if we're within + // 1ms of that interval, enabling rendering only if we are. + if (m_renderMode == RenderMode::RenderAtTargetRate) + { + constexpr AZStd::chrono::duration updateThresholdMs(0.001f); + const bool shouldRender = + m_lastRenderRequestTime - m_lastRenderStartTime + updateThresholdMs >= m_targetRefreshRate; + m_rootPass->SetEnabled(shouldRender); + } + + if (NeedsRender()) + { + m_prepareFrameEvent.Signal(); + } + } + void RenderPipeline::OnPassModified() { if (m_needsPassRecreate) @@ -375,11 +395,11 @@ namespace AZ m_scene->RemoveRenderPipeline(m_nameId); } - void RenderPipeline::OnStartFrame(const TickTimeInfo& tick) + void RenderPipeline::OnStartFrame() { AZ_PROFILE_FUNCTION(RPI); - m_lastRenderStartTime = tick.m_currentGameTime; + m_lastRenderStartTime = m_lastRenderRequestTime; OnPassModified(); @@ -407,6 +427,7 @@ namespace AZ { RemoveFromRenderTick(); } + m_endFrameEvent.Signal(); } void RenderPipeline::CollectPersistentViews(AZStd::map& outViewMasks) const @@ -489,6 +510,13 @@ namespace AZ m_renderMode = RenderMode::RenderEveryTick; } + void RenderPipeline::AddToRenderTickAtInterval(AZStd::chrono::duration renderInterval) + { + m_rootPass->SetEnabled(false); + m_renderMode = RenderMode::RenderAtTargetRate; + m_targetRefreshRate = renderInterval; + } + void RenderPipeline::RemoveFromRenderTick() { m_renderMode = RenderMode::NoRender; @@ -502,7 +530,7 @@ namespace AZ bool RenderPipeline::NeedsRender() const { - return m_renderMode != RenderMode::NoRender; + return m_rootPass->IsEnabled(); } RHI::DrawFilterTag RenderPipeline::GetDrawFilterTag() const @@ -515,6 +543,16 @@ namespace AZ return m_drawFilterMask; } + void RenderPipeline::ConnectPrepareFrameHandler(FrameNotificationEvent::Handler& handler) + { + handler.Connect(m_prepareFrameEvent); + } + + void RenderPipeline::ConnectEndFrameHandler(FrameNotificationEvent::Handler& handler) + { + handler.Connect(m_endFrameEvent); + } + void RenderPipeline::SetDrawFilterTag(RHI::DrawFilterTag tag) { m_drawFilterTag = tag; diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp index 0b0481b960..9fa49f7f2a 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Scene.cpp @@ -420,7 +420,7 @@ namespace AZ } } - void Scene::PrepareRender(const TickTimeInfo& tickInfo, RHI::JobPolicy jobPolicy) + void Scene::PrepareRender([[maybe_unused]]const TickTimeInfo& tickInfo, RHI::JobPolicy jobPolicy) { AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: PrepareRender"); @@ -432,20 +432,27 @@ namespace AZ SceneNotificationBus::Event(GetId(), &SceneNotification::OnBeginPrepareRender); - // Get active pipelines which need to be rendered and notify them frame started + // Get active pipelines which need to be rendered and notify them of an impending frame. AZStd::vector activePipelines; { - AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Scene: OnStartFrame"); + AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Scene: OnPrepareFrame"); for (auto& pipeline : m_pipelines) { + pipeline->OnPrepareFrame(); if (pipeline->NeedsRender()) { activePipelines.push_back(pipeline); - pipeline->OnStartFrame(tickInfo); } } } + // Get active pipelines which need to be rendered and notify them frame started + for (const auto& pipeline : activePipelines) + { + AZ_ATOM_PROFILE_TIME_GROUP_REGION("RPI", "Scene: OnStartFrame"); + pipeline->OnStartFrame(); + } + // Return if there is no active render pipeline if (activePipelines.empty()) { @@ -587,10 +594,12 @@ namespace AZ void Scene::OnFrameEnd() { AZ_ATOM_PROFILE_FUNCTION("RPI", "Scene: OnFrameEnd"); + bool didRender = false; for (auto& pipeline : m_pipelines) { if (pipeline->NeedsRender()) { + didRender = true; pipeline->OnFrameEnd(); } } @@ -598,6 +607,10 @@ namespace AZ { fp->OnRenderEnd(); } + if (didRender) + { + SceneNotificationBus::Event(GetId(), &SceneNotification::OnFrameEnd); + } } void Scene::UpdateSrgs() diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp index b07728938f..bdb3ea8899 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/View.cpp @@ -241,7 +241,10 @@ namespace AZ { AZ_PROFILE_FUNCTION(RPI); m_drawListContext.FinalizeLists(); - SortFinalizedDrawLists(); + if (m_passesByDrawList) + { + SortFinalizedDrawLists(); + } } void View::SortFinalizedDrawLists() diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp index 77114e5cf5..3dcbae2fb9 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/ViewportContext.cpp @@ -25,14 +25,13 @@ namespace AZ , m_viewportSize(1, 1) { m_windowContext->Initialize(device, nativeWindow); - AzFramework::WindowRequestBus::EventResult( - m_viewportSize, - nativeWindow, - &AzFramework::WindowRequestBus::Events::GetClientAreaSize); - AzFramework::WindowRequestBus::EventResult( - m_viewportDpiScaleFactor, - nativeWindow, - &AzFramework::WindowRequestBus::Events::GetDpiScaleFactor); + AzFramework::WindowRequestBus::Event(nativeWindow, [this](AzFramework::WindowRequestBus::Events* window) + { + m_viewportSize = window->GetClientAreaSize(); + m_viewportDpiScaleFactor = window->GetDpiScaleFactor(); + m_vsyncInterval = window->GetSyncInterval(); + m_refreshRate = window->GetDisplayRefreshRate(); + }); AzFramework::WindowNotificationBus::Handler::BusConnect(nativeWindow); AzFramework::ViewportRequestBus::Handler::BusConnect(id); @@ -46,6 +45,20 @@ namespace AZ m_viewMatrixChangedEvent.Signal(matrix); }); + m_prepareFrameHandler = RenderPipeline::FrameNotificationEvent::Handler( + [this]() + { + ViewportContextNotificationBus::Event(GetName(), &ViewportContextNotificationBus::Events::OnRenderTick); + ViewportContextIdNotificationBus::Event(GetId(), &ViewportContextIdNotificationBus::Events::OnRenderTick); + }); + + m_endFrameHandler = RenderPipeline::FrameNotificationEvent::Handler( + [this]() + { + ViewportContextNotificationBus::Event(GetName(), &ViewportContextNotificationBus::Events::OnFrameEnd); + ViewportContextIdNotificationBus::Event(GetId(), &ViewportContextIdNotificationBus::Events::OnFrameEnd); + }); + SetRenderScene(renderScene); } @@ -111,26 +124,38 @@ namespace AZ { SceneNotificationBus::Handler::BusConnect(m_rootScene->GetId()); } - m_currentPipeline.reset(); + ResetCurrentPipeline(); UpdatePipelineView(); + UpdatePipelineRefreshRate(); } m_sceneChangedEvent.Signal(scene); } - void ViewportContext::RenderTick() + float ViewportContext::GetFpsLimit() const { - // add the current pipeline to next render tick if it's not already added. - if (m_currentPipeline && m_currentPipeline->GetRenderMode() != RenderPipeline::RenderMode::RenderOnce) - { - m_currentPipeline->AddToRenderTickOnce(); - } + return m_fpsLimit; } - void ViewportContext::OnBeginPrepareRender() + void ViewportContext::SetFpsLimit(float fpsLimit) { - ViewportContextNotificationBus::Event(GetName(), &ViewportContextNotificationBus::Events::OnRenderTick); - ViewportContextIdNotificationBus::Event(GetId(), &ViewportContextIdNotificationBus::Events::OnRenderTick); + m_fpsLimit = fpsLimit; + UpdatePipelineRefreshRate(); + } + + float ViewportContext::GetTargetFrameRate() const + { + float targetFrameRate = GetFpsLimit(); + const AZ::u32 vsyncInterval = GetVsyncInterval(); + if (vsyncInterval != 0) + { + const float vsyncFrameRate = static_cast(GetRefreshRate()) / static_cast(vsyncInterval); + if (targetFrameRate == 0.f || vsyncFrameRate < targetFrameRate) + { + targetFrameRate = vsyncFrameRate; + } + } + return targetFrameRate; } AZ::Name ViewportContext::GetName() const @@ -158,6 +183,16 @@ namespace AZ return m_viewportDpiScaleFactor; } + uint32_t ViewportContext::GetVsyncInterval() const + { + return m_vsyncInterval; + } + + uint32_t ViewportContext::GetRefreshRate() const + { + return m_refreshRate; + } + void ViewportContext::ConnectSizeChangedHandler(SizeChangedEvent::Handler& handler) { handler.Connect(m_sizeChangedEvent); @@ -168,6 +203,16 @@ namespace AZ handler.Connect(m_dpiScalingFactorChangedEvent); } + void ViewportContext::ConnectVsyncIntervalChangedHandler(UintChangedEvent::Handler& handler) + { + handler.Connect(m_vsyncIntervalChangedEvent); + } + + void ViewportContext::ConnectRefreshRateChangedHandler(UintChangedEvent::Handler& handler) + { + handler.Connect(m_refreshRateChangedEvent); + } + void ViewportContext::ConnectViewMatrixChangedHandler(MatrixChangedEvent::Handler& handler) { handler.Connect(m_viewMatrixChangedEvent); @@ -263,12 +308,43 @@ namespace AZ m_currentPipelineChangedEvent.Signal(m_currentPipeline); } - if (auto pipeline = GetCurrentPipeline()) + if (m_currentPipeline) { - pipeline->SetDefaultView(m_defaultView); + if (!m_prepareFrameHandler.IsConnected()) + { + m_currentPipeline->ConnectPrepareFrameHandler(m_prepareFrameHandler); + m_currentPipeline->ConnectEndFrameHandler(m_endFrameHandler); + } + m_currentPipeline->SetDefaultView(m_defaultView); } } + void ViewportContext::UpdatePipelineRefreshRate() + { + if (!m_currentPipeline) + { + return; + } + + const float refreshRate = GetTargetFrameRate(); + // If we have a truly unlimited framerate, just render every tick + if (refreshRate == 0.f) + { + m_currentPipeline->AddToRenderTick(); + } + else + { + m_currentPipeline->AddToRenderTickAtInterval(AZStd::chrono::duration(1.f / refreshRate)); + } + } + + void ViewportContext::ResetCurrentPipeline() + { + m_prepareFrameHandler.Disconnect(); + m_endFrameHandler.Disconnect(); + m_currentPipeline.reset(); + } + RenderPipelinePtr ViewportContext::GetCurrentPipeline() { return m_currentPipeline; @@ -281,8 +357,9 @@ namespace AZ // in the event prioritization is added later if (pipeline->GetWindowHandle() == m_windowContext->GetWindowHandle()) { - m_currentPipeline.reset(); + ResetCurrentPipeline(); UpdatePipelineView(); + UpdatePipelineRefreshRate(); } } @@ -290,8 +367,9 @@ namespace AZ { if (m_currentPipeline.get() == pipeline) { - m_currentPipeline.reset(); + ResetCurrentPipeline(); UpdatePipelineView(); + UpdatePipelineRefreshRate(); } } @@ -305,10 +383,30 @@ namespace AZ } } + void ViewportContext::OnRefreshRateChanged(uint32_t refreshRate) + { + if (m_refreshRate != refreshRate) + { + m_refreshRate = refreshRate; + m_refreshRateChangedEvent.Signal(m_refreshRate); + UpdatePipelineRefreshRate(); + } + } + void ViewportContext::OnDpiScaleFactorChanged(float dpiScaleFactor) { m_viewportDpiScaleFactor = dpiScaleFactor; m_dpiScalingFactorChangedEvent.Signal(dpiScaleFactor); } + + void ViewportContext::OnVsyncIntervalChanged(uint32_t interval) + { + if (m_vsyncInterval != interval) + { + m_vsyncInterval = interval; + m_vsyncIntervalChangedEvent.Signal(m_vsyncInterval); + UpdatePipelineRefreshRate(); + } + } } // namespace RPI } // namespace AZ diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h index 4210c82921..60ddf33cf7 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidget.h @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -21,6 +22,8 @@ #include #include #include +#include +#include namespace AtomToolsFramework { @@ -35,6 +38,8 @@ namespace AtomToolsFramework , public AzFramework::WindowRequestBus::Handler , protected AzFramework::InputChannelEventListener , protected AZ::TickBus::Handler + , protected AZ::Render::Bootstrap::NotificationBus::Handler + , protected AtomToolsFramework::RenderViewportWidgetNotificationBus::Handler { public: //! Creates a RenderViewportWidget. @@ -121,6 +126,7 @@ namespace AtomToolsFramework // AZ::TickBus::Handler ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; + int GetTickOrder() override; // QWidget ... void resizeEvent(QResizeEvent *event) override; @@ -128,9 +134,21 @@ namespace AtomToolsFramework void enterEvent(QEvent* event) override; void leaveEvent(QEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; + void focusInEvent(QFocusEvent* event) override; + + // AZ::Render::Bootstrap::NotificationBus::Handler ... + void OnFrameRateLimitChanged(float fpsLimit) override; + + // AtomToolsFramework::RenderViewportWidgetNotificationBus::Handler ... + void OnInactiveViewportFrameRateChanged(float fpsLimit) override; private: + AzFramework::NativeWindowHandle GetNativeWindowHandle() const; + void UpdateFrameRate(); + + void SetScreen(QScreen* screen); void SendWindowResizeEvent(); + void NotifyUpdateRefreshRate(); // The underlying ViewportContext, our entry-point to the Atom RPI. AZ::RPI::ViewportContextPtr m_viewportContext; @@ -153,5 +171,11 @@ namespace AtomToolsFramework AZ::ScriptTimePoint m_time; // Maps our internal Qt events into AzFramework InputChannels for our ViewportControllerList. AzToolsFramework::QtEventToAzInputMapper* m_inputChannelMapper = nullptr; + // Stores our current screen, used for tracking the current refresh rate. + QScreen* m_screen = nullptr; + // Stores the last RenderViewportWidget that has received user focus. + // This is used for optional framerate throtting for "inactive" viewports via the + // ed_inactive_viewport_fps_limit CVAR. + AZ::EnvironmentVariable m_lastFocusedViewport; }; } //namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidgetNotificationBus.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidgetNotificationBus.h new file mode 100644 index 0000000000..0563bd6bf2 --- /dev/null +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Viewport/RenderViewportWidgetNotificationBus.h @@ -0,0 +1,35 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +namespace AtomToolsFramework +{ + //! Provides an interface for providing notifications specific to RenderViewportWidget. + //! @note Most behaviors in RenderViewportWidget are handled by its underyling + //! ViewportContext, this bus is specifically for functionality exclusive to the + //! Qt layer provided by RenderViewportWidget. + class RenderViewportWidgetNotifications : public AZ::EBusTraits + { + public: + static const AZ::EBusAddressPolicy AddressPolicy = AZ::EBusAddressPolicy::Single; + static const AZ::EBusHandlerPolicy HandlerPolicy = AZ::EBusHandlerPolicy::Multiple; + + //! Triggered when the idle frame rate limit for inactive viewports changed. + //! Controlled by the ed_inactive_viewport_fps_limit CVAR. + //! Active viewports are controlled by the r_fps_limit CVAR. + virtual void OnInactiveViewportFrameRateChanged([[maybe_unused]]float fpsLimit){} + + protected: + ~RenderViewportWidgetNotifications() = default; + }; + + using RenderViewportWidgetNotificationBus = AZ::EBus; +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp index 027ac80151..4446e11231 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Viewport/RenderViewportWidget.cpp @@ -6,23 +6,42 @@ * */ -#include +#include +#include +#include #include #include -#include +#include +#include +#include #include #include #include #include -#include -#include -#include #include -#include #include -#include +#include #include +#include +#include +#include + +static void OnInactiveViewportFrameRateChanged(const float& fpsLimit) +{ + AtomToolsFramework::RenderViewportWidgetNotificationBus::Broadcast( + &AtomToolsFramework::RenderViewportWidgetNotificationBus::Events::OnInactiveViewportFrameRateChanged, fpsLimit); +} + +AZ_CVAR( + float, + ed_inactive_viewport_fps_limit, + 0, + OnInactiveViewportFrameRateChanged, + AZ::ConsoleFunctorFlags::Null, + "The maximum framerate to render viewports that don't have focus at"); + +static constexpr const char* LastFocusedViewportVariableName = "AtomToolsFramework::RenderViewportWidget::LastFocusedViewport"; namespace AtomToolsFramework { @@ -30,6 +49,12 @@ namespace AtomToolsFramework : QWidget(parent) , AzFramework::InputChannelEventListener(AzFramework::InputChannelEventListener::GetPriorityDefault()) { + m_lastFocusedViewport = AZ::Environment::FindVariable(LastFocusedViewportVariableName); + if (!m_lastFocusedViewport) + { + m_lastFocusedViewport = AZ::Environment::CreateVariable(LastFocusedViewportVariableName, nullptr); + } + if (shouldInitializeViewportContext) { InitializeViewportContext(); @@ -38,13 +63,24 @@ namespace AtomToolsFramework setUpdatesEnabled(false); setFocusPolicy(Qt::FocusPolicy::WheelFocus); setMouseTracking(true); + + // Wait a frame for our window handle to be constructed, then wire up our screen change signals. + QTimer::singleShot( + 0, + [this]() + { + QObject::connect(windowHandle(), &QWindow::screenChanged, this, &RenderViewportWidget::SetScreen); + }); + SetScreen(screen()); } bool RenderViewportWidget::InitializeViewportContext(AzFramework::ViewportId id) { if (m_viewportContext != nullptr) { - AZ_Assert(id == AzFramework::InvalidViewportId || m_viewportContext->GetId() == id, "Attempted to reinitialize RenderViewportWidget with a different ID"); + AZ_Assert( + id == AzFramework::InvalidViewportId || m_viewportContext->GetId() == id, + "Attempted to reinitialize RenderViewportWidget with a different ID"); return true; } @@ -59,7 +95,7 @@ namespace AtomToolsFramework // Before we do anything else, we must create a ViewportContext which will give us a ViewportId if we didn't manually specify one. AZ::RPI::ViewportContextRequestsInterface::CreationParameters params; params.device = AZ::RHI::RHISystemInterface::Get()->GetDevice(); - params.windowHandle = reinterpret_cast(winId()); + params.windowHandle = GetNativeWindowHandle(); params.id = id; AzFramework::WindowRequestBus::Handler::BusConnect(params.windowHandle); m_viewportContext = viewportContextManager->CreateViewportContext(AZ::Name(), params); @@ -80,29 +116,46 @@ namespace AtomToolsFramework AzFramework::InputChannelEventListener::Connect(); AZ::TickBus::Handler::BusConnect(); AzFramework::WindowRequestBus::Handler::BusConnect(params.windowHandle); + AZ::Render::Bootstrap::NotificationBus::Handler::BusConnect(); + AtomToolsFramework::RenderViewportWidgetNotificationBus::Handler::BusConnect(); m_inputChannelMapper = new AzToolsFramework::QtEventToAzInputMapper(this, id); // Forward input events to our controller list. - QObject::connect(m_inputChannelMapper, &AzToolsFramework::QtEventToAzInputMapper::InputChannelUpdated, this, + QObject::connect( + m_inputChannelMapper, &AzToolsFramework::QtEventToAzInputMapper::InputChannelUpdated, this, [this](const AzFramework::InputChannel* inputChannel, QEvent* event) - { - AzFramework::NativeWindowHandle windowId = reinterpret_cast(winId()); - if (m_controllerList->HandleInputChannelEvent(AzFramework::ViewportControllerInputEvent{GetId(), windowId, *inputChannel})) { - // If the controller handled the input event, mark the event as accepted so it doesn't continue to propagate. - if (event) + const AzFramework::NativeWindowHandle windowId = GetNativeWindowHandle(); + if (m_controllerList->HandleInputChannelEvent( + AzFramework::ViewportControllerInputEvent{ GetId(), windowId, *inputChannel })) { - event->setAccepted(true); + // If the controller handled the input event, mark the event as accepted so it doesn't continue to propagate. + if (event) + { + event->setAccepted(true); + } } - } - }); + }); + + // Update our target frame rate. If we're the only viewport, become active. + if (m_lastFocusedViewport.Get() == nullptr) + { + m_lastFocusedViewport.Set(this); + } + UpdateFrameRate(); + return true; } RenderViewportWidget::~RenderViewportWidget() { + if (m_lastFocusedViewport.Get() == this) + { + m_lastFocusedViewport.Set(nullptr); + } + AzFramework::WindowRequestBus::Handler::BusDisconnect(); AZ::TickBus::Handler::BusDisconnect(); AzFramework::InputChannelEventListener::Disconnect(); @@ -181,17 +234,22 @@ namespace AtomToolsFramework bool shouldConsumeEvent = true; - AzFramework::NativeWindowHandle windowId = reinterpret_cast(winId()); - const bool eventHandled = m_controllerList->HandleInputChannelEvent({GetId(), windowId, inputChannel}); + const bool eventHandled = m_controllerList->HandleInputChannelEvent({ GetId(), GetNativeWindowHandle(), inputChannel }); - // If our controllers handled the event and it's one we can safely consume (i.e. it's not an Ended event that other viewports might need), consume it. + // If our controllers handled the event and it's one we can safely consume (i.e. it's not an Ended event that other viewports might + // need), consume it. return eventHandled && shouldConsumeEvent; } - void RenderViewportWidget::OnTick([[maybe_unused]]float deltaTime, AZ::ScriptTimePoint time) + void RenderViewportWidget::OnTick([[maybe_unused]] float deltaTime, AZ::ScriptTimePoint time) { m_time = time; - m_controllerList->UpdateViewport({GetId(), AzFramework::FloatSeconds(deltaTime), m_time}); + m_controllerList->UpdateViewport({ GetId(), AzFramework::FloatSeconds(deltaTime), m_time }); + } + + int RenderViewportWidget::GetTickOrder() + { + return AZ::ComponentTickBus::TICK_PRE_RENDER; } void RenderViewportWidget::resizeEvent([[maybe_unused]] QResizeEvent* event) @@ -236,6 +294,75 @@ namespace AtomToolsFramework m_mousePosition = event->localPos(); } + void RenderViewportWidget::focusInEvent([[maybe_unused]] QFocusEvent* event) + { + RenderViewportWidget* lastFocusedViewport = m_lastFocusedViewport.Get(); + if (lastFocusedViewport == this) + { + return; + } + + RenderViewportWidget* previousFocusWidget = lastFocusedViewport; + m_lastFocusedViewport.Set(this); + + // Ensure this viewport and whatever viewport last had focus (if any) respect + // the active / inactive viewport frame rate settings. + UpdateFrameRate(); + if (previousFocusWidget != nullptr) + { + previousFocusWidget->UpdateFrameRate(); + } + } + + void RenderViewportWidget::OnFrameRateLimitChanged([[maybe_unused]] float fpsLimit) + { + UpdateFrameRate(); + } + + void RenderViewportWidget::OnInactiveViewportFrameRateChanged([[maybe_unused]] float fpsLimit) + { + UpdateFrameRate(); + } + + AzFramework::NativeWindowHandle RenderViewportWidget::GetNativeWindowHandle() const + { + return reinterpret_cast(winId()); + } + + void RenderViewportWidget::UpdateFrameRate() + { + if (ed_inactive_viewport_fps_limit > 0.f && m_lastFocusedViewport.Get() != this) + { + m_viewportContext->SetFpsLimit(ed_inactive_viewport_fps_limit); + } + else + { + float fpsLimit = 0.f; + AZ::Render::Bootstrap::RequestBus::BroadcastResult(fpsLimit, &AZ::Render::Bootstrap::RequestBus::Events::GetFrameRateLimit); + m_viewportContext->SetFpsLimit(fpsLimit); + } + } + + void RenderViewportWidget::SetScreen(QScreen* screen) + { + if (m_screen != screen) + { + if (m_screen) + { + QObject::disconnect(m_screen, &QScreen::refreshRateChanged, this, &RenderViewportWidget::NotifyUpdateRefreshRate); + } + + if (screen) + { + QObject::connect(m_screen, &QScreen::refreshRateChanged, this, &RenderViewportWidget::NotifyUpdateRefreshRate); + } + + NotifyUpdateRefreshRate(); + + m_screen = screen; + } + } + void RenderViewportWidget::SendWindowResizeEvent() { // Scale the size by the DPI of the platform to @@ -243,11 +370,17 @@ namespace AtomToolsFramework const QSize uiWindowSize = size(); const QSize windowSize = uiWindowSize * devicePixelRatioF(); - const AzFramework::NativeWindowHandle windowId = reinterpret_cast(winId()); - AzFramework::WindowNotificationBus::Event(windowId, &AzFramework::WindowNotifications::OnWindowResized, windowSize.width(), windowSize.height()); + AzFramework::WindowNotificationBus::Event( + GetNativeWindowHandle(), &AzFramework::WindowNotifications::OnWindowResized, windowSize.width(), windowSize.height()); m_windowResizedEvent = false; } + void RenderViewportWidget::NotifyUpdateRefreshRate() + { + AzFramework::WindowNotificationBus::Event( + GetNativeWindowHandle(), &AzFramework::WindowNotificationBus::Events::OnRefreshRateChanged, GetDisplayRefreshRate()); + } + AZ::Name RenderViewportWidget::GetCurrentContextName() const { return m_viewportContext->GetName(); @@ -303,9 +436,7 @@ namespace AtomToolsFramework // Build camera state from Atom camera transforms AzFramework::CameraState cameraState = AzFramework::CreateCameraFromWorldFromViewMatrix( - currentView->GetViewToWorldMatrix(), - AZ::Vector2{aznumeric_cast(width()), aznumeric_cast(height())} - ); + currentView->GetViewToWorldMatrix(), AZ::Vector2{ aznumeric_cast(width()), aznumeric_cast(height()) }); AzFramework::SetCameraClippingVolumeFromPerspectiveFovMatrixRH(cameraState, currentView->GetViewToClipMatrix()); // Convert from Z-up @@ -317,8 +448,7 @@ namespace AtomToolsFramework AzFramework::ScreenPoint RenderViewportWidget::ViewportWorldToScreen(const AZ::Vector3& worldPosition) { - if (AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); - currentView == nullptr) + if (AZ::RPI::ViewPtr currentView = m_viewportContext->GetDefaultView(); currentView == nullptr) { return AzFramework::ScreenPoint(0, 0); } @@ -331,12 +461,10 @@ namespace AtomToolsFramework const auto& cameraProjection = m_viewportContext->GetCameraProjectionMatrix(); const auto& cameraView = m_viewportContext->GetCameraViewMatrix(); - const AZ::Vector4 normalizedScreenPosition { - screenPosition.m_x * 2.f / width() - 1.0f, - (height() - screenPosition.m_y) * 2.f / height() - 1.0f, - 1.f - depth, // [GFX TODO] [ATOM-1501] Currently we always assume reverse depth - 1.f - }; + const AZ::Vector4 normalizedScreenPosition{ screenPosition.m_x * 2.f / width() - 1.0f, + (height() - screenPosition.m_y) * 2.f / height() - 1.0f, + 1.f - depth, // [GFX TODO] [ATOM-1501] Currently we always assume reverse depth + 1.f }; AZ::Matrix4x4 worldFromScreen = cameraProjection * cameraView; worldFromScreen.InvertFull(); @@ -365,7 +493,7 @@ namespace AtomToolsFramework AZ::Vector3 rayDirection = pos1.value() - pos0.value(); rayDirection.Normalize(); - return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{rayOrigin, rayDirection}; + return AzToolsFramework::ViewportInteraction::ProjectedViewportRay{ rayOrigin, rayDirection }; } float RenderViewportWidget::DeviceScalingFactor() @@ -395,12 +523,12 @@ namespace AtomToolsFramework AzFramework::WindowSize RenderViewportWidget::GetClientAreaSize() const { - return AzFramework::WindowSize{aznumeric_cast(width()), aznumeric_cast(height())}; + return AzFramework::WindowSize{ aznumeric_cast(width()), aznumeric_cast(height()) }; } void RenderViewportWidget::ResizeClientArea(AzFramework::WindowSize clientAreaSize) { - const QSize targetSize = QSize{aznumeric_cast(clientAreaSize.m_width), aznumeric_cast(clientAreaSize.m_height)}; + const QSize targetSize = QSize{ aznumeric_cast(clientAreaSize.m_width), aznumeric_cast(clientAreaSize.m_height) }; resize(targetSize); } @@ -410,7 +538,7 @@ namespace AtomToolsFramework return false; } - void RenderViewportWidget::SetFullScreenState([[maybe_unused]]bool fullScreenState) + void RenderViewportWidget::SetFullScreenState([[maybe_unused]] bool fullScreenState) { // The RenderViewportWidget does not currently support full screen. } @@ -433,11 +561,20 @@ namespace AtomToolsFramework uint32_t RenderViewportWidget::GetDisplayRefreshRate() const { - return 60; + return static_cast(screen()->refreshRate()); } uint32_t RenderViewportWidget::GetSyncInterval() const { - return 1; + uint32_t interval = 1; + + // Get vsync_interval from AzFramework::NativeWindow, which owns it. + // NativeWindow also handles broadcasting OnVsyncIntervalChanged to all + // WindowNotificationBus listeners. + if (auto console = AZ::Interface::Get()) + { + console->GetCvarValue("vsync_interval", interval); + } + return interval; } -} //namespace AtomToolsFramework +} // namespace AtomToolsFramework diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake index 3d4bb82eec..a24b45179f 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/atomtoolsframework_files.cmake @@ -28,6 +28,7 @@ set(FILES Include/AtomToolsFramework/Util/MaterialPropertyUtil.h Include/AtomToolsFramework/Util/Util.h Include/AtomToolsFramework/Viewport/RenderViewportWidget.h + Include/AtomToolsFramework/Viewport/RenderViewportWidgetNotificationBus.h Include/AtomToolsFramework/Viewport/ModularViewportCameraController.h Include/AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h Include/AtomToolsFramework/Window/AtomToolsMainWindow.h diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp index 7d659ebb7a..bf356fa4b5 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.cpp @@ -183,6 +183,15 @@ namespace AZ::Render DrawFramerate(); } + void AtomViewportDisplayInfoSystemComponent::OnFrameEnd() + { + auto currentTime = AZStd::chrono::system_clock::now(); + if (!m_fpsHistory.empty()) + { + m_fpsHistory.back().m_endFrameTime = currentTime; + } + } + AtomBridge::ViewportInfoDisplayState AtomViewportDisplayInfoSystemComponent::GetDisplayState() const { return aznumeric_cast(r_displayInfo.operator int()); @@ -248,11 +257,11 @@ namespace AZ::Render void AtomViewportDisplayInfoSystemComponent::UpdateFramerate() { auto currentTime = AZStd::chrono::system_clock::now(); - while (!m_fpsHistory.empty() && (currentTime - m_fpsHistory.front()) > m_fpsInterval) + while (!m_fpsHistory.empty() && (currentTime - m_fpsHistory.front().m_beginFrameTime) > m_fpsInterval) { m_fpsHistory.pop_front(); } - m_fpsHistory.push_back(currentTime); + m_fpsHistory.push_back(FrameTimingInfo(currentTime)); } void AtomViewportDisplayInfoSystemComponent::DrawFramerate() @@ -261,25 +270,31 @@ namespace AZ::Render double minFPS = DBL_MAX; double maxFPS = 0; AZStd::chrono::duration deltaTime; + AZStd::chrono::milliseconds totalFrameMS(0); for (const auto& time : m_fpsHistory) { if (lastTime.has_value()) { - deltaTime = time - lastTime.value(); + deltaTime = time.m_beginFrameTime - lastTime.value(); double fps = AZStd::chrono::seconds(1) / deltaTime; minFPS = AZStd::min(minFPS, fps); maxFPS = AZStd::max(maxFPS, fps); } - lastTime = time; + lastTime = time.m_beginFrameTime; + + if (time.m_endFrameTime.has_value()) + { + totalFrameMS += time.m_endFrameTime.value() - time.m_beginFrameTime; + } } double averageFPS = 0; double averageFrameMs = 0; if (m_fpsHistory.size() > 1) { - deltaTime = m_fpsHistory.back() - m_fpsHistory.front(); - averageFPS = AZStd::chrono::seconds(m_fpsHistory.size()) / deltaTime; - averageFrameMs = 1000.0f/averageFPS; + deltaTime = m_fpsHistory.back().m_beginFrameTime - m_fpsHistory.front().m_beginFrameTime; + averageFPS = AZStd::chrono::seconds(m_fpsHistory.size() - 1) / deltaTime; + averageFrameMs = aznumeric_cast(totalFrameMS.count()) / (m_fpsHistory.size() - 1); } const double frameIntervalSeconds = m_fpsInterval.count(); @@ -288,7 +303,7 @@ namespace AZ::Render AZStd::string::format( "FPS %.1f [%.0f..%.0f], %.1fms/frame, avg over %.1fs", averageFPS, - minFPS, + minFPS == DBL_MAX ? 0.0 : minFPS, maxFPS, averageFrameMs, frameIntervalSeconds), diff --git a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h index 1d53e188d0..689cfdb43b 100644 --- a/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h +++ b/Gems/AtomLyIntegration/AtomViewportDisplayInfo/Code/Source/AtomViewportDisplayInfoSystemComponent.h @@ -45,6 +45,7 @@ namespace AZ // AZ::RPI::ViewportContextNotificationBus::Handler overrides... void OnRenderTick() override; + void OnFrameEnd() override; // AZ::AtomBridge::AtomViewportInfoDisplayRequestBus::Handler overrides... AtomBridge::ViewportInfoDisplayState GetDisplayState() const override; @@ -61,6 +62,8 @@ namespace AZ void DrawPassInfo(); void DrawFramerate(); + void UpdateScene(AZ::RPI::ScenePtr scene); + static constexpr float BaseFontSize = 0.7f; AZStd::string m_rendererDescription; @@ -68,7 +71,17 @@ namespace AZ AzFramework::FontDrawInterface* m_fontDrawInterface = nullptr; float m_lineSpacing; AZStd::chrono::duration m_fpsInterval = AZStd::chrono::seconds(1); - AZStd::deque m_fpsHistory; + struct FrameTimingInfo + { + AZStd::chrono::system_clock::time_point m_beginFrameTime; + AZStd::optional m_endFrameTime; + + explicit FrameTimingInfo(AZStd::chrono::system_clock::time_point beginFrameTime) + : m_beginFrameTime(beginFrameTime) + { + } + }; + AZStd::deque m_fpsHistory; AZStd::optional m_lastMemoryUpdate; bool m_updateRootPassQuery = true; }; From 9d2352c3b74e3cf03127b09a184c66ad9d0b1170 Mon Sep 17 00:00:00 2001 From: hultonha <82228511+hultonha@users.noreply.github.com> Date: Tue, 14 Sep 2021 13:24:01 +0100 Subject: [PATCH 10/26] Update the viewport interaction model to support single click select (#4094) * add support for single click select Signed-off-by: hultonha * remove redundant profile macro Signed-off-by: hultonha * updates following review feedback Signed-off-by: hultonha * fix behaviour for fallthrough to match previous code Signed-off-by: hultonha --- Code/Editor/EditorViewportWidget.cpp | 2 + .../ActionDispatcher.h | 15 +- .../ImmediateModeActionDispatcher.h | 1 + .../RetainedModeActionDispatcher.h | 55 --- .../Source/ImmediateModeActionDispatcher.cpp | 12 +- .../Source/RetainedModeActionDispatcher.cpp | 129 ------ .../azmanipulatortestframework_files.cmake | 2 - .../EditorTransformComponentSelection.cpp | 367 ++++++++++-------- .../EditorTransformComponentSelection.h | 6 + ...EditorTransformComponentSelectionTests.cpp | 170 +++++++- 10 files changed, 400 insertions(+), 359 deletions(-) delete mode 100644 Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/RetainedModeActionDispatcher.h delete mode 100644 Code/Framework/AzManipulatorTestFramework/Source/RetainedModeActionDispatcher.cpp diff --git a/Code/Editor/EditorViewportWidget.cpp b/Code/Editor/EditorViewportWidget.cpp index 7631ac6237..f009fe7602 100644 --- a/Code/Editor/EditorViewportWidget.cpp +++ b/Code/Editor/EditorViewportWidget.cpp @@ -1039,6 +1039,7 @@ void EditorViewportWidget::ConnectViewportInteractionRequestBus() { AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusConnect(GetViewportId()); + AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusConnect(); m_viewportUi.ConnectViewportUiBus(GetViewportId()); AzFramework::InputSystemCursorConstraintRequestBus::Handler::BusConnect(); @@ -1049,6 +1050,7 @@ void EditorViewportWidget::DisconnectViewportInteractionRequestBus() AzFramework::InputSystemCursorConstraintRequestBus::Handler::BusDisconnect(); m_viewportUi.DisconnectViewportUiBus(); + AzToolsFramework::ViewportInteraction::EditorModifierKeyRequestBus::Handler::BusDisconnect(); AzToolsFramework::ViewportInteraction::EditorEntityViewportInteractionRequestBus::Handler::BusDisconnect(); AzToolsFramework::ViewportInteraction::MainEditorViewportInteractionRequestBus::Handler::BusDisconnect(); } diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h index 1b555a4a81..6bd72f5101 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ActionDispatcher.h @@ -39,6 +39,8 @@ namespace AzManipulatorTestFramework DerivedDispatcherT* MouseLButtonDown(); //! Set the left mouse button up. DerivedDispatcherT* MouseLButtonUp(); + //! Send a double click event. + DerivedDispatcherT* MouseLButtonDoubleClick(); //! Set the keyboard modifier button down. DerivedDispatcherT* KeyboardModifierDown(const AzToolsFramework::ViewportInteraction::KeyboardModifier& keyModifier); //! Set the keyboard modifier button up. @@ -71,6 +73,7 @@ namespace AzManipulatorTestFramework virtual void CameraStateImpl(const AzFramework::CameraState& cameraState) = 0; virtual void MouseLButtonDownImpl() = 0; virtual void MouseLButtonUpImpl() = 0; + virtual void MouseLButtonDoubleClickImpl() = 0; virtual void MousePositionImpl(const AzFramework::ScreenPoint& position) = 0; virtual void KeyboardModifierDownImpl(const AzToolsFramework::ViewportInteraction::KeyboardModifier& keyModifier) = 0; virtual void KeyboardModifierUpImpl(const AzToolsFramework::ViewportInteraction::KeyboardModifier& keyModifier) = 0; @@ -167,7 +170,7 @@ namespace AzManipulatorTestFramework template DerivedDispatcherT* ActionDispatcher::MouseLButtonDown() { - Log("%s", "Mouse left button down"); + Log("Mouse left button down"); MouseLButtonDownImpl(); return static_cast(this); } @@ -175,11 +178,19 @@ namespace AzManipulatorTestFramework template DerivedDispatcherT* ActionDispatcher::MouseLButtonUp() { - Log("%s", "Mouse left button up"); + Log("Mouse left button up"); MouseLButtonUpImpl(); return static_cast(this); } + template + DerivedDispatcherT* ActionDispatcher::MouseLButtonDoubleClick() + { + Log("Mouse left button double click"); + MouseLButtonDoubleClickImpl(); + return static_cast(this); + } + template const char* ActionDispatcher::KeyboardModifierString( const AzToolsFramework::ViewportInteraction::KeyboardModifier& keyModifier) diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h index 7a4773a37c..9e11a7543c 100644 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h +++ b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h @@ -58,6 +58,7 @@ namespace AzManipulatorTestFramework void CameraStateImpl(const AzFramework::CameraState& cameraState) override; void MouseLButtonDownImpl() override; void MouseLButtonUpImpl() override; + void MouseLButtonDoubleClickImpl() override; void MousePositionImpl(const AzFramework::ScreenPoint& position) override; void KeyboardModifierDownImpl(const KeyboardModifier& keyModifier) override; void KeyboardModifierUpImpl(const KeyboardModifier& keyModifier) override; diff --git a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/RetainedModeActionDispatcher.h b/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/RetainedModeActionDispatcher.h deleted file mode 100644 index d9aceedf8a..0000000000 --- a/Code/Framework/AzManipulatorTestFramework/Include/AzManipulatorTestFramework/RetainedModeActionDispatcher.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace AzManipulatorTestFramework -{ - //! Buffers actions to be dispatched upon a call to Execute(). - class RetainedModeActionDispatcher - : public ActionDispatcher - { - public: - explicit RetainedModeActionDispatcher(ManipulatorViewportInteraction& viewportManipulatorInteraction); - //! Execute the sequence of actions and lock the dispatcher from adding further actions. - RetainedModeActionDispatcher* Execute(); - //! Reset the sequence of actions and unlock the dispatcher from adding further actions. - RetainedModeActionDispatcher* ResetSequence(); - - protected: - // ActionDispatcher ... - void EnableSnapToGridImpl() override; - void DisableSnapToGridImpl() override; - void GridSizeImpl(float size) override; - void CameraStateImpl(const AzFramework::CameraState& cameraState) override; - void MouseLButtonDownImpl() override; - void MouseLButtonUpImpl() override; - void MousePositionImpl(const AzFramework::ScreenPoint& position) override; - void KeyboardModifierDownImpl(const AzToolsFramework::ViewportInteraction::KeyboardModifier& keyModifier) override; - void KeyboardModifierUpImpl(const AzToolsFramework::ViewportInteraction::KeyboardModifier& keyModifier) override; - void ExpectManipulatorBeingInteractedImpl() override; - void ExpectManipulatorNotBeingInteractedImpl() override; - void SetEntityWorldTransformImpl(AZ::EntityId entityId, const AZ::Transform& transform) override; - void SetSelectedEntityImpl(AZ::EntityId entity) override; - void SetSelectedEntitiesImpl(const AzToolsFramework::EntityIdList& entities) override; - void EnterComponentModeImpl(const AZ::Uuid& uuid) override; - - private: - using Action = AZStd::function; - void AddActionToSequence(Action&& action); - ImmediateModeActionDispatcher m_dispatcher; - AZStd::list m_actions; - bool m_locked = false; - }; -} // namespace AzManipulatorTestFramework diff --git a/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp b/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp index 895899cf3f..23cc2a21f5 100644 --- a/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp +++ b/Code/Framework/AzManipulatorTestFramework/Source/ImmediateModeActionDispatcher.cpp @@ -83,7 +83,17 @@ namespace AzManipulatorTestFramework void ImmediateModeActionDispatcher::MouseLButtonUpImpl() { GetMouseInteractionEvent()->m_mouseEvent = AzToolsFramework::ViewportInteraction::MouseEvent::Up; - m_viewportManipulatorInteraction.GetManipulatorManager().ConsumeMouseInteractionEvent(*GetMouseInteractionEvent()); + m_viewportManipulatorInteraction.GetManipulatorManager().ConsumeMouseInteractionEvent(*m_event); + ToggleOff(GetMouseInteractionEvent()->m_mouseInteraction.m_mouseButtons.m_mouseButtons, MouseButton::Left); + // the mouse position will be the same as the previous event, thus the delta will be 0 + MouseMoveAfterButton(); + } + + void ImmediateModeActionDispatcher::MouseLButtonDoubleClickImpl() + { + GetMouseInteractionEvent()->m_mouseEvent = AzToolsFramework::ViewportInteraction::MouseEvent::DoubleClick; + ToggleOn(GetMouseInteractionEvent()->m_mouseInteraction.m_mouseButtons.m_mouseButtons, MouseButton::Left); + m_viewportManipulatorInteraction.GetManipulatorManager().ConsumeMouseInteractionEvent(*m_event); ToggleOff(GetMouseInteractionEvent()->m_mouseInteraction.m_mouseButtons.m_mouseButtons, MouseButton::Left); // the mouse position will be the same as the previous event, thus the delta will be 0 MouseMoveAfterButton(); diff --git a/Code/Framework/AzManipulatorTestFramework/Source/RetainedModeActionDispatcher.cpp b/Code/Framework/AzManipulatorTestFramework/Source/RetainedModeActionDispatcher.cpp deleted file mode 100644 index 34ae4aaf4a..0000000000 --- a/Code/Framework/AzManipulatorTestFramework/Source/RetainedModeActionDispatcher.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#include - -namespace AzManipulatorTestFramework -{ - using KeyboardModifier = AzToolsFramework::ViewportInteraction::KeyboardModifier; - - RetainedModeActionDispatcher::RetainedModeActionDispatcher( - ManipulatorViewportInteraction& viewportManipulatorInteraction) - : m_dispatcher(viewportManipulatorInteraction) - { - } - - void RetainedModeActionDispatcher::AddActionToSequence(Action&& action) - { - if (m_locked) - { - const char* error = "Couldn't add action to sequence, dispatcher is locked (you must call ResetSequence() \ - before adding actions to this dispatcher)"; - Log("%s", error); - AZ_Assert(false, "Error: %s", error); - } - - m_actions.emplace_back(action); - } - - void RetainedModeActionDispatcher::EnableSnapToGridImpl() - { - AddActionToSequence([=]() { m_dispatcher.EnableSnapToGrid(); }); - } - - void RetainedModeActionDispatcher::DisableSnapToGridImpl() - { - AddActionToSequence([=]() { m_dispatcher.DisableSnapToGrid(); }); - } - - void RetainedModeActionDispatcher::GridSizeImpl(float size) - { - AddActionToSequence([=]() { m_dispatcher.GridSize(size); }); - } - - void RetainedModeActionDispatcher::CameraStateImpl(const AzFramework::CameraState& cameraState) - { - AddActionToSequence([=]() { m_dispatcher.CameraState(cameraState); }); - } - - void RetainedModeActionDispatcher::MouseLButtonDownImpl() - { - AddActionToSequence([=]() { m_dispatcher.MouseLButtonDown(); }); - } - - void RetainedModeActionDispatcher::MouseLButtonUpImpl() - { - AddActionToSequence([=]() { m_dispatcher.MouseLButtonUp(); }); - } - - void RetainedModeActionDispatcher::MousePositionImpl(const AzFramework::ScreenPoint& position) - { - AddActionToSequence([=]() { m_dispatcher.MousePosition(position); }); - } - - void RetainedModeActionDispatcher::KeyboardModifierDownImpl(const KeyboardModifier& keyModifier) - { - AddActionToSequence([=]() { m_dispatcher.KeyboardModifierDown(keyModifier); }); - } - - void RetainedModeActionDispatcher::KeyboardModifierUpImpl(const KeyboardModifier& keyModifier) - { - AddActionToSequence([=]() { m_dispatcher.KeyboardModifierUp(keyModifier); }); - } - - void RetainedModeActionDispatcher::ExpectManipulatorBeingInteractedImpl() - { - AddActionToSequence([=]() { m_dispatcher.ExpectManipulatorBeingInteracted(); }); - } - - void RetainedModeActionDispatcher::ExpectManipulatorNotBeingInteractedImpl() - { - AddActionToSequence([=]() { m_dispatcher.ExpectManipulatorNotBeingInteracted(); }); - } - - void RetainedModeActionDispatcher::SetEntityWorldTransformImpl(AZ::EntityId entityId, const AZ::Transform& transform) - { - AddActionToSequence([=]() { m_dispatcher.SetEntityWorldTransform(entityId, transform); }); - } - - void RetainedModeActionDispatcher::SetSelectedEntityImpl(AZ::EntityId entity) - { - AddActionToSequence([=]() { m_dispatcher.SetSelectedEntity(entity); }); - } - - void RetainedModeActionDispatcher::SetSelectedEntitiesImpl(const AzToolsFramework::EntityIdList& entities) - { - AddActionToSequence([=]() { m_dispatcher.SetSelectedEntities(entities); }); - } - - void RetainedModeActionDispatcher::EnterComponentModeImpl(const AZ::Uuid& uuid) - { - AddActionToSequence([=]() { m_dispatcher.EnterComponentMode(uuid); }); - } - - RetainedModeActionDispatcher* RetainedModeActionDispatcher::ResetSequence() - { - Log("%s", "Resetting the action sequence"); - m_actions.clear(); - m_dispatcher.ResetEvent(); - m_locked = false; - return this; - } - - RetainedModeActionDispatcher* RetainedModeActionDispatcher::Execute() - { - Log("Executing %u actions", m_actions.size()); - for (auto& action : m_actions) - { - action(); - } - m_dispatcher.ResetEvent(); - m_locked = true; - return this; - } -} // namespace AzManipulatorTestFramework diff --git a/Code/Framework/AzManipulatorTestFramework/azmanipulatortestframework_files.cmake b/Code/Framework/AzManipulatorTestFramework/azmanipulatortestframework_files.cmake index 3fe9f4266c..9f480a3e2a 100644 --- a/Code/Framework/AzManipulatorTestFramework/azmanipulatortestframework_files.cmake +++ b/Code/Framework/AzManipulatorTestFramework/azmanipulatortestframework_files.cmake @@ -14,12 +14,10 @@ set(FILES Include/AzManipulatorTestFramework/DirectManipulatorViewportInteraction.h Include/AzManipulatorTestFramework/IndirectManipulatorViewportInteraction.h Include/AzManipulatorTestFramework/ImmediateModeActionDispatcher.h - Include/AzManipulatorTestFramework/RetainedModeActionDispatcher.h Include/AzManipulatorTestFramework/AzManipulatorTestFrameworkUtils.h Source/ViewportInteraction.cpp Source/DirectManipulatorViewportInteraction.cpp Source/IndirectManipulatorViewportInteraction.cpp Source/ImmediateModeActionDispatcher.cpp - Source/RetainedModeActionDispatcher.cpp Source/AzManipulatorTestFrameworkUtils.cpp ) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 3db8492d70..5a7b097e29 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -1770,6 +1770,12 @@ namespace AzToolsFramework return false; } + void EditorTransformComponentSelection::ChangeSelectedEntity(const AZ::EntityId entityId) + { + DeselectEntities(); + SelectDeselect(entityId); + } + bool EditorTransformComponentSelection::HandleMouseInteraction(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) { AZ_PROFILE_FUNCTION(AzToolsFramework); @@ -1821,202 +1827,239 @@ namespace AzToolsFramework return true; } - // double click to deselect all - if (Input::DeselectAll(mouseInteraction)) + if (ed_viewportStickySelect) { - // note: even if m_selectedEntityIds is technically empty, we - // may still have an entity selected that was clicked in the - // entity outliner - we still want to make sure the deselect all - // action clears the selection - DeselectEntities(); - return false; + // double click to deselect all + if (Input::DeselectAll(mouseInteraction)) + { + // note: even if m_selectedEntityIds is technically empty, we + // may still have an entity selected that was clicked in the + // entity outliner - we still want to make sure the deselect all + // action clears the selection + DeselectEntities(); + return false; + } + } + + // select/deselect (add/remove) entities with ctrl held + if (Input::AdditiveIndividualSelect(clickOutcome, mouseInteraction)) + { + if (SelectDeselect(entityIdUnderCursor)) + { + if (m_selectedEntityIds.empty()) + { + m_pivotOverrideFrame.Reset(); + } + + return false; + } } if (!m_selectedEntityIds.empty()) { - // select/deselect (add/remove) entities with ctrl held - if (Input::AdditiveIndividualSelect(clickOutcome, mouseInteraction)) - { - if (SelectDeselect(entityIdUnderCursor)) - { - if (m_selectedEntityIds.empty()) - { - m_pivotOverrideFrame.Reset(); - } - - return false; - } - } - // group copying/alignment to specific entity - 'ditto' position/orientation for group - if (Input::GroupDitto(mouseInteraction)) + if (Input::GroupDitto(mouseInteraction) && PerformGroupDitto(entityIdUnderCursor)) { - if (entityIdUnderCursor.IsValid()) - { - AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); - - switch (m_mode) - { - case Mode::Rotation: - CopyOrientationToSelectedEntitiesGroup(QuaternionFromTransformNoScaling(worldFromLocal)); - break; - case Mode::Scale: - CopyScaleToSelectedEntitiesIndividualWorld(worldFromLocal.GetUniformScale()); - break; - case Mode::Translation: - CopyTranslationToSelectedEntitiesGroup(worldFromLocal.GetTranslation()); - break; - default: - // do nothing - break; - } - - return false; - } + return false; } // individual copying/alignment to specific entity - 'ditto' position/orientation for individual - if (Input::IndividualDitto(mouseInteraction)) + if (Input::IndividualDitto(mouseInteraction) && PerformIndividualDitto(entityIdUnderCursor)) { - if (entityIdUnderCursor.IsValid()) - { - AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); - - switch (m_mode) - { - case Mode::Rotation: - CopyOrientationToSelectedEntitiesIndividual(QuaternionFromTransformNoScaling(worldFromLocal)); - break; - case Mode::Scale: - CopyScaleToSelectedEntitiesIndividualWorld(worldFromLocal.GetUniformScale()); - break; - case Mode::Translation: - CopyTranslationToSelectedEntitiesIndividual(worldFromLocal.GetTranslation()); - break; - default: - // do nothing - break; - } - - return false; - } + return false; } // try snapping to the terrain (if in Translation mode) and entity wasn't picked if (Input::SnapTerrain(mouseInteraction)) { - for (AZ::EntityId entityId : m_selectedEntityIds) - { - ScopedUndoBatch::MarkEntityDirty(entityId); - } - - if (m_mode == Mode::Translation) - { - const AZ::Vector3 finalSurfacePosition = PickTerrainPosition(mouseInteraction.m_mouseInteraction); - - // handle modifier alternatives - if (Input::IndividualDitto(mouseInteraction)) - { - CopyTranslationToSelectedEntitiesIndividual(finalSurfacePosition); - } - else if (Input::GroupDitto(mouseInteraction)) - { - CopyTranslationToSelectedEntitiesGroup(finalSurfacePosition); - } - } - else if (m_mode == Mode::Rotation) - { - // handle modifier alternatives - if (Input::IndividualDitto(mouseInteraction)) - { - CopyOrientationToSelectedEntitiesIndividual(AZ::Quaternion::CreateIdentity()); - } - else if (Input::GroupDitto(mouseInteraction)) - { - CopyOrientationToSelectedEntitiesGroup(AZ::Quaternion::CreateIdentity()); - } - } - + PerformSnapToTerrain(mouseInteraction); return false; } // set manipulator pivot override translation or orientation (update manipulators) if (Input::ManipulatorDitto(mouseInteraction)) { - if (m_entityIdManipulators.m_manipulators) - { - ScopedUndoBatch undoBatch(s_dittoManipulatorUndoRedoDesc); - - auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); - - if (entityIdUnderCursor.IsValid()) - { - AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); - AZ::TransformBus::EventResult(worldFromLocal, entityIdUnderCursor, &AZ::TransformBus::Events::GetWorldTM); - - // set orientation/translation to match picked entity - switch (m_mode) - { - case Mode::Rotation: - OverrideManipulatorOrientation(QuaternionFromTransformNoScaling(worldFromLocal)); - break; - case Mode::Translation: - OverrideManipulatorTranslation(worldFromLocal.GetTranslation()); - break; - case Mode::Scale: - // do nothing - break; - default: - break; - } - - // only update pivot override when in translation or rotation mode - switch (m_mode) - { - case Mode::Rotation: - m_pivotOverrideFrame.m_pickTypes |= OptionalFrame::PickType::Orientation; - [[fallthrough]]; - case Mode::Translation: - m_pivotOverrideFrame.m_pickTypes |= OptionalFrame::PickType::Translation; - m_pivotOverrideFrame.m_pickedEntityIdOverride = entityIdUnderCursor; - break; - case Mode::Scale: - // do nothing - break; - default: - break; - } - } - else - { - // match the same behavior as if we pressed Ctrl+R to reset the manipulator - DelegateClearManipulatorOverride(); - } - - manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State( - BuildPivotOverride(m_pivotOverrideFrame.HasTranslationOverride(), m_pivotOverrideFrame.HasOrientationOverride()), - m_entityIdManipulators.m_manipulators->GetLocalTransform(), entityIdUnderCursor)); - - manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); - manipulatorCommand.release(); - } + PerformManipulatorDitto(entityIdUnderCursor); + return false; } - return false; + if (ed_viewportStickySelect) + { + return false; + } } // standard toggle selection if (Input::IndividualSelect(clickOutcome)) { - SelectDeselect(entityIdUnderCursor); + if (!ed_viewportStickySelect) + { + ChangeSelectedEntity(entityIdUnderCursor); + } + else + { + SelectDeselect(entityIdUnderCursor); + } } return false; } + bool EditorTransformComponentSelection::PerformGroupDitto(const AZ::EntityId entityId) + { + if (entityId.IsValid()) + { + AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + + switch (m_mode) + { + case Mode::Rotation: + CopyOrientationToSelectedEntitiesGroup(QuaternionFromTransformNoScaling(worldFromLocal)); + break; + case Mode::Scale: + CopyScaleToSelectedEntitiesIndividualWorld(worldFromLocal.GetUniformScale()); + break; + case Mode::Translation: + CopyTranslationToSelectedEntitiesGroup(worldFromLocal.GetTranslation()); + break; + default: + // do nothing + break; + } + + return true; + } + + return false; + } + + bool EditorTransformComponentSelection::PerformIndividualDitto(const AZ::EntityId entityId) + { + if (entityId.IsValid()) + { + AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + + switch (m_mode) + { + case Mode::Rotation: + CopyOrientationToSelectedEntitiesIndividual(QuaternionFromTransformNoScaling(worldFromLocal)); + break; + case Mode::Scale: + CopyScaleToSelectedEntitiesIndividualWorld(worldFromLocal.GetUniformScale()); + break; + case Mode::Translation: + CopyTranslationToSelectedEntitiesIndividual(worldFromLocal.GetTranslation()); + break; + default: + // do nothing + break; + } + + return true; + } + + return false; + } + + void EditorTransformComponentSelection::PerformSnapToTerrain(const ViewportInteraction::MouseInteractionEvent& mouseInteraction) + { + for (AZ::EntityId entityId : m_selectedEntityIds) + { + ScopedUndoBatch::MarkEntityDirty(entityId); + } + + if (m_mode == Mode::Translation) + { + const AZ::Vector3 finalSurfacePosition = PickTerrainPosition(mouseInteraction.m_mouseInteraction); + + // handle modifier alternatives + if (Input::IndividualDitto(mouseInteraction)) + { + CopyTranslationToSelectedEntitiesIndividual(finalSurfacePosition); + } + else if (Input::GroupDitto(mouseInteraction)) + { + CopyTranslationToSelectedEntitiesGroup(finalSurfacePosition); + } + } + else if (m_mode == Mode::Rotation) + { + // handle modifier alternatives + if (Input::IndividualDitto(mouseInteraction)) + { + CopyOrientationToSelectedEntitiesIndividual(AZ::Quaternion::CreateIdentity()); + } + else if (Input::GroupDitto(mouseInteraction)) + { + CopyOrientationToSelectedEntitiesGroup(AZ::Quaternion::CreateIdentity()); + } + } + } + + void EditorTransformComponentSelection::PerformManipulatorDitto(const AZ::EntityId entityId) + { + if (m_entityIdManipulators.m_manipulators) + { + ScopedUndoBatch undoBatch(s_dittoManipulatorUndoRedoDesc); + + auto manipulatorCommand = + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + + if (entityId.IsValid()) + { + AZ::Transform worldFromLocal = AZ::Transform::CreateIdentity(); + AZ::TransformBus::EventResult(worldFromLocal, entityId, &AZ::TransformBus::Events::GetWorldTM); + + // set orientation/translation to match picked entity + switch (m_mode) + { + case Mode::Rotation: + OverrideManipulatorOrientation(QuaternionFromTransformNoScaling(worldFromLocal)); + break; + case Mode::Translation: + OverrideManipulatorTranslation(worldFromLocal.GetTranslation()); + break; + case Mode::Scale: + // do nothing + break; + default: + break; + } + + // only update pivot override when in translation or rotation mode + switch (m_mode) + { + case Mode::Rotation: + m_pivotOverrideFrame.m_pickTypes |= OptionalFrame::PickType::Orientation; + [[fallthrough]]; + case Mode::Translation: + m_pivotOverrideFrame.m_pickTypes |= OptionalFrame::PickType::Translation; + m_pivotOverrideFrame.m_pickedEntityIdOverride = entityId; + break; + case Mode::Scale: + // do nothing + break; + default: + break; + } + } + else + { + // match the same behavior as if we pressed Ctrl+R to reset the manipulator + DelegateClearManipulatorOverride(); + } + + manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State( + BuildPivotOverride(m_pivotOverrideFrame.HasTranslationOverride(), m_pivotOverrideFrame.HasOrientationOverride()), + m_entityIdManipulators.m_manipulators->GetLocalTransform(), entityId)); + + manipulatorCommand->SetParent(undoBatch.GetUndoBatch()); + manipulatorCommand.release(); + } + } + template static void AddAction( AZStd::vector>& actions, diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h index 35d3587d0b..478c0b775e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.h @@ -207,6 +207,7 @@ namespace AzToolsFramework void SetSelectedEntities(const EntityIdList& entityIds); void DeselectEntities(); bool SelectDeselect(AZ::EntityId entityId); + void ChangeSelectedEntity(AZ::EntityId entityId); void RefreshSelectedEntityIds(); void RefreshSelectedEntityIds(const EntityIdList& selectedEntityIds); @@ -298,6 +299,11 @@ namespace AzToolsFramework void SetEntityLocalRotation(AZ::EntityId entityId, const AZ::Vector3& localRotation); void SetEntityLocalRotation(AZ::EntityId entityId, const AZ::Quaternion& localRotation); + bool PerformGroupDitto(AZ::EntityId entityId); + bool PerformIndividualDitto(AZ::EntityId entityId); + void PerformManipulatorDitto(AZ::EntityId entityId); + void PerformSnapToTerrain(const ViewportInteraction::MouseInteractionEvent& mouseInteraction); + //! Responsible for keeping the space cluster in sync with the current reference frame. void UpdateSpaceCluster(ReferenceFrame referenceFrame); diff --git a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp index 8a958af567..241ee3f576 100644 --- a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp @@ -614,7 +614,7 @@ namespace UnitTest using EditorTransformComponentSelectionViewportPickingManipulatorTestFixture = IndirectCallManipulatorViewportInteractionFixtureMixin; - TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, SingleClickWithNoSelectionWillSelectEntity) + TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, StickySingleClickWithNoSelectionWillSelectEntity) { AzToolsFramework::ed_viewportStickySelect = true; @@ -637,19 +637,44 @@ namespace UnitTest EXPECT_THAT(selectedEntitiesAfter.front(), Eq(m_entityId1)); } - TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, SingleClickOffEntityWithSelectionWillNotDeselectEntity) + TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, UnstickySingleClickWithNoSelectionWillSelectEntity) + { + AzToolsFramework::ed_viewportStickySelect = false; + + PositionEntities(); + PositionCamera(m_cameraState); + + using ::testing::Eq; + auto selectedEntitiesBefore = SelectedEntities(); + EXPECT_TRUE(selectedEntitiesBefore.empty()); + + // calculate the position in screen space of the initial entity position + const auto entity1ScreenPosition = AzFramework::WorldToScreen(m_entity1WorldTranslation, m_cameraState); + + // click the entity in the viewport + m_actionDispatcher->CameraState(m_cameraState)->MousePosition(entity1ScreenPosition)->MouseLButtonDown()->MouseLButtonUp(); + + // entity is selected + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter.size(), Eq(1)); + EXPECT_THAT(selectedEntitiesAfter.front(), Eq(m_entityId1)); + } + + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, + StickySingleClickOffEntityWithSelectionWillNotDeselectEntity) { AzToolsFramework::ed_viewportStickySelect = true; PositionEntities(); PositionCamera(m_cameraState); - // position in space above the entity + // position in space above the entities const auto clickOffPositionWorld = AZ::Vector3(5.0f, 15.0f, 12.0f); AzToolsFramework::SelectEntity(m_entityId1); - // calculate the position in screen space of the initial position of the entity + // calculate the screen space position of the click const auto clickOffPositionScreen = AzFramework::WorldToScreen(clickOffPositionWorld, m_cameraState); // click the empty space in the viewport @@ -662,9 +687,32 @@ namespace UnitTest EXPECT_THAT(selectedEntitiesAfter.front(), Eq(m_entityId1)); } + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, UnstickySingleClickOffEntityWithSelectionWillDeselectEntity) + { + AzToolsFramework::ed_viewportStickySelect = false; + + PositionEntities(); + PositionCamera(m_cameraState); + + AzToolsFramework::SelectEntity(m_entityId1); + + // position in space above the entities + const auto clickOffPositionWorld = AZ::Vector3(5.0f, 15.0f, 12.0f); + // calculate the screen space position of the click + const auto clickOffPositionScreen = AzFramework::WorldToScreen(clickOffPositionWorld, m_cameraState); + + // click the empty space in the viewport + m_actionDispatcher->CameraState(m_cameraState)->MousePosition(clickOffPositionScreen)->MouseLButtonDown()->MouseLButtonUp(); + + // entity was deselected + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_TRUE(selectedEntitiesAfter.empty()); + } + TEST_F( EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, - SingleClickOnNewEntityWithSelectionWillNotChangeSelectedEntity) + StickySingleClickOnNewEntityWithSelectionWillNotChangeSelectedEntity) { AzToolsFramework::ed_viewportStickySelect = true; @@ -688,7 +736,31 @@ namespace UnitTest TEST_F( EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, - CtrlSingleClickOnNewEntityWithSelectionWillAppendSelectedEntityToSelection) + UnstickySingleClickOnNewEntityWithSelectionWillChangeSelectedEntity) + { + AzToolsFramework::ed_viewportStickySelect = false; + + PositionEntities(); + PositionCamera(m_cameraState); + + AzToolsFramework::SelectEntity(m_entityId1); + + // calculate the position in screen space of the second entity + const auto entity2ScreenPosition = AzFramework::WorldToScreen(m_entity2WorldTranslation, m_cameraState); + + // click the entity in the viewport + m_actionDispatcher->CameraState(m_cameraState)->MousePosition(entity2ScreenPosition)->MouseLButtonDown()->MouseLButtonUp(); + + // entity selection was changed + using ::testing::Eq; + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter.size(), Eq(1)); + EXPECT_THAT(selectedEntitiesAfter.front(), Eq(m_entityId2)); + } + + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, + StickyCtrlSingleClickOnNewEntityWithSelectionWillAppendSelectedEntityToSelection) { AzToolsFramework::ed_viewportStickySelect = true; @@ -715,7 +787,34 @@ namespace UnitTest TEST_F( EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, - CtrlSingleClickOnEntityInSelectionWillRemoveEntityFromSelection) + UnstickyCtrlSingleClickOnNewEntityWithSelectionWillAppendSelectedEntityToSelection) + { + AzToolsFramework::ed_viewportStickySelect = false; + + PositionEntities(); + PositionCamera(m_cameraState); + + AzToolsFramework::SelectEntity(m_entityId1); + + // calculate the position in screen space of the second entity + const auto entity2ScreenPosition = AzFramework::WorldToScreen(m_entity2WorldTranslation, m_cameraState); + + // click the entity in the viewport + m_actionDispatcher->CameraState(m_cameraState) + ->MousePosition(entity2ScreenPosition) + ->KeyboardModifierDown(AzToolsFramework::ViewportInteraction::KeyboardModifier::Control) + ->MouseLButtonDown() + ->MouseLButtonUp(); + + // entity selection was changed (one entity selected to two) + using ::testing::UnorderedElementsAre; + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter, UnorderedElementsAre(m_entityId1, m_entityId2)); + } + + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, + StickyCtrlSingleClickOnEntityInSelectionWillRemoveEntityFromSelection) { AzToolsFramework::ed_viewportStickySelect = true; @@ -740,7 +839,36 @@ namespace UnitTest EXPECT_THAT(selectedEntitiesAfter, UnorderedElementsAre(m_entityId1)); } - TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, BoxSelectWithNoInitialSelectionAddsEntitiesToSelection) + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, + UnstickyCtrlSingleClickOnEntityInSelectionWillRemoveEntityFromSelection) + { + AzToolsFramework::ed_viewportStickySelect = false; + + PositionEntities(); + PositionCamera(m_cameraState); + + AzToolsFramework::SelectEntities({ m_entityId1, m_entityId2 }); + + // calculate the position in screen space of the second entity + const auto entity2ScreenPosition = AzFramework::WorldToScreen(m_entity2WorldTranslation, m_cameraState); + + // click the entity in the viewport + m_actionDispatcher->CameraState(m_cameraState) + ->MousePosition(entity2ScreenPosition) + ->KeyboardModifierDown(AzToolsFramework::ViewportInteraction::KeyboardModifier::Control) + ->MouseLButtonDown() + ->MouseLButtonUp(); + + // entity selection was changed (entity2 was deselected) + using ::testing::UnorderedElementsAre; + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter, UnorderedElementsAre(m_entityId1)); + } + + TEST_F( + EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, + BoxSelectWithNoInitialSelectionAddsEntitiesToSelection) { AzToolsFramework::ed_viewportStickySelect = true; @@ -835,6 +963,32 @@ namespace UnitTest EXPECT_TRUE(selectedEntitiesAfter.empty()); } + TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, StickyDoubleClickWithSelectionWillDeselectEntities) + { + AzToolsFramework::ed_viewportStickySelect = true; + + PositionEntities(); + PositionCamera(m_cameraState); + + AzToolsFramework::SelectEntities({ m_entityId1, m_entityId2, m_entityId3 }); + + using ::testing::UnorderedElementsAre; + auto selectedEntitiesBefore = SelectedEntities(); + EXPECT_THAT(selectedEntitiesBefore, UnorderedElementsAre(m_entityId1, m_entityId2, m_entityId3)); + + // position in space above the entities + const auto clickOffPositionWorld = AZ::Vector3(5.0f, 15.0f, 12.0f); + // calculate the screen space position of the click + const auto clickOffPositionScreen = AzFramework::WorldToScreen(clickOffPositionWorld, m_cameraState); + + // double click to deselect entities + m_actionDispatcher->CameraState(m_cameraState)->MousePosition(clickOffPositionScreen)->MouseLButtonDoubleClick(); + + // no entities are selected + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_TRUE(selectedEntitiesAfter.empty()); + } + using EditorTransformComponentSelectionManipulatorTestFixture = IndirectCallManipulatorViewportInteractionFixtureMixin; From a91ea7d549eaefe55b1ffa08ecc0167d866fa576 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 14 Sep 2021 13:04:52 -0500 Subject: [PATCH 11/26] Removed unused EngineJson.cmake file (#4107) Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- cmake/EngineJson.cmake | 45 ----------------------------------------- cmake/cmake_files.cmake | 2 +- 2 files changed, 1 insertion(+), 46 deletions(-) delete mode 100644 cmake/EngineJson.cmake diff --git a/cmake/EngineJson.cmake b/cmake/EngineJson.cmake deleted file mode 100644 index f175ff5a8b..0000000000 --- a/cmake/EngineJson.cmake +++ /dev/null @@ -1,45 +0,0 @@ -# -# Copyright (c) Contributors to the Open 3D Engine Project. -# For complete copyright and license terms please see the LICENSE at the root of this distribution. -# -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# -# This file is copied during engine registration. Edits to this file will be lost next -# time a registration happens. - -include_guard() - -set(LY_EXTERNAL_SUBDIRS "" CACHE STRING "Additional list of subdirectory to recurse into via the cmake `add_subdirectory()` command. \ - The subdirectories are included after the restricted platform folders have been visited by a call to `add_subdirectory(restricted/\${restricted_platform})`") - -#! read_engine_external_subdirs -# Read the external subdirectories from the engine.json file -# External subdirectories are any folders with CMakeLists.txt in them -# This could be regular subdirectories, Gems(contains an additional gem.json), -# Restricted folders(contains an additional restricted.json), etc... -# \arg:output_external_subdirs name of output variable to store external subdirectories into -function(read_engine_external_subdirs output_external_subdirs) - ly_file_read(${LY_ROOT_FOLDER}/engine.json engine_json_data) - string(JSON external_subdirs_count ERROR_VARIABLE engine_json_error - LENGTH ${engine_json_data} "external_subdirectories") - if(engine_json_error) - message(FATAL_ERROR "Error querying number of elements in JSON array \"external_subdirectories\": ${engine_json_error}") - endif() - - if(external_subdirs_count GREATER 0) - math(EXPR external_subdir_range "${external_subdirs_count}-1") - # Convert the paths the relative paths to absolute paths using the engine root - # as the base directory - foreach(external_subdir_index RANGE ${external_subdir_range}) - string(JSON external_subdir ERROR_VARIABLE engine_json_error - GET ${engine_json_data} "external_subdirectories" "${external_subdir_index}") - if(engine_json_error) - message(FATAL_ERROR "Error reading field at index ${external_subdir_index} in \"external_subdirectories\" JSON array: ${engine_json_error}") - endif() - file(REAL_PATH ${external_subdir} real_external_subdir BASE_DIRECTORY ${CMAKE_SOURCE_DIR}) - list(APPEND external_subdirs ${real_external_subdir}) - endforeach() - endif() - set(${output_external_subdirs} ${external_subdirs} PARENT_SCOPE) -endfunction() diff --git a/cmake/cmake_files.cmake b/cmake/cmake_files.cmake index aa275b634a..caeab9d12e 100644 --- a/cmake/cmake_files.cmake +++ b/cmake/cmake_files.cmake @@ -15,7 +15,6 @@ set(FILES Configurations.cmake Dependencies.cmake Deployment.cmake - EngineJson.cmake FileUtil.cmake Findo3de.cmake Gems.cmake @@ -28,6 +27,7 @@ set(FILES LYPython.cmake LYWrappers.cmake Monolithic.cmake + O3DEJson.cmake OutputDirectory.cmake Packaging.cmake PAL.cmake From 73b04d7e34f1049f5d535e6bb7e7045c9ea41f9d Mon Sep 17 00:00:00 2001 From: Gene Walters <32776221+AMZN-Gene@users.noreply.github.com> Date: Tue, 14 Sep 2021 12:01:32 -0700 Subject: [PATCH 12/26] Network Input Exposed to Script (#3990) * NetworkInput now has new attribute called ExposeToScript. NetworkInput with this attribute set to True will be exposed to behavior context. Also added a CreateFromValues for the NetworkInput where scripters can create an instance of the MyComponentNetworkInput class which will eventually be passed around CreateInput and ProcessInput events. Signed-off-by: Gene Walters * Adding Create Input event handler. SC can now receive the event to create input, and send it over the network Signed-off-by: Gene Walters * Auto-component controller will now generate CreateInput/ProcessInput methods if they have input exposed to script, not ready for use yet, just stubbed in Signed-off-by: Gene Walters * Reducing code replication by putting common network input variables into AutoComponent_Common.jinja Signed-off-by: Gene Walters * Fix minor comment typo in the CreateInput method Signed-off-by: Gene Walters * Small fix. Changing ebus call from MyComponentNameCreateInput to just CreateInput. It's part of the MyComponentRequestBus so adding the component name before CreateInput is noisy Signed-off-by: Gene Walters * Cleaning with jinja a bit using macro calls to iterate over scriptable netinputs Signed-off-by: Gene Walters * ProcessInput will now be triggered in script Signed-off-by: Gene Walters * ProcessInput event is sent to script. Script can now create and process input. Tested locally with a simple script. Signed-off-by: Gene Walters * Created a seperate CreateInputFromScript and ProcessInputFromScript. Developers no longer need to remember to call the BaseClass::CreateInput and ProcessInput since CreateInputFromScript will automatically be called beforehand. Signed-off-by: Gene Walters --- .../Components/MultiplayerController.h | 12 +++ .../Source/AutoGen/AutoComponent_Common.jinja | 60 +++++++++++++- .../Source/AutoGen/AutoComponent_Header.jinja | 56 ++++++++++++- .../Source/AutoGen/AutoComponent_Source.jinja | 82 +++++++++++++++++-- .../Source/Components/NetBindComponent.cpp | 2 + 5 files changed, 204 insertions(+), 8 deletions(-) diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerController.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerController.h index 2467b0566d..545706db4b 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerController.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/MultiplayerController.h @@ -89,11 +89,23 @@ namespace Multiplayer //! @param deltaTime amount of time to integrate the provided inputs over virtual void ProcessInput(NetworkInput& networkInput, float deltaTime) = 0; + //! Similar to ProcessInput, do not call directly. + //! This only needs to be overridden in components which allow NetworkInput to be processed by script. + //! @param networkInput input structure to process + //! @param deltaTime amount of time to integrate the provided inputs over + virtual void ProcessInputFromScript([[maybe_unused]] NetworkInput& networkInput, [[maybe_unused]] float deltaTime){} + //! Only valid on a client, should never be invoked on the server. //! @param networkInput input structure to process //! @param deltaTime amount of time to integrate the provided inputs over virtual void CreateInput(NetworkInput& networkInput, float deltaTime) = 0; + //! Similar to CreateInput, should never be invoked on the server. + //! This only needs to be overridden in components which allow NetworkInput creation to be handled by scripts. + //! @param networkInput input structure to process + //! @param deltaTime amount of time to integrate the provided inputs over + virtual void CreateInputFromScript([[maybe_unused]]NetworkInput& networkInput, [[maybe_unused]] float deltaTime) {} + template const ComponentType* FindComponent() const; diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja index 811039feda..5bf0a4823f 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Common.jinja @@ -252,7 +252,44 @@ void Signal{{ PropertyName }}({{ ', '.join(paramDefines) }}); {# #} -{%- macro EmitDerivedClassesComment(dataFileNames, Component, ComponentName, ComponentNameBase, ComponentDerived, ControllerName, ControllerNameBase, ControllerDerived, NetworkInputCount) -%} +{% macro GetNetworkInputCount(Component) -%} +{{ Component.findall('NetworkInput') | len }} +{%- endmacro -%} +{# + +#} +{% macro ParseNetworkInputsExposedToScript(Component) -%} +{% set NetworkInputsExposedToScript = namespace(value=0) %} +{% for netInput in Component.findall('NetworkInput') %} +{% if ('ExposeToScript' in netInput.attrib) and (netInput.attrib['ExposeToScript'] |booleanTrue) %} +{{ caller(netInput) -}} +{% endif %} +{% endfor %} +{%- endmacro -%} +{# + +#} +{% macro GetNetworkInputsExposedToScriptCount(Component) -%} +{% set NetworkInputsExposedToScript = namespace(value=0) %} +{% call (netInput) ParseNetworkInputsExposedToScript(Component) %} +{% set NetworkInputsExposedToScript.value = NetworkInputsExposedToScript.value + 1 %} +{% endcall %} +{{ NetworkInputsExposedToScript.value }} +{%- endmacro -%} +{# + +#} +{% macro GetCommaSeparatedParamListOfScriptableNetworkInputs(Component) -%} +{% set parameters = [] %} +{% call (netInput) ParseNetworkInputsExposedToScript(Component) %} +{% set parameters = parameters.append(netInput.attrib['Type'] + ' ' + LowerFirst(netInput.attrib['Name'])) %} +{% endcall %} +{{ parameters | join(', ') }} +{%- endmacro -%} +{# + +#} +{%- macro EmitDerivedClassesComment(dataFileNames, Component, ComponentName, ComponentNameBase, ComponentDerived, ControllerName, ControllerNameBase, ControllerDerived) -%} {% if ComponentDerived or ControllerDerived %} /* /// You may use the classes below as a basis for your new derived classes. Derived classes must be marked in {{ (dataFileNames[0] | basename) }} @@ -293,7 +330,16 @@ namespace {{ Component.attrib['Namespace'] }} void OnActivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; void OnDeactivate(Multiplayer::EntityIsMigrating entityIsMigrating) override; +{% set NetworkInputCount = GetNetworkInputCount(Component) | int %} {% if NetworkInputCount > 0 %} + + //! Common input creation logic for the NetworkInput. + //! Fill out the input struct and the MultiplayerInputDriver will send the input data over the network + //! to ensure it's processed. + //! @param input input structure which to store input data for sending to the authority + //! @param deltaTime amount of time to integrate the provided inputs over + void CreateInput(Multiplayer::NetworkInput& input, float deltaTime) override; + //! Common input processing logic for the NetworkInput. //! @param input input structure to process //! @param deltaTime amount of time to integrate the provided inputs over @@ -366,6 +412,18 @@ namespace {{ Component.attrib['Namespace'] }} { } {% if NetworkInputCount > 0 %} +{% set net_input_parameters_name = [] %} +{% call (netInput) ParseNetworkInputsExposedToScript(Component) %} +{% set net_input_parameters_name = net_input_parameters_name.append(LowerFirst(netInput.attrib['Name'])) %} +{% endcall %} + + void {{ ControllerName }}::CreateInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) + { +{% if (GetNetworkInputsExposedToScriptCount(Component) | int) > 0 %} + // Remember the following NetworkInputs have been exposed to script: {{ net_input_parameters_name|join(', ') }}. + // If a script is handling these inputs they will have already be filled out by now. +{% endif %} + } void {{ ControllerName }}::ProcessInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) { diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja index 8cde9613b7..0f62da11f3 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Header.jinja @@ -230,7 +230,8 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } {% if ControllerDerived %} {% set ControllerBaseName = ControllerName + "Base" %} {% endif %} -{% set NetworkInputCount = Component.findall('NetworkInput') | len %} +{% set NetworkInputCount = AutoComponentMacros.GetNetworkInputCount(Component) | int %} +{% set NetworkInputsExposedToScriptCount = AutoComponentMacros.GetNetworkInputsExposedToScriptCount(Component) | int %} {% set NetworkPropertyCount = Component.findall('NetworkProperty') | len %} {% set RpcCount = Component.findall('RemoteProcedure') | len %} #include "AutoComponentTypes.h" @@ -250,6 +251,10 @@ AZStd::fixed_vector<{{ Property.attrib['Type'] }}, {{ Property.attrib['Count'] } {% call(Include) AutoComponentMacros.ParseIncludes(Component) %} #include <{{ Include.attrib['File'] }}> {% endcall %} +{% if NetworkInputsExposedToScriptCount > 0 %} +#include +{% endif %} + {% for Service in Component.iter('ComponentRelation') %} {% if Service.attrib['Constraint'] != 'Incompatible' %} @@ -263,7 +268,7 @@ namespace {{ Service.attrib['Namespace'] }} {% endif %} {% endfor %} -{{ AutoComponentMacros.EmitDerivedClassesComment(dataFileNames, Component, ComponentName, ComponentBaseName, ComponentDerived, ControllerName, ControllerBaseName, ControllerDerived, NetworkInputCount) }} +{{ AutoComponentMacros.EmitDerivedClassesComment(dataFileNames, Component, ComponentName, ComponentBaseName, ComponentDerived, ControllerName, ControllerBaseName, ControllerDerived) }} namespace {{ Component.attrib['Namespace'] }} { //! Forward declarations @@ -337,6 +342,13 @@ namespace {{ Component.attrib['Namespace'] }} : public Multiplayer::IMultiplayerComponentInput { public: +{% if NetworkInputsExposedToScriptCount > 0 %} + AZ_TYPE_INFO({{ ComponentName }}NetworkInput, "{{ (ComponentName ~ "NetworkInput") | createHashGuid }}") + {{ ComponentName }}NetworkInput() = default; + {{ ComponentName }}NetworkInput({{ AutoComponentMacros.GetCommaSeparatedParamListOfScriptableNetworkInputs(Component) }}); + static void Reflect(AZ::ReflectContext* context); + +{% endif%} Multiplayer::NetComponentId GetNetComponentId() const override; bool Serialize(AzNetworking::ISerializer& serializer) override; Multiplayer::IMultiplayerComponentInput& operator =(const Multiplayer::IMultiplayerComponentInput& rhs) override; @@ -348,7 +360,41 @@ namespace {{ Component.attrib['Namespace'] }} static Multiplayer::NetComponentId s_netComponentId; friend void RegisterMultiplayerComponents(); }; +{% if NetworkInputsExposedToScriptCount > 0 %} + class {{ ComponentName }}Requests + : public AZ::ComponentBus + { + public: + AZ_RTTI({{ ComponentName }}Requests, "{{ (ComponentName ~ "Requests") | createHashGuid }}") + + virtual {{ ComponentName }}NetworkInput CreateInput(float deltaTime) = 0; + virtual void ProcessInput({{ ComponentName }}NetworkInput* networkInput, float deltaTime) = 0; + }; + + using {{ ComponentName }}RequestBus = AZ::EBus<{{ ComponentName }}Requests>; + + class {{ ComponentName }}BusHandler final + : public {{ ComponentName }}RequestBus::Handler + , public AZ::BehaviorEBusHandler + { + public: + AZ_EBUS_BEHAVIOR_BINDER({{ ComponentName }}BusHandler, "{{ (ComponentName ~ "BusHandler") | createHashGuid }}", AZ::SystemAllocator, CreateInput, ProcessInput) + + {{ ComponentName }}NetworkInput CreateInput(float deltaTime) override + { + {{ ComponentName }}NetworkInput result; + CallResult(result, FN_CreateInput, deltaTime); + return result; + } + + void ProcessInput({{ ComponentName }}NetworkInput* networkInput, float deltaTime) override + { + Call(FN_ProcessInput, networkInput, deltaTime); + } + }; + +{% endif %} {% endif %} class {{ ControllerBaseName }}{% if not ControllerDerived %} final{% endif %}{{ "" }} : public Multiplayer::MultiplayerController @@ -373,8 +419,14 @@ namespace {{ Component.attrib['Namespace'] }} //! MultiplayerController interface //! @{ Multiplayer::MultiplayerController::InputPriorityOrder GetInputOrder() const override { return Multiplayer::MultiplayerController::InputPriorityOrder::Default; } + +{% if NetworkInputsExposedToScriptCount > 0 %} + void CreateInputFromScript([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) final; + void ProcessInputFromScript([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) final; +{% endif %} void CreateInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} void ProcessInput([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) override {} + //! @} {{ DeclareNetworkPropertyAccessors(Component, 'Authority', 'Server', false)|indent(8) -}} diff --git a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja index d8e729afd6..e57e8dad2f 100644 --- a/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja +++ b/Gems/Multiplayer/Code/Source/AutoGen/AutoComponent_Source.jinja @@ -1152,7 +1152,8 @@ m_{{ LowerFirst(Property.attrib['Name']) }} = m_{{ LowerFirst(Property.attrib['N {% else %} {% set ControllerBaseName = ControllerName %} {% endif %} -{% set NetworkInputCount = Component.findall('NetworkInput') | len %} +{% set NetworkInputCount = AutoComponentMacros.GetNetworkInputCount(Component) | int %} +{% set NetworkInputsExposedToScriptCount = AutoComponentMacros.GetNetworkInputsExposedToScriptCount(Component) | int %} {% set NetworkPropertyCount = Component.findall('NetworkProperty') | len %} {% set RpcCount = Component.findall('RemoteProcedure') | len %} #include "{{ includeFile }}" @@ -1299,6 +1300,56 @@ namespace {{ Component.attrib['Namespace'] }} } {% if NetworkInputCount > 0 %} +{% set ScriptableNetworkInputParamNames = [] %} +{% call(netInput) AutoComponentMacros.ParseNetworkInputsExposedToScript(Component) %} +{% set ScriptableNetworkInputParamNames = ScriptableNetworkInputParamNames.append(LowerFirst(netInput.attrib['Name'])) %} +{% endcall %} +{% if NetworkInputsExposedToScriptCount > 0 %} + {{ ComponentName }}NetworkInput Construct{{ ComponentName }}NetworkInput({{ AutoComponentMacros.GetCommaSeparatedParamListOfScriptableNetworkInputs(Component) }}) + { + return {{ ComponentName }}NetworkInput({{ ScriptableNetworkInputParamNames|join(', ') }}); + } + + {{ ComponentName }}NetworkInput::{{ ComponentName }}NetworkInput({{ AutoComponentMacros.GetCommaSeparatedParamListOfScriptableNetworkInputs(Component) }}) + : {% for param_name in ScriptableNetworkInputParamNames %}m_{{ LowerFirst(param_name) }}({{ LowerFirst(param_name) }}){% if not loop.last %}, {% endif %}{% endfor -%}{} + + void {{ ComponentName }}NetworkInput::Reflect(AZ::ReflectContext* context) + { + AZ::SerializeContext* serializeContext = azrtti_cast(context); + if (serializeContext) + { + serializeContext->Class<{{ ComponentName }}NetworkInput>() + ->Version(1) + ; + } + + AZ::BehaviorContext* behaviorContext = azrtti_cast(context); + if (behaviorContext) + { + behaviorContext->Class<{{ ComponentName }}NetworkInput>("{{ ComponentName }}NetworkInput") + ->Attribute(AZ::Script::Attributes::Module, "{{ LowerFirst(Component.attrib['Namespace']) }}") + ->Attribute(AZ::Script::Attributes::Category, "{{ UpperFirst(Component.attrib['Namespace']) }}") +{% set ScriptableNetInputNames = [] %} +{% call (netInput) AutoComponentMacros.ParseNetworkInputsExposedToScript(Component) %} +{% set ScriptableNetInputNames = ScriptableNetInputNames.append(netInput.attrib['Name']) %} +{% endcall %} + ->Method("CreateFromValues", &Construct{{ ComponentName }}NetworkInput, { { {% for param_name in ScriptableNetInputNames %}{"{{ LowerFirst(param_name) }}"}{% if not loop.last %}, {% endif %}{% endfor -%} } }) + +{% for param_name in ScriptableNetInputNames %} + ->Property("{{ param_name }}", BehaviorValueProperty(&{{ ComponentName }}NetworkInput::m_{{ LowerFirst(param_name) }})) +{% endfor %} + ; + + behaviorContext->EBus<{{ ComponentName }}RequestBus>("{{ ComponentName }}BusHandler") + ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) + ->Attribute(AZ::Script::Attributes::Module, "{{ LowerFirst(Component.attrib['Namespace']) }}") + ->Attribute(AZ::Script::Attributes::Category, "{{ UpperFirst(Component.attrib['Namespace']) }}") + ->Handler<{{ ComponentName }}BusHandler>() + ; + } + } +{% endif %} + Multiplayer::NetComponentId {{ ComponentName }}NetworkInput::GetNetComponentId() const { return {{ ComponentName }}NetworkInput::s_netComponentId; @@ -1347,6 +1398,26 @@ namespace {{ Component.attrib['Namespace'] }} {% endif %} } +{% if NetworkInputsExposedToScriptCount > 0 %} + void {{ ControllerBaseName }}::CreateInputFromScript([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) + { + {{ ComponentName }}NetworkInput result; + {{ ComponentName }}RequestBus::EventResult(result, GetEntity()->GetId(), &{{ ComponentName }}RequestBus::Events::CreateInput, deltaTime); + + // Inputs for your own component always exist + {{ ComponentName }}NetworkInput* {{ LowerFirst(ComponentName) }}Input = input.FindComponentInput<{{ ComponentName }}NetworkInput>(); +{% call(netInput) AutoComponentMacros.ParseNetworkInputsExposedToScript(Component) %} + {{ LowerFirst(ComponentName) }}Input->m_{{ LowerFirst(netInput.attrib['Name']) }} = result.m_{{ LowerFirst(netInput.attrib['Name']) }}; +{% endcall %} + } + + void {{ ControllerBaseName }}::ProcessInputFromScript([[maybe_unused]] Multiplayer::NetworkInput& input, [[maybe_unused]] float deltaTime) + { + {{ ComponentName }}NetworkInput* {{ LowerFirst(ComponentName) }}Input = input.FindComponentInput<{{ ComponentName }}NetworkInput>(); + {{ ComponentName }}RequestBus::Event(GetEntity()->GetId(), &{{ ComponentName }}RequestBus::Events::ProcessInput, {{ LowerFirst(ComponentName) }}Input, deltaTime); + } +{% endif %} + const {{ ComponentName }}& {{ ControllerBaseName }}::GetParent() const { return static_cast(GetOwner()); @@ -1399,6 +1470,9 @@ namespace {{ Component.attrib['Namespace'] }} } ReflectToEditContext(context); ReflectToBehaviorContext(context); +{% if NetworkInputsExposedToScriptCount > 0 %} + {{ ComponentName }}NetworkInput::Reflect(context); +{% endif %} } void {{ ComponentBaseName }}::ReflectToEditContext(AZ::ReflectContext* context) @@ -1448,8 +1522,8 @@ namespace {{ Component.attrib['Namespace'] }} {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Server', ComponentName) | indent(16) -}} {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Client', ComponentName) | indent(16) -}} {{ DefineNetworkPropertyBehaviorReflection(Component, 'Authority', 'Autonomous', ComponentName) | indent(16) -}} - {{ DefineNetworkPropertyBehaviorReflection(Component, 'Autonomous', 'Authority', ComponentName) | indent(16) -}} - + {{ DefineNetworkPropertyBehaviorReflection(Component, 'Autonomous', 'Authority', ComponentName) | indent(16) }} + // Reflect RPCs {{ ReflectRpcInvocations(Component, ComponentName, 'Server', 'Authority')|indent(4) -}} {{ ReflectRpcInvocations(Component, ComponentName, 'Autonomous', 'Authority')|indent(4) -}} @@ -1459,7 +1533,6 @@ namespace {{ Component.attrib['Namespace'] }} {{ ReflectRpcEvents(Component, ComponentName, 'Autonomous', 'Authority')|indent(4) -}} {{ ReflectRpcEvents(Component, ComponentName, 'Authority', 'Autonomous')|indent(4) -}} {{ ReflectRpcEvents(Component, ComponentName, 'Authority', 'Client')|indent(4) -}} - {{- DefineArchetypePropertyBehaviorReflection(Component, ComponentName) | indent(16) }} ; } @@ -1508,7 +1581,6 @@ namespace {{ Component.attrib['Namespace'] }} } {{ ComponentBaseName }}::{{ ComponentBaseName }}() = default; - {{ ComponentBaseName }}::~{{ ComponentBaseName }}() = default; void {{ ComponentBaseName }}::Init() diff --git a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp index d8e8a765ce..43577525c0 100644 --- a/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/NetBindComponent.cpp @@ -278,6 +278,7 @@ namespace Multiplayer AZ_Assert(IsNetEntityRoleAutonomous(), "Incorrect network role for input creation"); for (MultiplayerComponent* multiplayerComponent : m_multiplayerInputComponentVector) { + multiplayerComponent->GetController()->CreateInputFromScript(networkInput, deltaTime); multiplayerComponent->GetController()->CreateInput(networkInput, deltaTime); } } @@ -289,6 +290,7 @@ namespace Multiplayer AZ_Assert((NetworkRoleHasController(m_netEntityRole)), "Incorrect network role for input processing"); for (MultiplayerComponent* multiplayerComponent : m_multiplayerInputComponentVector) { + multiplayerComponent->GetController()->ProcessInputFromScript(networkInput, deltaTime); multiplayerComponent->GetController()->ProcessInput(networkInput, deltaTime); } m_isProcessingInput = false; From ae735ad3381d0d51c3b11647c5828d8c5504ec7f Mon Sep 17 00:00:00 2001 From: Jonny Gallowy Date: Tue, 14 Sep 2021 14:26:50 -0500 Subject: [PATCH 13/26] new postfx layer categories and ordering values Signed-off-by: Jonny Gallowy --- .../PostProcess/default.postfxlayercategories | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Assets/PostProcess/default.postfxlayercategories b/Gems/AtomLyIntegration/CommonFeatures/Assets/PostProcess/default.postfxlayercategories index 33adccfd33..d6bffb0e6a 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Assets/PostProcess/default.postfxlayercategories +++ b/Gems/AtomLyIntegration/CommonFeatures/Assets/PostProcess/default.postfxlayercategories @@ -1,17 +1,30 @@ + - - + + - - + + + + + + + + + + - + + + + + From c0426ba465dfd002a7cfded7b15ad953a1ec56d0 Mon Sep 17 00:00:00 2001 From: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> Date: Tue, 14 Sep 2021 12:35:56 -0700 Subject: [PATCH 14/26] PerScreenDpi | QLabels incorrectly handle scale for icons (#4070) * Fixes to icon generation. Generating a pixmap out of a size won't take the screen scaling factor into account, resulting in blurry results. Note that this is not a catchall solution, every case needs to be addressed manually. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> * HighDpi fixes for startup splashscreen and About dialog Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> * Add helper function to generate appropriate pixmaps for a screen based on its dpi settings. Signed-off-by: Danilo Aimini <82231674+AMZN-daimini@users.noreply.github.com> --- Code/Editor/AboutDialog.cpp | 10 ++++-- Code/Editor/StartupLogoDialog.cpp | 17 +++++----- .../WelcomeScreen/WelcomeScreenDialog.cpp | 6 +++- .../Utilities/PixmapScaleUtilities.cpp | 31 +++++++++++++++++++ .../Utilities/PixmapScaleUtilities.h | 19 ++++++++++++ .../AzQtComponents/azqtcomponents_files.cmake | 2 ++ .../EditorEntityUiHandlerBase.cpp | 4 +-- .../EditorEntityUiHandlerBase.h | 2 +- .../UI/Layer/LayerUiHandler.cpp | 4 +-- .../UI/Layer/LayerUiHandler.h | 2 +- .../UI/Outliner/EntityOutlinerListModel.cpp | 14 ++++----- .../UI/Prefab/LevelRootUiHandler.cpp | 4 +-- .../UI/Prefab/LevelRootUiHandler.h | 2 +- .../UI/Prefab/PrefabUiHandler.cpp | 6 ++-- .../UI/Prefab/PrefabUiHandler.h | 2 +- 15 files changed, 94 insertions(+), 31 deletions(-) create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.cpp create mode 100644 Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.h diff --git a/Code/Editor/AboutDialog.cpp b/Code/Editor/AboutDialog.cpp index f8abe67376..2c76526731 100644 --- a/Code/Editor/AboutDialog.cpp +++ b/Code/Editor/AboutDialog.cpp @@ -20,6 +20,7 @@ // AzCore #include // for aznumeric_cast +#include AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include @@ -46,8 +47,13 @@ CAboutDialog::CAboutDialog(QString versionText, QString richTextCopyrightNotice, CAboutDialog > QLabel#link { text-decoration: underline; color: #94D2FF; }"); // Prepare background image - QImage backgroundImage(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")); - m_backgroundImage = QPixmap::fromImage(backgroundImage.scaled(m_enforcedWidth, m_enforcedHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + m_backgroundImage = AzQtComponents::ScalePixmapForScreenDpi( + QPixmap(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")), + screen(), + QSize(m_enforcedWidth, m_enforcedHeight), + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation + ); // Draw the Open 3D Engine logo from svg m_ui->m_logo->load(QStringLiteral(":/StartupLogoDialog/o3de_logo.svg")); diff --git a/Code/Editor/StartupLogoDialog.cpp b/Code/Editor/StartupLogoDialog.cpp index d9625aff1a..ab251b1564 100644 --- a/Code/Editor/StartupLogoDialog.cpp +++ b/Code/Editor/StartupLogoDialog.cpp @@ -9,11 +9,11 @@ // Description : implementation file - #include "EditorDefs.h" - #include "StartupLogoDialog.h" +#include + // Qt #include #include @@ -22,8 +22,6 @@ AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING #include AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - ///////////////////////////////////////////////////////////////////////////// // CStartupLogoDialog dialog @@ -36,13 +34,16 @@ CStartupLogoDialog::CStartupLogoDialog(QString versionText, QString richTextCopy m_ui->setupUi(this); s_pLogoWindow = this; - - m_backgroundImage = QPixmap(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")); setFixedSize(QSize(600, 300)); // Prepare background image - QImage backgroundImage(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")); - m_backgroundImage = QPixmap::fromImage(backgroundImage.scaled(m_enforcedWidth, m_enforcedHeight, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); + m_backgroundImage = AzQtComponents::ScalePixmapForScreenDpi( + QPixmap(QStringLiteral(":/StartupLogoDialog/splashscreen_background_developer_preview.jpg")), + screen(), + QSize(m_enforcedWidth, m_enforcedHeight), + Qt::IgnoreAspectRatio, + Qt::SmoothTransformation + ); // Draw the Open 3D Engine logo from svg m_ui->m_logo->load(QStringLiteral(":/StartupLogoDialog/o3de_logo.svg")); diff --git a/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp b/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp index 0f73023acf..17f576b5ee 100644 --- a/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp +++ b/Code/Editor/WelcomeScreen/WelcomeScreenDialog.cpp @@ -34,6 +34,7 @@ // AzQtComponents #include #include +#include // Editor #include "Settings.h" @@ -79,8 +80,11 @@ WelcomeScreenDialog::WelcomeScreenDialog(QWidget* pParent) { projectPreviewPath = ":/WelcomeScreenDialog/DefaultProjectImage.png"; } + ui->activeProjectIcon->setPixmap( - QPixmap(projectPreviewPath).scaled( + AzQtComponents::ScalePixmapForScreenDpi( + QPixmap(projectPreviewPath), + screen(), ui->activeProjectIcon->size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.cpp b/Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.cpp new file mode 100644 index 0000000000..fa32b708d7 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include + +namespace AzQtComponents +{ + QPixmap ScalePixmapForScreenDpi( + QPixmap pixmap, QScreen* screen, QSize size, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode) + { + qreal screenDpiFactor = QHighDpiScaling::factor(screen); + pixmap.setDevicePixelRatio(screenDpiFactor); + + QPixmap scaledPixmap; + + size.setWidth(aznumeric_cast(aznumeric_cast(size.width()) * screenDpiFactor)); + size.setHeight(aznumeric_cast(aznumeric_cast(size.height()) * screenDpiFactor)); + + scaledPixmap = pixmap.scaled(size, aspectRatioMode, transformationMode); + + return scaledPixmap; + } +} diff --git a/Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.h b/Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.h new file mode 100644 index 0000000000..4b083855d5 --- /dev/null +++ b/Code/Framework/AzQtComponents/AzQtComponents/Utilities/PixmapScaleUtilities.h @@ -0,0 +1,19 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include + +#include +#include + +namespace AzQtComponents +{ + AZ_QT_COMPONENTS_API QPixmap ScalePixmapForScreenDpi(QPixmap pixmap, QScreen* screen, QSize size, Qt::AspectRatioMode aspectRatioMode, Qt::TransformationMode transformationMode); +}; // namespace AzQtComponents diff --git a/Code/Framework/AzQtComponents/AzQtComponents/azqtcomponents_files.cmake b/Code/Framework/AzQtComponents/AzQtComponents/azqtcomponents_files.cmake index c214b81405..8219ab04b2 100644 --- a/Code/Framework/AzQtComponents/AzQtComponents/azqtcomponents_files.cmake +++ b/Code/Framework/AzQtComponents/AzQtComponents/azqtcomponents_files.cmake @@ -276,6 +276,8 @@ set(FILES Utilities/HandleDpiAwareness.cpp Utilities/HandleDpiAwareness.h Utilities/MouseHider.h + Utilities/PixmapScaleUtilities.cpp + Utilities/PixmapScaleUtilities.h Utilities/QtPluginPaths.cpp Utilities/QtPluginPaths.h Utilities/QtWindowUtilities.cpp diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp index f0462532e6..a0da20ebf0 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.cpp @@ -47,9 +47,9 @@ namespace AzToolsFramework return QString(); } - QPixmap EditorEntityUiHandlerBase::GenerateItemIcon(AZ::EntityId /*entityId*/) const + QIcon EditorEntityUiHandlerBase::GenerateItemIcon(AZ::EntityId /*entityId*/) const { - return QPixmap(); + return QIcon(); } bool EditorEntityUiHandlerBase::CanToggleLockVisibility(AZ::EntityId /*entityId*/) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h index e7008b7abf..c37b099272 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/EditorEntityUi/EditorEntityUiHandlerBase.h @@ -40,7 +40,7 @@ namespace AzToolsFramework //! Returns the item tooltip text to display in the Outliner. virtual QString GenerateItemTooltip(AZ::EntityId entityId) const; //! Returns the item icon pixmap to display in the Outliner. - virtual QPixmap GenerateItemIcon(AZ::EntityId entityId) const; + virtual QIcon GenerateItemIcon(AZ::EntityId entityId) const; //! Returns whether the element's lock and visibility state should be accessible in the Outliner virtual bool CanToggleLockVisibility(AZ::EntityId entityId) const; //! Returns whether the element's name should be editable diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.cpp index b0eee96abc..8a001bc04f 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.cpp @@ -66,9 +66,9 @@ namespace AzToolsFramework return result; } - QPixmap LayerUiHandler::GenerateItemIcon(AZ::EntityId /*entityId*/) const + QIcon LayerUiHandler::GenerateItemIcon(AZ::EntityId /*entityId*/) const { - return QPixmap(m_layerIconPath); + return QIcon(m_layerIconPath); } void LayerUiHandler::PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.h index 56b62832ce..b1af9d694e 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Layer/LayerUiHandler.h @@ -24,7 +24,7 @@ namespace AzToolsFramework // EditorEntityUiHandler... QString GenerateItemInfoString(AZ::EntityId entityId) const override; - QPixmap GenerateItemIcon(AZ::EntityId entityId) const override; + QIcon GenerateItemIcon(AZ::EntityId entityId) const override; void PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; void PaintDescendantBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index, const QModelIndex& descendantIndex) const override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp index b9180f8ef6..d9f3ff8bb8 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Outliner/EntityOutlinerListModel.cpp @@ -280,17 +280,17 @@ namespace AzToolsFramework QVariant EntityOutlinerListModel::GetEntityIcon(const AZ::EntityId& id) const { auto entityUiHandler = m_editorEntityFrameworkInterface->GetHandler(id); - QPixmap pixmap; + QIcon icon; // Retrieve the icon from the handler if (entityUiHandler != nullptr) { - pixmap = entityUiHandler->GenerateItemIcon(id); + icon = entityUiHandler->GenerateItemIcon(id); } - if (!pixmap.isNull()) + if (!icon.isNull()) { - return QIcon(pixmap); + return icon; } // If no icon was returned by the handler, use the default one. @@ -299,7 +299,7 @@ namespace AzToolsFramework if (isEditorOnly) { - return QIcon(QPixmap(QString(":/Icons/Entity_Editor_Only.svg"))); + return QIcon(QString(":/Icons/Entity_Editor_Only.svg")); } AZ::Entity* entity = nullptr; @@ -308,10 +308,10 @@ namespace AzToolsFramework if (!isInitiallyActive) { - return QIcon(QPixmap(QString(":/Icons/Entity_Not_Active.svg"))); + return QIcon(QString(":/Icons/Entity_Not_Active.svg")); } - return QIcon(QPixmap(QString(":/Icons/Entity.svg"))); + return QIcon(QString(":/Icons/Entity.svg")); } QVariant EntityOutlinerListModel::GetEntityTooltip(const AZ::EntityId& id) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp index 73a28a3edc..c75f6aa86d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.cpp @@ -41,9 +41,9 @@ namespace AzToolsFramework } } - QPixmap LevelRootUiHandler::GenerateItemIcon(AZ::EntityId /*entityId*/) const + QIcon LevelRootUiHandler::GenerateItemIcon(AZ::EntityId /*entityId*/) const { - return QPixmap(m_levelRootIconPath); + return QIcon(m_levelRootIconPath); } QString LevelRootUiHandler::GenerateItemInfoString(AZ::EntityId entityId) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h index 29bb5a7d49..6eeccfe88d 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/LevelRootUiHandler.h @@ -29,7 +29,7 @@ namespace AzToolsFramework ~LevelRootUiHandler() override = default; // EditorEntityUiHandler... - QPixmap GenerateItemIcon(AZ::EntityId entityId) const override; + QIcon GenerateItemIcon(AZ::EntityId entityId) const override; QString GenerateItemInfoString(AZ::EntityId entityId) const override; bool CanToggleLockVisibility(AZ::EntityId entityId) const override; bool CanRename(AZ::EntityId entityId) const override; diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp index 1a9632b0e1..fda56b79f1 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.cpp @@ -81,14 +81,14 @@ namespace AzToolsFramework return tooltip; } - QPixmap PrefabUiHandler::GenerateItemIcon(AZ::EntityId entityId) const + QIcon PrefabUiHandler::GenerateItemIcon(AZ::EntityId entityId) const { if (m_prefabEditInterface->IsOwningPrefabBeingEdited(entityId)) { - return QPixmap(m_prefabEditIconPath); + return QIcon(m_prefabEditIconPath); } - return QPixmap(m_prefabIconPath); + return QIcon(m_prefabIconPath); } void PrefabUiHandler::PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h index 0d73fba049..d900fae427 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/Prefab/PrefabUiHandler.h @@ -31,7 +31,7 @@ namespace AzToolsFramework // EditorEntityUiHandler... QString GenerateItemInfoString(AZ::EntityId entityId) const override; QString GenerateItemTooltip(AZ::EntityId entityId) const override; - QPixmap GenerateItemIcon(AZ::EntityId entityId) const override; + QIcon GenerateItemIcon(AZ::EntityId entityId) const override; void PaintItemBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const override; void PaintDescendantBackground(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index, const QModelIndex& descendantIndex) const override; From 2382b5cbd3bcf53f83807b0160c897b5c8a6fb9a Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Tue, 14 Sep 2021 12:42:16 -0700 Subject: [PATCH 15/26] Linux fix launch project manager from editor (#4105) Signed-off-by: Steve Pham --- .../Process/ProcessWatcher_Linux.cpp | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Process/ProcessWatcher_Linux.cpp b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Process/ProcessWatcher_Linux.cpp index 2d29fac73d..d2cd681012 100644 --- a/Code/Framework/AzFramework/Platform/Linux/AzFramework/Process/ProcessWatcher_Linux.cpp +++ b/Code/Framework/AzFramework/Platform/Linux/AzFramework/Process/ProcessWatcher_Linux.cpp @@ -263,21 +263,29 @@ namespace AzFramework } commandAndArgs[commandTokens.size()] = nullptr; + AZStd::vector> environmentVariablesManaged; + AZStd::vector environmentVariablesVector; char** environmentVariables = nullptr; - int numEnvironmentVars = 0; if (processLaunchInfo.m_environmentVariables) { - numEnvironmentVars = processLaunchInfo.m_environmentVariables->size(); - // Adding one more as exec expects the array to have a nullptr as the last element - environmentVariables = new char*[numEnvironmentVars + 1]; - for (int i = 0; i < numEnvironmentVars; i++) + for (const auto& envVarString : *processLaunchInfo.m_environmentVariables) { - const AZStd::string& envVarString = processLaunchInfo.m_environmentVariables->at(i); - environmentVariables[i] = new char[envVarString.size() + 1]; - environmentVariables[i][0] = '\0'; - azstrcat(environmentVariables[i], envVarString.size(), envVarString.c_str()); + auto& environmentVariable = environmentVariablesManaged.emplace_back(AZStd::make_unique(envVarString.size() + 1)); + environmentVariable[0] = '\0'; + azstrcat(environmentVariable.get(), envVarString.size() + 1, envVarString.c_str()); + environmentVariablesVector.emplace_back(environmentVariable.get()); } - environmentVariables[numEnvironmentVars] = nullptr; + // Adding one more as exec expects the array to have a nullptr as the last element + environmentVariablesVector.emplace_back(nullptr); + environmentVariables = environmentVariablesVector.data(); + } + else + { + // If no environment variables were specified, then use the current process's environment variables + // and pass it along for the execute . + extern char **environ; // Defined in unistd.h + environmentVariables = ::environ; + AZ_Assert(environmentVariables, "Environment variables for current process not available\n"); } pid_t child_pid = fork(); @@ -290,15 +298,6 @@ namespace AzFramework // Close these handles as they are only to be used by the child process processData.m_startupInfo.CloseAllHandles(); - if (processLaunchInfo.m_environmentVariables) - { - for (int i = 0; i < numEnvironmentVars; i++) - { - delete [] environmentVariables[i]; - } - delete [] environmentVariables; - } - for (int i = 0; i < commandTokens.size(); i++) { delete [] commandAndArgs[i]; From 4e8d4c0c512b33ebb8697a72ebe30e55f32f1ef2 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 14 Sep 2021 16:15:46 -0500 Subject: [PATCH 16/26] Added a max_size function to all AZStd container style allocator functions (#4106) * Added a max_size function to all AZStd container style allocator functions The max_size functions returns the maximum value that a single contiguous allocation value returns Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * Updated the BestFitExternalMapSchema and MallocSchema GetMaxContiguousAllocationSize function Those functions now return a Max allocation size of AZ_CORE_MAX_ALLOCATOR size to indicate the maximum size for a single allocation Changed the IAllocatorAllocator::GetMaxContiguousAllocationSize function from a pure virtual function to regular virtual function Removed the left over String.cpp test to validate that the issue with the allocator::max_size() function was occuring Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- .../AzCore/AzCore/EBus/Environment.h | 2 +- .../AzCore/Memory/AllocatorOverrideShim.cpp | 5 ++ .../AzCore/Memory/AllocatorOverrideShim.h | 1 + .../Memory/BestFitExternalMapAllocator.cpp | 5 ++ .../Memory/BestFitExternalMapAllocator.h | 1 + .../Memory/BestFitExternalMapSchema.cpp | 6 ++ .../AzCore/Memory/BestFitExternalMapSchema.h | 1 + .../AzCore/AzCore/Memory/HeapSchema.cpp | 5 ++ .../AzCore/AzCore/Memory/HeapSchema.h | 1 + .../AzCore/AzCore/Memory/HphaSchema.cpp | 11 ++++ .../AzCore/AzCore/Memory/HphaSchema.h | 1 + .../AzCore/AzCore/Memory/IAllocator.h | 2 + .../AzCore/AzCore/Memory/MallocSchema.cpp | 5 ++ .../AzCore/AzCore/Memory/MallocSchema.h | 1 + Code/Framework/AzCore/AzCore/Memory/Memory.h | 11 +++- .../AzCore/AzCore/Memory/OSAllocator.h | 1 + .../Memory/OverrunDetectionAllocator.cpp | 11 ++++ .../AzCore/Memory/OverrunDetectionAllocator.h | 1 + .../AzCore/AzCore/Memory/PoolSchema.cpp | 10 +++ .../AzCore/AzCore/Memory/PoolSchema.h | 2 + .../AzCore/Memory/SimpleSchemaAllocator.h | 5 ++ .../AzCore/AzCore/Memory/SystemAllocator.h | 1 + .../AzCore/AzCore/Module/Environment.cpp | 2 +- .../AzCore/AzCore/Script/ScriptContext.cpp | 4 +- .../AzCore/AzCore/UnitTest/TestTypes.h | 5 +- .../Framework/AzCore/AzCore/std/allocator.cpp | 10 +-- Code/Framework/AzCore/AzCore/std/allocator.h | 9 +-- .../AzCore/AzCore/std/allocator_ref.h | 2 +- .../AzCore/AzCore/std/allocator_stack.h | 2 +- .../AzCore/AzCore/std/allocator_static.h | 4 +- .../AzCore/AzCore/std/containers/deque.h | 7 +-- .../AzCore/std/containers/forward_list.h | 2 +- .../AzCore/AzCore/std/containers/list.h | 8 +-- .../AzCore/AzCore/std/containers/rbtree.h | 2 +- .../AzCore/std/containers/ring_buffer.h | 10 ++- .../AzCore/AzCore/std/containers/vector.h | 3 +- .../parallel/allocator_concurrent_static.h | 4 +- .../AzCore/AzCore/std/string/string.h | 4 +- .../AzCore/Tests/AZStd/Allocators.cpp | 63 ++++++++++--------- .../Tests/AZStd/ConcurrentAllocators.cpp | 14 ++--- Code/Framework/AzCore/Tests/Memory.cpp | 2 + .../Code/MCore/Source/StaticAllocator.cpp | 2 +- .../Code/MCore/Source/StaticAllocator.h | 2 +- 43 files changed, 166 insertions(+), 84 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/EBus/Environment.h b/Code/Framework/AzCore/AzCore/EBus/Environment.h index e5cec765be..93a0f714f9 100644 --- a/Code/Framework/AzCore/AzCore/EBus/Environment.h +++ b/Code/Framework/AzCore/AzCore/EBus/Environment.h @@ -96,7 +96,7 @@ namespace AZ const char* get_name() const { return m_name; } void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } + constexpr size_type max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } size_type get_allocated_size() const { return 0; } bool is_lock_free() { return false; } diff --git a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp index 69fbe2a519..154d59edd3 100644 --- a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.cpp @@ -216,6 +216,11 @@ namespace AZ return m_source->GetMaxAllocationSize(); } + auto AllocatorOverrideShim::GetMaxContiguousAllocationSize() const -> size_type + { + return m_source->GetMaxContiguousAllocationSize(); + } + IAllocatorAllocate* AllocatorOverrideShim::GetSubAllocator() { return m_source->GetSubAllocator(); diff --git a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h index ae3859a938..3b45b9953e 100644 --- a/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h +++ b/Code/Framework/AzCore/AzCore/Memory/AllocatorOverrideShim.h @@ -52,6 +52,7 @@ namespace AZ size_type NumAllocatedBytes() const override; size_type Capacity() const override; size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; IAllocatorAllocate* GetSubAllocator() override; private: diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp index cf26c8f723..ca414df4b5 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.cpp @@ -188,6 +188,11 @@ BestFitExternalMapAllocator::GetMaxAllocationSize() const return m_schema->GetMaxAllocationSize(); } +auto BestFitExternalMapAllocator::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_schema->GetMaxContiguousAllocationSize(); +} + //========================================================================= // GetSubAllocator // [1/28/2011] diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h index 474619ad9f..17425625b7 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapAllocator.h @@ -63,6 +63,7 @@ namespace AZ size_type NumAllocatedBytes() const override; size_type Capacity() const override; size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; IAllocatorAllocate* GetSubAllocator() override; ////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp index d94d1dfe35..715ecd221e 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.cpp @@ -136,6 +136,12 @@ BestFitExternalMapSchema::GetMaxAllocationSize() const return 0; } +auto BestFitExternalMapSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + // Return the maximum size of any single allocation + return AZ_CORE_MAX_ALLOCATOR_SIZE; +} + //========================================================================= // GarbageCollect // [1/28/2011] diff --git a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h index 221407421f..eaab614593 100644 --- a/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/BestFitExternalMapSchema.h @@ -57,6 +57,7 @@ namespace AZ AZ_FORCE_INLINE size_type NumAllocatedBytes() const { return m_used; } AZ_FORCE_INLINE size_type Capacity() const { return m_desc.m_memoryBlockByteSize; } size_type GetMaxAllocationSize() const; + size_type GetMaxContiguousAllocationSize() const; AZ_FORCE_INLINE IAllocatorAllocate* GetSubAllocator() const { return m_desc.m_mapAllocator; } /** diff --git a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp index 50e6a47630..aceafa1b28 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.cpp @@ -244,6 +244,11 @@ namespace AZ return maxChunk; } + auto HeapSchema::GetMaxContiguousAllocationSize() const -> size_type + { + return MAX_REQUEST; + } + AZ_FORCE_INLINE HeapSchema::size_type HeapSchema::ChunckSize(pointer_type ptr) { diff --git a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h index af3e2d9986..f6c6f98315 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/HeapSchema.h @@ -57,6 +57,7 @@ namespace AZ virtual size_type NumAllocatedBytes() const { return m_used; } virtual size_type Capacity() const { return m_capacity; } virtual size_type GetMaxAllocationSize() const; + size_type GetMaxContiguousAllocationSize() const override; virtual IAllocatorAllocate* GetSubAllocator() { return m_subAllocator; } virtual void GarbageCollect() {} diff --git a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp index f5df0dfe96..6af8f201c2 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.cpp @@ -1069,6 +1069,7 @@ namespace AZ { /// returns allocation size for the pointer if it belongs to the allocator. result is undefined if the pointer doesn't belong to the allocator. size_t AllocationSize(void* ptr); size_t GetMaxAllocationSize() const; + size_t GetMaxContiguousAllocationSize() const; size_t GetUnAllocatedMemory(bool isPrint) const; void* SystemAlloc(size_t size, size_t align); @@ -2301,6 +2302,11 @@ namespace AZ { return maxSize; } + size_t HpAllocator::GetMaxContiguousAllocationSize() const + { + return AZ_CORE_MAX_ALLOCATOR_SIZE; + } + //========================================================================= // GetUnAllocatedMemory // [9/30/2013] @@ -2677,6 +2683,11 @@ namespace AZ { return m_allocator->GetMaxAllocationSize(); } + auto HphaSchema::GetMaxContiguousAllocationSize() const -> size_type + { + return m_allocator->GetMaxContiguousAllocationSize(); + } + //========================================================================= // GetUnAllocatedMemory // [9/30/2013] diff --git a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h index fc10bcd768..0f84ca1e68 100644 --- a/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/HphaSchema.h @@ -66,6 +66,7 @@ namespace AZ virtual size_type NumAllocatedBytes() const; virtual size_type Capacity() const; virtual size_type GetMaxAllocationSize() const; + size_type GetMaxContiguousAllocationSize() const override; virtual size_type GetUnAllocatedMemory(bool isPrint = false) const; virtual IAllocatorAllocate* GetSubAllocator() { return m_desc.m_subAllocator; } diff --git a/Code/Framework/AzCore/AzCore/Memory/IAllocator.h b/Code/Framework/AzCore/AzCore/Memory/IAllocator.h index 02f08fe77f..1aa4cf70f5 100644 --- a/Code/Framework/AzCore/AzCore/Memory/IAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/IAllocator.h @@ -62,6 +62,8 @@ namespace AZ virtual size_type Capacity() const = 0; /// Returns max allocation size if possible. If not returned value is 0 virtual size_type GetMaxAllocationSize() const { return 0; } + /// Returns the maximum contiguous allocation size of a single allocation + virtual size_type GetMaxContiguousAllocationSize() const { return 0; } /** * Returns memory allocated by the allocator and available to the user for allocations. * IMPORTANT: this is not the overhead memory this is just the memory that is allocated, but not used. Example: the pool allocators diff --git a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp index 581b6f2d57..76a71e0f08 100644 --- a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.cpp @@ -144,6 +144,11 @@ AZ::MallocSchema::size_type AZ::MallocSchema::GetMaxAllocationSize() const return 0xFFFFFFFFull; } +AZ::MallocSchema::size_type AZ::MallocSchema::GetMaxContiguousAllocationSize() const +{ + return AZ_CORE_MAX_ALLOCATOR_SIZE; +} + AZ::IAllocatorAllocate* AZ::MallocSchema::GetSubAllocator() { return nullptr; diff --git a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h index 3a363cb069..cbf928e189 100644 --- a/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/MallocSchema.h @@ -50,6 +50,7 @@ namespace AZ virtual size_type NumAllocatedBytes() const override; virtual size_type Capacity() const override; virtual size_type GetMaxAllocationSize() const override; + virtual size_type GetMaxContiguousAllocationSize() const override; virtual IAllocatorAllocate* GetSubAllocator() override; virtual void GarbageCollect() override; diff --git a/Code/Framework/AzCore/AzCore/Memory/Memory.h b/Code/Framework/AzCore/AzCore/Memory/Memory.h index af175c7a64..d09003f3f0 100644 --- a/Code/Framework/AzCore/AzCore/Memory/Memory.h +++ b/Code/Framework/AzCore/AzCore/Memory/Memory.h @@ -839,6 +839,11 @@ namespace AZ return AZ::AllocatorInstance::Get().GetMaxAllocationSize(); } + size_type GetMaxContiguousAllocationSize() const override + { + return AZ::AllocatorInstance::Get().GetMaxContiguousAllocationSize(); + } + size_type GetUnAllocatedMemory(bool isPrint = false) const override { return AZ::AllocatorInstance::Get().GetUnAllocatedMemory(isPrint); @@ -896,7 +901,7 @@ namespace AZ } AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return AllocatorInstance::Get().GetMaxAllocationSize(); } + size_type max_size() const { return AllocatorInstance::Get().GetMaxContiguousAllocationSize(); } size_type get_allocated_size() const { return AllocatorInstance::Get().NumAllocatedBytes(); } AZ_FORCE_INLINE bool is_lock_free() { return AllocatorInstance::Get().is_lock_free(); } @@ -954,7 +959,7 @@ namespace AZ } AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return m_allocator->GetMaxAllocationSize(); } + size_type max_size() const { return m_allocator->GetMaxContiguousAllocationSize(); } size_type get_allocated_size() const { return m_allocator->NumAllocatedBytes(); } AZ_FORCE_INLINE bool operator==(const AZStdIAllocator& rhs) const { return m_allocator == rhs.m_allocator; } @@ -1006,7 +1011,7 @@ namespace AZ } constexpr const char* get_name() const { return m_name; } void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return m_allocatorFunctor().GetMaxAllocationSize(); } + size_type max_size() const { return m_allocatorFunctor().GetMaxContiguousAllocationSize(); } size_type get_allocated_size() const { return m_allocatorFunctor().NumAllocatedBytes(); } constexpr bool operator==(const AZStdFunctorAllocator& rhs) const { return m_allocatorFunctor == rhs.m_allocatorFunctor; } diff --git a/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h b/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h index 6154e97f38..b327cf6349 100644 --- a/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/OSAllocator.h @@ -61,6 +61,7 @@ namespace AZ size_type NumAllocatedBytes() const override { return m_custom ? m_custom->NumAllocatedBytes() : m_numAllocatedBytes; } size_type Capacity() const override { return m_custom ? m_custom->Capacity() : AZ_CORE_MAX_ALLOCATOR_SIZE; } // custom size or unlimited size_type GetMaxAllocationSize() const override { return m_custom ? m_custom->GetMaxAllocationSize() : AZ_CORE_MAX_ALLOCATOR_SIZE; } // custom size or unlimited + size_type GetMaxContiguousAllocationSize() const override { return m_custom ? m_custom->GetMaxContiguousAllocationSize() : AZ_CORE_MAX_ALLOCATOR_SIZE; } // custom size or unlimited IAllocatorAllocate* GetSubAllocator() override { return m_custom ? m_custom : NULL; } protected: diff --git a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp index 35ad19dd9e..ed5e0febc2 100644 --- a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.cpp @@ -232,6 +232,7 @@ namespace AZ size_type NumAllocatedBytes() const; size_type Capacity() const; size_type GetMaxAllocationSize() const; + size_type GetMaxContiguousAllocationSize() const; IAllocatorAllocate* GetSubAllocator(); void GarbageCollect(); @@ -674,6 +675,11 @@ AZ::OverrunDetectionSchema::size_type AZ::OverrunDetectionSchemaImpl::GetMaxAllo return 0; } +auto AZ::OverrunDetectionSchemaImpl::GetMaxContiguousAllocationSize() const -> size_type +{ + return 0; +} + AZ::IAllocatorAllocate* AZ::OverrunDetectionSchemaImpl::GetSubAllocator() { return nullptr; @@ -799,6 +805,11 @@ AZ::OverrunDetectionSchema::size_type AZ::OverrunDetectionSchema::GetMaxAllocati return m_impl->GetMaxAllocationSize(); } +auto AZ::OverrunDetectionSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_impl->GetMaxContiguousAllocationSize(); +} + AZ::IAllocatorAllocate* AZ::OverrunDetectionSchema::GetSubAllocator() { return m_impl->GetSubAllocator(); diff --git a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h index 669fda8a04..3dffdfad56 100644 --- a/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/OverrunDetectionAllocator.h @@ -86,6 +86,7 @@ namespace AZ virtual size_type NumAllocatedBytes() const override; virtual size_type Capacity() const override; virtual size_type GetMaxAllocationSize() const override; + size_type GetMaxContiguousAllocationSize() const override; virtual IAllocatorAllocate* GetSubAllocator() override; virtual void GarbageCollect() override; diff --git a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp index 3e71f530a0..0bef6b7d28 100644 --- a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp +++ b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.cpp @@ -707,6 +707,11 @@ PoolSchema::GarbageCollect() //m_impl->GarbageCollect(); } +auto PoolSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_impl->m_allocator.m_maxAllocationSize; +} + //========================================================================= // NumAllocatedBytes // [11/1/2010] @@ -1052,6 +1057,11 @@ ThreadPoolSchema::GarbageCollect() m_impl->GarbageCollect(); } +auto ThreadPoolSchema::GetMaxContiguousAllocationSize() const -> size_type +{ + return m_impl->m_maxAllocationSize; +} + //========================================================================= // NumAllocatedBytes // [11/1/2010] diff --git a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h index d9c89d28bd..cfc5e3ea07 100644 --- a/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h +++ b/Code/Framework/AzCore/AzCore/Memory/PoolSchema.h @@ -70,6 +70,7 @@ namespace AZ /// Return unused memory to the OS. Don't call this too often because you will force unnecessary allocations. void GarbageCollect() override; + size_type GetMaxContiguousAllocationSize() const override; size_type NumAllocatedBytes() const override; size_type Capacity() const override; IAllocatorAllocate* GetSubAllocator() override; @@ -115,6 +116,7 @@ namespace AZ /// Return unused memory to the OS. Don't call this too often because you will force unnecessary allocations. void GarbageCollect() override; + size_type GetMaxContiguousAllocationSize() const override; size_type NumAllocatedBytes() const override; size_type Capacity() const override; IAllocatorAllocate* GetSubAllocator() override; diff --git a/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h b/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h index e9d001aec3..5fbc890203 100644 --- a/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/SimpleSchemaAllocator.h @@ -179,6 +179,11 @@ namespace AZ return m_schema->GetMaxAllocationSize(); } + size_type GetMaxContiguousAllocationSize() const override + { + return m_schema->GetMaxContiguousAllocationSize(); + } + size_type GetUnAllocatedMemory(bool isPrint = false) const override { return m_schema->GetUnAllocatedMemory(isPrint); diff --git a/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h b/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h index 9fd5734dbb..c02ada5843 100644 --- a/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h +++ b/Code/Framework/AzCore/AzCore/Memory/SystemAllocator.h @@ -103,6 +103,7 @@ namespace AZ size_type Capacity() const override { return m_allocator->Capacity(); } /// Keep in mind this operation will execute GarbageCollect to make sure it returns, max allocation. This function WILL be slow. size_type GetMaxAllocationSize() const override { return m_allocator->GetMaxAllocationSize(); } + size_type GetMaxContiguousAllocationSize() const override { return m_allocator->GetMaxContiguousAllocationSize(); } size_type GetUnAllocatedMemory(bool isPrint = false) const override { return m_allocator->GetUnAllocatedMemory(isPrint); } IAllocatorAllocate* GetSubAllocator() override { return m_isCustom ? m_allocator : m_allocator->GetSubAllocator(); } diff --git a/Code/Framework/AzCore/AzCore/Module/Environment.cpp b/Code/Framework/AzCore/AzCore/Module/Environment.cpp index c07b7444d4..71da948a35 100644 --- a/Code/Framework/AzCore/AzCore/Module/Environment.cpp +++ b/Code/Framework/AzCore/AzCore/Module/Environment.cpp @@ -61,7 +61,7 @@ namespace AZ const char* get_name() const { return m_name; } void set_name(const char* name) { m_name = name; } - size_type get_max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } + constexpr size_type max_size() const { return AZ_CORE_MAX_ALLOCATOR_SIZE; } size_type get_allocated_size() const { return 0; } bool is_lock_free() { return false; } diff --git a/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp b/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp index 5a35603d0a..b03d413507 100644 --- a/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp +++ b/Code/Framework/AzCore/AzCore/Script/ScriptContext.cpp @@ -2306,7 +2306,7 @@ LUA_API const Node* lua_getDummyNode() else // even references are stored by value as we need to convert from lua native type, i.e. there is not real reference for NativeTypes (numbers, strings, etc.) { bool usedBackupAlloc = false; - if (backupAllocator != nullptr && sizeof(T) > tempAllocator.get_max_size()) + if (backupAllocator != nullptr && sizeof(T) > AZStd::allocator_traits::max_size(tempAllocator)) { value.m_value = backupAllocator->allocate(sizeof(T), AZStd::alignment_of::value, 0); usedBackupAlloc = true; @@ -2340,7 +2340,7 @@ LUA_API const Node* lua_getDummyNode() else // it's a value type { bool usedBackupAlloc = false; - if (backupAllocator != nullptr && valueClass->m_size > tempAllocator.get_max_size()) + if (backupAllocator != nullptr && valueClass->m_size > AZStd::allocator_traits::max_size(tempAllocator)) { value.m_value = backupAllocator->allocate(valueClass->m_size, valueClass->m_alignment, 0); usedBackupAlloc = true; diff --git a/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h b/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h index c3e3f5210a..d9e3dfad1e 100644 --- a/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h +++ b/Code/Framework/AzCore/AzCore/UnitTest/TestTypes.h @@ -45,7 +45,7 @@ namespace UnitTest virtual ~AllocatorsBase() = default; - void SetupAllocator() + void SetupAllocator(const AZ::SystemAllocator::Descriptor& allocatorDesc = {}) { m_drillerManager = AZ::Debug::DrillerManager::Create(); m_drillerManager->Register(aznew AZ::Debug::MemoryDriller); @@ -54,7 +54,7 @@ namespace UnitTest // Only create the SystemAllocator if it s not ready if (!AZ::AllocatorInstance::IsReady()) { - AZ::AllocatorInstance::Create(); + AZ::AllocatorInstance::Create(allocatorDesc); m_ownsAllocator = true; } } @@ -85,6 +85,7 @@ namespace UnitTest { public: ScopedAllocatorSetupFixture() { SetupAllocator(); } + explicit ScopedAllocatorSetupFixture(const AZ::SystemAllocator::Descriptor& allocatorDesc) { SetupAllocator(allocatorDesc); } ~ScopedAllocatorSetupFixture() { TeardownAllocator(); } }; diff --git a/Code/Framework/AzCore/AzCore/std/allocator.cpp b/Code/Framework/AzCore/AzCore/std/allocator.cpp index 0aaad5a5a8..fdf1903882 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator.cpp +++ b/Code/Framework/AzCore/AzCore/std/allocator.cpp @@ -40,15 +40,11 @@ namespace AZStd return AZ::AllocatorInstance::Get().Resize(ptr, newSize); } - //========================================================================= - // get_max_size - // [1/1/2008] - //========================================================================= - allocator::size_type - allocator::get_max_size() const + auto allocator::max_size() const -> size_type { - return AZ::AllocatorInstance::Get().GetMaxAllocationSize(); + return AZ::AllocatorInstance::Get().GetMaxContiguousAllocationSize(); } + //========================================================================= // get_allocated_size // [1/1/2008] diff --git a/Code/Framework/AzCore/AzCore/std/allocator.h b/Code/Framework/AzCore/AzCore/std/allocator.h index 0fee5481e2..225350e883 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator.h +++ b/Code/Framework/AzCore/AzCore/std/allocator.h @@ -49,8 +49,8 @@ namespace AZStd * const char* get_name() const; * void set_name(const char* name); * - * // Returns maximum size we can allocate from this allocator. - * size_type get_max_size() const; + * // Returns theoretical maximum size of a single contiguous allocation from this allocator. + * size_type max_size() const; * size_type get_allocated_size() const; * }; * @@ -100,7 +100,8 @@ namespace AZStd pointer_type allocate(size_type byteSize, size_type alignment, int flags = 0); void deallocate(pointer_type ptr, size_type byteSize, size_type alignment); size_type resize(pointer_type ptr, size_type newSize); - size_type get_max_size() const; + // max_size actually returns the true maximum size of a single allocation + size_type max_size() const; size_type get_allocated_size() const; AZ_FORCE_INLINE bool is_lock_free() { return false; } @@ -157,7 +158,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const; AZ_FORCE_INLINE void set_name(const char* name); - AZ_FORCE_INLINE size_type get_max_size() const; + AZ_FORCE_INLINE size_type max_size() const; AZ_FORCE_INLINE bool is_lock_free(); AZ_FORCE_INLINE bool is_stale_read_allowed(); diff --git a/Code/Framework/AzCore/AzCore/std/allocator_ref.h b/Code/Framework/AzCore/AzCore/std/allocator_ref.h index 659ee0cc8f..62a3cf68de 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_ref.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_ref.h @@ -41,7 +41,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return m_allocator->get_max_size(); } + constexpr size_type max_size() const { return m_allocator->max_size(); } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_allocator->get_allocated_size(); } diff --git a/Code/Framework/AzCore/AzCore/std/allocator_stack.h b/Code/Framework/AzCore/AzCore/std/allocator_stack.h index 202e62bd0f..d8546bfd18 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_stack.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_stack.h @@ -59,7 +59,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return m_size - (m_freeData - m_data); } + constexpr size_type max_size() const { return m_size; } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_freeData - m_data; } pointer_type allocate(size_type byteSize, size_type alignment, int flags = 0) diff --git a/Code/Framework/AzCore/AzCore/std/allocator_static.h b/Code/Framework/AzCore/AzCore/std/allocator_static.h index 0c079eaa9d..7f793c6d6b 100644 --- a/Code/Framework/AzCore/AzCore/std/allocator_static.h +++ b/Code/Framework/AzCore/AzCore/std/allocator_static.h @@ -63,7 +63,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return Size - (m_freeData - reinterpret_cast(&m_data)); } + constexpr size_type max_size() const { return Size; } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_freeData - reinterpret_cast(&m_data); } pointer_type allocate(size_type byteSize, size_type alignment, int flags = 0) @@ -190,7 +190,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return (NumNodes - m_numOfAllocatedNodes) * sizeof(Node); } + constexpr size_type max_size() const { return NumNodes * sizeof(Node); } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_numOfAllocatedNodes * sizeof(Node); } inline Node* allocate() diff --git a/Code/Framework/AzCore/AzCore/std/containers/deque.h b/Code/Framework/AzCore/AzCore/std/containers/deque.h index 215845a8f4..db585e0ec9 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/deque.h +++ b/Code/Framework/AzCore/AzCore/std/containers/deque.h @@ -6,11 +6,10 @@ * */ #pragma once -#ifndef AZSTD_DEQUE_H -#define AZSTD_DEQUE_H 1 #include +#include #include #include #include @@ -350,7 +349,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_size; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.get_max_size() / sizeof(block_node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(block_node_type); } AZ_FORCE_INLINE bool empty() const { return m_size == 0; } AZ_FORCE_INLINE const_reference at(size_type offset) const { return *const_iterator(AZSTD_CHECKED_ITERATOR_2(const_iterator_impl, m_firstOffset + offset, this)); } @@ -1243,5 +1242,3 @@ namespace AZStd return removedCount; } } - -#endif // AZSTD_DEQUE_H diff --git a/Code/Framework/AzCore/AzCore/std/containers/forward_list.h b/Code/Framework/AzCore/AzCore/std/containers/forward_list.h index c311991ee3..407d65ffa9 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/forward_list.h +++ b/Code/Framework/AzCore/AzCore/std/containers/forward_list.h @@ -286,7 +286,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_numElements; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return (m_numElements == 0); } AZ_FORCE_INLINE iterator begin() { return iterator(AZSTD_CHECKED_ITERATOR(iterator_impl, m_head.m_next)); } diff --git a/Code/Framework/AzCore/AzCore/std/containers/list.h b/Code/Framework/AzCore/AzCore/std/containers/list.h index 124d8b7d7c..60d2977749 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/list.h +++ b/Code/Framework/AzCore/AzCore/std/containers/list.h @@ -5,11 +5,11 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_LIST_H -#define AZSTD_LIST_H 1 + #pragma once #include +#include #include #include #include @@ -316,7 +316,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_numElements; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return (m_numElements == 0); } AZ_FORCE_INLINE iterator begin() { return iterator(AZSTD_CHECKED_ITERATOR(iterator_impl, m_head.m_next)); } @@ -1346,5 +1346,3 @@ namespace AZStd return container.remove_if(predicate); } } - -#endif // AZSTD_LIST_H diff --git a/Code/Framework/AzCore/AzCore/std/containers/rbtree.h b/Code/Framework/AzCore/AzCore/std/containers/rbtree.h index c8f0883eaf..fd268f4936 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/rbtree.h +++ b/Code/Framework/AzCore/AzCore/std/containers/rbtree.h @@ -484,7 +484,7 @@ namespace AZStd AZ_FORCE_INLINE bool empty() const { return m_numElements == 0; } AZ_FORCE_INLINE size_type size() const { return m_numElements; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } rbtree(this_type&& rhs) : m_numElements(0) // it will be set during swap diff --git a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h index 7e84124958..d8c3c6ecda 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h +++ b/Code/Framework/AzCore/AzCore/std/containers/ring_buffer.h @@ -5,10 +5,11 @@ * SPDX-License-Identifier: Apache-2.0 OR MIT * */ -#ifndef AZSTD_RINGBUFFER_H -#define AZSTD_RINGBUFFER_H 1 + +#pragma once #include +#include #include #include #include @@ -416,7 +417,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_size; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return m_size == 0; } AZ_FORCE_INLINE bool full() const { return size_type(m_end - m_buff) == m_size; } AZ_FORCE_INLINE size_type free() const { return size_type(m_end - m_buff) - m_size; } @@ -1240,6 +1241,3 @@ namespace AZStd lhs.swap(rhs); } } - -#endif // AZSTD_RINGBUFFER_H -#pragma once diff --git a/Code/Framework/AzCore/AzCore/std/containers/vector.h b/Code/Framework/AzCore/AzCore/std/containers/vector.h index bf02527d77..48de12a5b4 100644 --- a/Code/Framework/AzCore/AzCore/std/containers/vector.h +++ b/Code/Framework/AzCore/AzCore/std/containers/vector.h @@ -9,6 +9,7 @@ #include #include +#include #include #include #include @@ -431,7 +432,7 @@ namespace AZStd } AZ_FORCE_INLINE size_type size() const { return m_last - m_start; } - AZ_FORCE_INLINE size_type max_size() const { return m_allocator.get_max_size() / sizeof(node_type); } + AZ_FORCE_INLINE size_type max_size() const { return AZStd::allocator_traits::max_size(m_allocator) / sizeof(node_type); } AZ_FORCE_INLINE bool empty() const { return m_start == m_last; } void reserve(size_type numElements) diff --git a/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h b/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h index 72c687beab..b9cd5207dd 100644 --- a/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h +++ b/Code/Framework/AzCore/AzCore/std/parallel/allocator_concurrent_static.h @@ -22,7 +22,7 @@ namespace AZStd * Internally the buffer is allocated using aligned_storage. * \note only allocate/deallocate are thread safe. * reset, leak_before_destroy and comparison operators are not thread safe. - * get_max_size and get_allocated_size are thread safe but the returned value is not perfectly in + * get_allocated_size is thread safe but the returned value is not perfectly in * sync on the actual number of allocations (the number of allocations is incremented before the * allocation happens and decremented after the allocation happens, trying to give a conservative * number) @@ -71,7 +71,7 @@ namespace AZStd AZ_FORCE_INLINE const char* get_name() const { return m_name; } AZ_FORCE_INLINE void set_name(const char* name) { m_name = name; } - AZ_FORCE_INLINE size_type get_max_size() const { return (NumNodes - m_numOfAllocatedNodes.load(AZStd::memory_order_relaxed)) * sizeof(Node); } + constexpr size_type max_size() const { return NumNodes * sizeof(Node); } AZ_FORCE_INLINE size_type get_allocated_size() const { return m_numOfAllocatedNodes.load(AZStd::memory_order_relaxed) * sizeof(Node); } inline Node* allocate() diff --git a/Code/Framework/AzCore/AzCore/std/string/string.h b/Code/Framework/AzCore/AzCore/std/string/string.h index ad3546ab09..c02c6805a1 100644 --- a/Code/Framework/AzCore/AzCore/std/string/string.h +++ b/Code/Framework/AzCore/AzCore/std/string/string.h @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -862,8 +863,7 @@ namespace AZStd inline size_type max_size() const { // return maximum possible length of sequence - size_type num = m_allocator.get_max_size(); - return (num <= 1 ? 1 : num - 1); + return AZStd::allocator_traits::max_size(m_allocator) / sizeof(value_type); } inline void resize(size_type newSize) diff --git a/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp b/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp index 6b82c642d5..8b5d1494fc 100644 --- a/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/Allocators.cpp @@ -122,8 +122,15 @@ namespace UnitTest TEST_F(AllocatorDefaultTest, AllocatorTraitsMaxSizeCompilesWithoutErrors) { - using AZStdAllocatorTraits = AZStd::allocator_traits; - AZStd::allocator testAllocator("trait allocator"); + struct AllocatorWithGetMaxSize + : AZStd::allocator + { + using AZStd::allocator::allocator; + size_t get_max_size() { return max_size(); } + }; + + using AZStdAllocatorTraits = AZStd::allocator_traits; + AllocatorWithGetMaxSize testAllocator("trait allocator"); typename AZStdAllocatorTraits::size_type maxSize = AZStdAllocatorTraits::max_size(testAllocator); EXPECT_EQ(testAllocator.get_max_size(), maxSize); } @@ -149,32 +156,32 @@ namespace UnitTest myalloc.set_name(newName); AZ_TEST_ASSERT(strcmp(myalloc.get_name(), newName) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); buffer_alloc_type::pointer_type data = myalloc.allocate(100, 1); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 100); + EXPECT_EQ(bufferSize - 100, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 100); myalloc.deallocate(data, 100, 1); // we can free the last allocation only - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); data = myalloc.allocate(100, 1); myalloc.allocate(3, 1); myalloc.deallocate(data); // can't free allocation which is not the last. - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 103); + EXPECT_EQ(bufferSize - 103, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 103); myalloc.reset(); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); data = myalloc.allocate(50, 64); AZ_TEST_ASSERT(data != nullptr); AZ_TEST_ASSERT(((AZStd::size_t)data & 63) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() <= bufferSize - 50); + EXPECT_LE(myalloc.max_size() - myalloc.get_allocated_size(), bufferSize - 50); AZ_TEST_ASSERT(myalloc.get_allocated_size() >= 50); buffer_alloc_type myalloc2; @@ -194,28 +201,28 @@ namespace UnitTest myalloc.set_name(newName); AZ_TEST_ASSERT(strcmp(myalloc.get_name(), newName) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() == sizeof(int) * numNodes); + EXPECT_EQ(numNodes * sizeof(int), myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); int* data = reinterpret_cast(myalloc.allocate(sizeof(int), 1)); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == (numNodes - 1) * sizeof(int)); + EXPECT_EQ((numNodes - 1) * sizeof(int), myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == sizeof(int)); myalloc.deallocate(data, sizeof(int), 1); - AZ_TEST_ASSERT(myalloc.get_max_size() == sizeof(int) * numNodes); + EXPECT_EQ(numNodes * sizeof(int), myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); for (int i = 0; i < numNodes; ++i) { data = reinterpret_cast(myalloc.allocate(sizeof(int), 1)); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == (numNodes - (i + 1)) * sizeof(int)); + EXPECT_EQ((numNodes - (i + 1)) * sizeof(int), myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == (i + 1) * sizeof(int)); } myalloc.reset(); - AZ_TEST_ASSERT(myalloc.get_max_size() == numNodes * sizeof(int)); + EXPECT_EQ(numNodes * sizeof(int), myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); AZ_TEST_ASSERT(myalloc == myalloc); @@ -233,7 +240,7 @@ namespace UnitTest AZ_TEST_ASSERT(aligned_data != nullptr); AZ_TEST_ASSERT(((AZStd::size_t)aligned_data & (dataAlignment - 1)) == 0); - AZ_TEST_ASSERT(myaligned_pool.get_max_size() == (numNodes - 1) * sizeof(aligned_int_type)); + EXPECT_EQ((numNodes - 1) * sizeof(aligned_int_type), myaligned_pool.max_size() - myaligned_pool.get_allocated_size()); AZ_TEST_ASSERT(myaligned_pool.get_allocated_size() == sizeof(aligned_int_type)); myaligned_pool.deallocate(aligned_data, sizeof(aligned_int_type), dataAlignment); // Make sure we free what we have allocated. @@ -268,32 +275,32 @@ namespace UnitTest ref_allocator_type::pointer_type data1 = ref_allocator1.allocate(10, 1); AZ_TEST_ASSERT(data1 != nullptr); - AZ_TEST_ASSERT(ref_allocator1.get_max_size() == bufferSize - 10); + EXPECT_EQ(bufferSize - 10, ref_allocator1.max_size() - ref_allocator1.get_allocated_size()); AZ_TEST_ASSERT(ref_allocator1.get_allocated_size() == 10); - AZ_TEST_ASSERT(shared_allocator.get_max_size() == bufferSize - 10); + EXPECT_EQ(bufferSize - 10, shared_allocator.max_size() - shared_allocator.get_allocated_size()); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() == 10); ref_allocator_type::pointer_type data2 = ref_allocator2.allocate(10, 1); AZ_TEST_ASSERT(data2 != nullptr); - AZ_TEST_ASSERT(ref_allocator2.get_max_size() <= bufferSize - 20); + EXPECT_LE(ref_allocator2.max_size() - ref_allocator2.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(ref_allocator2.get_allocated_size() >= 20); - AZ_TEST_ASSERT(shared_allocator.get_max_size() <= bufferSize - 20); + EXPECT_LE(shared_allocator.max_size() - shared_allocator.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() >= 20); shared_allocator.reset(); data1 = ref_allocator1.allocate(10, 32); AZ_TEST_ASSERT(data1 != nullptr); - AZ_TEST_ASSERT(ref_allocator1.get_max_size() <= bufferSize - 10); + EXPECT_LE(ref_allocator1.max_size() - ref_allocator1.get_allocated_size(), bufferSize - 10); AZ_TEST_ASSERT(ref_allocator1.get_allocated_size() >= 10); - AZ_TEST_ASSERT(shared_allocator.get_max_size() <= bufferSize - 10); + EXPECT_LE(shared_allocator.max_size() - shared_allocator.get_allocated_size(), bufferSize - 10); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() >= 10); data2 = ref_allocator2.allocate(10, 32); AZ_TEST_ASSERT(data2 != nullptr); - AZ_TEST_ASSERT(ref_allocator1.get_max_size() <= bufferSize - 20); + EXPECT_LE(ref_allocator1.max_size() - ref_allocator1.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(ref_allocator1.get_allocated_size() >= 20); - AZ_TEST_ASSERT(shared_allocator.get_max_size() <= bufferSize - 20); + EXPECT_LE(shared_allocator.max_size() - shared_allocator.get_allocated_size(), bufferSize - 20); AZ_TEST_ASSERT(shared_allocator.get_allocated_size() >= 20); AZ_TEST_ASSERT(ref_allocator1 == ref_allocator2); @@ -312,31 +319,31 @@ namespace UnitTest myalloc.set_name(newName); AZ_TEST_ASSERT(strcmp(myalloc.get_name(), newName) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); stack_allocator::pointer_type data = myalloc.allocate(100, 1); AZ_TEST_ASSERT(data != nullptr); - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 100); + EXPECT_EQ(bufferSize - 100, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 100); myalloc.deallocate(data, 100, 1); // this allocator doesn't free data - AZ_TEST_ASSERT(myalloc.get_max_size() == bufferSize - 100); + EXPECT_EQ(bufferSize - 100, myalloc.max_size() - myalloc.get_allocated_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 100); myalloc.reset(); - AZ_TEST_ASSERT(myalloc.get_max_size() == AZStd::size_t(bufferSize)); + EXPECT_EQ(bufferSize, myalloc.max_size()); AZ_TEST_ASSERT(myalloc.get_allocated_size() == 0); data = myalloc.allocate(50, 64); AZ_TEST_ASSERT(data != nullptr); AZ_TEST_ASSERT(((AZStd::size_t)data & 63) == 0); - AZ_TEST_ASSERT(myalloc.get_max_size() <= bufferSize - 50); + EXPECT_LE(myalloc.max_size() - myalloc.get_allocated_size(), bufferSize - 50); AZ_TEST_ASSERT(myalloc.get_allocated_size() >= 50); AZ_STACK_ALLOCATOR(myalloc2, 200); // test the macro declaration - AZ_TEST_ASSERT(myalloc2.get_max_size() == 200); + EXPECT_EQ(200, myalloc2.max_size() ); AZ_TEST_ASSERT(myalloc == myalloc); AZ_TEST_ASSERT((myalloc2 != myalloc)); diff --git a/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp b/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp index 5be17a75e2..86ac22bfc9 100644 --- a/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp +++ b/Code/Framework/AzCore/Tests/AZStd/ConcurrentAllocators.cpp @@ -49,7 +49,7 @@ namespace UnitTest const char newName[] = "My new test allocator"; myalloc.set_name(newName); EXPECT_EQ(0, strcmp(myalloc.get_name(), newName)); - EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.get_max_size()); + EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.max_size()); } } @@ -61,10 +61,10 @@ namespace UnitTest typename TestFixture::allocator_type::pointer_type data = myalloc.allocate(); EXPECT_NE(nullptr, data); EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_allocated_size()); - EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * (s_allocatorCapacity - 1), myalloc.get_max_size()); + EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * (s_allocatorCapacity - 1), myalloc.max_size() - myalloc.get_allocated_size()); myalloc.deallocate(data); EXPECT_EQ(0, myalloc.get_allocated_size()); - EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.get_max_size()); + EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * s_allocatorCapacity, myalloc.max_size()); } TYPED_TEST(ConcurrentAllocatorTestFixture, MultipleAllocateDeallocate) @@ -84,19 +84,19 @@ namespace UnitTest EXPECT_EQ(dataSize, dataSet.size()); dataSet.clear(); EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * dataSize, myalloc.get_allocated_size()); - EXPECT_EQ((s_allocatorCapacity - dataSize) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_max_size()); + EXPECT_EQ((s_allocatorCapacity - dataSize) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.max_size() - myalloc.get_allocated_size()); for (size_t i = 0; i < dataSize; i += 2) { myalloc.deallocate(data[i]); } EXPECT_EQ(sizeof(typename TestFixture::allocator_type::value_type) * (dataSize / 2), myalloc.get_allocated_size()); - EXPECT_EQ((s_allocatorCapacity - dataSize / 2) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_max_size()); + EXPECT_EQ((s_allocatorCapacity - dataSize / 2) * sizeof(typename TestFixture::allocator_type::value_type), myalloc.max_size() - myalloc.get_allocated_size()); for (size_t i = 1; i < dataSize; i += 2) { myalloc.deallocate(data[i]); } EXPECT_EQ(0, myalloc.get_allocated_size()); - EXPECT_EQ(s_allocatorCapacity * sizeof(typename TestFixture::allocator_type::value_type), myalloc.get_max_size()); + EXPECT_EQ(s_allocatorCapacity * sizeof(typename TestFixture::allocator_type::value_type), myalloc.max_size()); } TYPED_TEST(ConcurrentAllocatorTestFixture, ConcurrentAllocateoDeallocate) @@ -159,7 +159,7 @@ namespace UnitTest EXPECT_NE(nullptr, aligned_data); EXPECT_EQ(0, ((AZStd::size_t)aligned_data & (dataAlignment - 1))); - EXPECT_EQ((s_allocatorCapacity - 1) * sizeof(aligned_int_type), myaligned_pool.get_max_size()); + EXPECT_EQ((s_allocatorCapacity - 1) * sizeof(aligned_int_type), myaligned_pool.max_size() - myaligned_pool.get_allocated_size()); EXPECT_EQ(sizeof(aligned_int_type), myaligned_pool.get_allocated_size()); myaligned_pool.deallocate(aligned_data, sizeof(aligned_int_type), dataAlignment); // Make sure we free what we have allocated. diff --git a/Code/Framework/AzCore/Tests/Memory.cpp b/Code/Framework/AzCore/Tests/Memory.cpp index 611af827d2..eb854050b6 100644 --- a/Code/Framework/AzCore/Tests/Memory.cpp +++ b/Code/Framework/AzCore/Tests/Memory.cpp @@ -1179,6 +1179,8 @@ namespace UnitTest size_type Capacity() const override { return 1 * 1024 * 1024 * 1024; } /// Returns max allocation size if possible. If not returned value is 0 size_type GetMaxAllocationSize() const override { return 1 * 1024 * 1024 * 1024; } + /// Returns max allocation size of a single contiguous allocation + size_type GetMaxContiguousAllocationSize() const override { return 1 * 1024 * 1024 * 1024; } /// Returns a pointer to a sub-allocator or NULL. IAllocatorAllocate* GetSubAllocator() override { return NULL; } }; diff --git a/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.cpp b/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.cpp index dfb397a02c..35faa74b19 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.cpp +++ b/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.cpp @@ -39,7 +39,7 @@ namespace MCore return 0; } - StaticAllocator::size_type StaticAllocator::get_max_size() const + StaticAllocator::size_type StaticAllocator::max_size() const { return 0; } diff --git a/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.h b/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.h index d3b1c68855..50d8dac04c 100644 --- a/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.h +++ b/Gems/EMotionFX/Code/MCore/Source/StaticAllocator.h @@ -22,7 +22,7 @@ namespace MCore StaticAllocator::size_type resize(pointer_type ptr, size_type newSize); - StaticAllocator::size_type get_max_size() const; + StaticAllocator::size_type max_size() const; StaticAllocator::size_type get_allocated_size() const; }; From 2c066a81daec45277246757ec8be7fd5dfc068e4 Mon Sep 17 00:00:00 2001 From: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> Date: Tue, 14 Sep 2021 15:11:11 -0700 Subject: [PATCH 17/26] Adds support for creating an SDK layout from a Monolithic build (#4097) Adds support for creating an SDK layout from a Monolithic build and have the same install prefix used between monolithic and non-monolithic Signed-off-by: Esteban Papp <81431996+amznestebanpapp@users.noreply.github.com> --- cmake/Platform/Common/Install_common.cmake | 96 +++++++++++++++------- cmake/Platform/Mac/Install_mac.cmake | 10 +-- cmake/install/ConfigurationTypes.cmake | 11 ++- cmake/install/InstalledTarget.in | 2 +- 4 files changed, 82 insertions(+), 37 deletions(-) diff --git a/cmake/Platform/Common/Install_common.cmake b/cmake/Platform/Common/Install_common.cmake index 86f46a6e0b..fdd3256d78 100644 --- a/cmake/Platform/Common/Install_common.cmake +++ b/cmake/Platform/Common/Install_common.cmake @@ -23,12 +23,12 @@ ly_set(CMAKE_INSTALL_DEFAULT_COMPONENT_NAME Core) cmake_path(RELATIVE_PATH CMAKE_RUNTIME_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE runtime_output_directory) cmake_path(RELATIVE_PATH CMAKE_LIBRARY_OUTPUT_DIRECTORY BASE_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_VARIABLE library_output_directory) -# Anywhere CMAKE_INSTALL_PREFIX is used, it has to be escaped so it is baked into the cmake_install.cmake script instead -# of baking the path. This is needed so `cmake --install --prefix ` works regardless of the CMAKE_INSTALL_PREFIX -# used to generate the solution. -# CMAKE_INSTALL_PREFIX is still used when building the INSTALL target -set(install_output_folder "\${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$") +if(LY_MONOLITHIC_GAME) + set(LY_BUILD_PERMUTATION Monolithic) +else() + set(LY_BUILD_PERMUTATION Default) +endif() #! ly_setup_target: Setup the data needed to re-create the cmake target commands for a single target function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_target_source_dir) @@ -91,6 +91,10 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar cmake_path(RELATIVE_PATH target_library_output_directory BASE_DIRECTORY ${CMAKE_LIBRARY_OUTPUT_DIRECTORY} OUTPUT_VARIABLE target_library_output_subdirectory) endif() + cmake_path(APPEND archive_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") + cmake_path(APPEND library_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") + cmake_path(APPEND runtime_output_directory "${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") + if(COMMAND ly_install_target_override) # Mac needs special handling because of a cmake issue ly_install_target_override(TARGET ${TARGET_NAME} @@ -104,18 +108,18 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar install( TARGETS ${TARGET_NAME} ARCHIVE - DESTINATION ${archive_output_directory}/${PAL_PLATFORM_NAME}/$ + DESTINATION ${archive_output_directory} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} LIBRARY - DESTINATION ${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory} + DESTINATION ${library_output_directory}/${target_library_output_subdirectory} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} RUNTIME - DESTINATION ${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory} + DESTINATION ${runtime_output_directory}/${target_runtime_output_subdirectory} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) endif() - # CMakeLists.txt file + # CMakeLists.txt related files string(REGEX MATCH "(.*)::(.*)$" match ${ALIAS_TARGET_NAME}) if(match) set(NAMESPACE_PLACEHOLDER "NAMESPACE ${CMAKE_MATCH_1}") @@ -140,7 +144,7 @@ function(ly_setup_target OUTPUT_CONFIGURED_TARGET ALIAS_TARGET_NAME absolute_tar if(TARGET_TYPE_PLACEHOLDER IN_LIST GEM_LIBRARY_TYPES) get_target_property(gem_module ${TARGET_NAME} GEM_MODULE) if(gem_module) - set(TARGET_TYPE_PLACEHOLDER "GEM_MODULE") + string(PREPEND TARGET_TYPE_PLACEHOLDER "GEM_") endif() endif() @@ -222,32 +226,32 @@ set_target_properties(${RUN_TARGET_NAME} PROPERTIES ) endif() - # Config file + # Config files set(target_file_contents "# Generated by O3DE install\n\n") if(NOT target_type STREQUAL INTERFACE_LIBRARY) unset(target_location) set(runtime_types EXECUTABLE APPLICATION) if(target_type IN_LIST runtime_types) - set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${target_runtime_output_subdirectory}/$") + set(target_location "\${LY_ROOT_FOLDER}/${runtime_output_directory}/${target_runtime_output_subdirectory}/$") elseif(target_type STREQUAL MODULE_LIBRARY) - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${target_library_output_subdirectory}/$") elseif(target_type STREQUAL SHARED_LIBRARY) string(APPEND target_file_contents "set_property(TARGET ${NAME_PLACEHOLDER} APPEND_STRING PROPERTY IMPORTED_IMPLIB - $<$$:\"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\"$ + $<$$:\"\${LY_ROOT_FOLDER}/${archive_output_directory}/$\"$ ) ") string(APPEND target_file_contents "set_property(TARGET ${NAME_PLACEHOLDER} PROPERTY IMPORTED_IMPLIB_$> - \"\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$\" + \"\${LY_ROOT_FOLDER}/${archive_output_directory}/$\" ) ") - set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${PAL_PLATFORM_NAME}/$/${target_library_output_subdirectory}/$") + set(target_location "\${LY_ROOT_FOLDER}/${library_output_directory}/${target_library_output_subdirectory}/$") else() # STATIC_LIBRARY, OBJECT_LIBRARY, INTERFACE_LIBRARY - set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/${PAL_PLATFORM_NAME}/$/$") + set(target_location "\${LY_ROOT_FOLDER}/${archive_output_directory}/$") endif() if(target_location) @@ -265,9 +269,9 @@ set_property(TARGET ${NAME_PLACEHOLDER} endif() set(target_install_source_dir ${CMAKE_CURRENT_BINARY_DIR}/install/${relative_target_source_dir}) - file(GENERATE OUTPUT "${target_install_source_dir}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") - install(FILES "${target_install_source_dir}/${NAME_PLACEHOLDER}_$.cmake" - DESTINATION ${relative_target_source_dir} + file(GENERATE OUTPUT "${target_install_source_dir}/Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION}/${NAME_PLACEHOLDER}_$.cmake" CONTENT "${target_file_contents}") + install(FILES "${target_install_source_dir}/Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION}/${NAME_PLACEHOLDER}_$.cmake" + DESTINATION ${relative_target_source_dir}/Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) @@ -299,16 +303,44 @@ function(ly_setup_subdirectory absolute_target_source_dir) string(APPEND all_configured_targets "${configured_target}") endforeach() + # Initialize the target install source directory to path underneath the current binary directory + set(target_install_source_dir "${CMAKE_CURRENT_BINARY_DIR}/install/${relative_target_source_dir}") + + ly_file_read(${LY_ROOT_FOLDER}/cmake/install/Copyright.in cmake_copyright_comment) + + # 1. Create the base CMakeLists.txt that will just include a cmake file per platform + file(CONFIGURE OUTPUT "${target_install_source_dir}/CMakeLists.txt" CONTENT [[ +@cmake_copyright_comment@ +include(Platform/${PAL_PLATFORM_NAME}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake) +]] @ONLY) + install(FILES "${target_install_source_dir}/CMakeLists.txt" + DESTINATION ${relative_target_source_dir} + COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} + ) + + # 2. For this platform file, create a Platform/${PAL_PLATFORM_NAME}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake file + # that will include different configuration permutations (e.g. monolithic vs non-monolithic) + file(CONFIGURE OUTPUT "${target_install_source_dir}/Platform/${PAL_PLATFORM_NAME}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake" CONTENT [[ +@cmake_copyright_comment@ +if(LY_MONOLITHIC_GAME) + include(Platform/${PAL_PLATFORM_NAME}/Monolithic/permutation.cmake) +else() + include(Platform/${PAL_PLATFORM_NAME}/Default/permutation.cmake) +endif() +]]) + install(FILES "${target_install_source_dir}/Platform/${PAL_PLATFORM_NAME}/platform_${PAL_PLATFORM_NAME_LOWERCASE}.cmake" + DESTINATION ${relative_target_source_dir}/Platform/${PAL_PLATFORM_NAME} + COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} + ) + + # 3. For this configuration permutation, generate a Platform/${PAL_PLATFORM_NAME}/${permutation}/permutation.cmake + # that will declare the target and configure it ly_setup_subdirectory_create_alias("${absolute_target_source_dir}" CREATE_ALIASES_PLACEHOLDER) ly_setup_subdirectory_set_gem_variant_to_load("${absolute_target_source_dir}" GEM_VARIANT_TO_LOAD_PLACEHOLDER) ly_setup_subdirectory_enable_gems("${absolute_target_source_dir}" ENABLE_GEMS_PLACEHOLDER) - ly_file_read(${LY_ROOT_FOLDER}/cmake/install/Copyright.in cmake_copyright_comment) - - # Initialize the target install source directory to path underneath the current binary directory - set(target_install_source_dir ${CMAKE_CURRENT_BINARY_DIR}/install/${relative_target_source_dir}) # Write out all the aggregated ly_add_target function calls and the final ly_create_alias() calls to the target CMakeLists.txt - file(WRITE ${target_install_source_dir}/CMakeLists.txt + file(WRITE "${target_install_source_dir}/Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION}/permutation.cmake" "${cmake_copyright_comment}" "${all_configured_targets}" "\n" @@ -316,9 +348,8 @@ function(ly_setup_subdirectory absolute_target_source_dir) "${GEM_VARIANT_TO_LOAD_PLACEHOLDER}" "${ENABLE_GEMS_PLACEHOLDER}" ) - - install(FILES "${target_install_source_dir}/CMakeLists.txt" - DESTINATION ${relative_target_source_dir} + install(FILES "${target_install_source_dir}/Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION}/permutation.cmake" + DESTINATION ${relative_target_source_dir}//Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) @@ -362,10 +393,10 @@ function(ly_setup_cmake_install) # Inject code that will generate each ConfigurationType_.cmake file set(install_configuration_type_template [=[ configure_file(@LY_ROOT_FOLDER@/cmake/install/ConfigurationType_config.cmake.in - ${CMAKE_INSTALL_PREFIX}/cmake/ConfigurationTypes_${CMAKE_INSTALL_CONFIG_NAME}.cmake + ${CMAKE_INSTALL_PREFIX}/cmake/Platform/@PAL_PLATFORM_NAME@/@LY_BUILD_PERMUTATION@/ConfigurationTypes_${CMAKE_INSTALL_CONFIG_NAME}.cmake @ONLY ) - message(STATUS "Generated ${CMAKE_INSTALL_PREFIX}/cmake/ConfigurationTypes_${CMAKE_INSTALL_CONFIG_NAME}.cmake") + message(STATUS "Generated ${CMAKE_INSTALL_PREFIX}/cmake/Platform/@PAL_PLATFORM_NAME@/@LY_BUILD_PERMUTATION@/ConfigurationTypes_${CMAKE_INSTALL_CONFIG_NAME}.cmake") ]=]) string(CONFIGURE "${install_configuration_type_template}" install_configuration_type @ONLY) install(CODE "${install_configuration_type}" @@ -493,6 +524,11 @@ endfunction()" endif() # runtime dependencies that need to be copied to the output + # Anywhere CMAKE_INSTALL_PREFIX is used, it has to be escaped so it is baked into the cmake_install.cmake script instead + # of baking the path. This is needed so `cmake --install --prefix ` works regardless of the CMAKE_INSTALL_PREFIX + # used to generate the solution. + # CMAKE_INSTALL_PREFIX is still used when building the INSTALL target + set(install_output_folder "\${CMAKE_INSTALL_PREFIX}/${runtime_output_directory}/${PAL_PLATFORM_NAME}/$/${LY_BUILD_PERMUTATION}") set(target_file_dir "${install_output_folder}/${target_runtime_output_subdirectory}") ly_get_runtime_dependencies(runtime_dependencies ${target}) foreach(runtime_dependency ${runtime_dependencies}) diff --git a/cmake/Platform/Mac/Install_mac.cmake b/cmake/Platform/Mac/Install_mac.cmake index f3c2b31b31..8f07b1bfde 100644 --- a/cmake/Platform/Mac/Install_mac.cmake +++ b/cmake/Platform/Mac/Install_mac.cmake @@ -54,19 +54,19 @@ function(ly_install_target_override) install( TARGETS ${ly_platform_install_target_TARGET} ARCHIVE - DESTINATION ${ly_platform_install_target_ARCHIVE_DIR}/${PAL_PLATFORM_NAME}/$ + DESTINATION ${ly_platform_install_target_ARCHIVE_DIR} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} LIBRARY - DESTINATION ${ly_platform_install_target_LIBRARY_DIR}/${PAL_PLATFORM_NAME}/$/${ly_platform_install_target_LIBRARY_SUBDIR} + DESTINATION ${ly_platform_install_target_LIBRARY_DIR}/${ly_platform_install_target_LIBRARY_SUBDIR} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} RUNTIME - DESTINATION ${ly_platform_install_target_RUNTIME_DIR}/${PAL_PLATFORM_NAME}/$/${ly_platform_install_target_RUNTIME_SUBDIR} + DESTINATION ${ly_platform_install_target_RUNTIME_DIR}/${ly_platform_install_target_RUNTIME_SUBDIR} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} BUNDLE - DESTINATION ${ly_platform_install_target_RUNTIME_DIR}/${PAL_PLATFORM_NAME}/$/${ly_platform_install_target_RUNTIME_SUBDIR} + DESTINATION ${ly_platform_install_target_RUNTIME_DIR}/${ly_platform_install_target_RUNTIME_SUBDIR} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} RESOURCE - DESTINATION ${ly_platform_install_target_RUNTIME_DIR}/${PAL_PLATFORM_NAME}/$/${ly_platform_install_target_RUNTIME_SUBDIR}/ + DESTINATION ${ly_platform_install_target_RUNTIME_DIR}/${ly_platform_install_target_RUNTIME_SUBDIR} COMPONENT ${CMAKE_INSTALL_DEFAULT_COMPONENT_NAME} ) diff --git a/cmake/install/ConfigurationTypes.cmake b/cmake/install/ConfigurationTypes.cmake index 709f3e71ab..ce0fbd7963 100644 --- a/cmake/install/ConfigurationTypes.cmake +++ b/cmake/install/ConfigurationTypes.cmake @@ -15,7 +15,16 @@ include_guard(GLOBAL) set(CMAKE_CONFIGURATION_TYPES "" CACHE STRING "" FORCE) # For the SDK case, we want to only define the confiuguration types that have been added to the SDK -file(GLOB configuration_type_files "cmake/ConfigurationTypes_*.cmake") +# We need to redeclare LY_BUILD_PERMUTATION because Configurations is one of the first things included by the +# root CMakeLists.txt. Even LY_MONOLITHIC_GAME is declared after, but since is a passed cache variable, and +# default is the same as undeclared, we can use it at this point. +if(LY_MONOLITHIC_GAME) + set(LY_BUILD_PERMUTATION Monolithic) +else() + set(LY_BUILD_PERMUTATION Default) +endif() + +file(GLOB configuration_type_files "cmake/Platform/${PAL_PLATFORM_NAME}/${LY_BUILD_PERMUTATION}/ConfigurationTypes_*.cmake") foreach(configuration_type_file ${configuration_type_files}) include(${configuration_type_file}) endforeach() diff --git a/cmake/install/InstalledTarget.in b/cmake/install/InstalledTarget.in index 2095211bb2..5022a108e8 100644 --- a/cmake/install/InstalledTarget.in +++ b/cmake/install/InstalledTarget.in @@ -23,5 +23,5 @@ ly_add_target( set(configs @CMAKE_CONFIGURATION_TYPES@) foreach(config ${configs}) - include("@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) + include("Platform/@PAL_PLATFORM_NAME@/@LY_BUILD_PERMUTATION@/@NAME_PLACEHOLDER@_${config}.cmake" OPTIONAL) endforeach() From 603e33d7f774f17c61da0335a3c8077b11b526b1 Mon Sep 17 00:00:00 2001 From: mrieggeramzn <61609885+mrieggeramzn@users.noreply.github.com> Date: Tue, 14 Sep 2021 16:10:06 -0700 Subject: [PATCH 18/26] Removing the boundary search method. (#4024) * Removing the boundary search method. Bicubic is now the default and only PCF filtering method * Removing padding (based upon feedback) * Removing PCF method from py auto testing Signed-off-by: mrieggeramzn --- ...dra_AtomEditorComponents_LightComponent.py | 2 - .../atom_renderer/test_Atom_MainSuite.py | 2 - .../Shadow/DirectionalLightShadow.azsli | 96 +++------------ .../Features/Shadow/ProjectedShadow.azsli | 109 +++--------------- .../CoreLights/ViewSrg.azsli | 4 +- ...irectionalLightFeatureProcessorInterface.h | 9 -- .../DiskLightFeatureProcessorInterface.h | 4 - .../PointLightFeatureProcessorInterface.h | 5 - .../Atom/Feature/CoreLights/ShadowConstants.h | 8 -- ...ProjectedShadowFeatureProcessorInterface.h | 4 - .../DirectionalLightFeatureProcessor.cpp | 23 ---- .../DirectionalLightFeatureProcessor.h | 4 - .../CoreLights/DiskLightFeatureProcessor.cpp | 10 -- .../CoreLights/DiskLightFeatureProcessor.h | 2 - .../CoreLights/PointLightFeatureProcessor.cpp | 10 -- .../CoreLights/PointLightFeatureProcessor.h | 2 - .../ProjectedShadowFeatureProcessor.cpp | 24 +--- .../Shadows/ProjectedShadowFeatureProcessor.h | 5 +- .../CommonFeatures/CoreLights/AreaLightBus.h | 13 --- .../CoreLights/AreaLightComponentConfig.h | 8 -- .../CoreLights/DirectionalLightBus.h | 16 --- .../DirectionalLightComponentConfig.h | 8 -- .../CoreLights/AreaLightComponentConfig.cpp | 24 ---- .../AreaLightComponentController.cpp | 36 ------ .../CoreLights/AreaLightComponentController.h | 4 - .../DirectionalLightComponentConfig.cpp | 24 ---- .../DirectionalLightComponentController.cpp | 34 ------ .../DirectionalLightComponentController.h | 4 - .../Source/CoreLights/DiskLightDelegate.cpp | 16 --- .../Source/CoreLights/DiskLightDelegate.h | 2 - .../CoreLights/EditorAreaLightComponent.cpp | 18 +-- .../EditorDirectionalLightComponent.cpp | 18 +-- .../Source/CoreLights/LightDelegateBase.h | 2 - .../CoreLights/LightDelegateInterface.h | 4 - .../Source/CoreLights/SphereLightDelegate.cpp | 16 --- .../Source/CoreLights/SphereLightDelegate.h | 2 - 36 files changed, 37 insertions(+), 535 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py index 24866f3b19..8d138e67b8 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_LightComponent.py @@ -31,8 +31,6 @@ SPHERE_AND_SPOT_DISK_LIGHT_PROPERTIES = [ ("Controller|Configuration|Shadows|Shadow filter method", 1), # PCF ("Controller|Configuration|Shadows|Filtering sample count", 4.0), ("Controller|Configuration|Shadows|Filtering sample count", 64.0), - ("Controller|Configuration|Shadows|PCF method", 0), # Bicubic - ("Controller|Configuration|Shadows|PCF method", 1), # Boundary search ("Controller|Configuration|Shadows|Shadow filter method", 2), # ECM ("Controller|Configuration|Shadows|ESM exponent", 50), ("Controller|Configuration|Shadows|ESM exponent", 5000), diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index c40dc8f178..ce496ce268 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -200,8 +200,6 @@ class TestAtomEditorComponentsMain(object): "Controller|Configuration|Shadows|Shadow filter method set to 1", # PCF "Controller|Configuration|Shadows|Filtering sample count set to 4", "Controller|Configuration|Shadows|Filtering sample count set to 64", - "Controller|Configuration|Shadows|PCF method set to 0", - "Controller|Configuration|Shadows|PCF method set to 1", "Controller|Configuration|Shadows|Shadow filter method set to 2", # ESM "Controller|Configuration|Shadows|ESM exponent set to 50.0", "Controller|Configuration|Shadows|ESM exponent set to 5000.0", diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli index 8df13bd19a..dd235fcd3a 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/DirectionalLightShadow.azsli @@ -101,7 +101,6 @@ class DirectionalLightShadow // This outputs visibility ratio (from 0.0 to 1.0) for ESM+PCF. float GetVisibilityFromLightEsmPcf(); - float SamplePcfBicubic(); float SamplePcfBicubic(float3 shadowCoord, uint indexOfCascade); uint m_lightIndex; @@ -278,70 +277,26 @@ float DirectionalLightShadow::GetVisibilityFromLightNoFilter() } float DirectionalLightShadow::GetVisibilityFromLightPcf() -{ - const uint predictionCount = ViewSrg::m_directionalLightShadows[m_lightIndex].m_predictionSampleCount; +{ + static const float DepthMargin = 0.01; // avoiding artifact when near depth bounds. + static const float PixelMargin = 1.5; // avoiding artifact between cascade levels. - if (predictionCount <= 1) + const uint size = ViewSrg::m_directionalLightShadows[m_lightIndex].m_shadowmapSize; + const uint cascadeCount = ViewSrg::m_directionalLightShadows[m_lightIndex].m_cascadeCount; + for (uint indexOfCascade = 0; indexOfCascade < cascadeCount; ++indexOfCascade) { - return GetVisibilityFromLightNoFilter(); - } + const float3 shadowCoord = m_shadowCoords[indexOfCascade]; - if (ViewSrg::m_directionalLightShadows[m_lightIndex].m_pcfFilterMethod == PcfFilterMethod_Bicubic) - { - return SamplePcfBicubic(); - } - - const float3 lightDirection = - normalize(SceneSrg::m_directionalLights[m_lightIndex].m_direction); - const float4 jitterUnitVectorDepthDiffBase = - Shadow::GetJitterUnitVectorDepthDiffBase(m_normalVector, lightDirection); - const float3 jitterUnit = jitterUnitVectorDepthDiffBase.xyz; - const float jitterDepthDiffBase = jitterUnitVectorDepthDiffBase.w; - - uint shadowedCount = 0; - uint jitterIndex = 0; - - // Predicting - for (; jitterIndex < predictionCount; ++jitterIndex) - { - if (IsShadowedWithJitter( - jitterUnit, - jitterDepthDiffBase, - jitterIndex)) + if (shadowCoord.x >= 0. && shadowCoord.x * size < size - PixelMargin && + shadowCoord.y >= 0. && shadowCoord.y * size < size - PixelMargin && + shadowCoord.z < 1. - DepthMargin) { - ++shadowedCount; + m_debugInfo.m_cascadeIndex = indexOfCascade; + return SamplePcfBicubic(shadowCoord, indexOfCascade); } } - if (shadowedCount == 0) - { - return 1.; - } - else if (shadowedCount == predictionCount) - { - return 0.; - } - - // Filtering - - // When the prediction detects the point on the boundary of shadow, - // i.e., both of a lit point and a a shadowed one exists in the jittering area, - // we calculate the more precious lit ratio in the area. - const uint filteringCount = max( - predictionCount, - ViewSrg::m_directionalLightShadows[m_lightIndex].m_filteringSampleCount); - - for (; jitterIndex < filteringCount; ++jitterIndex) - { - if (IsShadowedWithJitter( - jitterUnit, - jitterDepthDiffBase, - jitterIndex)) - { - ++shadowedCount; - } - } - - return (filteringCount - shadowedCount) * 1. / filteringCount; + m_debugInfo.m_cascadeIndex = cascadeCount; + return 1.; } float DirectionalLightShadow::GetVisibilityFromLightEsm() @@ -415,29 +370,6 @@ float DirectionalLightShadow::GetVisibilityFromLightEsmPcf() return 1.; } -float DirectionalLightShadow::SamplePcfBicubic() -{ - static const float DepthMargin = 0.01; // avoiding artifact when near depth bounds. - static const float PixelMargin = 1.5; // avoiding artifact between cascade levels. - - const uint size = ViewSrg::m_directionalLightShadows[m_lightIndex].m_shadowmapSize; - const uint cascadeCount = ViewSrg::m_directionalLightShadows[m_lightIndex].m_cascadeCount; - for (uint indexOfCascade = 0; indexOfCascade < cascadeCount; ++indexOfCascade) - { - const float3 shadowCoord = m_shadowCoords[indexOfCascade]; - - if (shadowCoord.x >= 0. && shadowCoord.x * size < size - PixelMargin && - shadowCoord.y >= 0. && shadowCoord.y * size < size - PixelMargin && - shadowCoord.z < 1. - DepthMargin) - { - m_debugInfo.m_cascadeIndex = indexOfCascade; - return SamplePcfBicubic(shadowCoord, indexOfCascade); - } - } - m_debugInfo.m_cascadeIndex = cascadeCount; - return 1.; -} - float DirectionalLightShadow::SamplePcfBicubic(float3 shadowCoord, uint indexOfCascade) { const uint filteringSampleCount = ViewSrg::m_directionalLightShadows[m_lightIndex].m_filteringSampleCount; diff --git a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli index 2fea4650b3..899fbb1553 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderLib/Atom/Features/Shadow/ProjectedShadow.azsli @@ -44,8 +44,6 @@ class ProjectedShadow float GetVisibilityEsmPcf(); float GetThickness(); - float SamplePcfBicubic(); - bool IsShadowed(float3 shadowPosition); bool IsShadowedWithJitter( float3 jitterUnitX, @@ -87,8 +85,7 @@ float ProjectedShadow::GetVisibility( shadow.SetShadowPosition(); float visibility = 1.; - // Filter method is stored in top 16 bits. - uint filterMethod = ViewSrg::m_projectedShadows[shadow.m_shadowIndex].m_shadowFilterMethod & 0x0000FFFF; + const uint filterMethod = ViewSrg::m_projectedShadows[shadow.m_shadowIndex].m_shadowFilterMethod; switch (filterMethod) { case ViewSrg::ShadowFilterMethodNone: @@ -145,72 +142,29 @@ float ProjectedShadow::GetVisibilityNoFilter() float ProjectedShadow::GetVisibilityPcf() { - // PCF filter method is stored in bottom 16 bits. - const uint pcfFilterMethod = ViewSrg::m_projectedShadows[m_shadowIndex].m_shadowFilterMethod >> 16; - if (pcfFilterMethod == PcfFilterMethod_Bicubic) + const uint filteringSampleCount = ViewSrg::m_projectedShadows[m_shadowIndex].m_filteringSampleCount; + const float3 atlasPosition = GetAtlasPosition(m_shadowPosition.xy); + + SampleShadowMapBicubicParameters param; + param.shadowMap = PassSrg::m_projectedShadowmaps; + param.shadowPos = float3(atlasPosition.xy * ViewSrg::m_invShadowmapAtlasSize, atlasPosition.z); + param.shadowMapSize = ViewSrg::m_shadowmapAtlasSize; + param.invShadowMapSize = ViewSrg::m_invShadowmapAtlasSize; + param.comparisonValue = m_shadowPosition.z - m_bias; + param.samplerState = SceneSrg::m_hwPcfSampler; + + if (filteringSampleCount <= 4) { - return SamplePcfBicubic(); + return SampleShadowMapBicubic_4Tap(param); } - - const uint predictionCount = ViewSrg::m_projectedShadows[m_shadowIndex].m_predictionSampleCount; - - if (predictionCount <= 1) + else if (filteringSampleCount <= 9) { - return GetVisibilityNoFilter(); + return SampleShadowMapBicubic_9Tap(param); } - - const float4 jitterUnitVectorDepthDiffBase = - Shadow::GetJitterUnitVectorDepthDiffBase(m_normalVector, m_lightDirection); - const float3 jitterUnitY = jitterUnitVectorDepthDiffBase.xyz; - const float3 jitterUnitX = cross(jitterUnitY, m_lightDirection); - const float jitterDepthDiffBase = jitterUnitVectorDepthDiffBase.w; - - uint shadowedCount = 0; - uint jitterIndex = 0; - - // Predicting - for (; jitterIndex < predictionCount; ++jitterIndex) + else { - if (IsShadowedWithJitter( - jitterUnitX, - jitterUnitY, - jitterDepthDiffBase, - jitterIndex)) - { - ++shadowedCount; - } + return SampleShadowMapBicubic_16Tap(param); } - if (shadowedCount == 0) - { - return 1.; - } - else if (shadowedCount == predictionCount) - { - return 0.; - } - - // Filtering - - // When the prediction detects the point on the boundary of shadow, - // i.e., both of a lit point and a a shadowed one exists in the jittering area, - // we calculate the more precious lit ratio in the area. - const uint filteringCount = max( - predictionCount, - ViewSrg::m_projectedShadows[m_shadowIndex].m_filteringSampleCount); - - for (; jitterIndex < filteringCount; ++jitterIndex) - { - if (IsShadowedWithJitter( - jitterUnitX, - jitterUnitY, - jitterDepthDiffBase, - jitterIndex)) - { - ++shadowedCount; - } - } - - return (filteringCount - shadowedCount) * 1. / filteringCount; } float ProjectedShadow::GetVisibilityEsm() @@ -337,33 +291,6 @@ float ProjectedShadow::GetThickness() return 0.; } -float ProjectedShadow::SamplePcfBicubic() -{ - const uint filteringSampleCount = ViewSrg::m_projectedShadows[m_shadowIndex].m_filteringSampleCount; - const float3 atlasPosition = GetAtlasPosition(m_shadowPosition.xy); - - SampleShadowMapBicubicParameters param; - param.shadowMap = PassSrg::m_projectedShadowmaps; - param.shadowPos = float3(atlasPosition.xy * ViewSrg::m_invShadowmapAtlasSize, atlasPosition.z); - param.shadowMapSize = ViewSrg::m_shadowmapAtlasSize; - param.invShadowMapSize = ViewSrg::m_invShadowmapAtlasSize; - param.comparisonValue = m_shadowPosition.z - m_bias; - param.samplerState = SceneSrg::m_hwPcfSampler; - - if (filteringSampleCount <= 4) - { - return SampleShadowMapBicubic_4Tap(param); - } - else if (filteringSampleCount <= 9) - { - return SampleShadowMapBicubic_9Tap(param); - } - else - { - return SampleShadowMapBicubic_16Tap(param); - } -} - bool ProjectedShadow::IsShadowed(float3 shadowPosition) { static const float PixelMargin = 1.5; // avoiding artifact between cascade levels. diff --git a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli index 01e5f3e61c..2065e28703 100644 --- a/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli +++ b/Gems/Atom/Feature/Common/Assets/ShaderResourceGroups/CoreLights/ViewSrg.azsli @@ -82,7 +82,7 @@ partial ShaderResourceGroup ViewSrg { float4x4 m_depthBiasMatrix; uint m_shadowmapArraySlice; // array slice who has shadowmap in the atlas. - uint m_shadowFilterMethod; // Includes overall filter method in top 16 bits and pcf method in bottom 16 bits. + uint m_shadowFilterMethod; float m_boundaryScale; uint m_predictionSampleCount; uint m_filteringSampleCount; @@ -117,8 +117,6 @@ partial ShaderResourceGroup ViewSrg uint m_debugFlags; uint m_shadowFilterMethod; float m_far_minus_near; - uint m_pcfFilterMethod; // Matches with PcfFilterMethod in ShadowConstants.h - uint m_padding[3]; }; enum ShadowFilterMethod diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h index 3244c8249e..75d266cc52 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DirectionalLightFeatureProcessorInterface.h @@ -149,12 +149,6 @@ namespace AZ //! @param method filter method. virtual void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) = 0; - //! This sets sample count to predict boundary of shadow. - //! @param handle the light handle. - //! @param count Sample Count for prediction of whether the pixel is on the boundary (up to 16) - //! The value should be less than or equal to m_filteringSampleCount. - virtual void SetPredictionSampleCount(LightHandle handle, uint16_t count) = 0; - //! This sets sample count for filtering of shadow boundary. //! @param handle the light handle. //! @param count Sample Count for filtering (up to 64) @@ -166,9 +160,6 @@ namespace AZ //! If width == 0, softening edge is disabled. Units are in meters. virtual void SetShadowBoundaryWidth(LightHandle handle, float boundaryWidth) = 0; - //! Sets the shadowmap Pcf method. - virtual void SetPcfMethod(LightHandle handle, PcfMethod method) = 0; - //! Sets whether the directional shadowmap should use receiver plane bias. //! This attempts to reduce shadow acne when using large pcf filters. virtual void SetShadowReceiverPlaneBiasEnabled(LightHandle handle, bool enable) = 0; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h index bcb470d831..3ab83200ae 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/DiskLightFeatureProcessorInterface.h @@ -92,12 +92,8 @@ namespace AZ virtual void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) = 0; //! Specifies the width of boundary between shadowed area and lit area in radians. The degree ofshadowed gradually changes on the boundary. 0 disables softening. virtual void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) = 0; - //! Sets sample count to predict boundary of shadow (up to 16). It will be clamped to be less than or equal to the filtering sample count. - virtual void SetPredictionSampleCount(LightHandle handle, uint16_t count) = 0; //! Sets sample count for filtering of shadow boundary (up to 64) virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; - //! Sets the shadowmap Pcf (percentage closer filtering) method. - virtual void SetPcfMethod(LightHandle handle, PcfMethod method) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff in the border areas between light and shadow. virtual void SetEsmExponent(LightHandle handle, float exponent) = 0; diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h index 3383378dc7..6752ac4c52 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/PointLightFeatureProcessorInterface.h @@ -73,13 +73,8 @@ namespace AZ //! Specifies the width of boundary between shadowed area and lit area in radians. The degree ofshadowed gradually changes on //! the boundary. 0 disables softening. virtual void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) = 0; - //! Sets sample count to predict boundary of shadow (up to 16). It will be clamped to be less than or equal to the filtering - //! sample count. - virtual void SetPredictionSampleCount(LightHandle handle, uint16_t count) = 0; //! Sets sample count for filtering of shadow boundary (up to 64) virtual void SetFilteringSampleCount(LightHandle handle, uint16_t count) = 0; - //! Sets the shadowmap Pcf (percentage closer filtering) method. - virtual void SetPcfMethod(LightHandle handle, PcfMethod method) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff in the border areas between light and shadow. virtual void SetEsmExponent(LightHandle handle, float exponent) = 0; //! Sets all of the the point data for the provided LightHandle. diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h index 2d0811be9e..dbad3af21f 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/CoreLights/ShadowConstants.h @@ -37,14 +37,6 @@ namespace AZ Count }; - enum class PcfMethod : uint16_t - { - BoundarySearch = 0, // Performs a variable number of taps, first to determine if we are on a shadow boundary, then the remaining taps are to find the occlusion amount - Bicubic, // Uses a fixed size Pcf kernel with kernel weights set to approximate bicubic filtering - - Count - }; - namespace Shadow { // [GFX TODO][ATOM-2408] Make the max number of cascade modifiable at runtime. diff --git a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h index 6cbb0cfef1..3d6c0c3015 100644 --- a/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h +++ b/Gems/Atom/Feature/Common/Code/Include/Atom/Feature/Shadows/ProjectedShadowFeatureProcessorInterface.h @@ -52,14 +52,10 @@ namespace AZ::Render virtual void SetShadowmapMaxResolution(ShadowId id, ShadowmapSize size) = 0; //! Sets the shadow bias virtual void SetShadowBias(ShadowId id, float bias) = 0; - //! Sets the shadowmap Pcf method. - virtual void SetPcfMethod(ShadowId id, PcfMethod method) = 0; //! Sets the shadow filter method virtual void SetShadowFilterMethod(ShadowId id, ShadowFilterMethod method) = 0; //! Sets the width of boundary between shadowed area and lit area. virtual void SetSofteningBoundaryWidthAngle(ShadowId id, float boundaryWidthRadians) = 0; - //! Sets the sample count to predict the boundary of the shadow. Max 16, should be less than filtering sample count. - virtual void SetPredictionSampleCount(ShadowId id, uint16_t count) = 0; //! Sets the sample count for filtering of the shadow boundary, max 64. virtual void SetFilteringSampleCount(ShadowId id, uint16_t count) = 0; //! Sets all of the shadow properites in one call diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp index 44f95a8b85..c235f78595 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.cpp @@ -571,20 +571,6 @@ namespace AZ } } - void DirectionalLightFeatureProcessor::SetPredictionSampleCount(LightHandle handle, uint16_t count) - { - if (count > Shadow::MaxPcfSamplingCount) - { - AZ_Warning(FeatureProcessorName, false, "Sampling count exceed the limit."); - count = Shadow::MaxPcfSamplingCount; - } - for (auto& it : m_shadowData) - { - it.second.GetData(handle.GetIndex()).m_predictionSampleCount = count; - } - m_shadowBufferNeedsUpdate = true; - } - void DirectionalLightFeatureProcessor::SetFilteringSampleCount(LightHandle handle, uint16_t count) { if (count > Shadow::MaxPcfSamplingCount) @@ -608,15 +594,6 @@ namespace AZ m_shadowBufferNeedsUpdate = true; } - void DirectionalLightFeatureProcessor::SetPcfMethod(LightHandle handle, PcfMethod method) - { - for (auto& it : m_shadowData) - { - it.second.GetData(handle.GetIndex()).m_pcfMethod = method; - } - m_shadowBufferNeedsUpdate = true; - } - void DirectionalLightFeatureProcessor::SetShadowReceiverPlaneBiasEnabled(LightHandle handle, bool enable) { m_shadowProperties.GetData(handle.GetIndex()).m_isReceiverPlaneBiasEnabled = enable; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h index d57b3aaf2b..039f51d549 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DirectionalLightFeatureProcessor.h @@ -102,8 +102,6 @@ namespace AZ uint32_t m_debugFlags = 0; uint32_t m_shadowFilterMethod = 0; float m_far_minus_near = 0; - PcfMethod m_pcfMethod = PcfMethod::BoundarySearch; - uint32_t m_padding[3]; }; class DirectionalLightFeatureProcessor final @@ -218,10 +216,8 @@ namespace AZ void SetViewFrustumCorrectionEnabled(LightHandle handle, bool enabled) override; void SetDebugFlags(LightHandle handle, DebugDrawFlags flags) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; - void SetPredictionSampleCount(LightHandle handle, uint16_t count) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; void SetShadowBoundaryWidth(LightHandle handle, float boundaryWidth) override; - void SetPcfMethod(LightHandle handle, PcfMethod method) override; void SetShadowReceiverPlaneBiasEnabled(LightHandle handle, bool enable) override; const Data::Instance GetLightBuffer() const; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp index 55be9d232e..dfbeea0ffe 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.cpp @@ -329,21 +329,11 @@ namespace AZ SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetSofteningBoundaryWidthAngle, boundaryWidthRadians); } - void DiskLightFeatureProcessor::SetPredictionSampleCount(LightHandle handle, uint16_t count) - { - SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetPredictionSampleCount, count); - } - void DiskLightFeatureProcessor::SetFilteringSampleCount(LightHandle handle, uint16_t count) { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetFilteringSampleCount, count); } - void DiskLightFeatureProcessor::SetPcfMethod(LightHandle handle, PcfMethod method) - { - SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetPcfMethod, method); - } - void DiskLightFeatureProcessor::SetEsmExponent(LightHandle handle, float exponent) { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetEsmExponent, exponent); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h index 36837a67fb..d65f587718 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/DiskLightFeatureProcessor.h @@ -54,9 +54,7 @@ namespace AZ void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; - void SetPredictionSampleCount(LightHandle handle, uint16_t count) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; - void SetPcfMethod(LightHandle handle, PcfMethod method) override; void SetEsmExponent(LightHandle handle, float esmExponent) override; void SetDiskData(LightHandle handle, const DiskLightData& data) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp index 9baa2ae1c2..af440e5040 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.cpp @@ -298,21 +298,11 @@ namespace AZ SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetSofteningBoundaryWidthAngle, boundaryWidthRadians); } - void PointLightFeatureProcessor::SetPredictionSampleCount(LightHandle handle, uint16_t count) - { - SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetPredictionSampleCount, count); - } - void PointLightFeatureProcessor::SetFilteringSampleCount(LightHandle handle, uint16_t count) { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetFilteringSampleCount, count); } - void PointLightFeatureProcessor::SetPcfMethod(LightHandle handle, PcfMethod method) - { - SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetPcfMethod, method); - } - void PointLightFeatureProcessor::SetEsmExponent(LightHandle handle, float esmExponent) { SetShadowSetting(handle, &ProjectedShadowFeatureProcessor::SetEsmExponent, esmExponent); diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h index 3c231c1fb0..b784eb1bb5 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/PointLightFeatureProcessor.h @@ -51,9 +51,7 @@ namespace AZ void SetShadowmapMaxResolution(LightHandle handle, ShadowmapSize shadowmapSize) override; void SetShadowFilterMethod(LightHandle handle, ShadowFilterMethod method) override; void SetSofteningBoundaryWidthAngle(LightHandle handle, float boundaryWidthRadians) override; - void SetPredictionSampleCount(LightHandle handle, uint16_t count) override; void SetFilteringSampleCount(LightHandle handle, uint16_t count) override; - void SetPcfMethod(LightHandle handle, PcfMethod method) override; void SetEsmExponent(LightHandle handle, float esmExponent) override; void SetPointData(LightHandle handle, const PointLightData& data) override; diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp index 68dac8f773..68c31bd859 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.cpp @@ -165,15 +165,6 @@ namespace AZ::Render m_filterParameterNeedsUpdate = true; } - void ProjectedShadowFeatureProcessor::SetPcfMethod(ShadowId id, PcfMethod method) - { - AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetPcfMethod()."); - ShadowData& shadowData = m_shadowData.GetElement(id.GetIndex()); - shadowData.m_pcfMethod = method; - - m_deviceBufferNeedsUpdate = true; - } - void ProjectedShadowFeatureProcessor::SetEsmExponent(ShadowId id, float exponent) { AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetEsmExponent()."); @@ -188,7 +179,7 @@ namespace AZ::Render ShadowProperty& shadowProperty = GetShadowPropertyFromShadowId(id); ShadowData& shadowData = m_shadowData.GetElement(id.GetIndex()); - shadowData.m_shadowFilterMethod = aznumeric_cast(method); + shadowData.m_shadowFilterMethod = aznumeric_cast(method); UpdateShadowView(shadowProperty); @@ -207,19 +198,6 @@ namespace AZ::Render m_filterParameterNeedsUpdate = true; } - void ProjectedShadowFeatureProcessor::SetPredictionSampleCount(ShadowId id, uint16_t count) - { - AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetPredictionSampleCount()."); - - AZ_Warning("ProjectedShadowFeatureProcessor", count <= Shadow::MaxPcfSamplingCount, "Sampling count exceed the limit."); - count = GetMin(count, Shadow::MaxPcfSamplingCount); - - ShadowData& shadowData = m_shadowData.GetElement(id.GetIndex()); - shadowData.m_predictionSampleCount = count; - - m_deviceBufferNeedsUpdate = true; - } - void ProjectedShadowFeatureProcessor::SetFilteringSampleCount(ShadowId id, uint16_t count) { AZ_Assert(id.IsValid(), "Invalid ShadowId passed to ProjectedShadowFeatureProcessor::SetFilteringSampleCount()."); diff --git a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h index 8beed800b6..f4c6cad7bf 100644 --- a/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h +++ b/Gems/Atom/Feature/Common/Code/Source/Shadows/ProjectedShadowFeatureProcessor.h @@ -48,11 +48,9 @@ namespace AZ::Render void SetFieldOfViewY(ShadowId id, float fieldOfViewYRadians) override; void SetShadowmapMaxResolution(ShadowId id, ShadowmapSize size) override; void SetShadowBias(ShadowId id, float bias) override; - void SetPcfMethod(ShadowId id, PcfMethod method); void SetEsmExponent(ShadowId id, float exponent); void SetShadowFilterMethod(ShadowId id, ShadowFilterMethod method) override; void SetSofteningBoundaryWidthAngle(ShadowId id, float boundaryWidthRadians) override; - void SetPredictionSampleCount(ShadowId id, uint16_t count) override; void SetFilteringSampleCount(ShadowId id, uint16_t count) override; void SetShadowProperties(ShadowId id, const ProjectedShadowDescriptor& descriptor) override; const ProjectedShadowDescriptor& GetShadowProperties(ShadowId id) override; @@ -64,8 +62,7 @@ namespace AZ::Render { Matrix4x4 m_depthBiasMatrix = Matrix4x4::CreateIdentity(); uint32_t m_shadowmapArraySlice = 0; // array slice who has shadowmap in the atlas. - uint16_t m_shadowFilterMethod = 0; // filtering method of shadows. - PcfMethod m_pcfMethod = PcfMethod::BoundarySearch; // method for performing Pcf (uint16_t) + uint32_t m_shadowFilterMethod = 0; // filtering method of shadows. float m_boundaryScale = 0.f; // the half of boundary of lit/shadowed areas. (in degrees) uint32_t m_predictionSampleCount = 0; // sample count to judge whether it is on the shadow boundary or not. uint32_t m_filteringSampleCount = 0; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h index 06b00a6b84..557e6b3dd2 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightBus.h @@ -127,25 +127,12 @@ namespace AZ //! 0 disables softening. virtual void SetSofteningBoundaryWidthAngle(float degrees) = 0; - //! Gets the sample count to predict boundary of shadow. - virtual uint32_t GetPredictionSampleCount() const = 0; - - //! Sets the sample count to predict boundary of shadow. Maximum 16, and should also be - //! less than the filtering sample count. - virtual void SetPredictionSampleCount(uint32_t count) = 0; - //! Gets the sample count for filtering of the shadow boundary. virtual uint32_t GetFilteringSampleCount() const = 0; //! Sets the sample count for filtering of the shadow boundary. Maximum 64. virtual void SetFilteringSampleCount(uint32_t count) = 0; - //! Gets the type of Pcf (percentage-closer filtering) to use. - virtual PcfMethod GetPcfMethod() const = 0; - - //! Sets the type of Pcf (percentage-closer filtering) to use. - virtual void SetPcfMethod(PcfMethod method) = 0; - //! Gets the Esm exponent. Higher values produce a steeper falloff between light and shadow. virtual float GetEsmExponent() const = 0; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h index 74eb10fdb6..a6d3c6fbed 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/AreaLightComponentConfig.h @@ -59,9 +59,7 @@ namespace AZ float m_bias = 0.1f; ShadowmapSize m_shadowmapMaxSize = ShadowmapSize::Size256; ShadowFilterMethod m_shadowFilterMethod = ShadowFilterMethod::None; - PcfMethod m_pcfMethod = PcfMethod::Bicubic; float m_boundaryWidthInDegrees = 0.25f; - uint16_t m_predictionSampleCount = 4; uint16_t m_filteringSampleCount = 12; float m_esmExponent = 87.0f; @@ -119,14 +117,8 @@ namespace AZ //! Returns true if pcf shadows are disabled. bool IsShadowPcfDisabled() const; - //! Returns true if pcf boundary search is disabled. - bool IsPcfBoundarySearchDisabled() const; - //! Returns true if exponential shadow maps are disabled. bool IsEsmDisabled() const; - - //! Returns true if the softening boundary width parameter is disabled. - bool IsSofteningBoundaryWidthDisabled() const; }; } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h index 610578ee2d..644856e768 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightBus.h @@ -162,15 +162,6 @@ namespace AZ //! If width == 0, softening edge is disabled. Units are in meters. virtual void SetSofteningBoundaryWidth(float width) = 0; - //! This gets sample count to predict boundary of shadow. - //! @return Sample Count for prediction of whether the pixel is on the boundary (up to 16) - virtual uint32_t GetPredictionSampleCount() const = 0; - - //! This sets sample count to predict boundary of shadow. - //! @param count Sample Count for prediction of whether the pixel is on the boundary (up to 16) - //! The value should be less than or equal to m_filteringSampleCount. - virtual void SetPredictionSampleCount(uint32_t count) = 0; - //! This gets the sample count for filtering of the shadow boundary. //! @return Sample Count for filtering (up to 64) virtual uint32_t GetFilteringSampleCount() const = 0; @@ -179,13 +170,6 @@ namespace AZ //! @param count Sample Count for filtering (up to 64) virtual void SetFilteringSampleCount(uint32_t count) = 0; - //! This gets the type of Pcf (percentage-closer filtering) to use. - virtual PcfMethod GetPcfMethod() const = 0; - - //! This sets the type of Pcf (percentage-closer filtering) to use. - //! @param method The Pcf method to use. - virtual void SetPcfMethod(PcfMethod method) = 0; - //! Gets whether the directional shadowmap should use receiver plane bias. //! This attempts to reduce shadow acne when using large pcf filters. virtual bool GetShadowReceiverPlaneBiasEnabled() const = 0; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h index e9e5778086..0123d06275 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Include/AtomLyIntegration/CommonFeatures/CoreLights/DirectionalLightComponentConfig.h @@ -105,16 +105,10 @@ namespace AZ //! If this is 0, edge softening is disabled. Units are in meters. float m_boundaryWidth = 0.03f; // 3cm - //! Sample Count for prediction of whether the pixel is on the boundary (from 4 to 16) - //! The value should be less than or equal to m_filteringSampleCount. - uint16_t m_predictionSampleCount = 4; - //! Sample Count for filtering (from 4 to 64) //! It is used only when the pixel is predicted as on the boundary. uint16_t m_filteringSampleCount = 32; - PcfMethod m_pcfMethod = PcfMethod::Bicubic; - //! Whether not to enable the receiver plane bias. //! This uses partial derivatives to reduce shadow acne when using large pcf kernels. bool m_receiverPlaneBiasEnabled = true; @@ -124,8 +118,6 @@ namespace AZ bool IsCascadeCorrectionDisabled() const; bool IsShadowFilteringDisabled() const; bool IsShadowPcfDisabled() const; - bool IsPcfBoundarySearchDisabled() const; - bool IsSofteningBoundaryWidthDisabled() const; bool IsEsmDisabled() const; }; } // namespace Render diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp index 550a09469f..c7af44a28e 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentConfig.cpp @@ -37,9 +37,7 @@ namespace AZ ->Field("Shadowmap Max Size", &AreaLightComponentConfig::m_shadowmapMaxSize) ->Field("Shadow Filter Method", &AreaLightComponentConfig::m_shadowFilterMethod) ->Field("Softening Boundary Width", &AreaLightComponentConfig::m_boundaryWidthInDegrees) - ->Field("Prediction Sample Count", &AreaLightComponentConfig::m_predictionSampleCount) ->Field("Filtering Sample Count", &AreaLightComponentConfig::m_filteringSampleCount) - ->Field("Pcf Method", &AreaLightComponentConfig::m_pcfMethod) ->Field("Esm Exponent", &AreaLightComponentConfig::m_esmExponent) ; } @@ -182,31 +180,9 @@ namespace AZ m_shadowFilterMethod == ShadowFilterMethod::EsmPcf); } - bool AreaLightComponentConfig::IsPcfBoundarySearchDisabled() const - { - if (IsShadowPcfDisabled()) - { - return true; - } - - return m_pcfMethod != PcfMethod::BoundarySearch; - } - bool AreaLightComponentConfig::IsEsmDisabled() const { return !(m_shadowFilterMethod == ShadowFilterMethod::Esm || m_shadowFilterMethod == ShadowFilterMethod::EsmPcf); } - - bool AreaLightComponentConfig::IsSofteningBoundaryWidthDisabled() const - { - // softening boundary width is always available with ESM. It controls the width of the blur kernel during the ESM gaussian - // blur passes - if (!IsEsmDisabled()) - return false; - - // with PCF, softening boundary width is used with the boundary search method and NOT the bicubic pcf methods - return IsPcfBoundarySearchDisabled(); - } - } } diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp index 0a5598a74a..c0204ecac5 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.cpp @@ -76,12 +76,8 @@ namespace AZ::Render ->Event("SetShadowFilterMethod", &AreaLightRequestBus::Events::SetShadowFilterMethod) ->Event("GetSofteningBoundaryWidthAngle", &AreaLightRequestBus::Events::GetSofteningBoundaryWidthAngle) ->Event("SetSofteningBoundaryWidthAngle", &AreaLightRequestBus::Events::SetSofteningBoundaryWidthAngle) - ->Event("GetPredictionSampleCount", &AreaLightRequestBus::Events::GetPredictionSampleCount) - ->Event("SetPredictionSampleCount", &AreaLightRequestBus::Events::SetPredictionSampleCount) ->Event("GetFilteringSampleCount", &AreaLightRequestBus::Events::GetFilteringSampleCount) ->Event("SetFilteringSampleCount", &AreaLightRequestBus::Events::SetFilteringSampleCount) - ->Event("GetPcfMethod", &AreaLightRequestBus::Events::GetPcfMethod) - ->Event("SetPcfMethod", &AreaLightRequestBus::Events::SetPcfMethod) ->Event("GetEsmExponent", &AreaLightRequestBus::Events::GetEsmExponent) ->Event("SetEsmExponent", &AreaLightRequestBus::Events::SetEsmExponent) @@ -100,9 +96,7 @@ namespace AZ::Render ->VirtualProperty("ShadowmapMaxSize", "GetShadowmapMaxSize", "SetShadowmapMaxSize") ->VirtualProperty("ShadowFilterMethod", "GetShadowFilterMethod", "SetShadowFilterMethod") ->VirtualProperty("SofteningBoundaryWidthAngle", "GetSofteningBoundaryWidthAngle", "SetSofteningBoundaryWidthAngle") - ->VirtualProperty("PredictionSampleCount", "GetPredictionSampleCount", "SetPredictionSampleCount") ->VirtualProperty("FilteringSampleCount", "GetFilteringSampleCount", "SetFilteringSampleCount") - ->VirtualProperty("PcfMethod", "GetPcfMethod", "SetPcfMethod") ->VirtualProperty("EsmExponent", "GetEsmExponent", "SetEsmExponent"); ; } @@ -314,9 +308,7 @@ namespace AZ::Render m_lightShapeDelegate->SetShadowmapMaxSize(m_configuration.m_shadowmapMaxSize); m_lightShapeDelegate->SetShadowFilterMethod(m_configuration.m_shadowFilterMethod); m_lightShapeDelegate->SetSofteningBoundaryWidthAngle(m_configuration.m_boundaryWidthInDegrees); - m_lightShapeDelegate->SetPredictionSampleCount(m_configuration.m_predictionSampleCount); m_lightShapeDelegate->SetFilteringSampleCount(m_configuration.m_filteringSampleCount); - m_lightShapeDelegate->SetPcfMethod(m_configuration.m_pcfMethod); m_lightShapeDelegate->SetEsmExponent(m_configuration.m_esmExponent); } } @@ -528,20 +520,6 @@ namespace AZ::Render } } - uint32_t AreaLightComponentController::GetPredictionSampleCount() const - { - return m_configuration.m_predictionSampleCount; - } - - void AreaLightComponentController::SetPredictionSampleCount(uint32_t count) - { - m_configuration.m_predictionSampleCount = static_cast(count); - if (m_lightShapeDelegate) - { - m_lightShapeDelegate->SetPredictionSampleCount(count); - } - } - uint32_t AreaLightComponentController::GetFilteringSampleCount() const { return m_configuration.m_filteringSampleCount; @@ -568,20 +546,6 @@ namespace AZ::Render m_lightShapeDelegate->DrawDebugDisplay(transform, m_configuration.m_color, debugDisplay, isSelected); } } - - PcfMethod AreaLightComponentController::GetPcfMethod() const - { - return m_configuration.m_pcfMethod; - } - - void AreaLightComponentController::SetPcfMethod(PcfMethod method) - { - m_configuration.m_pcfMethod = method; - if (m_lightShapeDelegate) - { - m_lightShapeDelegate->SetPcfMethod(method); - } - } float AreaLightComponentController::GetEsmExponent() const { diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h index d290beb81d..3bec61551f 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/AreaLightComponentController.h @@ -84,12 +84,8 @@ namespace AZ void SetShadowFilterMethod(ShadowFilterMethod method) override; float GetSofteningBoundaryWidthAngle() const override; void SetSofteningBoundaryWidthAngle(float width) override; - uint32_t GetPredictionSampleCount() const override; - void SetPredictionSampleCount(uint32_t count) override; uint32_t GetFilteringSampleCount() const override; void SetFilteringSampleCount(uint32_t count) override; - PcfMethod GetPcfMethod() const override; - void SetPcfMethod(PcfMethod method) override; float GetEsmExponent() const override; void SetEsmExponent(float exponent) override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp index 24ce566fb4..37d94f5ed1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentConfig.cpp @@ -38,9 +38,7 @@ namespace AZ ->Field("IsDebugColoringEnabled", &DirectionalLightComponentConfig::m_isDebugColoringEnabled) ->Field("ShadowFilterMethod", &DirectionalLightComponentConfig::m_shadowFilterMethod) ->Field("SofteningBoundaryWidth", &DirectionalLightComponentConfig::m_boundaryWidth) - ->Field("PcfPredictionSampleCount", &DirectionalLightComponentConfig::m_predictionSampleCount) ->Field("PcfFilteringSampleCount", &DirectionalLightComponentConfig::m_filteringSampleCount) - ->Field("Pcf Method", &DirectionalLightComponentConfig::m_pcfMethod) ->Field("ShadowReceiverPlaneBiasEnabled", &DirectionalLightComponentConfig::m_receiverPlaneBiasEnabled); } } @@ -118,31 +116,9 @@ namespace AZ m_shadowFilterMethod == ShadowFilterMethod::EsmPcf); } - bool DirectionalLightComponentConfig::IsPcfBoundarySearchDisabled() const - { - if (IsShadowPcfDisabled()) - { - return true; - } - - return m_pcfMethod != PcfMethod::BoundarySearch; - } - bool DirectionalLightComponentConfig::IsEsmDisabled() const { return !(m_shadowFilterMethod == ShadowFilterMethod::Esm || m_shadowFilterMethod == ShadowFilterMethod::EsmPcf); } - - bool DirectionalLightComponentConfig::IsSofteningBoundaryWidthDisabled() const - { - // softening boundary width is always available with ESM. It controls the width of the blur kernel during the ESM gaussian - // blur passes - if (!IsEsmDisabled()) - return false; - - // with PCF, softening boundary width is used with the boundary search method and NOT the bicubic pcf methods - return IsPcfBoundarySearchDisabled(); - } - } // namespace Render } // namespace AZ diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp index 6bf449803b..fbc1ccc35d 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.cpp @@ -82,12 +82,8 @@ namespace AZ ->Event("SetShadowFilterMethod", &DirectionalLightRequestBus::Events::SetShadowFilterMethod) ->Event("GetSofteningBoundaryWidth", &DirectionalLightRequestBus::Events::GetSofteningBoundaryWidth) ->Event("SetSofteningBoundaryWidth", &DirectionalLightRequestBus::Events::SetSofteningBoundaryWidth) - ->Event("GetPredictionSampleCount", &DirectionalLightRequestBus::Events::GetPredictionSampleCount) - ->Event("SetPredictionSampleCount", &DirectionalLightRequestBus::Events::SetPredictionSampleCount) ->Event("GetFilteringSampleCount", &DirectionalLightRequestBus::Events::GetFilteringSampleCount) ->Event("SetFilteringSampleCount", &DirectionalLightRequestBus::Events::SetFilteringSampleCount) - ->Event("GetPcfMethod", &DirectionalLightRequestBus::Events::GetPcfMethod) - ->Event("SetPcfMethod", &DirectionalLightRequestBus::Events::SetPcfMethod) ->Event("GetShadowReceiverPlaneBiasEnabled", &DirectionalLightRequestBus::Events::GetShadowReceiverPlaneBiasEnabled) ->Event("SetShadowReceiverPlaneBiasEnabled", &DirectionalLightRequestBus::Events::SetShadowReceiverPlaneBiasEnabled) ->VirtualProperty("Color", "GetColor", "SetColor") @@ -104,9 +100,7 @@ namespace AZ ->VirtualProperty("DebugColoringEnabled", "GetDebugColoringEnabled", "SetDebugColoringEnabled") ->VirtualProperty("ShadowFilterMethod", "GetShadowFilterMethod", "SetShadowFilterMethod") ->VirtualProperty("SofteningBoundaryWidth", "GetSofteningBoundaryWidth", "SetSofteningBoundaryWidth") - ->VirtualProperty("PredictionSampleCount", "GetPredictionSampleCount", "SetPredictionSampleCount") ->VirtualProperty("FilteringSampleCount", "GetFilteringSampleCount", "SetFilteringSampleCount") - ->VirtualProperty("PcfMethod", "GetPcfMethod", "SetPcfMethod") ->VirtualProperty("ShadowReceiverPlaneBiasEnabled", "GetShadowReceiverPlaneBiasEnabled", "SetShadowReceiverPlaneBiasEnabled"); ; } @@ -425,21 +419,6 @@ namespace AZ } } - uint32_t DirectionalLightComponentController::GetPredictionSampleCount() const - { - return aznumeric_cast(m_configuration.m_predictionSampleCount); - } - - void DirectionalLightComponentController::SetPredictionSampleCount(uint32_t count) - { - const uint16_t count16 = GetMin(Shadow::MaxPcfSamplingCount, aznumeric_cast(count)); - m_configuration.m_predictionSampleCount = count16; - if (m_featureProcessor) - { - m_featureProcessor->SetPredictionSampleCount(m_lightHandle, count16); - } - } - uint32_t DirectionalLightComponentController::GetFilteringSampleCount() const { return aznumeric_cast(m_configuration.m_filteringSampleCount); @@ -539,9 +518,7 @@ namespace AZ SetDebugColoringEnabled(m_configuration.m_isDebugColoringEnabled); SetShadowFilterMethod(m_configuration.m_shadowFilterMethod); SetSofteningBoundaryWidth(m_configuration.m_boundaryWidth); - SetPredictionSampleCount(m_configuration.m_predictionSampleCount); SetFilteringSampleCount(m_configuration.m_filteringSampleCount); - SetPcfMethod(m_configuration.m_pcfMethod); SetShadowReceiverPlaneBiasEnabled(m_configuration.m_receiverPlaneBiasEnabled); // [GFX TODO][ATOM-1726] share config for multiple light (e.g., light ID). @@ -631,17 +608,6 @@ namespace AZ } } - PcfMethod DirectionalLightComponentController::GetPcfMethod() const - { - return m_configuration.m_pcfMethod; - } - - void DirectionalLightComponentController::SetPcfMethod(PcfMethod method) - { - m_configuration.m_pcfMethod = method; - m_featureProcessor->SetPcfMethod(m_lightHandle, method); - } - bool DirectionalLightComponentController::GetShadowReceiverPlaneBiasEnabled() const { return m_configuration.m_receiverPlaneBiasEnabled; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h index 6b788c241c..b8052bfc36 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DirectionalLightComponentController.h @@ -78,12 +78,8 @@ namespace AZ void SetShadowFilterMethod(ShadowFilterMethod method) override; float GetSofteningBoundaryWidth() const override; void SetSofteningBoundaryWidth(float width) override; - uint32_t GetPredictionSampleCount() const override; - void SetPredictionSampleCount(uint32_t count) override; uint32_t GetFilteringSampleCount() const override; void SetFilteringSampleCount(uint32_t count) override; - PcfMethod GetPcfMethod() const override; - void SetPcfMethod(PcfMethod method) override; bool GetShadowReceiverPlaneBiasEnabled() const override; void SetShadowReceiverPlaneBiasEnabled(bool enable) override; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp index 91856f7ee5..baf0cdced1 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.cpp @@ -155,14 +155,6 @@ namespace AZ::Render } } - void DiskLightDelegate::SetPredictionSampleCount(uint32_t count) - { - if (GetShadowsEnabled() && GetLightHandle().IsValid()) - { - GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), static_cast(count)); - } - } - void DiskLightDelegate::SetFilteringSampleCount(uint32_t count) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) @@ -171,14 +163,6 @@ namespace AZ::Render } } - void DiskLightDelegate::SetPcfMethod(PcfMethod method) - { - if (GetShadowsEnabled() && GetLightHandle().IsValid()) - { - GetFeatureProcessor()->SetPcfMethod(GetLightHandle(), method); - } - } - void DiskLightDelegate::SetEsmExponent(float exponent) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h index 6931068635..e0fd16f6be 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/DiskLightDelegate.h @@ -45,9 +45,7 @@ namespace AZ void SetShadowmapMaxSize(ShadowmapSize size) override; void SetShadowFilterMethod(ShadowFilterMethod method) override; void SetSofteningBoundaryWidthAngle(float widthInDegrees) override; - void SetPredictionSampleCount(uint32_t count) override; void SetFilteringSampleCount(uint32_t count) override; - void SetPcfMethod(PcfMethod method) override; void SetEsmExponent(float exponent) override; private: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp index 17fb9a5e1d..659c394cba 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorAreaLightComponent.cpp @@ -162,29 +162,13 @@ namespace AZ ->Attribute(Edit::Attributes::Max, 1.f) ->Attribute(Edit::Attributes::Suffix, " deg") ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) - ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsSofteningBoundaryWidthDisabled) - ->DataElement(Edit::UIHandlers::Slider, &AreaLightComponentConfig::m_predictionSampleCount, "Prediction sample count", - "Sample count for prediction of whether the pixel is on the boundary. Specific to PCF and ESM+PCF.") - ->Attribute(Edit::Attributes::Min, 4) - ->Attribute(Edit::Attributes::Max, 16) - ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) - ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsPcfBoundarySearchDisabled) + ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsEsmDisabled) ->DataElement(Edit::UIHandlers::Slider, &AreaLightComponentConfig::m_filteringSampleCount, "Filtering sample count", "This is only used when the pixel is predicted to be on the boundary. Specific to PCF and ESM+PCF.") ->Attribute(Edit::Attributes::Min, 4) ->Attribute(Edit::Attributes::Max, 64) ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsShadowPcfDisabled) - ->DataElement( - Edit::UIHandlers::ComboBox, &AreaLightComponentConfig::m_pcfMethod, "PCF method", - "Type of PCF to use.\n" - " Bicubic: a smooth, fixed-size kernel \n" - " Boundary search: do several taps to first determine if we are on a shadow boundary\n") - ->EnumAttribute(PcfMethod::Bicubic, "Bicubic") - ->EnumAttribute(PcfMethod::BoundarySearch, "Boundary search") - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::Visibility, &AreaLightComponentConfig::SupportsShadows) - ->Attribute(Edit::Attributes::ReadOnly, &AreaLightComponentConfig::IsShadowPcfDisabled) ->DataElement( Edit::UIHandlers::Slider, &AreaLightComponentConfig::m_esmExponent, "ESM exponent", "Exponent used by ESM shadows. " diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp index 18d9ad70e0..ef9c73c0b4 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/EditorDirectionalLightComponent.cpp @@ -141,14 +141,7 @@ namespace AZ ->Attribute(Edit::Attributes::Max, 0.1f) ->Attribute(Edit::Attributes::Suffix, " m") ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsSofteningBoundaryWidthDisabled) - ->DataElement(Edit::UIHandlers::Slider, &DirectionalLightComponentConfig::m_predictionSampleCount, "Prediction sample count", - "Sample count for prediction of whether the pixel is on the boundary. " - "Specific to PCF and ESM+PCF.") - ->Attribute(Edit::Attributes::Min, 4) - ->Attribute(Edit::Attributes::Max, 16) - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsPcfBoundarySearchDisabled) + ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsEsmDisabled) ->DataElement(Edit::UIHandlers::Slider, &DirectionalLightComponentConfig::m_filteringSampleCount, "Filtering sample count", "This is used only when the pixel is predicted as on the boundary. " "Specific to PCF and ESM+PCF.") @@ -156,15 +149,6 @@ namespace AZ ->Attribute(Edit::Attributes::Max, 64) ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsShadowPcfDisabled) - ->DataElement( - Edit::UIHandlers::ComboBox, &DirectionalLightComponentConfig::m_pcfMethod, "Pcf method", - "Type of PCF to use.\n" - " Bicubic: a smooth, fixed-size kernel \n" - " Boundary search: do several taps to first determine if we are on a shadow boundary\n") - ->EnumAttribute(PcfMethod::Bicubic, "Bicubic") - ->EnumAttribute(PcfMethod::BoundarySearch, "Boundary search") - ->Attribute(Edit::Attributes::ChangeNotify, Edit::PropertyRefreshLevels::ValuesOnly) - ->Attribute(Edit::Attributes::ReadOnly, &DirectionalLightComponentConfig::IsShadowPcfDisabled) ->DataElement( Edit::UIHandlers::CheckBox, &DirectionalLightComponentConfig::m_receiverPlaneBiasEnabled, "Shadow Receiver Plane Bias Enable", diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h index 415878081c..2bd25b76a3 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateBase.h @@ -57,9 +57,7 @@ namespace AZ void SetShadowmapMaxSize([[maybe_unused]] ShadowmapSize size) override {}; void SetShadowFilterMethod([[maybe_unused]] ShadowFilterMethod method) override {}; void SetSofteningBoundaryWidthAngle([[maybe_unused]] float widthInDegrees) override {}; - void SetPredictionSampleCount([[maybe_unused]] uint32_t count) override {}; void SetFilteringSampleCount([[maybe_unused]] uint32_t count) override {}; - void SetPcfMethod([[maybe_unused]] PcfMethod method) override {}; void SetEsmExponent([[maybe_unused]] float esmExponent) override{}; protected: diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h index f18c3ef9af..6d08971542 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/LightDelegateInterface.h @@ -77,12 +77,8 @@ namespace AZ virtual void SetShadowFilterMethod(ShadowFilterMethod method) = 0; //! Sets the width of boundary between shadowed area and lit area in degrees. virtual void SetSofteningBoundaryWidthAngle(float widthInDegrees) = 0; - //! Sets the sample count to predict the boundary of the shadow. Max 16, should be less than filtering sample count. - virtual void SetPredictionSampleCount(uint32_t count) = 0; //! Sets the sample count for filtering of the shadow boundary, max 64. virtual void SetFilteringSampleCount(uint32_t count) = 0; - //! Sets the Pcf (Percentage closer filtering) method to use. - virtual void SetPcfMethod(PcfMethod method) = 0; //! Sets the Esm exponent to use. Higher values produce a steeper falloff between light and shadow. virtual void SetEsmExponent(float exponent) = 0; }; diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp index b4728c0c38..8853db5751 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.cpp @@ -100,14 +100,6 @@ namespace AZ::Render } } - void SphereLightDelegate::SetPredictionSampleCount(uint32_t count) - { - if (GetShadowsEnabled() && GetLightHandle().IsValid()) - { - GetFeatureProcessor()->SetPredictionSampleCount(GetLightHandle(), static_cast(count)); - } - } - void SphereLightDelegate::SetFilteringSampleCount(uint32_t count) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) @@ -116,14 +108,6 @@ namespace AZ::Render } } - void SphereLightDelegate::SetPcfMethod(PcfMethod method) - { - if (GetShadowsEnabled() && GetLightHandle().IsValid()) - { - GetFeatureProcessor()->SetPcfMethod(GetLightHandle(), method); - } - } - void SphereLightDelegate::SetEsmExponent(float esmExponent) { if (GetShadowsEnabled() && GetLightHandle().IsValid()) diff --git a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h index 984af56c17..e2903b2d72 100644 --- a/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h +++ b/Gems/AtomLyIntegration/CommonFeatures/Code/Source/CoreLights/SphereLightDelegate.h @@ -35,9 +35,7 @@ namespace AZ void SetShadowmapMaxSize(ShadowmapSize size) override; void SetShadowFilterMethod(ShadowFilterMethod method) override; void SetSofteningBoundaryWidthAngle(float widthInDegrees) override; - void SetPredictionSampleCount(uint32_t count) override; void SetFilteringSampleCount(uint32_t count) override; - void SetPcfMethod(PcfMethod method) override; void SetEsmExponent(float esmExponent) override; private: From bd8c53550a5e00f89f4f89107c0a7bd8c24cac52 Mon Sep 17 00:00:00 2001 From: mrieggeramzn <61609885+mrieggeramzn@users.noreply.github.com> Date: Tue, 14 Sep 2021 17:12:17 -0700 Subject: [PATCH 19/26] Replacing the old esm shadow blur with faster blur (#4095) * Replacing the old gaussian blur with a much faster, better quality kawase blur Signed-off-by: mrieggeramzn * Removing atomtesting outdated msg Signed-off-by: mrieggeramzn * Some recommendations from Tommy Signed-off-by: mrieggeramzn * Adding early termination from previous gaussian filtering algorithm that kawase replaces Signed-off-by: mrieggeramzn * Removing pcf method Signed-off-by: mrieggeramzn * removing the old blur and adding in the new kawase blur into .cmake file Signed-off-by: mrieggeramzn --- .../Common/Assets/Passes/EsmShadowmaps.pass | 19 +-- .../Assets/Passes/FilterDepthHorizontal.pass | 72 ---------- ...pthVertical.pass => KawaseShadowBlur.pass} | 10 +- .../Assets/Passes/PassTemplates.azasset | 14 +- .../Math/GaussianFilterFloatHorizontal.azsl | 60 -------- .../Math/GaussianFilterFloatHorizontal.shader | 16 --- .../Math/GaussianFilterFloatVertical.azsl | 60 -------- .../Shaders/Shadow/KawaseShadowBlur.azsl | 132 ++++++++++++++++++ .../KawaseShadowBlur.shader} | 2 +- .../atom_feature_common_asset_files.cmake | 9 +- .../Source/CoreLights/EsmShadowmapsPass.cpp | 52 ++++--- .../Source/CoreLights/EsmShadowmapsPass.h | 14 +- 12 files changed, 201 insertions(+), 259 deletions(-) delete mode 100644 Gems/Atom/Feature/Common/Assets/Passes/FilterDepthHorizontal.pass rename Gems/Atom/Feature/Common/Assets/Passes/{FilterDepthVertical.pass => KawaseShadowBlur.pass} (88%) delete mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.azsl delete mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.shader delete mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.azsl create mode 100644 Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.azsl rename Gems/Atom/Feature/Common/Assets/Shaders/{Math/GaussianFilterFloatVertical.shader => Shadow/KawaseShadowBlur.shader} (79%) diff --git a/Gems/Atom/Feature/Common/Assets/Passes/EsmShadowmaps.pass b/Gems/Atom/Feature/Common/Assets/Passes/EsmShadowmaps.pass index 27b777d549..a3bd6604dc 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/EsmShadowmaps.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/EsmShadowmaps.pass @@ -40,9 +40,11 @@ } ] }, + { - "Name": "HorizontalGaussianFilter", - "TemplateName": "FilterDepthHorizontalTemplate", + "Name": "KawaseBlur0", + "TemplateName": "KawaseShadowBlurTemplate", + "Enabled": true, "Connections": [ { "LocalSlot": "Input", @@ -54,26 +56,27 @@ ] }, { - "Name": "VerticalGaussianFiter", - "TemplateName": "FilterDepthVerticalTemplate", + "Name": "KawaseBlur1", + "TemplateName": "KawaseShadowBlurTemplate", + "Enabled": true, "Connections": [ { "LocalSlot": "Input", "AttachmentRef": { - "Pass": "HorizontalGaussianFilter", + "Pass": "KawaseBlur0", "Attachment": "Output" } } ] - } + } ], "Connections": [ { "LocalSlot": "EsmShadowmaps", "AttachmentRef": { - "Pass": "VerticalGaussianFiter", + "Pass": "KawaseBlur1", "Attachment": "Output" - } + } } ] } diff --git a/Gems/Atom/Feature/Common/Assets/Passes/FilterDepthHorizontal.pass b/Gems/Atom/Feature/Common/Assets/Passes/FilterDepthHorizontal.pass deleted file mode 100644 index 2b2ae40fdc..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Passes/FilterDepthHorizontal.pass +++ /dev/null @@ -1,72 +0,0 @@ -{ - "Type": "JsonSerialization", - "Version": 1, - "ClassName": "PassAsset", - "ClassData": { - "PassTemplate": { - "Name": "FilterDepthHorizontalTemplate", - "PassClass": "ComputePass", - "Slots": [ - { - "Name": "Input", - "SlotType": "Input", - "ShaderInputName": "m_inputImage", - "ScopeAttachmentUsage": "Shader", - "LoadStoreAction": { - "LoadAction": "Load", - "StoreAction": "DontCare" - }, - "ImageViewDesc": { - "IsArray": 1 - } - }, - { - "Name": "Output", - "SlotType": "Output", - "ShaderInputName": "m_outputImage", - "ScopeAttachmentUsage": "Shader", - "LoadStoreAction": { - "LoadAction": "DontCare", - "StoreAction": "Store" - }, - "ImageViewDesc": { - "IsArray": 1 - } - } - ], - "PassData": { - "$type": "ComputePassData", - "ShaderAsset": { - "FilePath": "Shaders/Math/GaussianFilterFloatHorizontal.shader" - } - }, - "ImageAttachments": [ - { - "Name": "HorizontalFiltered", - "SizeSource": { - "Source": { - "Pass": "This", - "Attachment": "Input" - } - }, - "ArraySizeSource": { - "Pass": "This", - "Attachment": "Input" - }, - "ImageDescriptor": { - "Format": "R32_FLOAT" - } - } - ], - "Connections": [ - { - "localSlot": "Output", - "AttachmentRef": { - "Pass": "This", - "Attachment": "HorizontalFiltered" - } - } - ] - } - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Passes/FilterDepthVertical.pass b/Gems/Atom/Feature/Common/Assets/Passes/KawaseShadowBlur.pass similarity index 88% rename from Gems/Atom/Feature/Common/Assets/Passes/FilterDepthVertical.pass rename to Gems/Atom/Feature/Common/Assets/Passes/KawaseShadowBlur.pass index 5d8a4de21b..46ef8ba8ae 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/FilterDepthVertical.pass +++ b/Gems/Atom/Feature/Common/Assets/Passes/KawaseShadowBlur.pass @@ -4,7 +4,7 @@ "ClassName": "PassAsset", "ClassData": { "PassTemplate": { - "Name": "FilterDepthVerticalTemplate", + "Name": "KawaseShadowBlurTemplate", "PassClass": "ComputePass", "Slots": [ { @@ -28,7 +28,7 @@ "LoadStoreAction": { "LoadAction": "DontCare", "StoreAction": "Store" - }, + }, "ImageViewDesc": { "IsArray": 1 } @@ -37,12 +37,12 @@ "PassData": { "$type": "ComputePassData", "ShaderAsset": { - "FilePath": "Shaders/Math/GaussianFilterFloatVertical.shader" + "FilePath": "Shaders/Shadow/KawaseShadowBlur.shader" } }, "ImageAttachments": [ { - "Name": "VerticalFiltered", + "Name": "FilteredImage", "SizeSource": { "Source": { "Pass": "This", @@ -63,7 +63,7 @@ "localSlot": "Output", "AttachmentRef": { "Pass": "This", - "Attachment": "VerticalFiltered" + "Attachment": "FilteredImage" } } ] diff --git a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset index 57d35fb48d..8b7d6a8438 100644 --- a/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset +++ b/Gems/Atom/Feature/Common/Assets/Passes/PassTemplates.azasset @@ -184,14 +184,6 @@ "Name": "DepthOfFieldWriteFocusDepthFromGpuTemplate", "Path": "Passes/DepthOfFieldWriteFocusDepthFromGpu.pass" }, - { - "Name": "FilterDepthHorizontalTemplate", - "Path": "Passes/FilterDepthHorizontal.pass" - }, - { - "Name": "FilterDepthVerticalTemplate", - "Path": "Passes/FilterDepthVertical.pass" - }, { "Name": "EsmShadowmapsTemplate", "Path": "Passes/EsmShadowmaps.pass" @@ -503,7 +495,11 @@ { "Name": "LowEndPipelineTemplate", "Path": "Passes/LowEndPipeline.pass" - } + }, + { + "Name": "KawaseShadowBlurTemplate", + "Path": "Passes/KawaseShadowBlur.pass" + } ] } } diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.azsl deleted file mode 100644 index 353f08427d..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.azsl +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// [GFX TODO][ATOM-3365] optimization using intermediary results in groupshared memory. - -#include -#include -#include - -[numthreads(16,16,1)] -void MainCS(uint3 dispatchId: SV_DispatchThreadID) -{ - const float3 inputSize = GetImageSize(FilterPassSrg::m_inputImage); - const float3 outputSize = GetImageSize(FilterPassSrg::m_outputImage); - - const uint shadowmapIndex = GetShadowmapIndex( - FilterPassSrg::m_shadowmapIndexTable, - dispatchId, - inputSize.x); - // Early return if thread is outside of shadowmaps. - if (shadowmapIndex == ~0) - { - return; - } - const FilterParameter filterParameter = FilterPassSrg::m_filterParameters[shadowmapIndex]; - const uint shadowmapSize = filterParameter.m_shadowmapSize; - // Early return if filter is disabled. - if (!filterParameter.m_isEnabled || shadowmapSize <= 1) - { - return; // early return if filter parameter is empty. - } - - const uint sourceMin = filterParameter.m_shadowmapOriginInSlice.x; - const uint sourceMax = sourceMin + shadowmapSize - 1; - - uint filterTableSize = 0; - FilterPassSrg::m_filterTable.GetDimensions(filterTableSize); - if (filterTableSize == 0 || filterParameter.m_parameterCount == 0) - { - return; // If filter parameter is empty, early return. - } - - // [GFX TODO][ATOM-5676] pass proper source min/max for each shadowmap - const float result = FilteredFloat( - dispatchId, - FilterPassSrg::m_inputImage, - uint2(1, 0), // horizontal - sourceMin, - sourceMax, - FilterPassSrg::m_filterTable, - filterParameter.m_parameterOffset, - filterParameter.m_parameterCount); - - FilterPassSrg::m_outputImage[dispatchId].r = result; -} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.shader deleted file mode 100644 index 6998fd000c..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatHorizontal.shader +++ /dev/null @@ -1,16 +0,0 @@ -{ - "Source" : "GaussianFilterFloatHorizontal", - - "DrawList" : "shadow", - - "ProgramSettings": - { - "EntryPoints": - [ - { - "name": "MainCS", - "type": "Compute" - } - ] - } -} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.azsl deleted file mode 100644 index 11c7d04bb1..0000000000 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.azsl +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -// [GFX TODO][ATOM-3365] optimization using intermediary results in groupshared memory. - -#include -#include -#include - -[numthreads(16,16,1)] -void MainCS(uint3 dispatchId: SV_DispatchThreadID) -{ - const float3 inputSize = GetImageSize(FilterPassSrg::m_inputImage); - const float3 outputSize = GetImageSize(FilterPassSrg::m_outputImage); - - const uint shadowmapIndex = GetShadowmapIndex( - FilterPassSrg::m_shadowmapIndexTable, - dispatchId, - inputSize.x); - // Early return if thread is outside of shadowmaps. - if (shadowmapIndex == ~0) - { - return; - } - const FilterParameter filterParameter = FilterPassSrg::m_filterParameters[shadowmapIndex]; - const uint shadowmapSize = filterParameter.m_shadowmapSize; - // Early return if filter is disabled. - if (!filterParameter.m_isEnabled || shadowmapSize <= 1) - { - return; // early return if filter parameter is empty. - } - - const uint sourceMin = filterParameter.m_shadowmapOriginInSlice.y; - const uint sourceMax = sourceMin + shadowmapSize - 1; - - uint filterTableSize = 0; - FilterPassSrg::m_filterTable.GetDimensions(filterTableSize); - if (filterTableSize == 0 || filterParameter.m_parameterCount == 0) - { - return; // If filter parameter is empty, early return. - } - - // [GFX TODO][ATOM-5676] pass proper source min/max for each shadowmap - const float result = FilteredFloat( - dispatchId, - FilterPassSrg::m_inputImage, - uint2(0, 1), // vertical - sourceMin, - sourceMax, - FilterPassSrg::m_filterTable, - filterParameter.m_parameterOffset, - filterParameter.m_parameterCount); - - FilterPassSrg::m_outputImage[dispatchId].r = result; -} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.azsl new file mode 100644 index 0000000000..9b480a4e40 --- /dev/null +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.azsl @@ -0,0 +1,132 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +// [GFX TODO][ATOM-3365] optimization using intermediary results in groupshared memory. + +// This shader blurs the ESM results using a multi-pass kawase filter. +// It should generally be faster than separable gaussian blur +// https://software.intel.com/content/www/us/en/develop/blogs/an-investigation-of-fast-real-time-gpu-based-image-blur-algorithms.html + +#include +#include +#include +#include + +ShaderResourceGroup FilterPassSrg : SRG_PerPass +{ + // This shader filters multiple images with distinct filter parameters. + // So, the input and output are arrays of texture2Ds. + Texture2DArray m_inputImage; + RWTexture2DArray m_outputImage; + + // This can convert a coordinate in an atlas to + // the shadowmap index. + Buffer m_shadowmapIndexTable; + + // This contains parameters related to filtering. + StructuredBuffer m_filterParameters; + + // x and y contain the inverse of the texture map resolution, z contains the kawase iteration + // i.e. a two pass kawase blur passes in 0 for the 1st pass and 1 for the second pass + float4 m_rcpResolutionAndIteration; + + Sampler LinearSampler + { + MinFilter = Linear; + MagFilter = Linear; + MipFilter = Linear; + AddressU = Clamp; + AddressV = Clamp; + AddressW = Clamp; + }; +} + +void CalculateBlurBoundaries(const uint shadowmapIndex, out float2 sourceMinTex, out float2 sourceMaxTex) +{ + const float2 rcpPixelSize = FilterPassSrg::m_rcpResolutionAndIteration.xy; + + const FilterParameter filterParameter = FilterPassSrg::m_filterParameters[shadowmapIndex]; + const uint shadowmapSize = filterParameter.m_shadowmapSize; + + // location of the shadow bounds in texels + const uint2 sourceMinPixel = filterParameter.m_shadowmapOriginInSlice.xy; + const uint2 sourceMaxPixel = sourceMinPixel + shadowmapSize - 1; + + // location of the shadow bounds in uv space + sourceMinTex = (sourceMinPixel + 0.5f) * rcpPixelSize; + sourceMaxTex = (sourceMaxPixel + 0.5f) * rcpPixelSize; +} + +float AccumulateShadowSamples(Texture2DArray tex, float3 texCoord, SamplerState s) +{ + float4 values = tex.GatherRed(s, texCoord); + float result = values.x + values.y + values.z + values.w; + return result; +} + +[numthreads(16,16,1)] +void MainCS(uint3 dispatchId: SV_DispatchThreadID) +{ + const float inputSize = GetImageSize(FilterPassSrg::m_inputImage).x; + const uint shadowmapIndex = GetShadowmapIndex( + FilterPassSrg::m_shadowmapIndexTable, + dispatchId, + inputSize); + + // Early return if thread is outside of shadowmaps. + if (shadowmapIndex == ~0) + { + return; + } + + const FilterParameter filterParameter = FilterPassSrg::m_filterParameters[shadowmapIndex]; + const uint shadowmapSize = filterParameter.m_shadowmapSize; + // Early return if filter is disabled. + if (!filterParameter.m_isEnabled || shadowmapSize <= 1) + { + return; // early return if filter parameter is empty. + } + + const float2 rcpPixelSize = FilterPassSrg::m_rcpResolutionAndIteration.xy; + const float blurIteration = FilterPassSrg::m_rcpResolutionAndIteration.z; + + float2 sourceMinTex, sourceMaxTex; + CalculateBlurBoundaries(shadowmapIndex, sourceMinTex, sourceMaxTex); + + const float2 halfRcpPixelSize = rcpPixelSize / 2.0f; + const float2 dUV = rcpPixelSize.xy * blurIteration + halfRcpPixelSize.xy; + const float2 texCoord = (dispatchId.xy + 0.5f) * rcpPixelSize; + + const float3 texCoordSamples[4] = { + float3(texCoord.x - dUV.x, texCoord.y - dUV.y, dispatchId.z), + float3(texCoord.x - dUV.x, texCoord.y + dUV.y, dispatchId.z), + float3(texCoord.x + dUV.x, texCoord.y - dUV.y, dispatchId.z), + float3(texCoord.x + dUV.x, texCoord.y + dUV.y, dispatchId.z), + }; + + float accumulatedBlur = 0; + float numSamplesAccumulated = 0; + for(int i = 0 ; i < 4; ++i) + { + if (texCoordSamples[i].x >= sourceMinTex.x && + texCoordSamples[i].y >= sourceMinTex.y && + texCoordSamples[i].x < sourceMaxTex.x && + texCoordSamples[i].y < sourceMaxTex.y) + { + // we should be tapping the location directly in between 4 adjacent texels + accumulatedBlur += AccumulateShadowSamples(FilterPassSrg::m_inputImage, texCoordSamples[i], FilterPassSrg::LinearSampler); + numSamplesAccumulated += 4; + } + } + + if (numSamplesAccumulated > 0) + { + float result = accumulatedBlur / numSamplesAccumulated; + FilterPassSrg::m_outputImage[dispatchId].r = result; + } +} diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.shader b/Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.shader similarity index 79% rename from Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.shader rename to Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.shader index db303e1ea7..dacacdafff 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/Math/GaussianFilterFloatVertical.shader +++ b/Gems/Atom/Feature/Common/Assets/Shaders/Shadow/KawaseShadowBlur.shader @@ -1,5 +1,5 @@ { - "Source" : "GaussianFilterFloatVertical", + "Source" : "KawaseShadowBlur", "DrawList" : "shadow", diff --git a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake index e43498c55d..8435625833 100644 --- a/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake +++ b/Gems/Atom/Feature/Common/Assets/atom_feature_common_asset_files.cmake @@ -137,8 +137,6 @@ set(FILES Passes/FastDepthAwareBlur.pass Passes/FastDepthAwareBlurHor.pass Passes/FastDepthAwareBlurVer.pass - Passes/FilterDepthHorizontal.pass - Passes/FilterDepthVertical.pass Passes/Forward.pass Passes/ForwardCheckerboard.pass Passes/ForwardMSAA.pass @@ -146,6 +144,7 @@ set(FILES Passes/FullscreenCopy.pass Passes/FullscreenOutputOnly.pass Passes/ImGui.pass + Passes/KawaseShadowBlur.pass Passes/LightAdaptationParent.pass Passes/LightCulling.pass Passes/LightCullingHeatmap.pass @@ -331,10 +330,6 @@ set(FILES Shaders/LightCulling/LightCullingTilePrepare.shader Shaders/LuxCore/RenderTexture.azsl Shaders/LuxCore/RenderTexture.shader - Shaders/Math/GaussianFilterFloatHorizontal.azsl - Shaders/Math/GaussianFilterFloatHorizontal.shader - Shaders/Math/GaussianFilterFloatVertical.azsl - Shaders/Math/GaussianFilterFloatVertical.shader Shaders/MorphTargets/MorphTargetCS.azsl Shaders/MorphTargets/MorphTargetCS.shader Shaders/MorphTargets/MorphTargetSRG.azsli @@ -457,6 +452,8 @@ set(FILES Shaders/ScreenSpace/DeferredFog.shader Shaders/Shadow/DepthExponentiation.azsl Shaders/Shadow/DepthExponentiation.shader + Shaders/Shadow/KawaseShadowBlur.azsl + Shaders/Shadow/KawaseShadowBlur.shader Shaders/Shadow/Shadowmap.azsl Shaders/Shadow/Shadowmap.shader Shaders/SkinnedMesh/LinearSkinningCS.azsl diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp index 6948eb598e..99eaa8a919 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.cpp @@ -130,32 +130,17 @@ namespace AZ const AZStd::array_view>& children = GetChildren(); AZ_Assert(children.size() == EsmChildPassKindCount, "[EsmShadowmapsPass '%s'] The count of children is wrong.", GetPathName().GetCStr()); - for (uint32_t index = 0; index < EsmChildPassKindCount; ++index) + for (uint32_t childPassIndex = 0; childPassIndex < EsmChildPassKindCount; ++childPassIndex) { - RPI::ComputePass* child = azrtti_cast(children[index].get()); + RPI::ComputePass* child = azrtti_cast(children[childPassIndex].get()); AZ_Assert(child, "[EsmShadowmapsPass '%s'] A child does not compute.", GetPathName().GetCStr()); Data::Instance srg = child->GetShaderResourceGroup(); - if (m_shadowmapIndexTableBufferIndices[index].IsNull()) + SetBlurParameters(srg, childPassIndex); + if (childPassIndex >= aznumeric_cast(EsmChildPassKind::KawaseBlur0)) { - m_shadowmapIndexTableBufferIndices[index] = srg->FindShaderInputBufferIndex(Name("m_shadowmapIndexTable")); - } - srg->SetBuffer(m_shadowmapIndexTableBufferIndices[index], m_shadowmapIndexTableBuffer); - - if (m_filterParameterBufferIndices[index].IsNull()) - { - m_filterParameterBufferIndices[index] = srg->FindShaderInputBufferIndex(Name("m_filterParameters")); - } - srg->SetBuffer(m_filterParameterBufferIndices[index], m_filterParameterBuffer); - - if (index != static_cast(EsmChildPassKind::Exponentiation)) - { - if (m_filterTableBufferIndices[index].IsNull()) - { - m_filterTableBufferIndices[index] = srg->FindShaderInputBufferIndex(Name("m_filterTable")); - } - srg->SetBuffer(m_filterTableBufferIndices[index], m_filterTableBuffer); + SetKawaseBlurSpecificParameters(srg, childPassIndex - aznumeric_cast(EsmChildPassKind::KawaseBlur0)); } child->SetTargetThreadCounts( @@ -165,5 +150,32 @@ namespace AZ } } + void EsmShadowmapsPass::SetBlurParameters(Data::Instance srg, const uint32_t childPassIndex) + { + if (m_shadowmapIndexTableBufferIndices[childPassIndex].IsNull()) + { + m_shadowmapIndexTableBufferIndices[childPassIndex] = srg->FindShaderInputBufferIndex(Name("m_shadowmapIndexTable")); + } + srg->SetBuffer(m_shadowmapIndexTableBufferIndices[childPassIndex], m_shadowmapIndexTableBuffer); + + if (m_filterParameterBufferIndices[childPassIndex].IsNull()) + { + m_filterParameterBufferIndices[childPassIndex] = srg->FindShaderInputBufferIndex(Name("m_filterParameters")); + } + srg->SetBuffer(m_filterParameterBufferIndices[childPassIndex], m_filterParameterBuffer); + } + + void EsmShadowmapsPass::SetKawaseBlurSpecificParameters(Data::Instance srg, uint32_t kawaseBlurIndex) + { + if (m_kawaseBlurConstantIndices[kawaseBlurIndex].IsNull()) + { + m_kawaseBlurConstantIndices[kawaseBlurIndex] = srg->FindShaderInputConstantIndex(Name("m_rcpResolutionAndIteration")); + } + const AZ::Vector4 data( + 1.0f / m_shadowmapImageSize.m_width, 1.0f / m_shadowmapImageSize.m_height, aznumeric_cast(kawaseBlurIndex), 0.0f); + + srg->SetConstant(m_kawaseBlurConstantIndices[kawaseBlurIndex], data); + } + } // namespace Render } // namespace AZ diff --git a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h index 236855c8c5..6e5e1aa311 100644 --- a/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h +++ b/Gems/Atom/Feature/Common/Code/Source/CoreLights/EsmShadowmapsPass.h @@ -21,12 +21,17 @@ namespace AZ { + namespace RPI + { + class ShaderResourceGroup; + } + namespace Render { AZ_ENUM_CLASS_WITH_UNDERLYING_TYPE(EsmChildPassKind, uint32_t, (Exponentiation, 0), - HorizontalFilter, - VerticalFilter); + KawaseBlur0, + KawaseBlur1); //! This pass outputs filtered shadowmap images used in ESM. //! ESM is an abbreviation of Exponential Shadow Maps. @@ -88,6 +93,9 @@ namespace AZ void FrameBeginInternal(FramePrepareParams params) override; void UpdateChildren(); + // Parameters for both the depth exponentiation pass along with the kawase blur passes + void SetBlurParameters(Data::Instance srg, const uint32_t childPassIndex); + void SetKawaseBlurSpecificParameters(Data::Instance srg, const uint32_t kawaseBlurIndex); bool m_computationEnabled = false; Name m_lightTypeName; @@ -102,6 +110,8 @@ namespace AZ Data::Instance m_shadowmapIndexTableBuffer; AZStd::array m_filterParameterBufferIndices; Data::Instance m_filterParameterBuffer; + + AZStd::array m_kawaseBlurConstantIndices; }; } // namespace Render } // namespace AZ From ce72e32cfc640af8029194578fe1ecf4766c8d49 Mon Sep 17 00:00:00 2001 From: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> Date: Tue, 14 Sep 2021 19:21:29 -0500 Subject: [PATCH 20/26] Fixed issue where two Paths could compare equal to each other, but hash differently (#4126) * Fixed issue where two Paths could compare equal to each other, but hash differently This issue is caused by the Path comparison logic using the path separator of the left path in a comparison of two paths(left and right) to determine whether the PathComparison is case-sensitive or not. The logic has been updated to only perform a non-case-sensitive path comparison if both paths are using the WindowsPathSeperator of `\` Also fixed issue with the Hashing algorihtm of the Path class to always hash the root directory as if it is `/`. This allows a path of "C:\foo" and "C:/foo" to hash to the equivalent value. Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> * MS Build Tools 14.29 workaround around suppressing warnings using the external header feature Signed-off-by: lumberyard-employee-dm <56135373+lumberyard-employee-dm@users.noreply.github.com> --- Code/Framework/AzCore/AzCore/IO/Path/Path.h | 4 +- Code/Framework/AzCore/AzCore/IO/Path/Path.inl | 55 +++++--------- .../AzCore/AzCore/IO/Path/PathParser.inl | 56 ++++++++++++-- .../AzCore/Tests/IO/Path/PathTests.cpp | 76 +++++++++++++++++++ 4 files changed, 148 insertions(+), 43 deletions(-) diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.h b/Code/Framework/AzCore/AzCore/IO/Path/Path.h index c0c4b1c974..24f26daa51 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.h +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.h @@ -273,7 +273,7 @@ namespace AZ::IO // If the path input = 'D:bar', then the new PathIterable parts = [D:, 'bar' ] static constexpr void AppendNormalPathParts(PathIterable& pathIterableResult, const AZ::IO::PathView& path) noexcept; - constexpr int compare_string_view(AZStd::string_view other) const; + constexpr int ComparePathView(const PathView& other) const; constexpr AZStd::string_view root_name_view() const; constexpr AZStd::string_view root_directory_view() const; constexpr AZStd::string_view root_path_raw_view() const; @@ -480,6 +480,8 @@ namespace AZ::IO // compare //! Performs a compare of each of the path parts for equivalence //! Each part of the path is compare using string comparison + //! If both *this path and the input path uses the WindowsPathSeparator + //! then a non-case sensitive compare is performed //! Ex: Comparing "test/foo" against "test/fop" returns -1; //! Path separators of the contained path string aren't compared //! Ex. Comparing "C:/test\foo" against C:\test/foo" returns 0; diff --git a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl index 40cbf6f46b..0147ad3356 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/Path.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/Path.inl @@ -224,15 +224,15 @@ namespace AZ::IO // compare constexpr int PathView::Compare(const PathView& other) const noexcept { - return compare_string_view(other.m_path); + return ComparePathView(other); } constexpr int PathView::Compare(AZStd::string_view pathView) const noexcept { - return compare_string_view(pathView); + return ComparePathView(PathView(pathView, m_preferred_separator)); } constexpr int PathView::Compare(const value_type* path) const noexcept { - return compare_string_view(path); + return ComparePathView(PathView(path, m_preferred_separator)); } constexpr AZStd::fixed_string PathView::FixedMaxPathString() const noexcept @@ -398,10 +398,10 @@ namespace AZ::IO return true; } - constexpr int PathView::compare_string_view(AZStd::string_view pathView) const + constexpr int PathView::ComparePathView(const PathView& other) const { auto lhsPathParser = parser::PathParser::CreateBegin(m_path, m_preferred_separator); - auto rhsPathParser = parser::PathParser::CreateBegin(pathView, m_preferred_separator); + auto rhsPathParser = parser::PathParser::CreateBegin(other.m_path, other.m_preferred_separator); if (int res = CompareRootName(&lhsPathParser, &rhsPathParser); res != 0) { @@ -476,6 +476,8 @@ namespace AZ::IO template constexpr void PathView::MakeRelativeTo(PathResultType& pathResult, const AZ::IO::PathView& path, const AZ::IO::PathView& base) { + const bool exactCaseCompare = path.m_preferred_separator == PosixPathSeparator + || base.m_preferred_separator == PosixPathSeparator; { // perform root-name/root-directory mismatch checks auto pathParser = parser::PathParser::CreateBegin(path.m_path, path.m_preferred_separator); @@ -487,7 +489,7 @@ namespace AZ::IO }; if (pathParser.InRootName() && pathParserBase.InRootName()) { - if (int res = Internal::ComparePathSegment(*pathParser, *pathParserBase, pathParser.m_preferred_separator); + if (int res = Internal::ComparePathSegment(*pathParser, *pathParserBase, exactCaseCompare); res != 0) { pathResult.m_path = AZStd::string_view{}; @@ -519,7 +521,7 @@ namespace AZ::IO auto pathParser = parser::PathParser::CreateBegin(path.m_path, path.m_preferred_separator); auto pathParserBase = parser::PathParser::CreateBegin(base.m_path, base.m_preferred_separator); while (pathParser && pathParserBase && pathParser.m_parser_state == pathParserBase.m_parser_state && - Internal::ComparePathSegment(*pathParser, *pathParserBase, pathParser.m_preferred_separator) == 0) + Internal::ComparePathSegment(*pathParser, *pathParserBase, exactCaseCompare) == 0) { ++pathParser; ++pathParserBase; @@ -1080,25 +1082,25 @@ namespace AZ::IO template constexpr int BasicPath::Compare(const PathView& other) const noexcept { - return static_cast(*this).compare_string_view(other.m_path); + return static_cast(*this).ComparePathView(other); } template constexpr int BasicPath::Compare(const string_type& pathString) const { - return static_cast(*this).compare_string_view(pathString); + return static_cast(*this).ComparePathView(PathView(pathString, m_preferred_separator)); } template constexpr int BasicPath::Compare(AZStd::string_view pathView) const noexcept { - return static_cast(*this).compare_string_view(pathView); + return static_cast(*this).ComparePathView(pathView); } template constexpr int BasicPath::Compare(const value_type* pathString) const noexcept { - return static_cast(*this).compare_string_view(pathString); + return static_cast(*this).ComparePathView(pathString); } // decomposition @@ -1330,10 +1332,12 @@ namespace AZ::IO // PathView::LexicallyRelative is not being used as it returns a FixedMaxPath // which has a limitation that it requires the relative path to fit within // an AZ::IO::MaxPathLength buffer - auto ComparePathPart = [pathSeparator = m_preferred_separator]( + const bool exactCaseCompare = m_preferred_separator == PosixPathSeparator + || base.m_preferred_separator == PosixPathSeparator; + auto ComparePathPart = [exactCaseCompare]( const PathIterable::PartKindPair& left, const PathIterable::PartKindPair& right) -> bool { - return Internal::ComparePathSegment(left.first, right.first, pathSeparator) == 0; + return Internal::ComparePathSegment(left.first, right.first, exactCaseCompare) == 0; }; const PathIterable thisPathParts = GetNormalPathParts(*this); @@ -1471,37 +1475,16 @@ namespace AZStd template <> struct hash { - /// Path is using FNV-1a algorithm 64 bit version. - static size_t hash_path(AZStd::string_view pathSegment, const char pathSeparator) - { - size_t hash = 14695981039346656037ULL; - constexpr size_t fnvPrime = 1099511628211ULL; - - for (const char first : pathSegment) - { - hash ^= static_cast((pathSeparator == AZ::IO::PosixPathSeparator) - ? first : tolower(first)); - hash *= fnvPrime; - } - return hash; - } - size_t operator()(const AZ::IO::PathView& pathToHash) noexcept { auto pathParser = AZ::IO::parser::PathParser::CreateBegin(pathToHash.Native(), pathToHash.m_preferred_separator); - size_t hash_value = 0; - while (pathParser) - { - AZStd::hash_combine(hash_value, hash_path(*pathParser, pathToHash.m_preferred_separator)); - ++pathParser; - } - return hash_value; + return AZ::IO::parser::HashPath(pathParser); } }; template struct hash> { - const size_t operator()(const AZ::IO::BasicPath& pathToHash) noexcept + size_t operator()(const AZ::IO::BasicPath& pathToHash) noexcept { return AZStd::hash{}(pathToHash); } diff --git a/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl b/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl index 3ab2c4376c..b19c518ff9 100644 --- a/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl +++ b/Code/Framework/AzCore/AzCore/IO/Path/PathParser.inl @@ -183,13 +183,12 @@ namespace AZ::IO::Internal return IsAbsolute(pathView.begin(), pathView.end(), preferredSeparator); } - // Compares path segments using either Posix or Windows path rules based on the path separator in use - // Posix paths perform a case-sensitive comparison, while Windows paths perform a case-insensitive comparison - static int ComparePathSegment(AZStd::string_view left, AZStd::string_view right, char pathSeparator) + // Compares path segments using either Posix or Windows path rules based on the exactCaseCompare option + static int ComparePathSegment(AZStd::string_view left, AZStd::string_view right, bool exactCaseCompare) { const size_t maxCharsToCompare = (AZStd::min)(left.size(), right.size()); - int charCompareResult = pathSeparator == PosixPathSeparator + int charCompareResult = exactCaseCompare ? maxCharsToCompare ? strncmp(left.data(), right.data(), maxCharsToCompare) : 0 : maxCharsToCompare ? azstrnicmp(left.data(), right.data(), maxCharsToCompare) : 0; return charCompareResult == 0 @@ -594,7 +593,10 @@ namespace AZ::IO::parser { return pathParser->InRootName() ? **pathParser : ""; }; - int res = Internal::ComparePathSegment(GetRootName(lhsPathParser), GetRootName(rhsPathParser), lhsPathParser->m_preferred_separator); + + const bool exactCaseCompare = lhsPathParser->m_preferred_separator == PosixPathSeparator + || rhsPathParser->m_preferred_separator == PosixPathSeparator; + int res = Internal::ComparePathSegment(GetRootName(lhsPathParser), GetRootName(rhsPathParser), exactCaseCompare); ConsumeRootName(lhsPathParser); ConsumeRootName(rhsPathParser); return res; @@ -621,9 +623,11 @@ namespace AZ::IO::parser auto& lhsPathParser = *lhsPathParserPtr; auto& rhsPathParser = *rhsPathParserPtr; + const bool exactCaseCompare = lhsPathParser.m_preferred_separator == PosixPathSeparator + || rhsPathParser.m_preferred_separator == PosixPathSeparator; while (lhsPathParser && rhsPathParser) { - if (int res = Internal::ComparePathSegment(*lhsPathParser, *rhsPathParser, lhsPathParser.m_preferred_separator); + if (int res = Internal::ComparePathSegment(*lhsPathParser, *rhsPathParser, exactCaseCompare); res != 0) { return res; @@ -646,6 +650,46 @@ namespace AZ::IO::parser return 0; } + //path.hash + /// Path is using FNV-1a algorithm 64 bit version. + inline size_t HashSegment(AZStd::string_view pathSegment, bool hashExactPath) + { + size_t hash = 14695981039346656037ULL; + constexpr size_t fnvPrime = 1099511628211ULL; + + for (const char first : pathSegment) + { + hash ^= static_cast(hashExactPath ? first : tolower(first)); + hash *= fnvPrime; + } + return hash; + } + constexpr size_t HashPath(PathParser& pathParser) + { + size_t hash_value = 0; + const bool hashExactPath = pathParser.m_preferred_separator == AZ::IO::PosixPathSeparator; + while (pathParser) + { + switch (pathParser.m_parser_state) + { + case PS_InRootName: + case PS_InFilenames: + AZStd::hash_combine(hash_value, HashSegment(*pathParser, hashExactPath)); + break; + case PS_InRootDir: + // Only hash the PosixPathSeparator when a root directory is seen + // This makes the hash consistent for root directories path of C:\ and C:/ + AZStd::hash_combine(hash_value, HashSegment("/", hashExactPath)); + break; + default: + // The BeforeBegin and AtEnd states contain no segments to hash + break; + } + ++pathParser; + } + return hash_value; + } + constexpr int DetermineLexicalElementCount(PathParser pathParser) { int count = 0; diff --git a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp index dbdb4fee78..cf212aa34c 100644 --- a/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp +++ b/Code/Framework/AzCore/Tests/IO/Path/PathTests.cpp @@ -213,6 +213,82 @@ namespace UnitTest AZStd::tuple(R"(foO/Bar)", "foo/bar") )); + + struct PathHashCompareParams + { + AZ::IO::PathView m_testPath{}; + ::testing::Matcher m_compareMatcher; + ::testing::Matcher m_hashMatcher; + }; + + class PathHashCompareFixture + : public ScopedAllocatorSetupFixture + , public ::testing::WithParamInterface + {}; + + // Verifies that two paths that compare equal has their hash value compare equal + TEST_P(PathHashCompareFixture, PathsWhichCompareEqual_HashesToSameValue_Succeeds) + { + auto&& [testPath1, compareMatcher, hashMatcher] = GetParam(); + + // Compare path using parameterized Matcher + EXPECT_THAT(testPath1, compareMatcher); + // Compare hash using parameterized Matcher + const size_t testPath1Hash = AZStd::hash{}(testPath1); +AZ_PUSH_DISABLE_WARNING(4296, "-Wunknown-warning-option") + EXPECT_THAT(testPath1Hash, hashMatcher); +AZ_POP_DISABLE_WARNING + } + + INSTANTIATE_TEST_CASE_P( + HashPathCompareValidation, + PathHashCompareFixture, + ::testing::Values( + PathHashCompareParams{ AZ::IO::PathView("C:/test/foo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/foo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(/test/FOO)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/FOO)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("C:/test/foo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("C:/test/foo", AZ::IO::PosixPathSeparator), + testing::Ne(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(c:\test/foo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView(R"(C:\test\foo)", AZ::IO::WindowsPathSeparator), + testing::Ne(AZ::IO::PathView(R"(c:/test/foo)", AZ::IO::PosixPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(c:/test/foo)", AZ::IO::PosixPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::WindowsPathSeparator), + testing::Eq(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::PosixPathSeparator), + testing::Gt(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::WindowsPathSeparator), + testing::Gt(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::PosixPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/AOO)", AZ::IO::PosixPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/AOO", AZ::IO::PosixPathSeparator), + testing::Lt(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/AOO", AZ::IO::WindowsPathSeparator), + testing::Lt(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::PosixPathSeparator)), + testing::Eq(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::PosixPathSeparator))) }, + // Paths with different character values, comparison based on path separator + PathHashCompareParams{ AZ::IO::PathView("/test/BOO", AZ::IO::PosixPathSeparator), + testing::Le(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/BOO", AZ::IO::WindowsPathSeparator), + testing::Ge(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/aoo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::WindowsPathSeparator), + testing::Le(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator))) }, + PathHashCompareParams{ AZ::IO::PathView("/test/aoo", AZ::IO::PosixPathSeparator), + testing::Ge(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator)), + testing::Ne(AZStd::hash{}(AZ::IO::PathView(R"(/test/Boo)", AZ::IO::WindowsPathSeparator))) } + )); + class PathSingleParamFixture : public ScopedAllocatorSetupFixture , public ::testing::WithParamInterface> From 52095e3e165ccc0d1cab0d11da74e882efa73919 Mon Sep 17 00:00:00 2001 From: hultonha <82228511+hultonha@users.noreply.github.com> Date: Wed, 15 Sep 2021 11:12:26 +0100 Subject: [PATCH 21/26] Ensure undo/redo operation for change entity selection is atomic (#4122) --- .../EditorTransformComponentSelection.cpp | 258 +++++++++--------- ...EditorTransformComponentSelectionTests.cpp | 28 +- 2 files changed, 158 insertions(+), 128 deletions(-) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp index 5a7b097e29..064fbb9da6 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/ViewportSelection/EditorTransformComponentSelection.cpp @@ -86,59 +86,60 @@ namespace AzToolsFramework "Sticky select implies a single click will not change selection with an entity already selected"); // strings related to new viewport interaction model (EditorTransformComponentSelection) - static const char* const s_togglePivotTitleRightClick = "Toggle pivot"; - static const char* const s_togglePivotTitleEditMenu = "Toggle Pivot Location"; - static const char* const s_togglePivotDesc = "Toggle pivot location"; - static const char* const s_manipulatorUndoRedoName = "Manipulator Adjustment"; - static const char* const s_lockSelectionTitle = "Lock Selection"; - static const char* const s_lockSelectionDesc = "Lock the selected entities so that they can't be selected in the viewport"; - static const char* const s_hideSelectionTitle = "Hide Selection"; - static const char* const s_hideSelectionDesc = "Hide the selected entities so that they don't appear in the viewport"; - static const char* const s_unlockAllTitle = "Unlock All Entities"; - static const char* const s_unlockAllDesc = "Unlock all entities the level"; - static const char* const s_showAllTitle = "Show All"; - static const char* const s_showAllDesc = "Show all entities so that they appear in the viewport"; - static const char* const s_selectAllTitle = "Select All"; - static const char* const s_selectAllDesc = "Select all entities"; - static const char* const s_invertSelectionTitle = "Invert Selection"; - static const char* const s_invertSelectionDesc = "Invert the current entity selection"; - static const char* const s_duplicateTitle = "Duplicate"; - static const char* const s_duplicateDesc = "Duplicate selected entities"; - static const char* const s_deleteTitle = "Delete"; - static const char* const s_deleteDesc = "Delete selected entities"; - static const char* const s_resetEntityTransformTitle = "Reset Entity Transform"; - static const char* const s_resetEntityTransformDesc = "Reset transform based on manipulator mode"; - static const char* const s_resetManipulatorTitle = "Reset Manipulator"; - static const char* const s_resetManipulatorDesc = "Reset the manipulator to recenter it on the selected entity"; - static const char* const s_resetTransformLocalTitle = "Reset Transform (Local)"; - static const char* const s_resetTransformLocalDesc = "Reset transform to local space"; - static const char* const s_resetTransformWorldTitle = "Reset Transform (World)"; - static const char* const s_resetTransformWorldDesc = "Reset transform to world space"; + static const char* const TogglePivotTitleRightClick = "Toggle pivot"; + static const char* const TogglePivotTitleEditMenu = "Toggle Pivot Location"; + static const char* const TogglePivotDesc = "Toggle pivot location"; + static const char* const ManipulatorUndoRedoName = "Manipulator Adjustment"; + static const char* const LockSelectionTitle = "Lock Selection"; + static const char* const LockSelectionDesc = "Lock the selected entities so that they can't be selected in the viewport"; + static const char* const HideSelectionTitle = "Hide Selection"; + static const char* const HideSelectionDesc = "Hide the selected entities so that they don't appear in the viewport"; + static const char* const UnlockAllTitle = "Unlock All Entities"; + static const char* const UnlockAllDesc = "Unlock all entities the level"; + static const char* const ShowAllTitle = "Show All"; + static const char* const ShowAllDesc = "Show all entities so that they appear in the viewport"; + static const char* const SelectAllTitle = "Select All"; + static const char* const SelectAllDesc = "Select all entities"; + static const char* const InvertSelectionTitle = "Invert Selection"; + static const char* const InvertSelectionDesc = "Invert the current entity selection"; + static const char* const DuplicateTitle = "Duplicate"; + static const char* const DuplicateDesc = "Duplicate selected entities"; + static const char* const DeleteTitle = "Delete"; + static const char* const DeleteDesc = "Delete selected entities"; + static const char* const ResetEntityTransformTitle = "Reset Entity Transform"; + static const char* const ResetEntityTransformDesc = "Reset transform based on manipulator mode"; + static const char* const ResetManipulatorTitle = "Reset Manipulator"; + static const char* const ResetManipulatorDesc = "Reset the manipulator to recenter it on the selected entity"; + static const char* const ResetTransformLocalTitle = "Reset Transform (Local)"; + static const char* const ResetTransformLocalDesc = "Reset transform to local space"; + static const char* const ResetTransformWorldTitle = "Reset Transform (World)"; + static const char* const ResetTransformWorldDesc = "Reset transform to world space"; - static const char* const s_entityBoxSelectUndoRedoDesc = "Box Select Entities"; - static const char* const s_entityDeselectUndoRedoDesc = "Deselect Entity"; - static const char* const s_entitiesDeselectUndoRedoDesc = "Deselect Entities"; - static const char* const s_entitySelectUndoRedoDesc = "Select Entity"; - static const char* const s_dittoManipulatorUndoRedoDesc = "Ditto Manipulator"; - static const char* const s_resetManipulatorTranslationUndoRedoDesc = "Reset Manipulator Translation"; - static const char* const s_resetManipulatorOrientationUndoRedoDesc = "Reset Manipulator Orientation"; - static const char* const s_dittoEntityOrientationIndividualUndoRedoDesc = "Ditto orientation individual"; - static const char* const s_dittoEntityOrientationGroupUndoRedoDesc = "Ditto orientation group"; - static const char* const s_resetTranslationToParentUndoRedoDesc = "Reset translation to parent"; - static const char* const s_resetOrientationToParentUndoRedoDesc = "Reset orientation to parent"; - static const char* const s_dittoTranslationGroupUndoRedoDesc = "Ditto translation group"; - static const char* const s_dittoTranslationIndividualUndoRedoDesc = "Ditto translation individual"; - static const char* const s_dittoScaleIndividualWorldUndoRedoDesc = "Ditto scale individual world"; - static const char* const s_dittoScaleIndividualLocalUndoRedoDesc = "Ditto scale individual local"; - static const char* const s_snapToWorldGridUndoRedoDesc = "Snap to world grid"; - static const char* const s_showAllEntitiesUndoRedoDesc = s_showAllTitle; - static const char* const s_lockSelectionUndoRedoDesc = s_lockSelectionTitle; - static const char* const s_hideSelectionUndoRedoDesc = s_hideSelectionTitle; - static const char* const s_unlockAllUndoRedoDesc = s_unlockAllTitle; - static const char* const s_selectAllEntitiesUndoRedoDesc = s_selectAllTitle; - static const char* const s_invertSelectionUndoRedoDesc = s_invertSelectionTitle; - static const char* const s_duplicateUndoRedoDesc = s_duplicateTitle; - static const char* const s_deleteUndoRedoDesc = s_deleteTitle; + static const char* const EntityBoxSelectUndoRedoDesc = "Box Select Entities"; + static const char* const EntityDeselectUndoRedoDesc = "Deselect Entity"; + static const char* const EntitiesDeselectUndoRedoDesc = "Deselect Entities"; + static const char* const ChangeEntitySelectionUndoRedoDesc = "Change Selected Entity"; + static const char* const EntitySelectUndoRedoDesc = "Select Entity"; + static const char* const DittoManipulatorUndoRedoDesc = "Ditto Manipulator"; + static const char* const ResetManipulatorTranslationUndoRedoDesc = "Reset Manipulator Translation"; + static const char* const ResetManipulatorOrientationUndoRedoDesc = "Reset Manipulator Orientation"; + static const char* const DittoEntityOrientationIndividualUndoRedoDesc = "Ditto orientation individual"; + static const char* const DittoEntityOrientationGroupUndoRedoDesc = "Ditto orientation group"; + static const char* const ResetTranslationToParentUndoRedoDesc = "Reset translation to parent"; + static const char* const ResetOrientationToParentUndoRedoDesc = "Reset orientation to parent"; + static const char* const DittoTranslationGroupUndoRedoDesc = "Ditto translation group"; + static const char* const DittoTranslationIndividualUndoRedoDesc = "Ditto translation individual"; + static const char* const DittoScaleIndividualWorldUndoRedoDesc = "Ditto scale individual world"; + static const char* const DittoScaleIndividualLocalUndoRedoDesc = "Ditto scale individual local"; + static const char* const SnapToWorldGridUndoRedoDesc = "Snap to world grid"; + static const char* const ShowAllEntitiesUndoRedoDesc = ShowAllTitle; + static const char* const LockSelectionUndoRedoDesc = LockSelectionTitle; + static const char* const HideSelectionUndoRedoDesc = HideSelectionTitle; + static const char* const UnlockAllUndoRedoDesc = UnlockAllTitle; + static const char* const SelectAllEntitiesUndoRedoDesc = SelectAllTitle; + static const char* const InvertSelectionUndoRedoDesc = InvertSelectionTitle; + static const char* const DuplicateUndoRedoDesc = DuplicateTitle; + static const char* const DeleteUndoRedoDesc = DeleteTitle; static const char* const TransformModeClusterTranslateTooltip = "Switch to translate mode"; static const char* const TransformModeClusterRotateTooltip = "Switch to rotate mode"; @@ -148,14 +149,14 @@ namespace AzToolsFramework static const char* const SpaceClusterLocalTooltip = "Toggle local space lock"; static const char* const SnappingClusterSnapToWorldTooltip = "Snap selected entities to the world space grid"; - static const AZ::Color s_fadedXAxisColor = AZ::Color(AZ::u8(200), AZ::u8(127), AZ::u8(127), AZ::u8(255)); - static const AZ::Color s_fadedYAxisColor = AZ::Color(AZ::u8(127), AZ::u8(190), AZ::u8(127), AZ::u8(255)); - static const AZ::Color s_fadedZAxisColor = AZ::Color(AZ::u8(120), AZ::u8(120), AZ::u8(180), AZ::u8(255)); + static const AZ::Color FadedXAxisColor = AZ::Color(AZ::u8(200), AZ::u8(127), AZ::u8(127), AZ::u8(255)); + static const AZ::Color FadedYAxisColor = AZ::Color(AZ::u8(127), AZ::u8(190), AZ::u8(127), AZ::u8(255)); + static const AZ::Color FadedZAxisColor = AZ::Color(AZ::u8(120), AZ::u8(120), AZ::u8(180), AZ::u8(255)); - static const AZ::Color s_pickedOrientationColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); - static const AZ::Color s_selectedEntityAabbColor = AZ::Color(0.6f, 0.6f, 0.6f, 0.4f); + static const AZ::Color PickedOrientationColor = AZ::Color(0.0f, 1.0f, 0.0f, 1.0f); + static const AZ::Color SelectedEntityAabbColor = AZ::Color(0.6f, 0.6f, 0.6f, 0.4f); - static const float s_pivotSize = 0.075f; // the size of the pivot (box) to render when selected + static const float PivotSize = 0.075f; // the size of the pivot (box) to render when selected // data passed to manipulators when processing mouse interactions // m_entityIds should be sorted based on the entity hierarchy @@ -1107,7 +1108,7 @@ namespace AzToolsFramework { // begin selection undo/redo command entityBoxSelectData->m_boxSelectSelectionCommand = - AZStd::make_unique(EntityIdList(), s_entityBoxSelectUndoRedoDesc); + AZStd::make_unique(EntityIdList(), EntityBoxSelectUndoRedoDesc); // grab currently selected entities entityBoxSelectData->m_selectedEntityIdsBeforeBoxSelect = m_selectedEntityIds; }); @@ -1131,7 +1132,7 @@ namespace AzToolsFramework if (!entityBoxSelectData->m_potentialDeselectedEntityIds.empty() || !entityBoxSelectData->m_potentialSelectedEntityIds.empty()) { - ScopedUndoBatch undoBatch(s_entityBoxSelectUndoRedoDesc); + ScopedUndoBatch undoBatch(EntityBoxSelectUndoRedoDesc); // restore manipulator overrides when undoing if (m_entityIdManipulators.m_manipulators && m_selectedEntityIds.empty()) @@ -1174,7 +1175,7 @@ namespace AzToolsFramework } debugDisplay.DepthTestOff(); - debugDisplay.SetColor(s_selectedEntityAabbColor); + debugDisplay.SetColor(SelectedEntityAabbColor); for (AZ::EntityId entityId : entityBoxSelectData->m_potentialSelectedEntityIds) { @@ -1222,7 +1223,7 @@ namespace AzToolsFramework { // check here if translation or orientation override are set m_manipulatorMoveCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); } } @@ -1696,7 +1697,7 @@ namespace AzToolsFramework if (!UndoRedoOperationInProgress()) { - ScopedUndoBatch undoBatch(s_entitiesDeselectUndoRedoDesc); + ScopedUndoBatch undoBatch(EntitiesDeselectUndoRedoDesc); // restore manipulator overrides when undoing if (m_entityIdManipulators.m_manipulators) @@ -1706,7 +1707,7 @@ namespace AzToolsFramework // select must happen after to ensure in the undo/redo step the selection command // happens before the manipulator command - auto selectionCommand = AZStd::make_unique(EntityIdList(), s_entitiesDeselectUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(EntityIdList(), EntitiesDeselectUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); } @@ -1732,7 +1733,7 @@ namespace AzToolsFramework const auto nextEntityIds = EntityIdVectorFromContainer(m_selectedEntityIds); - ScopedUndoBatch undoBatch(s_entityDeselectUndoRedoDesc); + ScopedUndoBatch undoBatch(EntityDeselectUndoRedoDesc); // store manipulator state when removing last entity from selection if (m_entityIdManipulators.m_manipulators && nextEntityIds.empty()) @@ -1740,7 +1741,7 @@ namespace AzToolsFramework CreateEntityManipulatorDeselectCommand(undoBatch); } - auto selectionCommand = AZStd::make_unique(nextEntityIds, s_entityDeselectUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(nextEntityIds, EntityDeselectUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); @@ -1755,8 +1756,8 @@ namespace AzToolsFramework const auto nextEntityIds = EntityIdVectorFromContainer(m_selectedEntityIds); - ScopedUndoBatch undoBatch(s_entitySelectUndoRedoDesc); - auto selectionCommand = AZStd::make_unique(nextEntityIds, s_entitySelectUndoRedoDesc); + ScopedUndoBatch undoBatch(EntitySelectUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(nextEntityIds, EntitySelectUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); @@ -1772,6 +1773,13 @@ namespace AzToolsFramework void EditorTransformComponentSelection::ChangeSelectedEntity(const AZ::EntityId entityId) { + AZ_Assert( + !UndoRedoOperationInProgress(), + "ChangeSelectedEntity called from undo/redo operation - this is unexpected and not currently supported"); + + // ensure deselect/select is tracked as an atomic undo/redo operation + ScopedUndoBatch undoBatch(ChangeEntitySelectionUndoRedoDesc); + DeselectEntities(); SelectDeselect(entityId); } @@ -1799,7 +1807,7 @@ namespace AzToolsFramework const AZ::Transform& worldFromLocal = m_entityDataCache->GetVisibleEntityTransform(*entityIndex); const AZ::Vector3 boxPosition = worldFromLocal.TransformPoint(CalculateCenterOffset(entityId, m_pivotMode)); const AZ::Vector3 scaledSize = - AZ::Vector3(s_pivotSize) * CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); + AZ::Vector3(PivotSize) * CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); if (AabbIntersectMouseRay( mouseInteraction.m_mouseInteraction, @@ -2002,10 +2010,10 @@ namespace AzToolsFramework { if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch(s_dittoManipulatorUndoRedoDesc); + ScopedUndoBatch undoBatch(DittoManipulatorUndoRedoDesc); auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); if (entityId.IsValid()) { @@ -2131,7 +2139,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_lockSelectionUndoRedoDesc); + ScopedUndoBatch undoBatch(LockSelectionUndoRedoDesc); if (m_entityIdManipulators.m_manipulators) { @@ -2151,7 +2159,7 @@ namespace AzToolsFramework // lock selection AddAction( - m_actions, { QKeySequence(Qt::Key_L) }, LockSelection, s_lockSelectionTitle, s_lockSelectionDesc, + m_actions, { QKeySequence(Qt::Key_L) }, LockSelection, LockSelectionTitle, LockSelectionDesc, [lockUnlock]() { lockUnlock(true); @@ -2159,7 +2167,7 @@ namespace AzToolsFramework // unlock selection AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::Key_L) }, UnlockSelection, s_lockSelectionTitle, s_lockSelectionDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_L) }, UnlockSelection, LockSelectionTitle, LockSelectionDesc, [lockUnlock]() { lockUnlock(false); @@ -2169,7 +2177,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_hideSelectionUndoRedoDesc); + ScopedUndoBatch undoBatch(HideSelectionUndoRedoDesc); if (m_entityIdManipulators.m_manipulators) { @@ -2189,7 +2197,7 @@ namespace AzToolsFramework // hide selection AddAction( - m_actions, { QKeySequence(Qt::Key_H) }, HideSelection, s_hideSelectionTitle, s_hideSelectionDesc, + m_actions, { QKeySequence(Qt::Key_H) }, HideSelection, HideSelectionTitle, HideSelectionDesc, [showHide]() { showHide(false); @@ -2197,7 +2205,7 @@ namespace AzToolsFramework // show selection AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::Key_H) }, ShowSelection, s_hideSelectionTitle, s_hideSelectionDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_H) }, ShowSelection, HideSelectionTitle, HideSelectionDesc, [showHide]() { showHide(true); @@ -2205,12 +2213,12 @@ namespace AzToolsFramework // unlock all entities in the level/scene AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_L) }, UnlockAll, s_unlockAllTitle, s_unlockAllDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_L) }, UnlockAll, UnlockAllTitle, UnlockAllDesc, []() { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_unlockAllUndoRedoDesc); + ScopedUndoBatch undoBatch(UnlockAllUndoRedoDesc); EnumerateEditorEntities( [](AZ::EntityId entityId) @@ -2222,12 +2230,12 @@ namespace AzToolsFramework // show all entities in the level/scene AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_H) }, ShowAll, s_showAllTitle, s_showAllDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_H) }, ShowAll, ShowAllTitle, ShowAllDesc, []() { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_showAllEntitiesUndoRedoDesc); + ScopedUndoBatch undoBatch(ShowAllEntitiesUndoRedoDesc); EnumerateEditorEntities( [](AZ::EntityId entityId) @@ -2239,17 +2247,17 @@ namespace AzToolsFramework // select all entities in the level/scene AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::Key_A) }, SelectAll, s_selectAllTitle, s_selectAllDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_A) }, SelectAll, SelectAllTitle, SelectAllDesc, [this]() { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_selectAllEntitiesUndoRedoDesc); + ScopedUndoBatch undoBatch(SelectAllEntitiesUndoRedoDesc); if (m_entityIdManipulators.m_manipulators) { auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); // note, nothing will change that the manipulatorCommand needs to keep track // for after so no need to call SetManipulatorAfter @@ -2269,7 +2277,7 @@ namespace AzToolsFramework auto nextEntityIds = EntityIdVectorFromContainer(m_selectedEntityIds); - auto selectionCommand = AZStd::make_unique(nextEntityIds, s_selectAllEntitiesUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(nextEntityIds, SelectAllEntitiesUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); @@ -2279,17 +2287,17 @@ namespace AzToolsFramework // invert current selection AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I) }, InvertSelect, s_invertSelectionTitle, s_invertSelectionDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_I) }, InvertSelect, InvertSelectionTitle, InvertSelectionDesc, [this]() { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_invertSelectionUndoRedoDesc); + ScopedUndoBatch undoBatch(InvertSelectionUndoRedoDesc); if (m_entityIdManipulators.m_manipulators) { auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); // note, nothing will change that the manipulatorCommand needs to keep track // for after so no need to call SetManipulatorAfter @@ -2316,7 +2324,7 @@ namespace AzToolsFramework auto nextEntityIds = EntityIdVectorFromContainer(entityIds); - auto selectionCommand = AZStd::make_unique(nextEntityIds, s_invertSelectionUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(nextEntityIds, InvertSelectionUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); @@ -2326,7 +2334,7 @@ namespace AzToolsFramework // duplicate selection AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::Key_D) }, DuplicateSelect, s_duplicateTitle, s_duplicateDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_D) }, DuplicateSelect, DuplicateTitle, DuplicateDesc, []() { AZ_PROFILE_FUNCTION(AzToolsFramework); @@ -2338,8 +2346,8 @@ namespace AzToolsFramework QApplication::focusWidget()->clearFocus(); } - ScopedUndoBatch undoBatch(s_duplicateUndoRedoDesc); - auto selectionCommand = AZStd::make_unique(EntityIdList(), s_duplicateUndoRedoDesc); + ScopedUndoBatch undoBatch(DuplicateUndoRedoDesc); + auto selectionCommand = AZStd::make_unique(EntityIdList(), DuplicateUndoRedoDesc); selectionCommand->SetParent(undoBatch.GetUndoBatch()); selectionCommand.release(); @@ -2351,12 +2359,12 @@ namespace AzToolsFramework // delete selection AddAction( - m_actions, { QKeySequence(Qt::Key_Delete) }, DeleteSelect, s_deleteTitle, s_deleteDesc, + m_actions, { QKeySequence(Qt::Key_Delete) }, DeleteSelect, DeleteTitle, DeleteDesc, [this]() { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_deleteUndoRedoDesc); + ScopedUndoBatch undoBatch(DeleteUndoRedoDesc); CreateEntityManipulatorDeselectCommand(undoBatch); @@ -2375,14 +2383,14 @@ namespace AzToolsFramework }); AddAction( - m_actions, { QKeySequence(Qt::Key_P) }, EditPivot, s_togglePivotTitleEditMenu, s_togglePivotDesc, + m_actions, { QKeySequence(Qt::Key_P) }, EditPivot, TogglePivotTitleEditMenu, TogglePivotDesc, [this]() { ToggleCenterPivotSelection(); }); AddAction( - m_actions, { QKeySequence(Qt::Key_R) }, EditReset, s_resetEntityTransformTitle, s_resetEntityTransformDesc, + m_actions, { QKeySequence(Qt::Key_R) }, EditReset, ResetEntityTransformTitle, ResetEntityTransformDesc, [this]() { switch (m_mode) @@ -2400,11 +2408,11 @@ namespace AzToolsFramework }); AddAction( - m_actions, { QKeySequence(Qt::CTRL + Qt::Key_R) }, EditResetManipulator, s_resetManipulatorTitle, s_resetManipulatorDesc, + m_actions, { QKeySequence(Qt::CTRL + Qt::Key_R) }, EditResetManipulator, ResetManipulatorTitle, ResetManipulatorDesc, AZStd::bind(AZStd::mem_fn(&EditorTransformComponentSelection::DelegateClearManipulatorOverride), this)); AddAction( - m_actions, { QKeySequence(Qt::ALT + Qt::Key_R) }, EditResetLocal, s_resetTransformLocalTitle, s_resetTransformLocalDesc, + m_actions, { QKeySequence(Qt::ALT + Qt::Key_R) }, EditResetLocal, ResetTransformLocalTitle, ResetTransformLocalDesc, [this]() { switch (m_mode) @@ -2422,7 +2430,7 @@ namespace AzToolsFramework }); AddAction( - m_actions, { QKeySequence(Qt::SHIFT + Qt::Key_R) }, EditResetWorld, s_resetTransformWorldTitle, s_resetTransformWorldDesc, + m_actions, { QKeySequence(Qt::SHIFT + Qt::Key_R) }, EditResetWorld, ResetTransformWorldTitle, ResetTransformWorldDesc, [this]() { switch (m_mode) @@ -2431,7 +2439,7 @@ namespace AzToolsFramework { // begin an undo batch so operations inside CopyOrientation... and // DelegateClear... are grouped into a single undo/redo - ScopedUndoBatch undoBatch{ s_resetTransformWorldTitle }; + ScopedUndoBatch undoBatch{ ResetTransformWorldTitle }; CopyOrientationToSelectedEntitiesIndividual(AZ::Quaternion::CreateIdentity()); ClearManipulatorOrientationOverride(); } @@ -2685,7 +2693,7 @@ namespace AzToolsFramework const AZStd::array snapAxes = { AZ::Vector3::CreateAxisX(), AZ::Vector3::CreateAxisY(), AZ::Vector3::CreateAxisZ() }; - ScopedUndoBatch undoBatch(s_snapToWorldGridUndoRedoDesc); + ScopedUndoBatch undoBatch(SnapToWorldGridUndoRedoDesc); for (const AZ::EntityId& entityId : m_selectedEntityIds) { ScopedUndoBatch::MarkEntityDirty(entityId); @@ -2870,10 +2878,10 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch(s_resetManipulatorTranslationUndoRedoDesc); + ScopedUndoBatch undoBatch(ResetManipulatorTranslationUndoRedoDesc); auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); m_pivotOverrideFrame.ResetPickedTranslation(); m_pivotOverrideFrame.m_pickedEntityIdOverride.SetInvalid(); @@ -2896,10 +2904,10 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch{ s_resetManipulatorOrientationUndoRedoDesc }; + ScopedUndoBatch undoBatch{ ResetManipulatorOrientationUndoRedoDesc }; auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); m_pivotOverrideFrame.ResetPickedOrientation(); m_pivotOverrideFrame.m_pickedEntityIdOverride.SetInvalid(); @@ -2961,13 +2969,13 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch(s_dittoTranslationGroupUndoRedoDesc); + ScopedUndoBatch undoBatch(DittoTranslationGroupUndoRedoDesc); // store previous translation manipulator position const AZ::Vector3 previousPivotTranslation = m_entityIdManipulators.m_manipulators->GetLocalTransform().GetTranslation(); auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); // refresh the transform pivot override if it's set if (m_pivotOverrideFrame.m_translationOverride) @@ -3017,10 +3025,10 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch(s_dittoTranslationIndividualUndoRedoDesc); + ScopedUndoBatch undoBatch(DittoTranslationIndividualUndoRedoDesc); auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); // refresh the transform pivot override if it's set if (m_pivotOverrideFrame.m_translationOverride) @@ -3055,7 +3063,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_dittoScaleIndividualWorldUndoRedoDesc); + ScopedUndoBatch undoBatch(DittoScaleIndividualWorldUndoRedoDesc); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3089,7 +3097,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_dittoScaleIndividualLocalUndoRedoDesc); + ScopedUndoBatch undoBatch(DittoScaleIndividualLocalUndoRedoDesc); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3110,10 +3118,10 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch{ s_dittoEntityOrientationIndividualUndoRedoDesc }; + ScopedUndoBatch undoBatch{ DittoEntityOrientationIndividualUndoRedoDesc }; auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3148,10 +3156,10 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch(s_dittoEntityOrientationGroupUndoRedoDesc); + ScopedUndoBatch undoBatch(DittoEntityOrientationGroupUndoRedoDesc); auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3194,7 +3202,7 @@ namespace AzToolsFramework { AZ_PROFILE_FUNCTION(AzToolsFramework); - ScopedUndoBatch undoBatch(s_resetOrientationToParentUndoRedoDesc); + ScopedUndoBatch undoBatch(ResetOrientationToParentUndoRedoDesc); for (const auto& entityIdLookup : m_entityIdManipulators.m_lookups) { ScopedUndoBatch::MarkEntityDirty(entityIdLookup.first); @@ -3215,7 +3223,7 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { - ScopedUndoBatch undoBatch(s_resetTranslationToParentUndoRedoDesc); + ScopedUndoBatch undoBatch(ResetTranslationToParentUndoRedoDesc); ManipulatorEntityIds manipulatorEntityIds; BuildSortedEntityIdVectorFromEntityIdMap(m_entityIdManipulators.m_lookups, manipulatorEntityIds.m_entityIds); @@ -3251,7 +3259,7 @@ namespace AzToolsFramework void EditorTransformComponentSelection::PopulateEditorGlobalContextMenu( QMenu* menu, [[maybe_unused]] const AZ::Vector2& point, [[maybe_unused]] int flags) { - QAction* action = menu->addAction(QObject::tr(s_togglePivotTitleRightClick)); + QAction* action = menu->addAction(QObject::tr(TogglePivotTitleRightClick)); QObject::connect( action, &QAction::triggered, action, [this]() @@ -3329,15 +3337,15 @@ namespace AzToolsFramework : 1.0f; }; - display.SetColor(s_fadedXAxisColor); + display.SetColor(FadedXAxisColor); display.DrawLine( transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisX().GetNormalizedSafe() * axisLength * axisFlip(AZ::Vector3::CreateAxisX())); - display.SetColor(s_fadedYAxisColor); + display.SetColor(FadedYAxisColor); display.DrawLine( transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisY().GetNormalizedSafe() * axisLength * axisFlip(AZ::Vector3::CreateAxisY())); - display.SetColor(s_fadedZAxisColor); + display.SetColor(FadedZAxisColor); display.DrawLine( transform.GetTranslation(), transform.GetTranslation() + transform.GetBasisZ().GetNormalizedSafe() * axisLength * axisFlip(AZ::Vector3::CreateAxisZ())); @@ -3416,11 +3424,11 @@ namespace AzToolsFramework CalculatePivotTranslation(m_pivotOverrideFrame.m_pickedEntityIdOverride, m_pivotMode)); const float scaledSize = - s_pivotSize * CalculateScreenToWorldMultiplier(pickedEntityWorldTransform.GetTranslation(), cameraState); + PivotSize * CalculateScreenToWorldMultiplier(pickedEntityWorldTransform.GetTranslation(), cameraState); debugDisplay.DepthWriteOff(); debugDisplay.DepthTestOff(); - debugDisplay.SetColor(s_pickedOrientationColor); + debugDisplay.SetColor(PickedOrientationColor); debugDisplay.DrawWireSphere(pickedEntityWorldTransform.GetTranslation(), scaledSize); @@ -3462,7 +3470,7 @@ namespace AzToolsFramework const AZ::Vector3 boxPosition = worldFromLocal.TransformPoint(CalculateCenterOffset(entityId, m_pivotMode)); const AZ::Vector3 scaledSize = - AZ::Vector3(s_pivotSize) * CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); + AZ::Vector3(PivotSize) * CalculateScreenToWorldMultiplier(worldFromLocal.GetTranslation(), cameraState); const AZ::Color hiddenNormal[] = { AzFramework::ViewportColors::SelectedColor, AzFramework::ViewportColors::HiddenColor }; @@ -3708,7 +3716,7 @@ namespace AzToolsFramework if (m_entityIdManipulators.m_manipulators) { auto manipulatorCommand = - AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), s_manipulatorUndoRedoName); + AZStd::make_unique(CreateManipulatorCommandStateFromSelf(), ManipulatorUndoRedoName); manipulatorCommand->SetManipulatorAfter(EntityManipulatorCommand::State()); diff --git a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp index 241ee3f576..72cafe5cd5 100644 --- a/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp +++ b/Code/Framework/AzToolsFramework/Tests/EditorTransformComponentSelectionTests.cpp @@ -866,9 +866,7 @@ namespace UnitTest EXPECT_THAT(selectedEntitiesAfter, UnorderedElementsAre(m_entityId1)); } - TEST_F( - EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, - BoxSelectWithNoInitialSelectionAddsEntitiesToSelection) + TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, BoxSelectWithNoInitialSelectionAddsEntitiesToSelection) { AzToolsFramework::ed_viewportStickySelect = true; @@ -989,6 +987,30 @@ namespace UnitTest EXPECT_TRUE(selectedEntitiesAfter.empty()); } + TEST_F(EditorTransformComponentSelectionViewportPickingManipulatorTestFixture, UnstickyUndoOperationForChangeInSelectionIsAtomic) + { + AzToolsFramework::ed_viewportStickySelect = false; + + PositionEntities(); + PositionCamera(m_cameraState); + + AzToolsFramework::SelectEntity(m_entityId1); + + // calculate the position in screen space of the second entity + const auto entity2ScreenPosition = AzFramework::WorldToScreen(m_entity2WorldTranslation, m_cameraState); + + // single click select entity2 + m_actionDispatcher->CameraState(m_cameraState)->MousePosition(entity2ScreenPosition)->MouseLButtonDown()->MouseLButtonUp(); + + // undo action + AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequestBus::Events::UndoPressed); + + // entity1 is selected after undo + using ::testing::UnorderedElementsAre; + auto selectedEntitiesAfter = SelectedEntities(); + EXPECT_THAT(selectedEntitiesAfter, UnorderedElementsAre(m_entityId1)); + } + using EditorTransformComponentSelectionManipulatorTestFixture = IndirectCallManipulatorViewportInteractionFixtureMixin; From 169b8f36793f93d0dcab7902f736617b1952cd4c Mon Sep 17 00:00:00 2001 From: galibzon <66021303+galibzon@users.noreply.github.com> Date: Wed, 15 Sep 2021 07:50:14 -0500 Subject: [PATCH 22/26] [ATOM-5441] Shader Builders May Fail When Multiple New Files Are Added (#3862) * [ATOM-5441] Shader Builders May Fail When Multiple New Files Are Added ShaderAssetBuilder::CreateJobs now recursively parses *.azsl files looking for #include lines and builds the list of source dependencies using a depth-first algorithm. It was using MCPP before but not anymore (during CreateJobs). The new algorithm may over prescribe, but fixes the issues when multiple new shader related files are added, at once or out of order, to a game project or Gem. Overall the new ShaderAssetBuilder::CreateJobs() is around 40% faster and, of course, handles source dependencies in a robust way. * Added new test suite to AutomatedTesting project: Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py Bug fix to Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp discovered thanks to the automated test suite. The idea is that CreateJobs doesn't fail if the AZSL file doesn't exist. The failure is deferred during ProcessJob. This way if the AZSL file exists the .shader file is rebuilt automatically. * For testability purposes and avoid memory leakage errors during Unit Tests created the class ShaderBuilderUtility::IncludedFilesParser Now accepts "# include " with space between '#' and 'include'. Also now accepts the '-' character inside the file path. Added Unit Test to validate all cases of "#include " parsing. * Fixed linux runtime issues for Unit Tests in Atom_Asset_Shader.Tests Signed-off-by: garrieta --- .../PythonTests/atom_renderer/CMakeLists.txt | 11 + .../DependencyValidation.azsl.txt | 55 +++++ .../DependencyValidation.shader.txt | 26 +++ .../ShaderAssetBuilder/Test1Color.azsli.txt | 18 ++ .../ShaderAssetBuilder/Test2Color.azsli.txt | 16 ++ .../ShaderAssetBuilder/Test3Color.azsli.txt | 16 ++ ...pilesShaderAsChainOfDependenciesChanges.py | 188 ++++++++++++++++++ .../test_Atom_ShaderBuildPipelineSuite.py | 19 ++ Gems/Atom/Asset/Shader/Code/CMakeLists.txt | 1 + .../Code/Source/Editor/ShaderAssetBuilder.cpp | 150 +++++++++++--- .../Source/Editor/ShaderBuilderUtility.cpp | 46 +++++ .../Code/Source/Editor/ShaderBuilderUtility.h | 23 +++ .../Code/Tests/ShaderBuilderUtilityTests.cpp | 86 ++++++++ ...om_asset_shader_builders_tests_files.cmake | 1 + .../PostProcessing/FastDepthAwareBlurHor.azsl | 2 +- .../PostProcessing/FastDepthAwareBlurVer.azsl | 2 +- .../Assets/Shaders/PostProcessing/SMAA.azsli | 2 +- 17 files changed, 629 insertions(+), 33 deletions(-) create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py create mode 100644 AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py create mode 100644 Gems/Atom/Asset/Shader/Code/Tests/ShaderBuilderUtilityTests.cpp diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt index f056623ecd..992420904c 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/CMakeLists.txt @@ -46,4 +46,15 @@ if(PAL_TRAIT_BUILD_HOST_TOOLS AND PAL_TRAIT_BUILD_TESTS_SUPPORTED AND AutomatedT AutomatedTesting.Assets Editor ) + ly_add_pytest( + NAME AutomatedTesting::AtomRenderer_HydraTests_ShaderBuildPipeline + TEST_SUITE main + PATH ${CMAKE_CURRENT_LIST_DIR}/test_Atom_ShaderBuildPipelineSuite.py + TEST_SERIAL + TIMEOUT 600 + RUNTIME_DEPENDENCIES + AssetProcessor + AutomatedTesting.Assets + Editor + ) endif() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt new file mode 100644 index 0000000000..c0b64f40b7 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.azsl.txt @@ -0,0 +1,55 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +#include + +#include "Test1Color.azsli" +#include + +ShaderResourceGroup DummySrg : SRG_PerDraw +{ + float4 m_color; +} + +struct VSInput +{ + float3 m_position : POSITION; + float4 m_color : COLOR0; +}; + +struct VSOutput +{ + float4 m_position : SV_Position; + float4 m_color : COLOR0; +}; + +VSOutput MainVS(VSInput vsInput) +{ + VSOutput OUT; + OUT.m_position = float4(vsInput.m_position, 1.0); + OUT.m_color = vsInput.m_color; + return OUT; +} + +struct PSOutput +{ + float4 m_color : SV_Target0; +}; + +PSOutput MainPS(VSOutput vsOutput) +{ + PSOutput OUT; + + OUT.m_color = GetTest1Color(DummySrg::m_color) + GetTest3Color(DummySrg::m_color); + + return OUT; +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt new file mode 100644 index 0000000000..b0eac1783e --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/DependencyValidation.shader.txt @@ -0,0 +1,26 @@ +// This is a dummy shader used to validate detection of "#included files" +{ + "Source" : "DependencyValidation.azsl", + + "DepthStencilState" : { + "Depth" : { "Enable" : false, "CompareFunc" : "GreaterEqual" } + }, + + "DrawList" : "forward", + + "ProgramSettings": + { + "EntryPoints": + [ + { + "name": "MainVS", + "type": "Vertex" + }, + { + "name": "MainPS", + "type": "Fragment" + } + ] + } + +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt new file mode 100644 index 0000000000..7d097beafb --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test1Color.azsli.txt @@ -0,0 +1,18 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +#include "Test2Color.azsli" + +float4 GetTest1Color(float4 color) +{ + return color + GetTest2Color(color); +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt new file mode 100644 index 0000000000..2ef946b947 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test2Color.azsli.txt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +float4 GetTest2Color(float4 color) +{ + return color * 0.5; +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt new file mode 100644 index 0000000000..73b0cca434 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/TestAssets/ShaderAssetBuilder/Test3Color.azsli.txt @@ -0,0 +1,16 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + + /* + This is a dummy shader used to validate detection of "#included files" + */ + +float4 GetTest3Color(float4 color) +{ + return color * 0.13; +} diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py new file mode 100644 index 0000000000..a05420d960 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges.py @@ -0,0 +1,188 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +""" + +import os +import shutil + +def _copy_file(src_file, src_path, target_file, target_path): + # type: (str, str, str, str) -> None + """ + Copies the [src_file] located in [src_path] to the [target_file] located at [target_path]. + Leaves the [target_file] unlocked for reading and writing privileges + :param src_file: The source file to copy (file name) + :param src_path: The source file's path + :param target_file: The target file to copy into (file name) + :param target_path: The target file's path + :return: None + """ + target_file_path = os.path.join(target_path, target_file) + src_file_path = os.path.join(src_path, src_file) + if os.path.exists(target_file_path): + fs.unlock_file(target_file_path) + shutil.copyfile(src_file_path, target_file_path) + +def _copy_tmp_files_in_order(src_directory, file_list, dst_directory, wait_time_in_between = 0.0): + # type: (str, list, str, float) -> None + """ + This function assumes that for each file name listed in @file_list + there's file named "@filename.txt" which the original source file + but they will be copied with just the @filename (.txt removed). + """ + for filename in file_list: + src_name = f"{filename}.txt" + _copy_file(src_name, src_directory, filename, dst_directory) + if wait_time_in_between > 0.0: + print(f"Created {filename} in {dst_directory}") + general.idle_wait(wait_time_in_between) + + +def _remove_file(src_file, src_path): + # type: (str, str) -> None + """ + Removes the [src_file] located in [src_path]. + :param src_file: The source file to copy (file name) + :param src_path: The source file's path + :return: None + """ + src_file_path = os.path.join(src_path, src_file) + if os.path.exists(src_file_path): + fs.unlock_file(src_file_path) + os.remove(src_file_path) + + +def _remove_files(directory, file_list): + for filename in file_list: + _remove_file(filename, directory) + + +def _asset_exists(cache_relative_path): + asset_id = azasset.AssetCatalogRequestBus(azbus.Broadcast, "GetAssetIdByPath", cache_relative_path, azmath.Uuid(), False) + return asset_id.is_valid() + +# List of results that we want to check, this is not 100% necessary but it's a good +# practice to make it easier to debug tests. +# Here we define a tuple of tests +class Results(): + azshader_was_removed = ("azshader was removed", "Failed to remove azshader") + azshader_was_compiled = ("azshader was compiled", "Failed to compile azshader") + + +def ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(): + """ + This test validates [ATOM-5441] Shader Builders May Fail When Multiple New Files Are Added + It creates source assets to compile a particular shader. + 1- The first phase generates the source assets out of order and slowly. The AP should + wakeup each time one of the source dependencies appears but will fail each time. Only when the + last dependency appears then the shader should build successfully. + 2- The second phase is similar as above, except that all source assets will be created + at once and We also expect that in the end the shader is built successfully. + """ + # Required for automated tests + helper.init_idle() + + game_root_path = os.path.normpath(general.get_game_folder()) + game_asset_path = os.path.join(game_root_path, "Assets") + + base_dir = os.path.dirname(__file__) + src_assets_subdir = os.path.join(base_dir, "TestAssets", "ShaderAssetBuilder") + + with Tracer() as error_tracer: + # The script drives the execution of the test, to return the flow back to the editor, + # we will tick it one time + general.idle_wait_frames(1) + + # This is the order in which the source assets should be deployed + # to avoid source dependency issues with the old MCPP-based CreateJobs. + file_list = [ + "Test2Color.azsli", + "Test3Color.azsli", + "Test1Color.azsli", + "DependencyValidation.azsl", + "DependencyValidation.shader" + ] + + reverse_file_list = file_list[::-1] + + # Remove files in reverse order + _remove_files(game_asset_path, reverse_file_list) + + # Wait here until the azshader doesn't exist anymore. + azshader_name = "assets/dependencyvalidation.azshader" + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + + Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + + _copy_tmp_files_in_order(src_assets_subdir, file_list, game_asset_path, 1.0) + + # Give enough time to AP to compile the shader + helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) + + Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + + # The first part was about compiling the shader under normal conditions. + # Let's remove the files from the previous phase and will proceed + # to make the source files visible to the AP in reverse order. The + # ShaderAssetBuilder will only succeed when the last file becomes visible. + _remove_files(game_asset_path, reverse_file_list) + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + + # Remark, if you are running this test manually from the Editor with "pyRunFile", + # You'll notice how the AP issues notifications that it fails to compile the shader + # as the source files are being copied to the "Assets" subfolder. + # Those errors are OK and also expected because We need the AP to wake up as each + # reported source dependency exists. Once the last file is copied then all source + # dependencies are fully satisfied and the shader should compile successfully. + # And this summarizes the importance of this Test: The previous version + # of ShaderAssetBuilder::CreateJobs was incapable of compiling the shader under the conditions + # presented in this test, but with the new version of ShaderAssetBuilder::CreateJobs, which + # doesn't use MCPP for #include files discovery, it should eventually compile the shader + # once all the source files are in place. + _copy_tmp_files_in_order(src_assets_subdir, reverse_file_list, game_asset_path, 3.0) + + # Give enough time to AP to compile the shader + helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) + + Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + + # The last phase of the test puts stress on potential race conditions + # when all required files appear as soon as possible. + + # First Clean up. + # Remove left over files. + _remove_files(game_asset_path, reverse_file_list) + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + Report.critical_result(Results.azshader_was_removed, not _asset_exists(azshader_name)) + + # Now let's copy all the source files to the "Assets" folder as fast as possible. + _copy_tmp_files_in_order(src_assets_subdir, reverse_file_list, game_asset_path) + + # Give enough time to AP to compile the shader + helper.wait_for_condition(lambda: _asset_exists(azshader_name), 60.0) + + Report.critical_result(Results.azshader_was_compiled, _asset_exists(azshader_name)) + + # All good, let's cleanup leftover files before closing the test. + _remove_files(game_asset_path, reverse_file_list) + helper.wait_for_condition(lambda: not _asset_exists(azshader_name), 5.0) + + +if __name__ == "__main__": + # All exposed python bindings are in azlmbr + import azlmbr.legacy.general as general + import azlmbr.bus as azbus + import azlmbr.asset as azasset + import azlmbr.math as azmath + + # Import report and test helper utilities + from editor_python_test_tools.utils import Report + from editor_python_test_tools.utils import TestHelper as helper + from editor_python_test_tools.utils import Tracer + import ly_test_tools.environment.file_system as fs + + Report.start_test(ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges) \ No newline at end of file diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py new file mode 100644 index 0000000000..9ef93ea238 --- /dev/null +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_ShaderBuildPipelineSuite.py @@ -0,0 +1,19 @@ +""" +Copyright (c) Contributors to the Open 3D Engine Project. +For complete copyright and license terms please see the LICENSE at the root of this distribution. + +SPDX-License-Identifier: Apache-2.0 OR MIT + +Main suite tests for the Shader Build Pipeline. +""" +import pytest +from ly_test_tools import LAUNCHERS +from ly_test_tools.o3de.editor_test import EditorTestSuite, EditorSingleTest + +@pytest.mark.parametrize("project", ["AutomatedTesting"]) +@pytest.mark.parametrize("launcher_platform", ['windows_editor']) +class TestShaderBuildPipelineMain(EditorTestSuite): + """Holds tests for Shader Build Pipeline validation""" + + class ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges(EditorSingleTest): + from .atom_hydra_scripts import hydra_ShaderAssetBuilder_RecompilesShaderAsChainOfDependenciesChanges as test_module \ No newline at end of file diff --git a/Gems/Atom/Asset/Shader/Code/CMakeLists.txt b/Gems/Atom/Asset/Shader/Code/CMakeLists.txt index c0bdfd4a8b..efbedb0a38 100644 --- a/Gems/Atom/Asset/Shader/Code/CMakeLists.txt +++ b/Gems/Atom/Asset/Shader/Code/CMakeLists.txt @@ -65,6 +65,7 @@ ly_add_target( AZ::AzFramework AZ::AzToolsFramework Gem::Atom_RHI.Edit + Gem::Atom_RPI.Edit Gem::Atom_RPI.Public ) diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp index 6673da2be3..2babba1ecc 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderAssetBuilder.cpp @@ -61,10 +61,99 @@ namespace AZ static constexpr char ShaderAssetBuilderName[] = "ShaderAssetBuilder"; static constexpr uint32_t ShaderAssetBuildTimestampParam = 0; + //! The search will start in @currentFolderPath. + //! if the file is not found then it searches in order of appearence in @includeDirectories. + //! If the search yields no existing file it returns an empty string. + static AZStd::string DiscoverFullPath(AZStd::string_view normalizedRelativePath, AZStd::string_view currentFolderPath, const AZStd::vector& includeDirectories) + { + AZStd::string fullPath; + AzFramework::StringFunc::Path::Join(currentFolderPath.data(), normalizedRelativePath.data(), fullPath); + if (AZ::IO::SystemFile::Exists(fullPath.c_str())) + { + return fullPath; + } + + for (const auto &includeDir : includeDirectories) + { + AzFramework::StringFunc::Path::Join(includeDir.c_str(), normalizedRelativePath.data(), fullPath); + if (AZ::IO::SystemFile::Exists(fullPath.c_str())) + { + return fullPath; + } + } + + return ""; + } + + // Appends to @includedFiles normalized paths of possible future locations of the file @normalizedRelativePath. + // The future locations are each directory listed in @includeDirectories joined with @normalizedRelativePath. + // This function is called when an included file doesn't exist but We need to declare source dependency so a .shader + // asset is rebuilt when the missing file appears in the future. + static void AppendListOfPossibleFutureLocations(AZStd::unordered_set& includedFiles, AZStd::string_view normalizedRelativePath, AZStd::string_view currentFolderPath, const AZStd::vector& includeDirectories) + { + AZStd::string fullPath; + AzFramework::StringFunc::Path::Join(currentFolderPath.data(), normalizedRelativePath.data(), fullPath); + includedFiles.insert(fullPath); + for (const auto &includeDir : includeDirectories) + { + AzFramework::StringFunc::Path::Join(includeDir.c_str(), normalizedRelativePath.data(), fullPath); + includedFiles.insert(fullPath); + } + } + + //! Parses, using depth-first recursive approach, azsl files. Looks for '#include ' or '#include "foo/bar/blah.h"' lines + //! and in turn parses the included files. + //! The included files are searched in the directories listed in @includeDirectories. Basically it's a similar approach + //! as how most C-preprocessors would find included files. + static void GetListOfIncludedFiles(AZStd::string_view sourceFilePath, const AZStd::vector& includeDirectories, + const ShaderBuilderUtility::IncludedFilesParser& includedFilesParser, AZStd::unordered_set& includedFiles) + { + auto outcome = includedFilesParser.ParseFileAndGetIncludedFiles(sourceFilePath); + if (!outcome.IsSuccess()) + { + AZ_Warning(ShaderAssetBuilderName, false, outcome.GetError().c_str()); + return; + } + + // Cache the path of the folder where @sourceFilePath is located. + AZStd::string sourceFileFolderPath; + { + AZStd::string drive; + AzFramework::StringFunc::Path::Split(sourceFilePath.data(), &drive, &sourceFileFolderPath); + if (!drive.empty()) + { + AzFramework::StringFunc::Path::Join(drive.c_str(), sourceFileFolderPath.c_str(), sourceFileFolderPath); + } + } + + auto listOfRelativePaths = outcome.TakeValue(); + for (auto relativePath : listOfRelativePaths) + { + auto fullPath = DiscoverFullPath(relativePath, sourceFileFolderPath, includeDirectories); + if (fullPath.empty()) + { + // The file doesn't exist in any of the includeDirectories. It doesn't exist in @sourceFileFolderPath either. + // The file may appear in the future in one of those directories, We must build an exhaustive list + // of full file paths where the file may appear in the future. + AppendListOfPossibleFutureLocations(includedFiles, relativePath, sourceFileFolderPath, includeDirectories); + continue; + } + + // Add the file to the list and keep parsing recursively. + if (includedFiles.count(fullPath)) + { + continue; + } + includedFiles.insert(fullPath); + GetListOfIncludedFiles(fullPath, includeDirectories, includedFilesParser, includedFiles); + } + } + void ShaderAssetBuilder::CreateJobs(const AssetBuilderSDK::CreateJobsRequest& request, AssetBuilderSDK::CreateJobsResponse& response) const { AZStd::string fullPath; AzFramework::StringFunc::Path::ConstructFull(request.m_watchFolder.data(), request.m_sourceFile.data(), fullPath, true); + ShaderBuilderUtility::IncludedFilesParser includedFilesParser; AZ_TracePrintf(ShaderAssetBuilderName, "CreateJobs for Shader \"%s\"\n", fullPath.data()); @@ -90,36 +179,6 @@ namespace AZ AZStd::string azslFullPath; ShaderBuilderUtility::GetAbsolutePathToAzslFile(fullPath, shaderSourceData.m_source, azslFullPath); - if (!IO::FileIOBase::GetInstance()->Exists(azslFullPath.c_str())) - { - AZ_Error( - ShaderAssetBuilderName, false, "Shader program listed as the source entry does not exist: %s.", azslFullPath.c_str()); - response.m_result = AssetBuilderSDK::CreateJobsResultCode::Failed; - return; - } - - - GlobalBuildOptions buildOptions = ReadBuildOptions(ShaderAssetBuilderName); - - // [GFX TODO] [ATOM-14966] In principle, based on macro definitions, included files can change per supervariant. - // So, the list of source asset dependencies must be collected by running MCPP on each supervariant. - // For now, we will run MCPP only once because CreateJobs() should be as light as possible. - // - // Regardless of the PlatformInfo and enabled ShaderPlatformInterfaces, the azsl file will be preprocessed - // with the sole purpose of extracting all included files. For each included file a SourceDependency will be declared. - PreprocessorData output; - buildOptions.m_compilerArguments.Merge(shaderSourceData.m_compiler); - PreprocessFile(azslFullPath, output, buildOptions.m_preprocessorSettings, true, true); - for (auto includePath : output.includedPaths) - { - // m_sourceFileDependencyList does not support paths with "." or ".." for relative lookup, but the preprocessor - // may produce path strings like "C:/a/b/c/../../d/file.azsli" so we have to normalize - AzFramework::StringFunc::Path::Normalize(includePath); - - AssetBuilderSDK::SourceFileDependency includeFileDependency; - includeFileDependency.m_sourceFileDependencyPath = includePath; - response.m_sourceFileDependencyList.emplace_back(includeFileDependency); - } { // Add the AZSL as source dependency @@ -128,6 +187,26 @@ namespace AZ response.m_sourceFileDependencyList.emplace_back(azslFileDependency); } + if (!IO::FileIOBase::GetInstance()->Exists(azslFullPath.c_str())) + { + AZ_Error( + ShaderAssetBuilderName, false, "Shader program listed as the source entry does not exist: %s.", azslFullPath.c_str()); + // Treat as success, so when the azsl file shows up the AP will try to recompile. + response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; + return; + } + + GlobalBuildOptions buildOptions = ReadBuildOptions(ShaderAssetBuilderName); + + AZStd::unordered_set includedFiles; + GetListOfIncludedFiles(azslFullPath, buildOptions.m_preprocessorSettings.m_projectIncludePaths, includedFilesParser, includedFiles); + for (auto includePath : includedFiles) + { + AssetBuilderSDK::SourceFileDependency includeFileDependency; + includeFileDependency.m_sourceFileDependencyPath = includePath; + response.m_sourceFileDependencyList.emplace_back(includeFileDependency); + } + for (const AssetBuilderSDK::PlatformInfo& platformInfo : request.m_enabledPlatforms) { AZ_TraceContext("For platform", platformInfo.m_identifier.data()); @@ -149,6 +228,10 @@ namespace AZ response.m_createJobOutputs.push_back(jobDescriptor); } // for all request.m_enabledPlatforms + const AZStd::sys_time_t createJobsEndStamp = AZStd::GetTimeNowMicroSecond(); + const u64 createJobDurationMicros = createJobsEndStamp - shaderAssetBuildTimestamp; + AZ_TracePrintf(ShaderAssetBuilderName, "CreateJobs for %s took %llu microseconds", fullPath.c_str(), createJobDurationMicros ); + response.m_result = AssetBuilderSDK::CreateJobsResultCode::Success; } @@ -286,6 +369,13 @@ namespace AZ return; } } + else + { + // CreateJobs was not successful if there's no timestamp property in m_jobParameters. + response.m_resultCode = AssetBuilderSDK::ProcessJobResult_Failed; + AZ_Assert(false, "Missing ShaderAssetBuildTimestampParam"); + return; + } auto supervariantList = ShaderBuilderUtility::GetSupervariantListFromShaderSourceData(shaderSourceData); diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp index e47dd55a97..eb91d9e866 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.cpp @@ -20,6 +20,7 @@ #include #include #include +#include #include @@ -814,6 +815,51 @@ namespace AZ return success; } + IncludedFilesParser::IncludedFilesParser() + { + AZStd::regex regex(R"(#\s*include\s+[<|"]([\w|/|\\|\.|-]+)[>|"])", AZStd::regex::ECMAScript); + m_includeRegex.swap(regex); + } + + AZStd::vector IncludedFilesParser::ParseStringAndGetIncludedFiles(AZStd::string_view haystack) const + { + AZStd::vector listOfFilePaths; + AZStd::smatch match; + AZStd::string::const_iterator searchStart(haystack.cbegin()); + while (AZStd::regex_search(searchStart, haystack.cend(), match, m_includeRegex)) + { + if (match.size() > 1) + { + AZStd::string relativeFilePath(match[1].str().c_str()); + AzFramework::StringFunc::Path::Normalize(relativeFilePath); + listOfFilePaths.push_back(relativeFilePath); + } + searchStart = match.suffix().first; + } + return listOfFilePaths; + } + + AZ::Outcome, AZStd::string> IncludedFilesParser::ParseFileAndGetIncludedFiles(AZStd::string_view sourceFilePath) const + { + AZ::IO::FileIOStream stream(sourceFilePath.data(), AZ::IO::OpenMode::ModeRead); + if (!stream.IsOpen()) + { + return AZ::Failure(AZStd::string::format("\"%s\" source file could not be opened.", sourceFilePath.data())); + } + + if (!stream.CanRead()) + { + return AZ::Failure(AZStd::string::format("\"%s\" source file could not be read.", sourceFilePath.data())); + } + + AZStd::string hayStack; + hayStack.resize_no_construct(stream.GetLength()); + stream.Read(stream.GetLength(), hayStack.data()); + + auto listOfFilePaths = ParseStringAndGetIncludedFiles(hayStack); + return AZ::Success(AZStd::move(listOfFilePaths)); + } + } // namespace ShaderBuilderUtility } // namespace ShaderBuilder } // AZ diff --git a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h index c000ba9df6..5d45ade9cb 100644 --- a/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h +++ b/Gems/Atom/Asset/Shader/Code/Source/Editor/ShaderBuilderUtility.h @@ -141,6 +141,29 @@ namespace AZ const uint32_t rhiUniqueIndex, const AZStd::string& platformIdentifier, const AZStd::string& shaderJsonPath, const uint32_t supervariantIndex, RPI::ShaderAssetSubId shaderAssetSubId); + + class IncludedFilesParser + { + public: + IncludedFilesParser(); + ~IncludedFilesParser() = default; + + //! This static function was made public for testability purposes only. + //! Parses the string @haystack, looking for "#include file" lines with a regular expression. + //! Returns the list of relative paths as included by the file. + //! REMARK: The algorithm may over prescribe what files to include because it doesn't discern between comments, etc. + //! Also, a #include line may be protected by #ifdef macros but this algorithm doesn't care. + //! Over prescribing is not a real problem, albeit potential waste in processing. Under prescribing would be a real problem. + AZStd::vector ParseStringAndGetIncludedFiles(AZStd::string_view haystack) const; + + //! This static function was made public for testability purposes only. + //! Opens the file @sourceFilePath, loads the content into a string and returns ParseStringAndGetIncludedFiles(content) + AZ::Outcome, AZStd::string> ParseFileAndGetIncludedFiles(AZStd::string_view sourceFilePath) const; + + private: + AZStd::regex m_includeRegex; + }; + } // ShaderBuilderUtility namespace } // ShaderBuilder namespace } // AZ diff --git a/Gems/Atom/Asset/Shader/Code/Tests/ShaderBuilderUtilityTests.cpp b/Gems/Atom/Asset/Shader/Code/Tests/ShaderBuilderUtilityTests.cpp new file mode 100644 index 0000000000..d477060d04 --- /dev/null +++ b/Gems/Atom/Asset/Shader/Code/Tests/ShaderBuilderUtilityTests.cpp @@ -0,0 +1,86 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include "Common/ShaderBuilderTestFixture.h" + +#include + +namespace UnitTest +{ + using namespace AZ; + + // The main purpose of this class is to test ShaderBuilderUtility functions + class ShaderBuilderUtilityTests : public ShaderBuilderTestFixture + { + }; // class ShaderBuilderUtilityTests + + + TEST_F(ShaderBuilderUtilityTests, IncludedFilesParser_ParseStringAndGetIncludedFiles) + { + AZStd::string haystack( + "Some content to parse\n" + "#include \n" + "// #include \n" + "blah # include \"valid_file3.azsli\"\n" + "bar include \n" + "foo # include \"a/directory/valid-file5.azsli\"\n" + "# include \n" + "#includ \"a\\dire-ctory\\invalid-file7.azsli\"\n" + ); + + AZ::ShaderBuilder::ShaderBuilderUtility::IncludedFilesParser includedFilesParser; + auto fileList = includedFilesParser.ParseStringAndGetIncludedFiles(haystack); + EXPECT_EQ(fileList.size(), 5); + + auto it = AZStd::find(fileList.begin(), fileList.end(), "valid_file1.azsli"); + EXPECT_TRUE(it != fileList.end()); + + it = AZStd::find(fileList.begin(), fileList.end(), "valid_file2.azsli"); + EXPECT_TRUE(it != fileList.end()); + + it = AZStd::find(fileList.begin(), fileList.end(), "valid_file3.azsli"); + EXPECT_TRUE(it != fileList.end()); + + // Remark: From now on We must normalize because internally AZ::ShaderBuilder::ShaderBuilderUtility::IncludedFilesParser + // always returns normalized paths. + { + AZStd::string fileName("a\\dire-ctory\\invalid-file4.azsli"); + AzFramework::StringFunc::Path::Normalize(fileName); + it = AZStd::find(fileList.begin(), fileList.end(), fileName); + EXPECT_TRUE(it == fileList.end()); + } + + { + AZStd::string fileName("a\\directory\\valid-file5.azsli"); + AzFramework::StringFunc::Path::Normalize(fileName); + it = AZStd::find(fileList.begin(), fileList.end(), fileName); + EXPECT_TRUE(it != fileList.end()); + } + + { + AZStd::string fileName("a\\dire-ctory\\valid-file6.azsli"); + AzFramework::StringFunc::Path::Normalize(fileName); + it = AZStd::find(fileList.begin(), fileList.end(), fileName); + EXPECT_TRUE(it != fileList.end()); + } + + { + AZStd::string fileName("a\\dire-ctory\\invalid-file7.azsli"); + AzFramework::StringFunc::Path::Normalize(fileName); + it = AZStd::find(fileList.begin(), fileList.end(), fileName); + EXPECT_TRUE(it == fileList.end()); + } + } + +} //namespace UnitTest + +//AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); + diff --git a/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake b/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake index 033b399478..ab8df70bdb 100644 --- a/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake +++ b/Gems/Atom/Asset/Shader/Code/atom_asset_shader_builders_tests_files.cmake @@ -11,4 +11,5 @@ set(FILES Tests/Common/ShaderBuilderTestFixture.cpp Tests/SupervariantCmdArgumentTests.cpp Tests/McppBinderTests.cpp + Tests/ShaderBuilderUtilityTests.cpp ) diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurHor.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurHor.azsl index 64f6b3a4b5..a7dfad1c24 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurHor.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurHor.azsl @@ -55,7 +55,7 @@ int GetLdsIndex(int2 ldsPosition) // --- Common file start --- -// #include +// include ('#' symbol before 'include' was removed on purpose to avoid parsing this azsli file during ShaderAssetBuilder::CreateJobs) // This include fails with the asset processor when generating the .shader for this file // Everything below this is copy pasted from FastDepthAwareBlurCommon.azsli up until the // "Common file end" marker below diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurVer.azsl b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurVer.azsl index cfb49f5911..b4f230c99c 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurVer.azsl +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/FastDepthAwareBlurVer.azsl @@ -55,7 +55,7 @@ int GetLdsIndex(int2 ldsPosition) // --- Common file start --- -// #include +// include ('#' symbol before 'include' was removed on purpose to avoid parsing this azsli file during ShaderAssetBuilder::CreateJobs) // This include fails with the asset processor when generating the .shader for this file // Everything below this is copy pasted from FastDepthAwareBlurCommon.azsli up until the // "Common file end" marker below diff --git a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli index 8c03816b26..a32b56857c 100644 --- a/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli +++ b/Gems/Atom/Feature/Common/Assets/Shaders/PostProcessing/SMAA.azsli @@ -157,7 +157,7 @@ * #define SMAA_RT_METRICS float4(1.0 / 1280.0, 1.0 / 720.0, 1280.0, 720.0) * #define SMAA_HLSL_4 * #define SMAA_PRESET_HIGH - * #include "SMAA.h" + * include "SMAA.h" ('#' symbol before 'include' was removed on purpose to avoid parsing this azsli file during ShaderAssetBuilder::CreateJobs) * * Note that SMAA_RT_METRICS doesn't need to be a macro, it can be a * uniform variable. The code is designed to minimize the impact of not From dc930a5987af99e333e7f858a498faf682c045e7 Mon Sep 17 00:00:00 2001 From: Steve Pham <82231385+spham-amzn@users.noreply.github.com> Date: Wed, 15 Sep 2021 08:32:52 -0700 Subject: [PATCH 23/26] Fix LuaIDE crash at startup caused by missing System Allocator Initialization (#4130) Signed-off-by: Steve Pham --- Code/Tools/Standalone/Source/Editor/LuaEditor.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Code/Tools/Standalone/Source/Editor/LuaEditor.cpp b/Code/Tools/Standalone/Source/Editor/LuaEditor.cpp index 89ab8207ff..f6d905515b 100644 --- a/Code/Tools/Standalone/Source/Editor/LuaEditor.cpp +++ b/Code/Tools/Standalone/Source/Editor/LuaEditor.cpp @@ -35,6 +35,10 @@ int main(int argc, char* argv[]) { AZ::AllocatorInstance::Create(); } + if (!AZ::AllocatorInstance::IsReady()) + { + AZ::AllocatorInstance::Create(); + } AZStd::unique_ptr fileIO = AZStd::unique_ptr(aznew AZ::IO::LocalFileIO()); AZ::IO::FileIOBase::SetInstance(fileIO.get()); @@ -70,6 +74,10 @@ int main(int argc, char* argv[]) // if its in GUI mode or not. } + if (AZ::AllocatorInstance::IsReady()) + { + AZ::AllocatorInstance::Destroy(); + } if (AZ::AllocatorInstance::IsReady()) { AZ::AllocatorInstance::Destroy(); From 089391f761ab3a1e1bda34273e8c7f3333ee1b9b Mon Sep 17 00:00:00 2001 From: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> Date: Wed, 15 Sep 2021 10:57:37 -0500 Subject: [PATCH 24/26] Terrain System cleanups and unit tests (#4119) * Remove the "TEST_SUPPORTED" traits. Terrain unit tests should be usable on all platforms, so they shouldn't need a platform-specific trait to enable/disable. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Fix a few misc terrain bugs. * Change Activate/Deactivate to happen immediately instead of deferring. There were too many order-of-operation bugs caused by trying to defer this. * Added implementation for calculating normals. * Fixed bug where GetHeightSynchronous wasn't stopping at the highest-priority layer. * Added locks for SurfaceData bus to help ensure we lock our mutexes in the correct order and avoid deadlocks. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Add trivial TerrainSystem tests. Tests construction, Activate(), Deactivate(), and destruction. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Unified Terrain system calls on single bus. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Added mock for TerrainDataNotificationBus listener. Also added unit tests to verify the listener, and added in missing notification events. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Removed extra Sampler class. Fixed up APIs to correctly pass Sampler and terrainExistsPtr around. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Switched MockTerrainSystem to be proper gmock. This makes it for flexible to use and easier to reuse from other test environments. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Fix settings bug caused by bad order of operations that occurred when the methods moved to a different bus. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Eliminate extra EBus by simplifying area initialization. Previously, there was a back-and-forth ebus signal used for the terrain system to find any terrain spawners that were created prior to the terrain system activation. Now it uses the more simple technique of just grabbing all the spawners that are currently hooked up to the spawner ebus. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Switch to NiceMock so that "uninteresting" mock calls get ignored. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Addressed PR feedback. Filled in terrainExistsPtr at the end, and added it to GetNormal as well. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> * Fixed shader height calculation. It was off by half a pixel, and it was interpolating, both of which were wrong. Signed-off-by: Mike Balfour <82224783+mbalfour-amzn@users.noreply.github.com> --- Code/Editor/GameExporter.cpp | 2 +- .../Terrain/TerrainDataRequestBus.cpp | 3 +- .../Terrain/TerrainDataRequestBus.h | 5 +- Gems/PhysX/Code/Tests/PhysXTestUtil.h | 23 +- .../Shaders/Terrain/TerrainCommon.azsli | 14 +- Gems/Terrain/Code/CMakeLists.txt | 67 +++--- .../TerrainHeightGradientListComponent.cpp | 12 +- .../TerrainHeightGradientListComponent.h | 10 +- .../TerrainLayerSpawnerComponent.cpp | 7 - .../Components/TerrainLayerSpawnerComponent.h | 5 +- .../Components/TerrainWorldComponent.cpp | 14 +- .../TerrainWorldDebuggerComponent.cpp | 4 +- .../Source/TerrainSystem/TerrainSystem.cpp | 221 +++++++++++------- .../Code/Source/TerrainSystem/TerrainSystem.h | 17 +- .../Source/TerrainSystem/TerrainSystemBus.h | 47 +--- Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp | 59 +++-- Gems/Terrain/Code/Tests/TerrainMocks.h | 60 ++--- Gems/Terrain/Code/Tests/TerrainSystemTest.cpp | 92 ++++++++ Gems/Terrain/Code/Tests/TerrainTest.cpp | 20 -- Gems/Terrain/Code/terrain_tests_files.cmake | 1 + 20 files changed, 395 insertions(+), 288 deletions(-) create mode 100644 Gems/Terrain/Code/Tests/TerrainSystemTest.cpp diff --git a/Code/Editor/GameExporter.cpp b/Code/Editor/GameExporter.cpp index 1fc980fdac..00dc3d8de1 100644 --- a/Code/Editor/GameExporter.cpp +++ b/Code/Editor/GameExporter.cpp @@ -318,7 +318,7 @@ void CGameExporter::ExportLevelInfo(const QString& path) root->setAttr("Name", levelName.toUtf8().data()); auto terrain = AzFramework::Terrain::TerrainDataRequestBus::FindFirstHandler(); const AZ::Aabb terrainAabb = terrain ? terrain->GetTerrainAabb() : AZ::Aabb::CreateFromPoint(AZ::Vector3::CreateZero()); - const AZ::Vector2 terrainGridResolution = terrain ? terrain->GetTerrainGridResolution() : AZ::Vector2::CreateOne(); + const AZ::Vector2 terrainGridResolution = terrain ? terrain->GetTerrainHeightQueryResolution() : AZ::Vector2::CreateOne(); const int compiledHeightmapSize = static_cast(terrainAabb.GetXExtent() / terrainGridResolution.GetX()); root->setAttr("HeightmapSize", compiledHeightmapSize); diff --git a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp index 947d3821ab..1fb29cfa30 100644 --- a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp +++ b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.cpp @@ -51,7 +51,8 @@ namespace AzFramework ->Event("GetNormal", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetNormal) ->Event("GetNormalFromFloats", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetNormalFromFloats) ->Event("GetTerrainAabb", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainAabb) - ->Event("GetTerrainGridResolution", &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainGridResolution) + ->Event("GetTerrainHeightQueryResolution", + &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainHeightQueryResolution) ; } diff --git a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h index 08e238434e..92eb28a110 100644 --- a/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h +++ b/Code/Framework/AzFramework/AzFramework/Terrain/TerrainDataRequestBus.h @@ -59,8 +59,11 @@ namespace AzFramework static AZ::Vector3 GetDefaultTerrainNormal() { return AZ::Vector3::CreateAxisZ(); } // System-level queries to understand world size and resolution - virtual AZ::Vector2 GetTerrainGridResolution() const = 0; + virtual AZ::Vector2 GetTerrainHeightQueryResolution() const = 0; + virtual void SetTerrainHeightQueryResolution(AZ::Vector2 queryResolution) = 0; + virtual AZ::Aabb GetTerrainAabb() const = 0; + virtual void SetTerrainAabb(const AZ::Aabb& worldBounds) = 0; //! Returns terrains height in meters at location x,y. //! @terrainExistsPtr: Can be nullptr. If != nullptr then, if there's no terrain at location x,y or location x,y is inside a terrain HOLE then *terrainExistsPtr will become false, diff --git a/Gems/PhysX/Code/Tests/PhysXTestUtil.h b/Gems/PhysX/Code/Tests/PhysXTestUtil.h index b1ba23600a..8e81b9cb89 100644 --- a/Gems/PhysX/Code/Tests/PhysXTestUtil.h +++ b/Gems/PhysX/Code/Tests/PhysXTestUtil.h @@ -93,9 +93,26 @@ namespace PhysX //////////////////////////////////////////////////////////////////////// // TerrainDataRequestBus interface dummy implementation - AZ::Vector2 GetTerrainGridResolution() const override { return {}; } - AZ::Aabb GetTerrainAabb() const override { return {}; } - float GetHeight(AZ::Vector3, Sampler, bool*) const override { return {}; } + AZ::Vector2 GetTerrainHeightQueryResolution() const override + { + return {}; + } + void SetTerrainHeightQueryResolution([[maybe_unused]] AZ::Vector2 queryResolution) override + { + } + + AZ::Aabb GetTerrainAabb() const override + { + return {}; + } + void SetTerrainAabb([[maybe_unused]] const AZ::Aabb& worldBounds) override + { + } + + float GetHeight(AZ::Vector3, Sampler, bool*) const override + { + return {}; + } float GetHeightFromFloats(float, float, Sampler, bool*) const override { return {}; } AzFramework::SurfaceData::SurfaceTagWeight GetMaxSurfaceWeight(AZ::Vector3, Sampler, bool*) const override { return {}; } AzFramework::SurfaceData::SurfaceTagWeight GetMaxSurfaceWeightFromFloats(float, float, Sampler, bool*) const override { return {}; } diff --git a/Gems/Terrain/Assets/Shaders/Terrain/TerrainCommon.azsli b/Gems/Terrain/Assets/Shaders/Terrain/TerrainCommon.azsli index 6e489796d7..18b85bbd43 100644 --- a/Gems/Terrain/Assets/Shaders/Terrain/TerrainCommon.azsli +++ b/Gems/Terrain/Assets/Shaders/Terrain/TerrainCommon.azsli @@ -11,16 +11,16 @@ ShaderResourceGroup ObjectSrg : SRG_PerObject { Texture2D m_heightmapImage; - Sampler LinearSampler + Sampler PointSampler { - MinFilter = Linear; - MagFilter = Linear; - MipFilter = Linear; + MinFilter = Point; + MagFilter = Point; + MipFilter = Point; AddressU = Clamp; AddressV = Clamp; AddressW = Clamp; }; - + row_major float3x4 m_modelToWorld; struct TerrainData @@ -57,8 +57,8 @@ float4x4 GetObject_WorldMatrix() float GetHeight(float2 origUv) { - float2 uv = clamp(origUv, 0.0f, 1.0f); - return ObjectSrg::m_terrainData.m_heightScale * (ObjectSrg::m_heightmapImage.SampleLevel(ObjectSrg::LinearSampler, uv, 0).r - 0.5f); + float2 uv = clamp(origUv + (ObjectSrg::m_terrainData.m_uvStep * 0.5f), 0.0f, 1.0f); + return ObjectSrg::m_terrainData.m_heightScale * (ObjectSrg::m_heightmapImage.SampleLevel(ObjectSrg::PointSampler, uv, 0).r - 0.5f); } float4 GetTerrainProjectedPosition(ObjectSrg::TerrainData terrainData, float2 vertexPosition, float2 uv) diff --git a/Gems/Terrain/Code/CMakeLists.txt b/Gems/Terrain/Code/CMakeLists.txt index b4a35edbbf..0feacdaf71 100644 --- a/Gems/Terrain/Code/CMakeLists.txt +++ b/Gems/Terrain/Code/CMakeLists.txt @@ -83,15 +83,36 @@ endif() ################################################################################ # See if globally, tests are supported if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) - # We globally support tests, see if we support tests on this platform for Terrain.Static - if(PAL_TRAIT_TERRAIN_TEST_SUPPORTED) - # We support Terrain.Tests on this platform, add Terrain.Tests target which depends on Terrain.Static + ly_add_target( + NAME Terrain.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAMESPACE Gem + FILES_CMAKE + terrain_files.cmake + terrain_tests_files.cmake + INCLUDE_DIRECTORIES + PRIVATE + Tests + Source + BUILD_DEPENDENCIES + PRIVATE + AZ::AzTest + AZ::AzFramework + Gem::Terrain.Static + ) + + # Add Terrain.Tests to googletest + ly_add_googletest( + NAME Gem::Terrain.Tests + ) + + # If we are a host platform we want to add tools test like editor tests here + if(PAL_TRAIT_BUILD_HOST_TOOLS) + # We support Terrain.Editor.Tests on this platform, add Terrain.Editor.Tests target which depends on Terrain.Editor ly_add_target( - NAME Terrain.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} + NAME Terrain.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} NAMESPACE Gem FILES_CMAKE - terrain_files.cmake - terrain_tests_files.cmake + terrain_editor_tests_files.cmake INCLUDE_DIRECTORIES PRIVATE Tests @@ -99,40 +120,12 @@ if(PAL_TRAIT_BUILD_TESTS_SUPPORTED) BUILD_DEPENDENCIES PRIVATE AZ::AzTest - AZ::AzFramework - Gem::Terrain.Static + Gem::Terrain.Editor ) - # Add Terrain.Tests to googletest + # Add Terrain.Editor.Tests to googletest ly_add_googletest( - NAME Gem::Terrain.Tests + NAME Gem::Terrain.Editor.Tests ) endif() - - # If we are a host platform we want to add tools test like editor tests here - if(PAL_TRAIT_BUILD_HOST_TOOLS) - # We are a host platform, see if Editor tests are supported on this platform - if(PAL_TRAIT_TERRAIN_EDITOR_TEST_SUPPORTED) - # We support Terrain.Editor.Tests on this platform, add Terrain.Editor.Tests target which depends on Terrain.Editor - ly_add_target( - NAME Terrain.Editor.Tests ${PAL_TRAIT_TEST_TARGET_TYPE} - NAMESPACE Gem - FILES_CMAKE - terrain_editor_tests_files.cmake - INCLUDE_DIRECTORIES - PRIVATE - Tests - Source - BUILD_DEPENDENCIES - PRIVATE - AZ::AzTest - Gem::Terrain.Editor - ) - - # Add Terrain.Editor.Tests to googletest - ly_add_googletest( - NAME Gem::Terrain.Editor.Tests - ) - endif() - endif() endif() diff --git a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp index d64f660d90..4d0cb6576d 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.cpp @@ -166,14 +166,20 @@ namespace Terrain } void TerrainHeightGradientListComponent::GetHeight( - const AZ::Vector3& inPosition, AZ::Vector3& outPosition, [[maybe_unused]] Sampler sampleFilter = Sampler::DEFAULT) + const AZ::Vector3& inPosition, + AZ::Vector3& outPosition, + [[maybe_unused]] AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = + AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) { const float height = GetHeight(inPosition.GetX(), inPosition.GetY()); outPosition.SetZ(height); } void TerrainHeightGradientListComponent::GetNormal( - const AZ::Vector3& inPosition, AZ::Vector3& outNormal, [[maybe_unused]] Sampler sampleFilter = Sampler::DEFAULT) + const AZ::Vector3& inPosition, + AZ::Vector3& outNormal, + [[maybe_unused]] AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = + AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) { const float x = inPosition.GetX(); const float y = inPosition.GetY(); @@ -206,7 +212,7 @@ namespace Terrain // Get the height range of the entire world m_cachedHeightQueryResolution = AZ::Vector2(1.0f); AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( - m_cachedHeightQueryResolution, &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainGridResolution); + m_cachedHeightQueryResolution, &AzFramework::Terrain::TerrainDataRequestBus::Events::GetTerrainHeightQueryResolution); AZ::Aabb worldBounds = AZ::Aabb::CreateNull(); AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( diff --git a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h index 7635680815..509f003afa 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainHeightGradientListComponent.h @@ -64,8 +64,14 @@ namespace Terrain TerrainHeightGradientListComponent() = default; ~TerrainHeightGradientListComponent() = default; - void GetHeight(const AZ::Vector3& inPosition, AZ::Vector3& outPosition, Sampler sampleFilter) override; - void GetNormal(const AZ::Vector3& inPosition, AZ::Vector3& outNormal, Sampler sampleFilter) override; + void GetHeight( + const AZ::Vector3& inPosition, + AZ::Vector3& outPosition, + AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter) override; + void GetNormal( + const AZ::Vector3& inPosition, + AZ::Vector3& outNormal, + AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter) override; ////////////////////////////////////////////////////////////////////////// // AZ::Component interface implementation diff --git a/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.cpp index e17dbd0e93..245c98ccac 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.cpp @@ -104,7 +104,6 @@ namespace Terrain { AZ::TransformNotificationBus::Handler::BusConnect(GetEntityId()); LmbrCentral::ShapeComponentNotificationsBus::Handler::BusConnect(GetEntityId()); - TerrainAreaRequestBus::Handler::BusConnect(GetEntityId()); TerrainSpawnerRequestBus::Handler::BusConnect(GetEntityId()); TerrainSystemServiceRequestBus::Broadcast(&TerrainSystemServiceRequestBus::Events::RegisterArea, GetEntityId()); @@ -114,7 +113,6 @@ namespace Terrain { TerrainSystemServiceRequestBus::Broadcast(&TerrainSystemServiceRequestBus::Events::UnregisterArea, GetEntityId()); TerrainSpawnerRequestBus::Handler::BusDisconnect(); - TerrainAreaRequestBus::Handler::BusDisconnect(); LmbrCentral::ShapeComponentNotificationsBus::Handler::BusDisconnect(); AZ::TransformNotificationBus::Handler::BusDisconnect(); @@ -161,11 +159,6 @@ namespace Terrain return m_configuration.m_useGroundPlane; } - void TerrainLayerSpawnerComponent::RegisterArea() - { - TerrainSystemServiceRequestBus::Broadcast(&TerrainSystemServiceRequestBus::Events::RegisterArea, GetEntityId()); - } - void TerrainLayerSpawnerComponent::RefreshArea() { TerrainSystemServiceRequestBus::Broadcast(&TerrainSystemServiceRequestBus::Events::RefreshArea, GetEntityId()); diff --git a/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.h b/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.h index 3f8e72e1b8..c7398bf93e 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.h +++ b/Gems/Terrain/Code/Source/Components/TerrainLayerSpawnerComponent.h @@ -58,7 +58,6 @@ namespace Terrain : public AZ::Component , private AZ::TransformNotificationBus::Handler , private LmbrCentral::ShapeComponentNotificationsBus::Handler - , private Terrain::TerrainAreaRequestBus::Handler , private Terrain::TerrainSpawnerRequestBus::Handler { public: @@ -81,6 +80,7 @@ namespace Terrain bool ReadInConfig(const AZ::ComponentConfig* baseConfig) override; bool WriteOutConfig(AZ::ComponentConfig* outBaseConfig) const override; + protected: ////////////////////////////////////////////////////////////////////////// // AZ::TransformNotificationBus::Handler void OnTransformChanged(const AZ::Transform& local, const AZ::Transform& world) override; @@ -92,8 +92,7 @@ namespace Terrain void GetPriority(AZ::u32& outLayer, AZ::u32& outPriority) override; bool GetUseGroundPlane() override; - void RegisterArea() override; - void RefreshArea() override; + void RefreshArea(); private: TerrainLayerSpawnerConfig m_configuration; diff --git a/Gems/Terrain/Code/Source/Components/TerrainWorldComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainWorldComponent.cpp index 669a8f4b02..d8b7308ef7 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainWorldComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainWorldComponent.cpp @@ -13,6 +13,7 @@ #include #include #include +#include namespace Terrain { @@ -85,17 +86,16 @@ namespace Terrain void TerrainWorldComponent::Activate() { - TerrainSystemServiceRequestBus::Broadcast( - &TerrainSystemServiceRequestBus::Events::SetWorldBounds, - AZ::Aabb::CreateFromMinMax(m_configuration.m_worldMin, m_configuration.m_worldMax) - ); - TerrainSystemServiceRequestBus::Broadcast( - &TerrainSystemServiceRequestBus::Events::SetHeightQueryResolution, m_configuration.m_heightQueryResolution); - // Currently, the Terrain System Component owns the Terrain System instance because the Terrain World component gets recreated // every time an entity is added or removed to a level. If this ever changes, the Terrain System ownership could move into // the level component. TerrainSystemServiceRequestBus::Broadcast(&TerrainSystemServiceRequestBus::Events::Activate); + + AzFramework::Terrain::TerrainDataRequestBus::Broadcast( + &AzFramework::Terrain::TerrainDataRequestBus::Events::SetTerrainAabb, + AZ::Aabb::CreateFromMinMax(m_configuration.m_worldMin, m_configuration.m_worldMax)); + AzFramework::Terrain::TerrainDataRequestBus::Broadcast( + &AzFramework::Terrain::TerrainDataRequestBus::Events::SetTerrainHeightQueryResolution, m_configuration.m_heightQueryResolution); } void TerrainWorldComponent::Deactivate() diff --git a/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp b/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp index d7504295c2..89ffa6364f 100644 --- a/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp +++ b/Gems/Terrain/Code/Source/Components/TerrainWorldDebuggerComponent.cpp @@ -171,7 +171,7 @@ namespace Terrain // Determine how far to draw in each direction in world space based on our MaxSectorsToDraw AZ::Vector2 queryResolution = AZ::Vector2(1.0f); AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( - queryResolution, &AzFramework::Terrain::TerrainDataRequests::GetTerrainGridResolution); + queryResolution, &AzFramework::Terrain::TerrainDataRequests::GetTerrainHeightQueryResolution); AZ::Vector3 viewDistance( queryResolution.GetX() * SectorSizeInGridPoints * sqrtf(MaxSectorsToDraw), queryResolution.GetY() * SectorSizeInGridPoints * sqrtf(MaxSectorsToDraw), @@ -214,7 +214,7 @@ namespace Terrain AZ::Vector2 queryResolution = AZ::Vector2(1.0f); AzFramework::Terrain::TerrainDataRequestBus::BroadcastResult( - queryResolution, &AzFramework::Terrain::TerrainDataRequests::GetTerrainGridResolution); + queryResolution, &AzFramework::Terrain::TerrainDataRequests::GetTerrainHeightQueryResolution); // Calculate the world size of each sector. Note that this size actually ends at the last point, not the last square. // So for example, the sector size for 3 points will go from (*--*--*) even though it will be used to draw (*--*--*--). diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp index a271d624f5..674af376e4 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -53,7 +54,7 @@ TerrainSystem::TerrainSystem() m_currentSettings.m_worldBounds = AZ::Aabb::CreateNull(); m_requestedSettings = m_currentSettings; - m_requestedSettings.m_worldBounds = AZ::Aabb::CreateFromMinMax(AZ::Vector3(0.0f, 0.0f, 0.0f), AZ::Vector3(4096.0f, 4096.0f, 2048.0f)); + m_requestedSettings.m_worldBounds = AZ::Aabb::CreateFromMinMax(AZ::Vector3(-512.0f), AZ::Vector3(512.0f)); } TerrainSystem::~TerrainSystem() @@ -66,23 +67,76 @@ TerrainSystem::~TerrainSystem() void TerrainSystem::Activate() { - m_requestedSettings.m_systemActive = true; + AzFramework::Terrain::TerrainDataNotificationBus::Broadcast( + &AzFramework::Terrain::TerrainDataNotificationBus::Events::OnTerrainDataCreateBegin); + + m_dirtyRegion = AZ::Aabb::CreateNull(); + m_terrainHeightDirty = true; m_terrainSettingsDirty = true; + m_requestedSettings.m_systemActive = true; + + { + AZStd::shared_lock lock(m_areaMutex); + m_registeredAreas.clear(); + } + + AzFramework::Terrain::TerrainDataRequestBus::Handler::BusConnect(); + + // Register any terrain spawners that were already active before the terrain system activated. + auto enumerationCallback = [&]([[maybe_unused]] Terrain::TerrainSpawnerRequests* terrainSpawner) -> bool + { + AZ::EntityId areaId = *(Terrain::TerrainSpawnerRequestBus::GetCurrentBusId()); + RegisterArea(areaId); + + // Keep Enumerating + return true; + }; + Terrain::TerrainSpawnerRequestBus::EnumerateHandlers(enumerationCallback); + + AzFramework::Terrain::TerrainDataNotificationBus::Broadcast( + &AzFramework::Terrain::TerrainDataNotificationBus::Events::OnTerrainDataCreateEnd); } void TerrainSystem::Deactivate() { - m_requestedSettings.m_systemActive = false; + AzFramework::Terrain::TerrainDataNotificationBus::Broadcast( + &AzFramework::Terrain::TerrainDataNotificationBus::Events::OnTerrainDataDestroyBegin); + + AzFramework::Terrain::TerrainDataRequestBus::Handler::BusDisconnect(); + + { + AZStd::shared_lock lock(m_areaMutex); + m_registeredAreas.clear(); + } + + m_dirtyRegion = AZ::Aabb::CreateNull(); + m_terrainHeightDirty = true; m_terrainSettingsDirty = true; + m_requestedSettings.m_systemActive = false; + + if (auto rpi = AZ::RPI::RPISystemInterface::Get(); rpi) + { + if (auto defaultScene = rpi->GetDefaultScene(); defaultScene) + { + const AZ::RPI::Scene* scene = defaultScene.get(); + if (auto terrainFeatureProcessor = scene->GetFeatureProcessor(); terrainFeatureProcessor) + { + terrainFeatureProcessor->RemoveTerrainData(); + } + } + } + + AzFramework::Terrain::TerrainDataNotificationBus::Broadcast( + &AzFramework::Terrain::TerrainDataNotificationBus::Events::OnTerrainDataDestroyEnd); } -void TerrainSystem::SetWorldBounds(const AZ::Aabb& worldBounds) +void TerrainSystem::SetTerrainAabb(const AZ::Aabb& worldBounds) { m_requestedSettings.m_worldBounds = worldBounds; m_terrainSettingsDirty = true; } -void TerrainSystem::SetHeightQueryResolution(AZ::Vector2 queryResolution) +void TerrainSystem::SetTerrainHeightQueryResolution(AZ::Vector2 queryResolution) { m_requestedSettings.m_heightQueryResolution = queryResolution; m_terrainSettingsDirty = true; @@ -93,13 +147,15 @@ AZ::Aabb TerrainSystem::GetTerrainAabb() const return m_currentSettings.m_worldBounds; } -AZ::Vector2 TerrainSystem::GetTerrainGridResolution() const +AZ::Vector2 TerrainSystem::GetTerrainHeightQueryResolution() const { return m_currentSettings.m_heightQueryResolution; } -float TerrainSystem::GetHeightSynchronous(float x, float y) const +float TerrainSystem::GetHeightSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const { + bool terrainExists = false; + AZ::Vector3 inPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); AZ::Vector3 outPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); @@ -111,67 +167,77 @@ float TerrainSystem::GetHeightSynchronous(float x, float y) const if (areaBounds.Contains(inPosition)) { Terrain::TerrainAreaHeightRequestBus::Event( - areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeight, inPosition, outPosition, - Terrain::TerrainAreaHeightRequestBus::Events::Sampler::DEFAULT); + areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeight, inPosition, outPosition, sampler); + + terrainExists = true; + + break; } } + if (terrainExistsPtr) + { + *terrainExistsPtr = terrainExists; + } + return AZ::GetClamp( outPosition.GetZ(), m_currentSettings.m_worldBounds.GetMin().GetZ(), m_currentSettings.m_worldBounds.GetMax().GetZ()); } -float TerrainSystem::GetHeight(AZ::Vector3 position, [[maybe_unused]] Sampler sampler, [[maybe_unused]] bool* terrainExistsPtr) const +float TerrainSystem::GetHeight(AZ::Vector3 position, Sampler sampler, bool* terrainExistsPtr) const { - if (terrainExistsPtr) + return GetHeightSynchronous(position.GetX(), position.GetY(), sampler, terrainExistsPtr); +} + +float TerrainSystem::GetHeightFromFloats(float x, float y, Sampler sampler, bool* terrainExistsPtr) const +{ + return GetHeightSynchronous(x, y, sampler, terrainExistsPtr); +} + +bool TerrainSystem::GetIsHoleFromFloats(float x, float y, Sampler sampler) const +{ + bool terrainExists = false; + GetHeightSynchronous(x, y, sampler, &terrainExists); + return !terrainExists; +} + +AZ::Vector3 TerrainSystem::GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const +{ + bool terrainExists = false; + + AZ::Vector3 inPosition((float)x, (float)y, m_currentSettings.m_worldBounds.GetMin().GetZ()); + AZ::Vector3 outNormal = AZ::Vector3::CreateAxisZ(); + + AZStd::shared_lock lock(m_areaMutex); + + for (auto& [areaId, areaBounds] : m_registeredAreas) { - *terrainExistsPtr = true; + inPosition.SetZ(areaBounds.GetMin().GetZ()); + if (areaBounds.Contains(inPosition)) + { + Terrain::TerrainAreaHeightRequestBus::Event( + areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetNormal, inPosition, outNormal, sampler); + terrainExists = true; + break; + } } - return GetHeightSynchronous(position.GetX(), position.GetY()); -} - -float TerrainSystem::GetHeightFromFloats( - float x, float y, [[maybe_unused]] Sampler sampler, [[maybe_unused]] bool* terrainExistsPtr) const -{ if (terrainExistsPtr) { - *terrainExistsPtr = true; + *terrainExistsPtr = terrainExists; } - return GetHeightSynchronous(x, y); + return outNormal; } -bool TerrainSystem::GetIsHoleFromFloats( - [[maybe_unused]] float x, [[maybe_unused]] float y, [[maybe_unused]] Sampler sampleFilter) const +AZ::Vector3 TerrainSystem::GetNormal(AZ::Vector3 position, Sampler sampler, bool* terrainExistsPtr) const { - return false; + return GetNormalSynchronous(position.GetX(), position.GetY(), sampler, terrainExistsPtr); } -AZ::Vector3 TerrainSystem::GetNormalSynchronous([[maybe_unused]] float x, [[maybe_unused]] float y) const +AZ::Vector3 TerrainSystem::GetNormalFromFloats(float x, float y, Sampler sampler, bool* terrainExistsPtr) const { - return AZ::Vector3::CreateAxisZ(); -} - -AZ::Vector3 TerrainSystem::GetNormal( - AZ::Vector3 position, [[maybe_unused]] Sampler sampleFilter, [[maybe_unused]] bool* terrainExistsPtr) const -{ - if (terrainExistsPtr) - { - *terrainExistsPtr = true; - } - - return GetNormalSynchronous(position.GetX(), position.GetY()); -} - -AZ::Vector3 TerrainSystem::GetNormalFromFloats( - float x, float y, [[maybe_unused]] Sampler sampleFilter, [[maybe_unused]] bool* terrainExistsPtr) const -{ - if (terrainExistsPtr) - { - *terrainExistsPtr = true; - } - - return GetNormalSynchronous(x, y); + return GetNormalSynchronous(x, y, sampler, terrainExistsPtr); } @@ -298,35 +364,6 @@ void TerrainSystem::ProcessSurfacePointsFromRegion(const AZ::Aabb& inRegion, con } */ -void TerrainSystem::SystemActivate() -{ - { - AZStd::shared_lock lock(m_areaMutex); - m_registeredAreas.clear(); - } - - AzFramework::Terrain::TerrainDataRequestBus::Handler::BusConnect(); - - TerrainAreaRequestBus::Broadcast(&TerrainAreaRequestBus::Events::RegisterArea); -} - -void TerrainSystem::SystemDeactivate() -{ - AzFramework::Terrain::TerrainDataRequestBus::Handler::BusDisconnect(); - - { - AZStd::shared_lock lock(m_areaMutex); - m_registeredAreas.clear(); - } - - const AZ::RPI::Scene* scene = AZ::RPI::RPISystemInterface::Get()->GetDefaultScene().get(); - auto terrainFeatureProcessor = scene->GetFeatureProcessor(); - if (terrainFeatureProcessor) - { - terrainFeatureProcessor->RemoveTerrainData(); - } -} - void TerrainSystem::RegisterArea(AZ::EntityId areaId) { AZStd::unique_lock lock(m_areaMutex); @@ -383,6 +420,7 @@ void TerrainSystem::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) if (m_terrainSettingsDirty) { + terrainSettingsChanged = true; m_terrainSettingsDirty = false; // This needs to happen before the "system active" check below, because activating the system will cause the various @@ -393,24 +431,12 @@ void TerrainSystem::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) m_dirtyRegion.AddAabb(m_requestedSettings.m_worldBounds); m_terrainHeightDirty = true; m_currentSettings.m_worldBounds = m_requestedSettings.m_worldBounds; - terrainSettingsChanged = true; } if (m_requestedSettings.m_heightQueryResolution != m_currentSettings.m_heightQueryResolution) { m_dirtyRegion = AZ::Aabb::CreateNull(); m_terrainHeightDirty = true; - terrainSettingsChanged = true; - } - - if (m_requestedSettings.m_systemActive != m_currentSettings.m_systemActive) - { - m_requestedSettings.m_systemActive ? SystemActivate() : SystemDeactivate(); - - // Null dirty region will be interpreted as updating everything - m_dirtyRegion = AZ::Aabb::CreateNull(); - m_terrainHeightDirty = true; - terrainSettingsChanged = true; } m_currentSettings = m_requestedSettings; @@ -420,6 +446,14 @@ void TerrainSystem::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) { AZStd::shared_lock lock(m_areaMutex); + // Block other threads from accessing the surface data bus while we are in GetValue (which may call into the SurfaceData bus). + // We lock our surface data mutex *before* checking / setting "isRequestInProgress" so that we prevent race conditions + // that create false detection of cyclic dependencies when multiple requests occur on different threads simultaneously. + // (One case where this was previously able to occur was in rapid updating of the Preview widget on the + // GradientSurfaceDataComponent in the Editor when moving the threshold sliders back and forth rapidly) + auto& surfaceDataContext = SurfaceData::SurfaceDataSystemRequestBus::GetOrCreateContext(false); + typename SurfaceData::SurfaceDataSystemRequestBus::Context::DispatchLockGuard scopeLock(surfaceDataContext.m_contextMutex); + AZ::Transform transform = AZ::Transform::CreateTranslation(m_currentSettings.m_worldBounds.GetCenter()); uint32_t width = aznumeric_cast( @@ -449,7 +483,8 @@ void TerrainSystem::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) } AZ::Vector3 outPosition; - const Terrain::TerrainAreaHeightRequests::Sampler sampleFilter = Terrain::TerrainAreaHeightRequests::Sampler::DEFAULT; + const AzFramework::Terrain::TerrainDataRequestBus::Events::Sampler sampleFilter = + AzFramework::Terrain::TerrainDataRequestBus::Events::Sampler::DEFAULT; Terrain::TerrainAreaHeightRequestBus::Event( areaId, &Terrain::TerrainAreaHeightRequestBus::Events::GetHeight, inPosition, outPosition, sampleFilter); @@ -476,6 +511,14 @@ void TerrainSystem::OnTick(float /*deltaTime*/, AZ::ScriptTimePoint /*time*/) if (terrainSettingsChanged || m_terrainHeightDirty) { + // Block other threads from accessing the surface data bus while we are in GetValue (which may call into the SurfaceData bus). + // We lock our surface data mutex *before* checking / setting "isRequestInProgress" so that we prevent race conditions + // that create false detection of cyclic dependencies when multiple requests occur on different threads simultaneously. + // (One case where this was previously able to occur was in rapid updating of the Preview widget on the + // GradientSurfaceDataComponent in the Editor when moving the threshold sliders back and forth rapidly) + auto& surfaceDataContext = SurfaceData::SurfaceDataSystemRequestBus::GetOrCreateContext(false); + typename SurfaceData::SurfaceDataSystemRequestBus::Context::DispatchLockGuard scopeLock(surfaceDataContext.m_contextMutex); + AzFramework::Terrain::TerrainDataNotifications::TerrainDataChangedMask changeMask = AzFramework::Terrain::TerrainDataNotifications::TerrainDataChangedMask::None; diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h index a75685fb12..c52165da6b 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystem.h @@ -42,10 +42,6 @@ namespace Terrain /////////////////////////////////////////// // TerrainSystemServiceRequestBus::Handler Impl - - void SetWorldBounds(const AZ::Aabb& worldBounds) override; - void SetHeightQueryResolution(AZ::Vector2 queryResolution) override; - void Activate() override; void Deactivate() override; @@ -55,8 +51,12 @@ namespace Terrain /////////////////////////////////////////// // TerrainDataRequestBus::Handler Impl - AZ::Vector2 GetTerrainGridResolution() const override; + AZ::Vector2 GetTerrainHeightQueryResolution() const override; + void SetTerrainHeightQueryResolution(AZ::Vector2 queryResolution) override; + AZ::Aabb GetTerrainAabb() const override; + void SetTerrainAabb(const AZ::Aabb& worldBounds) override; + //! Returns terrains height in meters at location x,y. //! @terrainExistsPtr: Can be nullptr. If != nullptr then, if there's no terrain at location x,y or location x,y is inside a terrain @@ -94,15 +94,12 @@ namespace Terrain float x, float y, Sampler sampleFilter = Sampler::BILINEAR, bool* terrainExistsPtr = nullptr) const override; private: - float GetHeightSynchronous(float x, float y) const; - AZ::Vector3 GetNormalSynchronous(float x, float y) const; + float GetHeightSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const; + AZ::Vector3 GetNormalSynchronous(float x, float y, Sampler sampler, bool* terrainExistsPtr) const; // AZ::TickBus::Handler overrides ... void OnTick(float deltaTime, AZ::ScriptTimePoint time) override; - void SystemActivate(); - void SystemDeactivate(); - struct TerrainSystemSettings { AZ::Aabb m_worldBounds; diff --git a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h index cb41ba9957..1ba63a8f84 100644 --- a/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h +++ b/Gems/Terrain/Code/Source/TerrainSystem/TerrainSystemBus.h @@ -16,6 +16,8 @@ #include #include +#include + namespace Terrain { /** @@ -39,9 +41,6 @@ namespace Terrain virtual void Activate() = 0; virtual void Deactivate() = 0; - virtual void SetWorldBounds(const AZ::Aabb& worldBounds) = 0; - virtual void SetHeightQueryResolution(AZ::Vector2 queryResolution) = 0; - // register an area to override terrain virtual void RegisterArea(AZ::EntityId areaId) = 0; virtual void UnregisterArea(AZ::EntityId areaId) = 0; @@ -50,27 +49,6 @@ namespace Terrain using TerrainSystemServiceRequestBus = AZ::EBus; - /** - * A bus to signal the life times of terrain areas - * Note: all the API are meant to be queued events - */ - class TerrainAreaRequests - : public AZ::ComponentBus - { - public: - //////////////////////////////////////////////////////////////////////// - // EBusTraits - using MutexType = AZStd::recursive_mutex; - //////////////////////////////////////////////////////////////////////// - - virtual ~TerrainAreaRequests() = default; - - virtual void RegisterArea() = 0; - virtual void RefreshArea() = 0; - - }; - - using TerrainAreaRequestBus = AZ::EBus; /** * A bus to signal the life times of terrain areas @@ -87,15 +65,6 @@ namespace Terrain virtual ~TerrainAreaHeightRequests() = default; - enum class Sampler - { - BILINEAR, // Get the value at the requested location, using terrain sample grid to bilinear filter between sample grid points - CLAMP, // Clamp the input point to the terrain sample grid, then get the exact value - EXACT, // Directly get the value at the location, regardless of terrain sample grid density - - DEFAULT = BILINEAR - }; - enum SurfacePointDataMask { POSITION = 0x01, @@ -107,8 +76,16 @@ namespace Terrain // Synchronous single input location. The Vector3 input position versions are defined to ignore the input Z value. - virtual void GetHeight(const AZ::Vector3& inPosition, AZ::Vector3& outPosition, Sampler sampleFilter = Sampler::DEFAULT) = 0; - virtual void GetNormal(const AZ::Vector3& inPosition, AZ::Vector3& outNormal, Sampler sampleFilter = Sampler::DEFAULT) = 0; + virtual void GetHeight( + const AZ::Vector3& inPosition, + AZ::Vector3& outPosition, + AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = + AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) = 0; + virtual void GetNormal( + const AZ::Vector3& inPosition, + AZ::Vector3& outNormal, + AzFramework::Terrain::TerrainDataRequests::Sampler sampleFilter = + AzFramework::Terrain::TerrainDataRequests::Sampler::DEFAULT) = 0; }; using TerrainAreaHeightRequestBus = AZ::EBus; diff --git a/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp b/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp index 91d6a26f75..f0533322c8 100644 --- a/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp +++ b/Gems/Terrain/Code/Tests/LayerSpawnerTests.cpp @@ -17,6 +17,10 @@ #include +using ::testing::NiceMock; +using ::testing::AtLeast; +using ::testing::_; + class LayerSpawnerComponentTest : public ::testing::Test { @@ -26,7 +30,7 @@ protected: AZStd::unique_ptr m_entity; Terrain::TerrainLayerSpawnerComponent* m_layerSpawnerComponent; UnitTest::MockBoxShapeComponent* m_shapeComponent; - AZStd::unique_ptr m_terrainSystem; + AZStd::unique_ptr> m_terrainSystem; void SetUp() override { @@ -40,10 +44,8 @@ protected: void TearDown() override { - if (m_terrainSystem) - { - m_terrainSystem->Deactivate(); - } + m_entity.reset(); + m_terrainSystem.reset(); m_app.Destroy(); } @@ -72,16 +74,9 @@ protected: ASSERT_TRUE(m_shapeComponent); } - void ResetEntity() - { - m_entity->Deactivate(); - m_entity->Reset(); - } - void CreateMockTerrainSystem() { - m_terrainSystem = AZStd::make_unique(); - m_terrainSystem->Activate(); + m_terrainSystem = AZStd::make_unique>(); } }; @@ -93,7 +88,7 @@ TEST_F(LayerSpawnerComponentTest, ActivatEntityActivateSuccess) m_entity->Activate(); EXPECT_EQ(m_entity->GetState(), AZ::Entity::State::Active); - ResetEntity(); + m_entity->Deactivate(); } TEST_F(LayerSpawnerComponentTest, LayerSpawnerDefaultValuesCorrect) @@ -115,7 +110,7 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerDefaultValuesCorrect) EXPECT_TRUE(useGroundPlane); - ResetEntity(); + m_entity->Deactivate(); } TEST_F(LayerSpawnerComponentTest, LayerSpawnerConfigValuesCorrect) @@ -147,7 +142,7 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerConfigValuesCorrect) EXPECT_FALSE(useGroundPlane); - ResetEntity(); + m_entity->Deactivate(); } TEST_F(LayerSpawnerComponentTest, LayerSpawnerRegisterAreaUpdatesTerrainSystem) @@ -156,14 +151,14 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerRegisterAreaUpdatesTerrainSystem) CreateMockTerrainSystem(); + // The Activate call should register the area. + EXPECT_CALL(*m_terrainSystem, RegisterArea(_)).Times(1); + AddLayerSpawnerAndShapeComponentToEntity(); m_entity->Activate(); - // The Activate call should have registered the area. - EXPECT_EQ(1, m_terrainSystem->m_registerAreaCalledCount); - - ResetEntity(); + m_entity->Deactivate(); } TEST_F(LayerSpawnerComponentTest, LayerSpawnerUnregisterAreaUpdatesTerrainSystem) @@ -172,16 +167,14 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerUnregisterAreaUpdatesTerrainSystem CreateMockTerrainSystem(); + // The Deactivate call should unregister the area. + EXPECT_CALL(*m_terrainSystem, UnregisterArea(_)).Times(1); + AddLayerSpawnerAndShapeComponentToEntity(); m_entity->Activate(); - m_layerSpawnerComponent->Deactivate(); - - // The Deactivate call should have unregistered the area. - EXPECT_EQ(1, m_terrainSystem->m_unregisterAreaCalledCount); - - ResetEntity(); + m_entity->Deactivate(); } TEST_F(LayerSpawnerComponentTest, LayerSpawnerTransformChangedUpdatesTerrainSystem) @@ -190,6 +183,9 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerTransformChangedUpdatesTerrainSyst CreateMockTerrainSystem(); + // The TransformChanged call should refresh the area. + EXPECT_CALL(*m_terrainSystem, RefreshArea(_)).Times(1); + AddLayerSpawnerAndShapeComponentToEntity(); m_entity->Activate(); @@ -197,9 +193,7 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerTransformChangedUpdatesTerrainSyst AZ::TransformNotificationBus::Event( m_entity->GetId(), &AZ::TransformNotificationBus::Events::OnTransformChanged, AZ::Transform(), AZ::Transform()); - EXPECT_EQ(1, m_terrainSystem->m_refreshAreaCalledCount); - - ResetEntity(); + m_entity->Deactivate(); } TEST_F(LayerSpawnerComponentTest, LayerSpawnerShapeChangedUpdatesTerrainSystem) @@ -208,6 +202,9 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerShapeChangedUpdatesTerrainSystem) CreateMockTerrainSystem(); + // The ShapeChanged call should refresh the area. + EXPECT_CALL(*m_terrainSystem, RefreshArea(_)).Times(1); + AddLayerSpawnerAndShapeComponentToEntity(); m_entity->Activate(); @@ -216,7 +213,5 @@ TEST_F(LayerSpawnerComponentTest, LayerSpawnerShapeChangedUpdatesTerrainSystem) m_entity->GetId(), &LmbrCentral::ShapeComponentNotificationsBus::Events::OnShapeChanged, LmbrCentral::ShapeComponentNotifications::ShapeChangeReasons::ShapeChanged); - EXPECT_EQ(1, m_terrainSystem->m_refreshAreaCalledCount); - - ResetEntity(); + m_entity->Deactivate(); } diff --git a/Gems/Terrain/Code/Tests/TerrainMocks.h b/Gems/Terrain/Code/Tests/TerrainMocks.h index 674104e26b..03a2eccf1d 100644 --- a/Gems/Terrain/Code/Tests/TerrainMocks.h +++ b/Gems/Terrain/Code/Tests/TerrainMocks.h @@ -7,7 +7,10 @@ */ #pragma once +#include + #include +#include #include namespace UnitTest @@ -62,44 +65,45 @@ namespace UnitTest } }; - class MockTerrainSystem : private Terrain::TerrainSystemServiceRequestBus::Handler + class MockTerrainSystemService : private Terrain::TerrainSystemServiceRequestBus::Handler { public: - void Activate() override + MockTerrainSystemService() { Terrain::TerrainSystemServiceRequestBus::Handler::BusConnect(); } - void Deactivate() override + ~MockTerrainSystemService() { Terrain::TerrainSystemServiceRequestBus::Handler::BusDisconnect(); } - void SetWorldBounds([[maybe_unused]] const AZ::Aabb& worldBounds) override - { - } + MOCK_METHOD0(Activate, void()); + MOCK_METHOD0(Deactivate, void()); - void SetHeightQueryResolution([[maybe_unused]] AZ::Vector2 queryResolution) override - { - } - - void RegisterArea([[maybe_unused]] AZ::EntityId areaId) override - { - m_registerAreaCalledCount++; - } - - void UnregisterArea([[maybe_unused]] AZ::EntityId areaId) override - { - m_unregisterAreaCalledCount++; - } - - void RefreshArea([[maybe_unused]] AZ::EntityId areaId) override - { - m_refreshAreaCalledCount++; - } - - int m_registerAreaCalledCount = 0; - int m_refreshAreaCalledCount = 0; - int m_unregisterAreaCalledCount = 0; + MOCK_METHOD1(RegisterArea, void(AZ::EntityId areaId)); + MOCK_METHOD1(UnregisterArea, void(AZ::EntityId areaId)); + MOCK_METHOD1(RefreshArea, void(AZ::EntityId areaId)); }; + + class MockTerrainDataNotificationListener : public AzFramework::Terrain::TerrainDataNotificationBus::Handler + { + public: + MockTerrainDataNotificationListener() + { + AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusConnect(); + } + + ~MockTerrainDataNotificationListener() + { + AzFramework::Terrain::TerrainDataNotificationBus::Handler::BusDisconnect(); + } + + MOCK_METHOD0(OnTerrainDataCreateBegin, void()); + MOCK_METHOD0(OnTerrainDataCreateEnd, void()); + MOCK_METHOD0(OnTerrainDataDestroyBegin, void()); + MOCK_METHOD0(OnTerrainDataDestroyEnd, void()); + MOCK_METHOD2(OnTerrainDataChanged, void(const AZ::Aabb& dirtyRegion, TerrainDataChangedMask dataChangedMask)); + }; + } diff --git a/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp b/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp new file mode 100644 index 0000000000..3e557c66a6 --- /dev/null +++ b/Gems/Terrain/Code/Tests/TerrainSystemTest.cpp @@ -0,0 +1,92 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include + +#include + +#include +#include + +using ::testing::AtLeast; +using ::testing::NiceMock; + +class TerrainSystemTest : public ::testing::Test +{ +protected: + AZ::ComponentApplication m_app; + + AZStd::unique_ptr m_entity; + AZStd::unique_ptr m_terrainSystem; + + void SetUp() override + { + AZ::ComponentApplication::Descriptor appDesc; + appDesc.m_memoryBlocksByteSize = 20 * 1024 * 1024; + appDesc.m_recordingMode = AZ::Debug::AllocationRecords::RECORD_NO_RECORDS; + appDesc.m_stackRecordLevels = 20; + + m_app.Create(appDesc); + } + + void TearDown() override + { + m_terrainSystem.reset(); + m_app.Destroy(); + } + + void CreateEntity() + { + m_entity = AZStd::make_unique(); + m_entity->Init(); + + ASSERT_TRUE(m_entity); + } + + void ResetEntity() + { + m_entity->Deactivate(); + m_entity->Reset(); + } +}; + +TEST_F(TerrainSystemTest, TrivialCreateDestroy) +{ + m_terrainSystem = AZStd::make_unique(); +} + +TEST_F(TerrainSystemTest, TrivialActivateDeactivate) +{ + m_terrainSystem = AZStd::make_unique(); + m_terrainSystem->Activate(); + m_terrainSystem->Deactivate(); +} + +TEST_F(TerrainSystemTest, CreateEventsCalledOnActivation) +{ + NiceMock mockTerrainListener; + EXPECT_CALL(mockTerrainListener, OnTerrainDataCreateBegin()).Times(AtLeast(1)); + EXPECT_CALL(mockTerrainListener, OnTerrainDataCreateEnd()).Times(AtLeast(1)); + + m_terrainSystem = AZStd::make_unique(); + m_terrainSystem->Activate(); +} + +TEST_F(TerrainSystemTest, DestroyEventsCalledOnDeactivation) +{ + NiceMock mockTerrainListener; + EXPECT_CALL(mockTerrainListener, OnTerrainDataDestroyBegin()).Times(AtLeast(1)); + EXPECT_CALL(mockTerrainListener, OnTerrainDataDestroyEnd()).Times(AtLeast(1)); + + m_terrainSystem = AZStd::make_unique(); + m_terrainSystem->Activate(); + m_terrainSystem->Deactivate(); +} + + diff --git a/Gems/Terrain/Code/Tests/TerrainTest.cpp b/Gems/Terrain/Code/Tests/TerrainTest.cpp index 9b47c91a31..40217ff9bc 100644 --- a/Gems/Terrain/Code/Tests/TerrainTest.cpp +++ b/Gems/Terrain/Code/Tests/TerrainTest.cpp @@ -8,24 +8,4 @@ #include -class TerrainTest - : public ::testing::Test -{ -protected: - void SetUp() override - { - - } - - void TearDown() override - { - - } -}; - -TEST_F(TerrainTest, SanityTest) -{ - ASSERT_TRUE(true); -} - AZ_UNIT_TEST_HOOK(DEFAULT_UNIT_TEST_ENV); diff --git a/Gems/Terrain/Code/terrain_tests_files.cmake b/Gems/Terrain/Code/terrain_tests_files.cmake index b44f143f3b..6d1cf97fd9 100644 --- a/Gems/Terrain/Code/terrain_tests_files.cmake +++ b/Gems/Terrain/Code/terrain_tests_files.cmake @@ -9,5 +9,6 @@ set(FILES Tests/TerrainMocks.h Tests/TerrainTest.cpp + Tests/TerrainSystemTest.cpp Tests/LayerSpawnerTests.cpp ) From b53bf52e0dc0a2af6886b35478a9c65eb64e03ba Mon Sep 17 00:00:00 2001 From: Chris Burel Date: Wed, 15 Sep 2021 09:48:08 -0700 Subject: [PATCH 25/26] Perform global deinitialization when exiting the game launcher (#4131) * Fix code that deregisters the Atom Scene subsystem from the AzFramework Scene The AzFramework Scene subsystem API is a generic container based on the type of argument that is passed to it. It maintains a vector of typeids, and only one object of any type is stored at a time. The Bootstrap system component registers the Atom scene as a `ScenePtr` (aka `AZStd::shared_ptr`) with the AzFramework Scene's generic subsystem. However, the component was previously deregistering the type by value, `RPI::Scene`. Since no subsystem for the type `RPI::Scene` was set, unsetting this type did nothing. The result was that the `RPI::Scene` object would still be around by the time that all the Atom `InstanceDatabse`s were being destroyed, resulting in a large number of errors reported about leaked instances during global shutdown. This fixes the above issue by passing the `m_defaultScene` as a parameter to `AzFramework::Scene::UnsetSubsystem`, the same value that is passed to `SetSubsystem`. This is better, because instead of providing explicit template arguments (which were specifying the incorrect type), this now allows the compiler to deduce the correct type, and the syntax is symmetric with the call to `SetSubsystem`. Signed-off-by: Chris Burel * Correctly release the AWS API from the `HttpRequestManager` module This code was incorrectly assuming that `AWSNativeSDKInit::InitializationManager::Shutdown()` would be called automatically by the `InitializationManager` itself. However, all that `InitAwsApi()` does is create an `AZ::EnvironmentVariable`, which is a ref-counted type, and stores it in a global static. That global static is defined in a static library (namely `AWSNativeSDKInit`), which is linked in to the `HttpRequestManager` dynamic lib. Because it is a global static, it has to be explicitly cleared with the call to `Shutdown()`. Otherwise the destructor of the EnvironmentVariable doesn't happen until global destruction, by which time the allocator that is supplied to the AWS SDK has already been destroyed, and the shutdown of the AWS SDK attempts to use the already-destroyed allocator. Signed-off-by: Chris Burel * Avoid blocking the remote console server thread if there are no connections The Remote console server runs in a separate thread. Previously, it would directly call `AzSock::Accept()` and block the server thread until some client connected to it. However, if no client connected, the thread would continue to be blocked, even if the game launcher tried to exit. This adds a check to see if there's a client on the socket before calling `Accept()`, to avoid the deadlock on launcher exit. Signed-off-by: Chris Burel * Fix a log message to print one message per line Signed-off-by: Chris Burel * Allow pumping the event loop to close the launcher window Events from the OS are handled in the game's main loop. The general loop looks like this: * Read events from the OS * Tick the game application One of the events that can come from the OS is that the window hosting the game is closed. When this event happens, many resources provided by the renderer are freed, and the game application's `shouldExit` bit is set. However, when the game's `Tick()` is called, there is lots of code that assumes the renderer is still there. To avoid crashing in the `Tick()` call, check if the game should exit after pumping the system events. Signed-off-by: Chris Burel * Unload the level when exiting the launcher This ensures that any resources held onto by the level are freed before the launcher exits. Signed-off-by: Chris Burel * Add an explicit bus `Disconnect()` call to `AZCoreLogSink` This is necessary because this bus has virtual functions and can be called from multiple threads. Signed-off-by: Chris Burel * Allow normal cleanup to take place when exiting the game launcher Previously, global cleanup was side-stepped by calling `TerminateProcess` or `exit`, when quitting the game launcher. This is in contrast to the call to `_exit` on Linux and Mac when exiting the Editor. That leading `_` makes a big difference: the former runs object destruction, the latter does not. Instead of making the launcher exit with `_exit` on Linux, instead, remove that call and actually run all the atexit code. This does not modify the Editor's behavior however. It still uses `_exit` and `TerminateProcess`. Signed-off-by: Chris Burel --- .../AzFramework/Archive/Archive.cpp | 2 +- Code/LauncherUnified/Launcher.cpp | 11 +++++---- Code/Legacy/CrySystem/AZCoreLogSink.h | 5 ++++ .../CrySystem/LevelSystem/LevelSystem.cpp | 1 + Code/Legacy/CrySystem/System.cpp | 23 ------------------- .../RemoteConsole/Core/RemoteConsoleCore.cpp | 5 ++++ .../Code/Source/BootstrapSystemComponent.cpp | 2 +- .../Code/Source/HttpRequestManager.cpp | 3 +-- 8 files changed, 20 insertions(+), 32 deletions(-) diff --git a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp index 012d713cf5..1891c50d10 100644 --- a/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp +++ b/Code/Framework/AzFramework/AzFramework/Archive/Archive.cpp @@ -2185,7 +2185,7 @@ namespace AZ::IO AZStd::unique_lock lock(m_archiveMutex); if (pArchive) { - AZ_TracePrintf("Archive", "Closing Archive file: %s", pArchive->GetFullPath()); + AZ_TracePrintf("Archive", "Closing Archive file: %s\n", pArchive->GetFullPath()); } ArchiveArray::iterator it; if (m_arrArchives.size() < 16) diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index de4c496b2a..27aab074ef 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -232,13 +232,17 @@ namespace // our frame time to be managed by AzGameFramework::GameApplication // instead, which probably isn't going to happen anytime soon given // how many things depend on the ITimer interface). - bool continueRunning = true; ISystem* system = gEnv ? gEnv->pSystem : nullptr; - while (continueRunning) + while (!gameApplication.WasExitMainLoopRequested()) { // Pump the system event loop gameApplication.PumpSystemEventLoopUntilEmpty(); + if (gameApplication.WasExitMainLoopRequested()) + { + break; + } + // Update the AzFramework system tick bus gameApplication.TickSystem(); @@ -256,9 +260,6 @@ namespace { system->UpdatePostTickBus(); } - - // Check for quit requests - continueRunning = !gameApplication.WasExitMainLoopRequested() && continueRunning; } } } diff --git a/Code/Legacy/CrySystem/AZCoreLogSink.h b/Code/Legacy/CrySystem/AZCoreLogSink.h index e824c4c172..a54a78157c 100644 --- a/Code/Legacy/CrySystem/AZCoreLogSink.h +++ b/Code/Legacy/CrySystem/AZCoreLogSink.h @@ -31,6 +31,11 @@ class AZCoreLogSink : public AZ::Debug::TraceMessageBus::Handler { public: + ~AZCoreLogSink() + { + Disconnect(); + } + inline static void Connect() { GetInstance().m_ignoredAsserts = new IgnoredAssertMap(); diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index a0338941b5..c5d364a025 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -233,6 +233,7 @@ CLevelSystem::CLevelSystem(ISystem* pSystem, const char* levelsFolder) //------------------------------------------------------------------------ CLevelSystem::~CLevelSystem() { + UnloadLevel(); } //------------------------------------------------------------------------ diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp index 4a9d9ece5f..2e18e13841 100644 --- a/Code/Legacy/CrySystem/System.cpp +++ b/Code/Legacy/CrySystem/System.cpp @@ -548,29 +548,6 @@ void CSystem::Quit() logger->Flush(); } - /* - * TODO: This call to _exit, _Exit, TerminateProcess etc. needs to - * eventually be removed. This causes an extremely early exit before we - * actually perform cleanup. When this gets called most managers are - * simply never deleted and we leave it to the OS to clean up our mess - * which is just really bad practice. However there are LOTS of issues - * with shutdown at the moment. Removing this will simply cause - * a crash when either the Editor or Launcher initiate shutdown. Both - * applications crash differently too. Bugs will be logged about those - * issues. - */ -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEM_CPP_SECTION_4 -#include AZ_RESTRICTED_FILE(System_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#elif defined(WIN32) || defined(WIN64) - TerminateProcess(GetCurrentProcess(), m_env.retCode); -#else - exit(m_env.retCode); -#endif - #ifdef WIN32 //Post a WM_QUIT message to the Win32 api which causes the message loop to END //This is not the same as handling a WM_DESTROY event which destroys a window diff --git a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp index d0e9e6a760..0a8d9d8eb7 100644 --- a/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp +++ b/Code/Tools/RemoteConsole/Core/RemoteConsoleCore.cpp @@ -239,6 +239,11 @@ void SRemoteServer::Run() while (m_bAcceptClients) { + AZTIMEVAL timeout { 1, 0 }; + if (!AZ::AzSock::IsRecvPending(m_socket, &timeout)) + { + continue; + } AZ::AzSock::AzSocketAddress clientAddress; sClient = AZ::AzSock::Accept(m_socket, clientAddress); if (!m_bAcceptClients || !AZ::AzSock::IsAzSocketValid(sClient)) diff --git a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp index 97faa7380f..ddd88a1f52 100644 --- a/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp +++ b/Gems/Atom/Bootstrap/Code/Source/BootstrapSystemComponent.cpp @@ -386,7 +386,7 @@ namespace AZ // Unbind m_defaultScene to the GameEntityContext's AzFramework::Scene if (m_defaultFrameworkScene) { - m_defaultFrameworkScene->UnsetSubsystem(); + m_defaultFrameworkScene->UnsetSubsystem(m_defaultScene); } m_defaultScene = nullptr; diff --git a/Gems/HttpRequestor/Code/Source/HttpRequestManager.cpp b/Gems/HttpRequestor/Code/Source/HttpRequestManager.cpp index 8ed40c1599..523d84f0f5 100644 --- a/Gems/HttpRequestor/Code/Source/HttpRequestManager.cpp +++ b/Gems/HttpRequestor/Code/Source/HttpRequestManager.cpp @@ -35,7 +35,6 @@ namespace HttpRequestor desc.m_name = s_loggingName; desc.m_cpuId = AFFINITY_MASK_USERTHREADS; m_runThread = true; - // Shutdown will be handled by the InitializationManager - no need to call in the destructor AWSNativeSDKInit::InitializationManager::InitAwsApi(); auto function = AZStd::bind(&Manager::ThreadFunction, this); m_thread = AZStd::thread(function, &desc); @@ -43,7 +42,7 @@ namespace HttpRequestor Manager::~Manager() { - // NativeSDK Shutdown does not need to be called here - will be taken care of by the InitializationManager + AWSNativeSDKInit::InitializationManager::Shutdown(); m_runThread = false; m_requestConditionVar.notify_all(); if (m_thread.joinable()) From a5306f10f346ff465b0805b1279ed493b6af732a Mon Sep 17 00:00:00 2001 From: smurly Date: Wed, 15 Sep 2021 11:27:26 -0700 Subject: [PATCH 26/26] Reflection Probe component added to AtomEditorComponents test (#4135) Signed-off-by: Scott Murray --- ...ydra_AtomEditorComponents_AddedToEntity.py | 22 +++++++++++++++++-- .../atom_renderer/test_Atom_MainSuite.py | 15 +++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py index cd10caf57b..a2e950e1dc 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/atom_hydra_scripts/hydra_AtomEditorComponents_AddedToEntity.py @@ -3,8 +3,6 @@ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT - -Hydra script that creates an entity and attaches Atom components to it for test verification. """ import os @@ -17,6 +15,7 @@ import azlmbr.asset as asset import azlmbr.entity as entity import azlmbr.legacy.general as general import azlmbr.editor as editor +import azlmbr.render as render sys.path.append(os.path.join(azlmbr.paths.devroot, "AutomatedTesting", "Gem", "PythonTests")) @@ -125,6 +124,19 @@ def run(): def verify_set_property(entity_obj, path, value): entity_obj.get_set_test(0, path, value) + # Verify cubemap generation + def verify_cubemap_generation(component_name, entity_obj): + # Initially Check if the component has Reflection Probe component + if not hydra.has_components(entity_obj.id, ["Reflection Probe"]): + raise ValueError(f"Given entity {entity_obj.name} has no Reflection Probe component") + render.EditorReflectionProbeBus(azlmbr.bus.Event, "BakeReflectionProbe", entity_obj.id) + + def get_value(): + hydra.get_component_property_value(entity_obj.components[0], "Cubemap|Baked Cubemap Path") + + TestHelper.wait_for_condition(lambda: get_value() != "", 20.0) + general.log(f"{component_name}_test: Cubemap is generated: {get_value() != ''}") + # Wait for Editor idle loop before executing Python hydra scripts. TestHelper.init_idle() @@ -215,6 +227,12 @@ def run(): # Display Mapper Component ComponentTests("Display Mapper") + # Reflection Probe Component + reflection_probe = "Reflection Probe" + ComponentTests( + reflection_probe, + lambda entity_obj: verify_required_component_addition(entity_obj, ["Box Shape"], reflection_probe), + lambda entity_obj: verify_cubemap_generation(reflection_probe, entity_obj),) if __name__ == "__main__": run() diff --git a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py index ce496ce268..16e281e494 100644 --- a/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py +++ b/AutomatedTesting/Gem/PythonTests/atom_renderer/test_Atom_MainSuite.py @@ -161,6 +161,21 @@ class TestAtomEditorComponentsMain(object): "Display Mapper_test: Entity deleted: True", "Display Mapper_test: UNDO entity deletion works: True", "Display Mapper_test: REDO entity deletion works: True", + # Reflection Probe Component + "Reflection Probe Entity successfully created", + "Reflection Probe_test: Component added to the entity: True", + "Reflection Probe_test: Component removed after UNDO: True", + "Reflection Probe_test: Component added after REDO: True", + "Reflection Probe_test: Entered game mode: True", + "Reflection Probe_test: Exit game mode: True", + "Reflection Probe_test: Entity disabled initially: True", + "Reflection Probe_test: Entity enabled after adding required components: True", + "Reflection Probe_test: Cubemap is generated: True", + "Reflection Probe_test: Entity is hidden: True", + "Reflection Probe_test: Entity is shown: True", + "Reflection Probe_test: Entity deleted: True", + "Reflection Probe_test: UNDO entity deletion works: True", + "Reflection Probe_test: REDO entity deletion works: True", ] unexpected_lines = [