2
0

SandboxIntegration.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include "SandboxIntegration.h"
  9. #include <AzCore/Component/ComponentApplicationBus.h>
  10. #include <AzCore/Component/Entity.h>
  11. #include <AzCore/Component/TransformBus.h>
  12. #include <AzCore/Debug/Profiler.h>
  13. #include <AzCore/Math/Transform.h>
  14. #include <AzCore/RTTI/AttributeReader.h>
  15. #include <AzCore/std/functional.h>
  16. #include <AzCore/std/string/string.h>
  17. #include <AzCore/std/algorithm.h>
  18. #include <AzCore/std/numeric.h>
  19. #include <AzCore/Asset/AssetManager.h>
  20. #include <AzCore/Outcome/Outcome.h>
  21. #include <AzCore/Interface/Interface.h>
  22. #include <AzFramework/Asset/AssetSystemBus.h>
  23. #include <AzFramework/Entity/EntityContextBus.h>
  24. #include <AzFramework/StringFunc/StringFunc.h>
  25. #include <AzFramework/Visibility/BoundsBus.h>
  26. #include <AzToolsFramework/ActionManager/Action/ActionManagerInterface.h>
  27. #include <AzToolsFramework/ActionManager/Menu/MenuManagerInterface.h>
  28. #include <AzToolsFramework/ActionManager/HotKey/HotKeyManagerInterface.h>
  29. #include <AzToolsFramework/API/ComponentEntityObjectBus.h>
  30. #include <AzToolsFramework/API/EditorAssetSystemAPI.h>
  31. #include <AzToolsFramework/API/EditorEntityAPI.h>
  32. #include <AzToolsFramework/API/EntityCompositionRequestBus.h>
  33. #include <AzToolsFramework/API/ToolsApplicationAPI.h>
  34. #include <AzToolsFramework/AssetBrowser/AssetBrowserBus.h>
  35. #include <AzToolsFramework/AssetBrowser/AssetBrowserEntry.h>
  36. #include <AzToolsFramework/AssetBrowser/AssetSelectionModel.h>
  37. #include <AzToolsFramework/Commands/SelectionCommand.h>
  38. #include <AzToolsFramework/ContainerEntity/ContainerEntityInterface.h>
  39. #include <AzToolsFramework/Editor/ActionManagerIdentifiers/EditorContextIdentifiers.h>
  40. #include <AzToolsFramework/Editor/ActionManagerIdentifiers/EditorMenuIdentifiers.h>
  41. #include <AzToolsFramework/Editor/ActionManagerIdentifiers/EditorActionUpdaterIdentifiers.h>
  42. #include <AzToolsFramework/Editor/ActionManagerUtils.h>
  43. #include <AzToolsFramework/Entity/EditorEntityHelpers.h>
  44. #include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
  45. #include <AzToolsFramework/Entity/ReadOnly/ReadOnlyEntityInterface.h>
  46. #include <AzToolsFramework/ToolsComponents/EditorVisibilityComponent.h>
  47. #include <AzToolsFramework/ToolsComponents/GenericComponentWrapper.h>
  48. #include <AzToolsFramework/Undo/UndoSystem.h>
  49. #include <AzToolsFramework/UI/Prefab/PrefabIntegrationInterface.h>
  50. #include <AzToolsFramework/UI/PropertyEditor/InstanceDataHierarchy.h>
  51. #include <AzToolsFramework/UI/PropertyEditor/PropertyEditorAPI.h>
  52. #include <AzToolsFramework/UI/PropertyEditor/EntityPropertyEditor.hxx>
  53. #include <AzToolsFramework/ViewportSelection/EditorHelpers.h>
  54. #include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h>
  55. #include <MathConversion.h>
  56. #include <Atom/ImageProcessing/ImageProcessingDefines.h>
  57. #include <Atom/RPI.Public/ViewportContext.h>
  58. #include <Atom/RPI.Public/ViewportContextBus.h>
  59. #include <Atom/RPI.Reflect/Image/StreamingImageAsset.h>
  60. #include <AtomToolsFramework/Viewport/ModularViewportCameraControllerRequestBus.h>
  61. #include "UI/QComponentEntityEditorMainWindow.h"
  62. #include <LmbrCentral/Scripting/TagComponentBus.h>
  63. #include <LmbrCentral/Scripting/EditorTagComponentBus.h>
  64. // Sandbox imports.
  65. #include <Editor/CryEditDoc.h>
  66. #include <Editor/GameEngine.h>
  67. #include <Editor/DisplaySettings.h>
  68. #include <Editor/Settings.h>
  69. #include <Editor/QtViewPaneManager.h>
  70. #include <Editor/EditorViewportSettings.h>
  71. #include <Editor/EditorViewportCamera.h>
  72. #include <Editor/Util/PathUtil.h>
  73. #include "CryEdit.h"
  74. #include "Undo/Undo.h"
  75. #include <QMenu>
  76. #include <QAction>
  77. #include <QWidgetAction>
  78. #include <QHBoxLayout>
  79. #include "MainWindow.h"
  80. #include <AzCore/std/algorithm.h>
  81. #ifdef CreateDirectory
  82. #undef CreateDirectory
  83. #endif
  84. //////////////////////////////////////////////////////////////////////////
  85. // Gathers all selected entities, culling any that have an ancestor in the selection.
  86. void GetSelectedEntitiesSetWithFlattenedHierarchy(AzToolsFramework::EntityIdSet& out)
  87. {
  88. AzToolsFramework::EntityIdList entities;
  89. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  90. entities,
  91. &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities);
  92. for (const AZ::EntityId& entityId : entities)
  93. {
  94. bool selectionIncludesTransformHeritage = false;
  95. AZ::EntityId parent = entityId;
  96. do
  97. {
  98. AZ::EntityId nextParentId;
  99. AZ::TransformBus::EventResult(
  100. /*result*/ nextParentId,
  101. /*address*/ parent,
  102. &AZ::TransformBus::Events::GetParentId);
  103. parent = nextParentId;
  104. if (!parent.IsValid())
  105. {
  106. break;
  107. }
  108. for (const AZ::EntityId& parentCheck : entities)
  109. {
  110. if (parentCheck == parent)
  111. {
  112. selectionIncludesTransformHeritage = true;
  113. break;
  114. }
  115. }
  116. } while (parent.IsValid() && !selectionIncludesTransformHeritage);
  117. if (!selectionIncludesTransformHeritage)
  118. {
  119. out.insert(entityId);
  120. }
  121. }
  122. }
  123. SandboxIntegrationManager::SandboxIntegrationManager()
  124. : m_startedUndoRecordingNestingLevel(0)
  125. {
  126. // Required to receive events from the Cry Engine undo system.
  127. GetIEditor()->GetUndoManager()->AddListener(this);
  128. // Create the PrefabIntegrationManager, which initializes prefab-related operations.
  129. m_prefabIntegrationManager = aznew AzToolsFramework::Prefab::PrefabIntegrationManager();
  130. // Connect to the Action Manager Registration bus to correctly register actions, menus, toolbars etc.
  131. AzToolsFramework::ActionManagerRegistrationNotificationBus::Handler::BusConnect();
  132. }
  133. SandboxIntegrationManager::~SandboxIntegrationManager()
  134. {
  135. AzToolsFramework::ActionManagerRegistrationNotificationBus::Handler::BusDisconnect();
  136. GetIEditor()->GetUndoManager()->RemoveListener(this);
  137. delete m_prefabIntegrationManager;
  138. m_prefabIntegrationManager = nullptr;
  139. }
  140. void SandboxIntegrationManager::Setup()
  141. {
  142. AzToolsFramework::ToolsApplicationEvents::Bus::Handler::BusConnect();
  143. AzToolsFramework::EditorRequests::Bus::Handler::BusConnect();
  144. AzToolsFramework::EditorWindowRequests::Bus::Handler::BusConnect();
  145. AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusConnect();
  146. m_prefabIntegrationInterface = AZ::Interface<AzToolsFramework::Prefab::PrefabIntegrationInterface>::Get();
  147. AZ_Assert(
  148. (m_prefabIntegrationInterface != nullptr),
  149. "SandboxIntegrationManager requires a PrefabIntegrationInterface instance to be present on Setup().");
  150. m_editorEntityAPI = AZ::Interface<AzToolsFramework::EditorEntityAPI>::Get();
  151. AZ_Assert(m_editorEntityAPI, "SandboxIntegrationManager requires an EditorEntityAPI instance to be present on Setup().");
  152. m_readOnlyEntityPublicInterface = AZ::Interface<AzToolsFramework::ReadOnlyEntityPublicInterface>::Get();
  153. AZ_Assert(m_readOnlyEntityPublicInterface, "SandboxIntegrationManager requires an ReadOnlyEntityPublicInterface instance to be present on Setup().");
  154. m_contextMenuBottomHandler.Setup();
  155. }
  156. void SandboxIntegrationManager::Teardown()
  157. {
  158. m_contextMenuBottomHandler.Teardown();
  159. AzToolsFramework::EditorEntityContextNotificationBus::Handler::BusDisconnect();
  160. AzToolsFramework::EditorWindowRequests::Bus::Handler::BusDisconnect();
  161. AzToolsFramework::EditorRequests::Bus::Handler::BusDisconnect();
  162. AzToolsFramework::ToolsApplicationEvents::Bus::Handler::BusDisconnect();
  163. }
  164. void SandboxIntegrationManager::OnBeginUndo([[maybe_unused]] const char* label)
  165. {
  166. AzToolsFramework::UndoSystem::URSequencePoint* currentBatch = nullptr;
  167. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  168. currentBatch, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetCurrentUndoBatch);
  169. AZ_Assert(currentBatch, "No undo batch is active.");
  170. // Only generate a Sandbox placeholder for root-level undo batches.
  171. if (nullptr == currentBatch->GetParent())
  172. {
  173. // start Cry Undo
  174. if (!CUndo::IsRecording())
  175. {
  176. GetIEditor()->BeginUndo();
  177. // flag that we started recording the undo batch
  178. m_startedUndoRecordingNestingLevel = 1;
  179. }
  180. }
  181. else
  182. {
  183. if (m_startedUndoRecordingNestingLevel)
  184. {
  185. // if we previously started recording the undo, increment the nesting level so we can
  186. // detect when we need to accept the undo in OnEndUndo()
  187. m_startedUndoRecordingNestingLevel++;
  188. }
  189. }
  190. }
  191. void SandboxIntegrationManager::OnEndUndo(const char* label, bool changed)
  192. {
  193. // Add the undo only after we know it's got a legit change, we can't remove undos from the cry undo system so we do it here instead of OnBeginUndo
  194. if (changed && CUndo::IsRecording())
  195. {
  196. CUndo::Record(new CToolsApplicationUndoLink());
  197. }
  198. if (m_startedUndoRecordingNestingLevel)
  199. {
  200. m_startedUndoRecordingNestingLevel--;
  201. if (m_startedUndoRecordingNestingLevel == 0)
  202. {
  203. if (changed)
  204. {
  205. // only accept the undo batch that we initially started undo recording on
  206. GetIEditor()->AcceptUndo(label);
  207. }
  208. else
  209. {
  210. GetIEditor()->CancelUndo();
  211. }
  212. }
  213. }
  214. }
  215. void SandboxIntegrationManager::OpenPinnedInspector(const AzToolsFramework::EntityIdSet& entities)
  216. {
  217. QDockWidget* dockWidget = InstanceViewPane(LyViewPane::EntityInspectorPinned);
  218. if (dockWidget)
  219. {
  220. QComponentEntityEditorInspectorWindow* editor = static_cast<QComponentEntityEditorInspectorWindow*>(dockWidget->widget());
  221. if (editor && editor->GetPropertyEditor())
  222. {
  223. editor->GetPropertyEditor()->SetOverrideEntityIds(entities);
  224. AZStd::string widgetTitle;
  225. if (entities.size() == 1)
  226. {
  227. AZStd::string entityName;
  228. AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationBus::Events::GetEntityName, *entities.begin());
  229. widgetTitle = AZStd::string::format("%s Inspector", entityName.c_str());
  230. QObject::connect(editor->GetPropertyEditor(), &AzToolsFramework::EntityPropertyEditor::SelectedEntityNameChanged, [dockWidget](const AZ::EntityId& /*entityId*/, const AZStd::string& name)
  231. {
  232. AZStd::string newTitle = AZStd::string::format("%s Inspector", name.c_str());
  233. dockWidget->setWindowTitle(newTitle.c_str());
  234. });
  235. }
  236. else
  237. {
  238. widgetTitle = AZStd::string::format("%zu Entities - Inspector", entities.size());
  239. }
  240. dockWidget->setWindowTitle(widgetTitle.c_str());
  241. }
  242. }
  243. }
  244. void SandboxIntegrationManager::ClosePinnedInspector(AzToolsFramework::EntityPropertyEditor* editor)
  245. {
  246. QWidget* currentWidget = editor->parentWidget();
  247. while (currentWidget)
  248. {
  249. QDockWidget* dockWidget = qobject_cast<QDockWidget*>(currentWidget);
  250. if (dockWidget)
  251. {
  252. QtViewPaneManager::instance()->ClosePaneInstance(LyViewPane::EntityInspectorPinned, dockWidget);
  253. return;
  254. }
  255. currentWidget = currentWidget->parentWidget();
  256. }
  257. }
  258. void SandboxIntegrationManager::CreateEditorRepresentation(AZ::Entity* entity)
  259. {
  260. // Add required editor components to the entity.
  261. AzToolsFramework::EditorEntityContextRequestBus::Broadcast(
  262. &AzToolsFramework::EditorEntityContextRequestBus::Events::AddRequiredComponents, *entity);
  263. }
  264. //////////////////////////////////////////////////////////////////////////
  265. void SandboxIntegrationManager::GoToSelectedOrHighlightedEntitiesInViewports()
  266. {
  267. AzToolsFramework::EntityIdList entityIds;
  268. GetSelectedOrHighlightedEntities(entityIds);
  269. GoToEntitiesInViewports(entityIds);
  270. }
  271. //////////////////////////////////////////////////////////////////////////
  272. void SandboxIntegrationManager::GoToSelectedEntitiesInViewports()
  273. {
  274. AzToolsFramework::EntityIdList entityIds;
  275. GetSelectedEntities(entityIds);
  276. GoToEntitiesInViewports(entityIds);
  277. }
  278. bool SandboxIntegrationManager::CanGoToSelectedEntitiesInViewports()
  279. {
  280. AzToolsFramework::EntityIdList entityIds;
  281. GetSelectedEntities(entityIds);
  282. if (entityIds.size() == 0)
  283. {
  284. return false;
  285. }
  286. for (const AZ::EntityId& entityId : entityIds)
  287. {
  288. if (CanGoToEntityOrChildren(entityId))
  289. {
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. bool SandboxIntegrationManager::CanGoToEntityOrChildren(const AZ::EntityId& entityId) const
  296. {
  297. AZ::Entity* entity = nullptr;
  298. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId);
  299. if (entity == nullptr)
  300. {
  301. return false;
  302. }
  303. // Skip if this entity doesn't have a transform;
  304. // UI entities and system components don't have transforms and thus aren't visible in the Editor viewport
  305. return entity->GetTransform() != nullptr;
  306. }
  307. AZ::Vector3 SandboxIntegrationManager::GetWorldPositionAtViewportCenter()
  308. {
  309. if (GetIEditor() && GetIEditor()->GetViewManager())
  310. {
  311. CViewport* view = GetIEditor()->GetViewManager()->GetGameViewport();
  312. if (view)
  313. {
  314. int width, height;
  315. view->GetDimensions(&width, &height);
  316. return LYVec3ToAZVec3(view->ViewToWorld(QPoint(width / 2, height / 2)));
  317. }
  318. }
  319. return AZ::Vector3::CreateZero();
  320. }
  321. AZ::Vector3 SandboxIntegrationManager::GetWorldPositionAtViewportInteraction() const
  322. {
  323. const auto& iEditor = GetIEditor();
  324. if (const auto& viewManager = (iEditor != nullptr) ? iEditor->GetViewManager() : nullptr)
  325. {
  326. return viewManager->GetClickPositionInViewportSpace();
  327. }
  328. return AZ::Vector3::CreateZero();
  329. }
  330. void SandboxIntegrationManager::ClearRedoStack()
  331. {
  332. // We have two separate undo systems that are assumed to be kept in sync,
  333. // So here we tell the legacy Undo system to clear the redo stack and at the same time
  334. // tell the new AZ undo system to clear redo stack ("slice" the stack)
  335. // Clear legacy redo stack
  336. GetIEditor()->ClearRedoStack();
  337. // Clear AZ redo stack
  338. AzToolsFramework::UndoSystem::UndoStack* undoStack = nullptr;
  339. AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(undoStack, &AzToolsFramework::ToolsApplicationRequestBus::Events::GetUndoStack);
  340. if (undoStack)
  341. {
  342. undoStack->Slice();
  343. }
  344. }
  345. //////////////////////////////////////////////////////////////////////////
  346. void SandboxIntegrationManager::CloneSelection(bool& handled)
  347. {
  348. AZ_PROFILE_FUNCTION(AzToolsFramework);
  349. AzToolsFramework::EntityIdList entities;
  350. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  351. entities,
  352. &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities);
  353. AzToolsFramework::EntityIdSet duplicationSet = AzToolsFramework::GetCulledEntityHierarchy(entities);
  354. if (!duplicationSet.empty())
  355. {
  356. m_editorEntityAPI->DuplicateSelected();
  357. handled = true;
  358. }
  359. else
  360. {
  361. handled = false;
  362. }
  363. }
  364. void SandboxIntegrationManager::DeleteSelectedEntities([[maybe_unused]] const bool includeDescendants)
  365. {
  366. AzToolsFramework::EntityIdList selectedEntityIds;
  367. AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(
  368. selectedEntityIds, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities);
  369. AzToolsFramework::ToolsApplicationRequestBus::Broadcast(
  370. &AzToolsFramework::ToolsApplicationRequests::DeleteEntitiesAndAllDescendants, selectedEntityIds);
  371. }
  372. AZ::EntityId SandboxIntegrationManager::CreateNewEntity(AZ::EntityId parentId)
  373. {
  374. AZ::Vector3 position = AZ::Vector3::CreateZero();
  375. // If we have an invalid parent, base new entity's position on the viewport.
  376. if (!parentId.IsValid())
  377. {
  378. position = GetWorldPositionAtViewportCenter();
  379. }
  380. return CreateNewEntityAtPosition(position, parentId);
  381. }
  382. AZ::EntityId SandboxIntegrationManager::CreateNewEntityAsChild(AZ::EntityId parentId)
  383. {
  384. AZ_Assert(parentId.IsValid(), "Entity created as a child of an invalid parent entity.");
  385. auto newEntityId = CreateNewEntity(parentId);
  386. // Some modules need to know that this special action has taken place; broadcast an event.
  387. ToolsApplicationEvents::Bus::Broadcast(&ToolsApplicationEvents::EntityCreatedAsChild, newEntityId, parentId);
  388. return newEntityId;
  389. }
  390. AZ::EntityId SandboxIntegrationManager::CreateNewEntityAtPosition(const AZ::Vector3& pos, AZ::EntityId parentId)
  391. {
  392. using namespace AzToolsFramework;
  393. return m_prefabIntegrationInterface->CreateNewEntityAtPosition(pos, parentId);
  394. }
  395. AzFramework::EntityContextId SandboxIntegrationManager::GetEntityContextId()
  396. {
  397. AzFramework::EntityContextId editorEntityContextId = AzFramework::EntityContextId::CreateNull();
  398. AzToolsFramework::EditorEntityContextRequestBus::BroadcastResult(editorEntityContextId, &AzToolsFramework::EditorEntityContextRequestBus::Events::GetEditorEntityContextId);
  399. return editorEntityContextId;
  400. }
  401. //////////////////////////////////////////////////////////////////////////
  402. QWidget* SandboxIntegrationManager::GetAppMainWindow()
  403. {
  404. return MainWindow::instance();
  405. }
  406. QWidget* SandboxIntegrationManager::GetMainWindow()
  407. {
  408. return MainWindow::instance();
  409. }
  410. IEditor* SandboxIntegrationManager::GetEditor()
  411. {
  412. return GetIEditor();
  413. }
  414. //////////////////////////////////////////////////////////////////////////
  415. void SandboxIntegrationManager::LaunchLuaEditor(const char* files)
  416. {
  417. CCryEditApp::instance()->OpenLUAEditor(files);
  418. }
  419. bool SandboxIntegrationManager::IsLevelDocumentOpen()
  420. {
  421. return (GetIEditor() && GetIEditor()->GetDocument() && GetIEditor()->GetDocument()->IsDocumentReady());
  422. }
  423. AZStd::string SandboxIntegrationManager::GetLevelName()
  424. {
  425. return AZStd::string(GetIEditor()->GetGameEngine()->GetLevelName().toUtf8().constData());
  426. }
  427. void SandboxIntegrationManager::OnPrepareForContextReset()
  428. {
  429. // Deselect everything.
  430. AzToolsFramework::ToolsApplicationRequests::Bus::Broadcast(
  431. &AzToolsFramework::ToolsApplicationRequests::Bus::Events::SetSelectedEntities, AzToolsFramework::EntityIdList());
  432. }
  433. void SandboxIntegrationManager::OnActionRegistrationHook()
  434. {
  435. auto actionManagerInterface = AZ::Interface<AzToolsFramework::ActionManagerInterface>::Get();
  436. auto hotKeyManagerInterface = AZ::Interface<AzToolsFramework::HotKeyManagerInterface>::Get();
  437. if (!actionManagerInterface || !hotKeyManagerInterface)
  438. {
  439. return;
  440. }
  441. // Create entity
  442. {
  443. const AZStd::string_view actionIdentifier = "o3de.action.sandbox.createEntity";
  444. AzToolsFramework::ActionProperties actionProperties;
  445. actionProperties.m_name = "Create entity";
  446. actionProperties.m_description = "Creates an entity under the current selection";
  447. actionProperties.m_category = "Entity";
  448. actionProperties.m_menuVisibility = AzToolsFramework::ActionVisibility::HideWhenDisabled;
  449. actionManagerInterface->RegisterAction(
  450. EditorIdentifiers::MainWindowActionContextIdentifier,
  451. actionIdentifier,
  452. actionProperties,
  453. [this]()
  454. {
  455. AZ::Vector3 worldPosition = GetWorldPositionAtViewportInteraction();
  456. AzToolsFramework::EntityIdList selectedEntities;
  457. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  458. selectedEntities, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetSelectedEntities);
  459. // when nothing is selected, entity is created at root level.
  460. if (selectedEntities.empty())
  461. {
  462. CreateNewEntityAtPosition(worldPosition);
  463. }
  464. // when a single entity is selected, entity is created as its child.
  465. else if (selectedEntities.size() == 1)
  466. {
  467. AZ::EntityId selectedEntityId = selectedEntities.front();
  468. bool selectedEntityIsReadOnly = m_readOnlyEntityPublicInterface->IsReadOnly(selectedEntityId);
  469. auto containerEntityInterface = AZ::Interface<AzToolsFramework::ContainerEntityInterface>::Get();
  470. if (containerEntityInterface && containerEntityInterface->IsContainerOpen(selectedEntityId) && !selectedEntityIsReadOnly)
  471. {
  472. AZ::Transform entityTransform = AZ::Transform::CreateIdentity();
  473. AZ::TransformBus::EventResult(entityTransform, selectedEntityId, &AZ::TransformBus::Events::GetWorldTM);
  474. CreateNewEntityAtPosition(entityTransform.GetInverse().TransformPoint(worldPosition), selectedEntityId);
  475. }
  476. }
  477. }
  478. );
  479. actionManagerInterface->InstallEnabledStateCallback(
  480. actionIdentifier,
  481. [readOnlyEntityPublicInterface = m_readOnlyEntityPublicInterface]() -> bool
  482. {
  483. AzToolsFramework::EntityIdList selectedEntities;
  484. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  485. selectedEntities, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetSelectedEntities);
  486. if (selectedEntities.size() == 0)
  487. {
  488. return true;
  489. }
  490. else if (selectedEntities.size() == 1)
  491. {
  492. AZ::EntityId selectedEntityId = selectedEntities.front();
  493. bool selectedEntityIsReadOnly = readOnlyEntityPublicInterface->IsReadOnly(selectedEntityId);
  494. auto containerEntityInterface = AZ::Interface<AzToolsFramework::ContainerEntityInterface>::Get();
  495. return (containerEntityInterface && containerEntityInterface->IsContainerOpen(selectedEntityId) && !selectedEntityIsReadOnly);
  496. }
  497. return false;
  498. }
  499. );
  500. // Trigger update whenever entity selection changes.
  501. actionManagerInterface->AddActionToUpdater(EditorIdentifiers::EntitySelectionChangedUpdaterIdentifier, actionIdentifier);
  502. hotKeyManagerInterface->SetActionHotKey(actionIdentifier, "Ctrl+Alt+N");
  503. }
  504. }
  505. void SandboxIntegrationManager::OnMenuBindingHook()
  506. {
  507. auto menuManagerInterface = AZ::Interface<AzToolsFramework::MenuManagerInterface>::Get();
  508. if (!menuManagerInterface)
  509. {
  510. return;
  511. }
  512. // Entity Outliner Context Menu
  513. auto outcome = menuManagerInterface->AddActionToMenu(EditorIdentifiers::EntityOutlinerContextMenuIdentifier, "o3de.action.sandbox.createEntity", 100);
  514. // Viewport Context Menu
  515. menuManagerInterface->AddActionToMenu(EditorIdentifiers::ViewportContextMenuIdentifier, "o3de.action.sandbox.createEntity", 100);
  516. }
  517. void SandboxIntegrationManager::ContextMenu_NewEntity()
  518. {
  519. AZ::Vector3 worldPosition = AZ::Vector3::CreateZero();
  520. // If we don't have a viewport active to aid in placement, the object
  521. // will be created at the origin.
  522. if (CViewport* view = GetIEditor()->GetViewManager()->GetGameViewport();
  523. view && m_contextMenuViewPoint.has_value())
  524. {
  525. worldPosition = AzToolsFramework::FindClosestPickIntersection(
  526. view->GetViewportId(), m_contextMenuViewPoint.value(), AzToolsFramework::EditorPickRayLength,
  527. AzToolsFramework::GetDefaultEntityPlacementDistance());
  528. }
  529. CreateNewEntityAtPosition(worldPosition);
  530. }
  531. //////////////////////////////////////////////////////////////////////////
  532. void SandboxIntegrationManager::GoToEntitiesInViewports(const AzToolsFramework::EntityIdList& entityIds)
  533. {
  534. if (entityIds.empty())
  535. {
  536. return;
  537. }
  538. const AZ::Aabb aabb = AZStd::accumulate(
  539. AZStd::begin(entityIds), AZStd::end(entityIds), AZ::Aabb::CreateNull(), [](AZ::Aabb acc, const AZ::EntityId entityId) {
  540. const AZ::Aabb aabb = AzFramework::CalculateEntityWorldBoundsUnion(AzToolsFramework::GetEntityById(entityId));
  541. acc.AddAabb(aabb);
  542. return acc;
  543. });
  544. float radius;
  545. AZ::Vector3 center;
  546. aabb.GetAsSphere(center, radius);
  547. auto viewportContextManager = AZ::Interface<AZ::RPI::ViewportContextRequestsInterface>::Get();
  548. const int viewCount = GetIEditor()->GetViewManager()->GetViewCount(); // legacy call
  549. for (int viewIndex = 0; viewIndex < viewCount; ++viewIndex)
  550. {
  551. if (auto viewportContext = viewportContextManager->GetViewportContextById(viewIndex))
  552. {
  553. if (const AZStd::optional<AZ::Transform> nextCameraTransform = SandboxEditor::CalculateGoToEntityTransform(
  554. viewportContext->GetCameraTransform(),
  555. AzFramework::RetrieveFov(viewportContext->GetCameraProjectionMatrix()),
  556. center,
  557. radius);
  558. nextCameraTransform.has_value())
  559. {
  560. SandboxEditor::HandleDefaultViewportCameraTransitionFromSetting(*nextCameraTransform);
  561. }
  562. }
  563. }
  564. }
  565. void SandboxIntegrationManager::ContextMenu_Duplicate()
  566. {
  567. bool handled = true;
  568. AzToolsFramework::EditorRequestBus::Broadcast(&AzToolsFramework::EditorRequests::CloneSelection, handled);
  569. }
  570. void SandboxIntegrationManager::ContextMenu_DeleteSelected()
  571. {
  572. DeleteSelectedEntities(true);
  573. }
  574. void SandboxIntegrationManager::GetSelectedEntities(AzToolsFramework::EntityIdList& entities)
  575. {
  576. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  577. entities, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetSelectedEntities);
  578. }
  579. void SandboxIntegrationManager::GetSelectedOrHighlightedEntities(AzToolsFramework::EntityIdList& entities)
  580. {
  581. AzToolsFramework::EntityIdList selectedEntities;
  582. AzToolsFramework::EntityIdList highlightedEntities;
  583. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  584. selectedEntities, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetSelectedEntities);
  585. AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(
  586. highlightedEntities, &AzToolsFramework::ToolsApplicationRequests::Bus::Events::GetHighlightedEntities);
  587. entities = AZStd::move(selectedEntities);
  588. for (AZ::EntityId highlightedId : highlightedEntities)
  589. {
  590. if (entities.end() == AZStd::find(entities.begin(), entities.end(), highlightedId))
  591. {
  592. entities.push_back(highlightedId);
  593. }
  594. }
  595. }
  596. AZStd::string SandboxIntegrationManager::GetComponentEditorIcon(const AZ::Uuid& componentType, const AZ::Component* component)
  597. {
  598. AZStd::string iconPath = GetComponentIconPath(componentType, AZ::Edit::Attributes::Icon, component);
  599. return iconPath;
  600. }
  601. AZStd::string SandboxIntegrationManager::GetComponentTypeEditorIcon(const AZ::Uuid& componentType)
  602. {
  603. return GetComponentEditorIcon(componentType, nullptr);
  604. }
  605. AZStd::string SandboxIntegrationManager::GetComponentIconPath(const AZ::Uuid& componentType,
  606. AZ::Crc32 componentIconAttrib, const AZ::Component* component)
  607. {
  608. AZ_PROFILE_FUNCTION(AzToolsFramework);
  609. if (componentIconAttrib != AZ::Edit::Attributes::Icon
  610. && componentIconAttrib != AZ::Edit::Attributes::ViewportIcon
  611. && componentIconAttrib != AZ::Edit::Attributes::HideIcon)
  612. {
  613. AZ_Warning("SandboxIntegration", false, "Unrecognized component icon attribute!");
  614. }
  615. // return blank path if component shouldn't have icon at all
  616. AZStd::string iconPath;
  617. AZ::SerializeContext* serializeContext = nullptr;
  618. AZ::ComponentApplicationBus::BroadcastResult(serializeContext, &AZ::ComponentApplicationBus::Events::GetSerializeContext);
  619. AZ_Assert(serializeContext, "No serialize context");
  620. auto classData = serializeContext->FindClassData(componentType);
  621. if (classData && classData->m_editData)
  622. {
  623. // check if component icon should be hidden
  624. bool hideIcon = false;
  625. auto editorElementData = classData->m_editData->FindElementData(AZ::Edit::ClassElements::EditorData);
  626. if (editorElementData)
  627. {
  628. if (auto hideIconAttribute = editorElementData->FindAttribute(AZ::Edit::Attributes::HideIcon))
  629. {
  630. auto hideIconAttributeData = azdynamic_cast<const AZ::Edit::AttributeData<bool>*>(hideIconAttribute);
  631. if (hideIconAttributeData)
  632. {
  633. hideIcon = hideIconAttributeData->Get(nullptr);
  634. }
  635. }
  636. }
  637. if (!hideIcon)
  638. {
  639. // component should have icon. start with default
  640. iconPath = GetDefaultComponentEditorIcon();
  641. // check for specific icon
  642. if (editorElementData)
  643. {
  644. if (auto iconAttribute = editorElementData->FindAttribute(componentIconAttrib))
  645. {
  646. if (auto iconAttributeData = azdynamic_cast<const AZ::Edit::AttributeData<const char*>*>(iconAttribute))
  647. {
  648. AZStd::string iconAttributeValue = iconAttributeData->Get(component);
  649. if (!iconAttributeValue.empty())
  650. {
  651. iconPath = AZStd::move(iconAttributeValue);
  652. }
  653. }
  654. auto iconOverrideAttribute = editorElementData->FindAttribute(AZ::Edit::Attributes::DynamicIconOverride);
  655. // If it has an override and we're given an instance, then get any potential override from the instance here
  656. if (component &&
  657. (componentIconAttrib == AZ::Edit::Attributes::Icon || componentIconAttrib == AZ::Edit::Attributes::ViewportIcon) &&
  658. iconOverrideAttribute)
  659. {
  660. AZStd::string iconValue;
  661. AZ::AttributeReader iconReader(const_cast<AZ::Component*>(component), iconOverrideAttribute);
  662. iconReader.Read<AZStd::string>(iconValue);
  663. if (!iconValue.empty())
  664. {
  665. iconPath = AZStd::move(iconValue);
  666. }
  667. }
  668. }
  669. }
  670. // If Qt doesn't know where the relative path is we have to use the more expensive full path
  671. if (!QFile::exists(QString(iconPath.c_str())))
  672. {
  673. // use absolute path if possible
  674. AZStd::string iconFullPath;
  675. bool pathFound = false;
  676. using AssetSysReqBus = AzToolsFramework::AssetSystemRequestBus;
  677. AssetSysReqBus::BroadcastResult(
  678. pathFound, &AssetSysReqBus::Events::GetFullSourcePathFromRelativeProductPath,
  679. iconPath, iconFullPath);
  680. if (pathFound)
  681. {
  682. iconPath = AZStd::move(iconFullPath);
  683. }
  684. else
  685. {
  686. // If we couldn't find the full source path, try appending the product extension if the icon
  687. // source asset is one of the supported image assets. Most component icons are in .svg format,
  688. // which isn't actually consumed by the Asset Processor so the GetFullSourcePathFromRelativeProductPath
  689. // API can find the source asset without needing the product extension as well. So this edge case is
  690. // to cover any component icons that are still using other formats (e.g. png), that haven't been converted
  691. // to .svg yet, or for customers that prefer to use image formats besides .svg.
  692. AZStd::string extension;
  693. AzFramework::StringFunc::Path::GetExtension(iconPath.c_str(), extension);
  694. bool supportedStreamingImage = false;
  695. for (int i = 0; i < ImageProcessingAtom::s_TotalSupportedImageExtensions; ++i)
  696. {
  697. if (AZStd::wildcard_match(ImageProcessingAtom::s_SupportedImageExtensions[i], extension.c_str()))
  698. {
  699. supportedStreamingImage = true;
  700. break;
  701. }
  702. }
  703. if (supportedStreamingImage)
  704. {
  705. iconPath = AZStd::string::format("%s.%s", iconPath.c_str(), AZ::RPI::StreamingImageAsset::Extension);
  706. AssetSysReqBus::BroadcastResult(
  707. pathFound, &AssetSysReqBus::Events::GetFullSourcePathFromRelativeProductPath,
  708. iconPath, iconFullPath);
  709. }
  710. if (pathFound)
  711. {
  712. iconPath = AZStd::move(iconFullPath);
  713. }
  714. else
  715. {
  716. AZ_Warning(
  717. "SandboxIntegration",
  718. false,
  719. "Unable to find icon path \"%s\" for component type: %s",
  720. iconPath.c_str(),
  721. classData->m_editData->m_name);
  722. }
  723. }
  724. }
  725. }
  726. }
  727. return iconPath;
  728. }
  729. void SandboxIntegrationManager::UndoStackFlushed()
  730. {
  731. AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequestBus::Events::FlushUndo);
  732. }
  733. void SandboxIntegrationManager::RegisterViewPane(const char* name, const char* category, const AzToolsFramework::ViewPaneOptions& viewOptions, const WidgetCreationFunc& widgetCreationFunc)
  734. {
  735. QtViewPaneManager::instance()->RegisterPane(name, category, widgetCreationFunc, viewOptions);
  736. }
  737. void SandboxIntegrationManager::RegisterCustomViewPane(const char* name, const char* category, const AzToolsFramework::ViewPaneOptions& viewOptions)
  738. {
  739. QtViewPaneManager::instance()->RegisterPane(name, category, nullptr, viewOptions);
  740. }
  741. void SandboxIntegrationManager::UnregisterViewPane(const char* name)
  742. {
  743. QtViewPaneManager::instance()->UnregisterPane(name);
  744. }
  745. QWidget* SandboxIntegrationManager::GetViewPaneWidget(const char* viewPaneName)
  746. {
  747. return FindViewPane<QWidget>(viewPaneName);
  748. }
  749. void SandboxIntegrationManager::OpenViewPane(const char* paneName)
  750. {
  751. const QtViewPane* pane = QtViewPaneManager::instance()->OpenPane(paneName);
  752. if (pane)
  753. {
  754. pane->m_dockWidget->raise();
  755. pane->m_dockWidget->activateWindow();
  756. }
  757. }
  758. QDockWidget* SandboxIntegrationManager::InstanceViewPane(const char* paneName)
  759. {
  760. return QtViewPaneManager::instance()->InstancePane(paneName);
  761. }
  762. void SandboxIntegrationManager::CloseViewPane(const char* paneName)
  763. {
  764. QtViewPaneManager::instance()->ClosePane(paneName);
  765. }
  766. void SandboxIntegrationManager::BrowseForAssets(AssetSelectionModel& selection)
  767. {
  768. AssetBrowserComponentRequestBus::Broadcast(&AssetBrowserComponentRequests::PickAssets, selection, GetMainWindow());
  769. }