2
0

ComponentEntityObject.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  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 "ComponentEntityObject.h"
  9. #include "Settings.h"
  10. #include "IIconManager.h"
  11. #include "Include/IObjectManager.h"
  12. #include "Objects/SelectionGroup.h"
  13. #include <AzCore/Component/Entity.h>
  14. #include <AzCore/Component/ComponentApplicationBus.h>
  15. #include <AzCore/Component/TransformBus.h>
  16. #include <AzCore/Serialization/Utils.h>
  17. #include <AzCore/std/string/string.h>
  18. #include <AzCore/Math/Transform.h>
  19. #include <AzFramework/Viewport/DisplayContextRequestBus.h>
  20. #include <AzToolsFramework/API/ComponentEntitySelectionBus.h>
  21. #include <AzToolsFramework/Commands/PreemptiveUndoCache.h>
  22. #include <AzToolsFramework/Entity/EditorEntityContextBus.h>
  23. #include <AzToolsFramework/Entity/EditorEntityInfoBus.h>
  24. #include <AzToolsFramework/Entity/EditorEntityHelpers.h>
  25. #include <AzToolsFramework/ToolsComponents/EditorLayerComponentBus.h>
  26. #include <AzToolsFramework/ToolsComponents/EditorLockComponent.h>
  27. #include <AzToolsFramework/ToolsComponents/EditorVisibilityComponent.h>
  28. #include <AzToolsFramework/ToolsComponents/SelectionComponent.h>
  29. #include <AzToolsFramework/ToolsComponents/TransformComponent.h>
  30. #include <AzToolsFramework/ToolsComponents/GenericComponentWrapper.h>
  31. #include <AzToolsFramework/ToolsComponents/EditorSelectionAccentSystemComponent.h>
  32. #include <AzToolsFramework/ToolsComponents/EditorEntityIconComponentBus.h>
  33. #include <AzToolsFramework/Undo/UndoCacheInterface.h>
  34. #include <LmbrCentral/Rendering/RenderNodeBus.h>
  35. #include <IDisplayViewport.h>
  36. #include <CryCommon/Cry_GeoIntersect.h>
  37. #include <MathConversion.h>
  38. #include <TrackView/TrackViewAnimNode.h>
  39. #include <ViewManager.h>
  40. #include <Viewport.h>
  41. /**
  42. * Scalars for icon drawing behavior.
  43. */
  44. static const int s_kIconSize = 36; /// Icon display size (in pixels)
  45. CComponentEntityObject::CComponentEntityObject()
  46. : m_hasIcon(false)
  47. , m_entityIconVisible(false)
  48. , m_iconOnlyHitTest(false)
  49. , m_drawAccents(true)
  50. , m_accentType(AzToolsFramework::EntityAccentType::None)
  51. , m_isIsolated(false)
  52. , m_iconTexture(nullptr)
  53. {
  54. }
  55. CComponentEntityObject::~CComponentEntityObject()
  56. {
  57. DeleteEntity();
  58. }
  59. bool CComponentEntityObject::Init(IEditor* ie, CBaseObject* copyFrom, const QString& file)
  60. {
  61. SetColor(RGB(0, 255, 0));
  62. SetTextureIcon(GetClassDesc()->GetTextureIconId());
  63. // Sandbox does not serialize this object with others in the layer.
  64. SetFlags(OBJFLAG_DONT_SAVE);
  65. const bool result = CEntityObject::Init(ie, copyFrom, file);
  66. return result;
  67. }
  68. void CComponentEntityObject::UpdatePreemptiveUndoCache()
  69. {
  70. using namespace AzToolsFramework;
  71. auto undoCacheInterface = AZ::Interface<UndoSystem::UndoCacheInterface>::Get();
  72. if (undoCacheInterface)
  73. {
  74. undoCacheInterface->UpdateCache(m_entityId);
  75. }
  76. }
  77. void CComponentEntityObject::AssignEntity(AZ::Entity* entity, bool destroyOld)
  78. {
  79. const AZ::EntityId newEntityId = entity ? entity->GetId() : AZ::EntityId();
  80. if (m_entityId.IsValid())
  81. {
  82. AZ::TransformNotificationBus::Handler::BusDisconnect();
  83. LmbrCentral::RenderBoundsNotificationBus::Handler::BusDisconnect();
  84. AzToolsFramework::ComponentEntityEditorRequestBus::Handler::BusDisconnect();
  85. AZ::EntityBus::Handler::BusDisconnect();
  86. AzToolsFramework::ComponentEntityObjectRequestBus::Handler::BusDisconnect();
  87. AzToolsFramework::EditorLockComponentNotificationBus::Handler::BusDisconnect();
  88. AzToolsFramework::EditorVisibilityNotificationBus::Handler::BusDisconnect();
  89. AzToolsFramework::EditorEntityIconComponentNotificationBus::Handler::BusDisconnect();
  90. if (destroyOld && m_entityId != newEntityId)
  91. {
  92. EBUS_EVENT(AzToolsFramework::EditorEntityContextRequestBus, DestroyEditorEntity, m_entityId);
  93. }
  94. m_entityId.SetInvalid();
  95. }
  96. if (entity)
  97. {
  98. m_entityId = entity->GetId();
  99. // note: GetObjectManager() will always be valid during normal operation but
  100. // will not exist when running unit tests
  101. if (IObjectManager* objectManager = GetObjectManager())
  102. {
  103. // Use the entity id to generate a GUID for this CEO because we need it to stay consistent for systems
  104. // that register by GUID such as undo/redo since our own undo/redo system constantly recreates CEOs
  105. GUID entityBasedGUID;
  106. entityBasedGUID.Data1 = 0;
  107. entityBasedGUID.Data2 = 0;
  108. entityBasedGUID.Data3 = 0;
  109. static_assert(sizeof(m_entityId) >= sizeof(entityBasedGUID.Data4), "The data contained in entity Id should fit inside Data4, if not switch to some other method of conversion to GUID");
  110. memcpy(&entityBasedGUID.Data4, &m_entityId, sizeof(entityBasedGUID.Data4));
  111. objectManager->ChangeObjectId(GetId(), entityBasedGUID);
  112. // Synchronize sandbox name to new entity's name.
  113. {
  114. EditorActionScope nameChange(m_nameReentryGuard);
  115. SetName(QString(entity->GetName().c_str()));
  116. }
  117. }
  118. EBUS_EVENT(AzToolsFramework::EditorEntityContextRequestBus, AddRequiredComponents, *entity);
  119. AZ::TransformNotificationBus::Handler::BusConnect(m_entityId);
  120. LmbrCentral::RenderBoundsNotificationBus::Handler::BusConnect(m_entityId);
  121. AzToolsFramework::ComponentEntityEditorRequestBus::Handler::BusConnect(m_entityId);
  122. AZ::EntityBus::Handler::BusConnect(m_entityId);
  123. AzToolsFramework::ComponentEntityObjectRequestBus::Handler::BusConnect(this);
  124. AzToolsFramework::EditorLockComponentNotificationBus::Handler::BusConnect(m_entityId);
  125. AzToolsFramework::EditorVisibilityNotificationBus::Handler::BusConnect(m_entityId);
  126. AzToolsFramework::EditorEntityIconComponentNotificationBus::Handler::BusConnect(m_entityId);
  127. // Synchronize transform to Sandbox.
  128. AzToolsFramework::Components::TransformComponent* transformComponent =
  129. entity->FindComponent<AzToolsFramework::Components::TransformComponent>();
  130. if (transformComponent)
  131. {
  132. OnTransformChanged(transformComponent->GetLocalTM(), transformComponent->GetWorldTM());
  133. }
  134. }
  135. RefreshVisibilityAndLock();
  136. }
  137. void CComponentEntityObject::RefreshVisibilityAndLock()
  138. {
  139. using AzToolsFramework::EditorEntityInfoRequestBus;
  140. using AzToolsFramework::EditorEntityLockComponentNotificationBus;
  141. using AzToolsFramework::EditorEntityVisibilityNotificationBus;
  142. // Lock state is tracked in 3 places:
  143. // EditorLockComponent, EditorEntityModel, and ComponentEntityObject.
  144. // Entities in layers have additional behavior in relation to lock state, if the layer is locked it supersedes the entity's lock state.
  145. // The viewport controls for manipulating entities are disabled during lock state here in ComponentEntityObject using the OBJFLAG_FROZEN.
  146. // In this case, the lock behavior should include the layer hierarchy as well, if the layer is locked this entity can't move.
  147. // EditorEntityModel can report this information.
  148. bool locked = false;
  149. EditorEntityInfoRequestBus::EventResult(
  150. locked, m_entityId, &EditorEntityInfoRequestBus::Events::IsLocked);
  151. EditorEntityLockComponentNotificationBus::Event(
  152. m_entityId, &EditorEntityLockComponentNotificationBus::Events::OnEntityLockChanged, locked);
  153. // OBJFLAG_HIDDEN should match EditorVisibilityComponent's VisibilityFlag.
  154. // Visibility state is similar to lock state in the number of areas it can be set / tracked. See the comment about the lock state above.
  155. bool visibility = true;
  156. EditorEntityInfoRequestBus::EventResult(
  157. visibility, m_entityId, &EditorEntityInfoRequestBus::Events::IsVisible);
  158. EditorEntityVisibilityNotificationBus::Event(
  159. m_entityId, &EditorEntityVisibilityNotificationBus::Events::OnEntityVisibilityChanged, visibility);
  160. }
  161. void CComponentEntityObject::SetName(const QString& name)
  162. {
  163. if (m_nameReentryGuard)
  164. {
  165. EditorActionScope nameChange(m_nameReentryGuard);
  166. AZ::Entity* entity = nullptr;
  167. EBUS_EVENT_RESULT(entity, AZ::ComponentApplicationBus, FindEntity, m_entityId);
  168. if (entity)
  169. {
  170. entity->SetName(name.toUtf8().data());
  171. }
  172. }
  173. CEntityObject::SetName(name);
  174. }
  175. void CComponentEntityObject::DeleteEntity()
  176. {
  177. AssignEntity(nullptr);
  178. CEntityObject::DeleteEntity();
  179. }
  180. float CComponentEntityObject::GetRadius()
  181. {
  182. static const float s_defaultRadius = 0.5f;
  183. return s_defaultRadius;
  184. }
  185. void CComponentEntityObject::SetSelected(bool bSelect)
  186. {
  187. CEntityObject::SetSelected(bSelect);
  188. if (m_selectionReentryGuard)
  189. {
  190. // Ignore event when received from the tools app, since the action is originating in Sandbox.
  191. EditorActionScope selectionChange(m_selectionReentryGuard);
  192. // Pass the action to the tools application.
  193. if (bSelect)
  194. {
  195. AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequests::MarkEntitySelected, m_entityId);
  196. }
  197. else
  198. {
  199. AzToolsFramework::ToolsApplicationRequestBus::Broadcast(&AzToolsFramework::ToolsApplicationRequests::MarkEntityDeselected, m_entityId);
  200. }
  201. }
  202. bool anySelected = false;
  203. AzToolsFramework::ToolsApplicationRequestBus::BroadcastResult(anySelected, &AzToolsFramework::ToolsApplicationRequests::AreAnyEntitiesSelected);
  204. if (!anySelected)
  205. {
  206. GetIEditor()->Notify(eNotify_OnEntitiesDeselected);
  207. }
  208. else
  209. {
  210. GetIEditor()->Notify(eNotify_OnEntitiesSelected);
  211. }
  212. }
  213. void CComponentEntityObject::SetHighlight(bool bHighlight)
  214. {
  215. CEntityObject::SetHighlight(bHighlight);
  216. if (m_entityId.IsValid())
  217. {
  218. EBUS_EVENT(AzToolsFramework::ToolsApplicationRequests::Bus, SetEntityHighlighted, m_entityId, bHighlight);
  219. }
  220. }
  221. IRenderNode* CComponentEntityObject::GetEngineNode() const
  222. {
  223. // It's possible for AZ::Entities to have multiple IRenderNodes.
  224. // However, the editor currently expects a single IRenderNode per "editor object".
  225. // Therefore, return the highest priority handler.
  226. if (auto* renderNodeHandler = LmbrCentral::RenderNodeRequestBus::FindFirstHandler(m_entityId))
  227. {
  228. return renderNodeHandler->GetRenderNode();
  229. }
  230. return nullptr;
  231. }
  232. void CComponentEntityObject::OnEntityNameChanged(const AZStd::string& name)
  233. {
  234. if (m_nameReentryGuard)
  235. {
  236. EditorActionScope selectionChange(m_nameReentryGuard);
  237. SetName(QString(name.c_str()));
  238. }
  239. }
  240. void CComponentEntityObject::AttachChild(CBaseObject* child, bool /*bKeepPos*/)
  241. {
  242. if (child->GetType() == OBJTYPE_AZENTITY)
  243. {
  244. CComponentEntityObject* childComponentEntity = static_cast<CComponentEntityObject*>(child);
  245. AZ::EntityId childEntityId = childComponentEntity->GetAssociatedEntityId();
  246. if (childEntityId.IsValid())
  247. {
  248. // The action is originating from Sandbox, so ignore the return event.
  249. EditorActionScope parentChange(childComponentEntity->m_parentingReentryGuard);
  250. {
  251. AzToolsFramework::ScopedUndoBatch undoBatch("Editor Parent");
  252. EBUS_EVENT_ID(childEntityId, AZ::TransformBus, SetParent, m_entityId);
  253. undoBatch.MarkEntityDirty(childEntityId);
  254. }
  255. EBUS_EVENT(AzToolsFramework::ToolsApplicationEvents::Bus, InvalidatePropertyDisplay, AzToolsFramework::Refresh_Values);
  256. }
  257. }
  258. }
  259. void CComponentEntityObject::DetachAll(bool /*bKeepPos*/)
  260. {
  261. }
  262. void CComponentEntityObject::DetachThis(bool /*bKeepPos*/)
  263. {
  264. if (m_parentingReentryGuard)
  265. {
  266. EditorActionScope parentChange(m_parentingReentryGuard);
  267. if (m_entityId.IsValid())
  268. {
  269. AzToolsFramework::ScopedUndoBatch undoBatch("Editor Unparent");
  270. EBUS_EVENT_ID(m_entityId, AZ::TransformBus, SetParent, AZ::EntityId());
  271. undoBatch.MarkEntityDirty(m_entityId);
  272. }
  273. EBUS_EVENT(AzToolsFramework::ToolsApplicationEvents::Bus, InvalidatePropertyDisplay, AzToolsFramework::Refresh_Values);
  274. }
  275. }
  276. CBaseObject* CComponentEntityObject::GetLinkParent() const
  277. {
  278. AZ::EntityId parentId;
  279. EBUS_EVENT_ID_RESULT(parentId, m_entityId, AZ::TransformBus, GetParentId);
  280. return CComponentEntityObject::FindObjectForEntity(parentId);
  281. }
  282. bool CComponentEntityObject::IsFrozen() const
  283. {
  284. return CheckFlags(OBJFLAG_FROZEN);
  285. }
  286. void CComponentEntityObject::SetFrozen(bool frozen)
  287. {
  288. if (m_lockedReentryGuard)
  289. {
  290. EditorActionScope flagChange(m_lockedReentryGuard);
  291. AzToolsFramework::SetEntityLockState(m_entityId, frozen);
  292. }
  293. }
  294. void CComponentEntityObject::OnEntityLockChanged(bool locked)
  295. {
  296. CEntityObject::SetFrozen(locked);
  297. }
  298. void CComponentEntityObject::SetHidden(
  299. bool bHidden, [[maybe_unused]] uint64 hiddenId /*=CBaseObject::s_invalidHiddenID*/, [[maybe_unused]] bool bAnimated /*=false*/)
  300. {
  301. if (m_visibilityFlagReentryGuard)
  302. {
  303. EditorActionScope flagChange(m_visibilityFlagReentryGuard);
  304. AzToolsFramework::SetEntityVisibility(m_entityId, !bHidden);
  305. }
  306. }
  307. void CComponentEntityObject::OnEntityVisibilityChanged(bool visible)
  308. {
  309. CEntityObject::SetHidden(!visible);
  310. }
  311. void CComponentEntityObject::OnEntityIconChanged(const AZ::Data::AssetId& entityIconAssetId)
  312. {
  313. (void)entityIconAssetId;
  314. SetupEntityIcon();
  315. }
  316. void CComponentEntityObject::OnParentChanged([[maybe_unused]] AZ::EntityId oldParent, [[maybe_unused]] AZ::EntityId newParent)
  317. {
  318. }
  319. void CComponentEntityObject::OnRenderBoundsReset()
  320. {
  321. CEntityObject::InvalidateTM(0);
  322. }
  323. void CComponentEntityObject::SetSandboxObjectAccent(AzToolsFramework::EntityAccentType accent)
  324. {
  325. m_accentType = accent;
  326. AzToolsFramework::EditorComponentSelectionNotificationsBus::Event(m_entityId,
  327. &AzToolsFramework::EditorComponentSelectionNotificationsBus::Events::OnAccentTypeChanged, m_accentType);
  328. }
  329. void CComponentEntityObject::SetSandBoxObjectIsolated(bool isIsolated)
  330. {
  331. m_isIsolated = isIsolated;
  332. GetIEditor()->GetObjectManager()->InvalidateVisibleList();
  333. }
  334. bool CComponentEntityObject::IsSandBoxObjectIsolated()
  335. {
  336. return m_isIsolated;
  337. }
  338. bool CComponentEntityObject::SetPos(const Vec3& pos, int flags)
  339. {
  340. bool isAzEditorTransformLocked = false;
  341. AzToolsFramework::Components::TransformComponentMessages::Bus::EventResult(isAzEditorTransformLocked, m_entityId,
  342. &AzToolsFramework::Components::TransformComponentMessages::IsTransformLocked);
  343. bool lockTransformOnUserInput = isAzEditorTransformLocked && (flags & eObjectUpdateFlags_UserInput);
  344. if (IsLayer() || lockTransformOnUserInput)
  345. {
  346. return false;
  347. }
  348. if ((flags & eObjectUpdateFlags_MoveTool) || (flags & eObjectUpdateFlags_UserInput))
  349. {
  350. // If we have a parent also in the selection set, don't allow the move tool to manipulate our position.
  351. if (IsNonLayerAncestorSelected())
  352. {
  353. return false;
  354. }
  355. }
  356. return CEntityObject::SetPos(pos, flags);
  357. }
  358. bool CComponentEntityObject::SetRotation(const Quat& rotate, int flags)
  359. {
  360. bool isAzEditorTransformLocked = false;
  361. AzToolsFramework::Components::TransformComponentMessages::Bus::EventResult(isAzEditorTransformLocked, m_entityId,
  362. &AzToolsFramework::Components::TransformComponentMessages::IsTransformLocked);
  363. bool lockTransformOnUserInput = isAzEditorTransformLocked && (flags & eObjectUpdateFlags_UserInput);
  364. if (IsLayer() || lockTransformOnUserInput)
  365. {
  366. return false;
  367. }
  368. if (flags & eObjectUpdateFlags_UserInput)
  369. {
  370. // If we have a parent also in the selection set, don't allow the rotate tool to manipulate our position.
  371. if (IsNonLayerAncestorSelected())
  372. {
  373. return false;
  374. }
  375. }
  376. return CEntityObject::SetRotation(rotate, flags);
  377. }
  378. bool CComponentEntityObject::SetScale(const Vec3& scale, int flags)
  379. {
  380. bool isAzEditorTransformLocked = false;
  381. AzToolsFramework::Components::TransformComponentMessages::Bus::EventResult(isAzEditorTransformLocked, m_entityId,
  382. &AzToolsFramework::Components::TransformComponentMessages::IsTransformLocked);
  383. bool lockTransformOnUserInput = isAzEditorTransformLocked && (flags & eObjectUpdateFlags_UserInput);
  384. if (IsLayer() || lockTransformOnUserInput)
  385. {
  386. return false;
  387. }
  388. if ((flags & eObjectUpdateFlags_ScaleTool) || (flags & eObjectUpdateFlags_UserInput))
  389. {
  390. // If we have a parent also in the selection set, don't allow the scale tool to manipulate our position.
  391. if (IsNonLayerAncestorSelected())
  392. {
  393. return false;
  394. }
  395. }
  396. return CEntityObject::SetScale(scale, flags);
  397. }
  398. bool CComponentEntityObject::IsNonLayerAncestorSelected() const
  399. {
  400. AZ::EntityId parentId;
  401. AZ::TransformBus::EventResult(parentId, m_entityId, &AZ::TransformBus::Events::GetParentId);
  402. while (parentId.IsValid())
  403. {
  404. CComponentEntityObject* parentObject = CComponentEntityObject::FindObjectForEntity(parentId);
  405. if (parentObject && parentObject->IsSelected())
  406. {
  407. bool isLayerEntity = false;
  408. AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult(
  409. isLayerEntity,
  410. parentObject->GetAssociatedEntityId(),
  411. &AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer);
  412. if (!isLayerEntity)
  413. {
  414. return true;
  415. }
  416. }
  417. AZ::EntityId currentParentId = parentId;
  418. parentId.SetInvalid();
  419. AZ::TransformBus::EventResult(parentId, currentParentId, &AZ::TransformBus::Events::GetParentId);
  420. }
  421. return false;
  422. }
  423. bool CComponentEntityObject::IsLayer() const
  424. {
  425. bool isLayerEntity = false;
  426. AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult(
  427. isLayerEntity,
  428. m_entityId,
  429. &AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer);
  430. return isLayerEntity;
  431. }
  432. bool CComponentEntityObject::IsAncestorIconDrawingAtSameLocation() const
  433. {
  434. if (m_entityId.IsValid())
  435. {
  436. AZ::EntityId parentId;
  437. AZ::TransformBus::EventResult(parentId, m_entityId, &AZ::TransformBus::Events::GetParentId);
  438. if (!parentId.IsValid())
  439. {
  440. return false;
  441. }
  442. AZ::Vector3 worldTranslation;
  443. AZ::TransformBus::EventResult(worldTranslation, m_entityId, &AZ::TransformBus::Events::GetWorldTranslation);
  444. while (parentId.IsValid())
  445. {
  446. AZ::Vector3 parentTranslation;
  447. AZ::TransformBus::EventResult(parentTranslation, parentId, &AZ::TransformBus::Events::GetWorldTranslation);
  448. if (parentTranslation.GetDistanceSq(worldTranslation) < 0.01f)
  449. {
  450. CComponentEntityObject* parentObject = CComponentEntityObject::FindObjectForEntity(parentId);
  451. if (parentObject && !parentObject->IsSelected() && parentObject->IsEntityIconVisible())
  452. {
  453. // An ancestor in the same location that's not selected and has icon visible has been found
  454. return true;
  455. }
  456. }
  457. AZ::EntityId currentParentId = parentId;
  458. parentId.SetInvalid();
  459. AZ::TransformBus::EventResult(parentId, currentParentId, &AZ::TransformBus::Events::GetParentId);
  460. }
  461. }
  462. return false;
  463. }
  464. bool CComponentEntityObject::IsDescendantSelectedAtSameLocation() const
  465. {
  466. if (m_entityId.IsValid())
  467. {
  468. if (GetObjectManager()->GetSelection() && GetObjectManager()->GetSelection()->GetCount() == 0)
  469. {
  470. return false;
  471. }
  472. AZ::Vector3 worldTranslation;
  473. AZ::TransformBus::EventResult(worldTranslation, m_entityId, &AZ::TransformBus::Events::GetWorldTranslation);
  474. // For each descendant, check if it's selected and if so if it's located at the same location as we are
  475. AzToolsFramework::EntityIdList descendantIds;
  476. AZ::TransformBus::EventResult(descendantIds, m_entityId, &AZ::TransformBus::Events::GetAllDescendants);
  477. for (AZ::EntityId entityId : descendantIds)
  478. {
  479. CComponentEntityObject* descendantObject = CComponentEntityObject::FindObjectForEntity(entityId);
  480. if (descendantObject && descendantObject->IsSelected())
  481. {
  482. // Check if this entity is at the exact location of us
  483. AZ::Vector3 entityTranslation;
  484. AZ::TransformBus::EventResult(entityTranslation, entityId, &AZ::TransformBus::Events::GetWorldTranslation);
  485. if (entityTranslation.GetDistanceSq(worldTranslation) < 0.01f)
  486. {
  487. return true;
  488. }
  489. }
  490. }
  491. }
  492. return false;
  493. }
  494. void CComponentEntityObject::InvalidateTM(int nWhyFlags)
  495. {
  496. CEntityObject::InvalidateTM(nWhyFlags);
  497. if (m_transformReentryGuard)
  498. {
  499. EditorActionScope transformChange(m_transformReentryGuard);
  500. if (m_entityId.IsValid())
  501. {
  502. Matrix34 worldTransform = GetWorldTM();
  503. EBUS_EVENT_ID(m_entityId, AZ::TransformBus, SetWorldTM, LYTransformToAZTransform(worldTransform));
  504. }
  505. }
  506. }
  507. void CComponentEntityObject::OnTransformChanged([[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world)
  508. {
  509. if (m_transformReentryGuard) // Ignore if action originated from Sandbox.
  510. {
  511. EditorActionScope transformChange(m_transformReentryGuard);
  512. Matrix34 worlTM = AZTransformToLYTransform(world);
  513. SetLocalTM(worlTM, eObjectUpdateFlags_Animated);
  514. }
  515. }
  516. int CComponentEntityObject::MouseCreateCallback(CViewport* view, EMouseEvent event, QPoint& point, int flags)
  517. {
  518. if (event == eMouseMove || event == eMouseLDown)
  519. {
  520. Vec3 pos;
  521. if (GetIEditor()->GetAxisConstrains() != AXIS_TERRAIN)
  522. {
  523. pos = view->MapViewToCP(point);
  524. }
  525. else
  526. {
  527. // Snap to terrain.
  528. bool hitTerrain;
  529. pos = view->ViewToWorld(point, &hitTerrain);
  530. if (hitTerrain)
  531. {
  532. pos.z = GetIEditor()->GetTerrainElevation(pos.x, pos.y);
  533. }
  534. pos = view->SnapToGrid(pos);
  535. }
  536. pos = view->SnapToGrid(pos);
  537. SetPos(pos);
  538. if (event == eMouseLDown)
  539. {
  540. return MOUSECREATE_OK;
  541. }
  542. return MOUSECREATE_CONTINUE;
  543. }
  544. return CBaseObject::MouseCreateCallback(view, event, point, flags);
  545. }
  546. bool CComponentEntityObject::HitHelperTest(HitContext& hc)
  547. {
  548. bool hit = CEntityObject::HitHelperTest(hc);
  549. if (!hit && m_entityId.IsValid())
  550. {
  551. // Pick against icon in screen space.
  552. if (IsEntityIconVisible())
  553. {
  554. const QPoint entityScreenPos = hc.view->WorldToView(GetWorldPos());
  555. const float screenPosX = static_cast<float>(entityScreenPos.x());
  556. const float screenPosY = static_cast<float>(entityScreenPos.y());
  557. const float iconRange = static_cast<float>(s_kIconSize / 2);
  558. if ((hc.point2d.x() >= screenPosX - iconRange && hc.point2d.x() <= screenPosX + iconRange)
  559. && (hc.point2d.y() >= screenPosY - iconRange && hc.point2d.y() <= screenPosY + iconRange))
  560. {
  561. hc.dist = hc.raySrc.GetDistance(GetWorldPos());
  562. hc.iconHit = true;
  563. return true;
  564. }
  565. }
  566. }
  567. return hit;
  568. }
  569. bool CComponentEntityObject::HitTest(HitContext& hc)
  570. {
  571. AZ_PROFILE_FUNCTION(Entity);
  572. if (m_iconOnlyHitTest)
  573. {
  574. return false;
  575. }
  576. if (m_entityId.IsValid())
  577. {
  578. // Pick against bounding box/geometry
  579. AABB bounds(AABB::RESET);
  580. GetBoundBox(bounds);
  581. if (!bounds.IsReset())
  582. {
  583. Vec3 hitPos;
  584. if (Intersect::Ray_AABB(Ray(hc.raySrc, hc.rayDir), bounds, hitPos))
  585. {
  586. bool rayIntersection = false;
  587. bool preciseSelectionRequired = false;
  588. float closestDistance = std::numeric_limits<float>::max();
  589. const int viewportId = GetIEditor()->GetViewManager()->GetGameViewport()->GetViewportId();
  590. AzToolsFramework::EditorComponentSelectionRequestsBus::EnumerateHandlersId(m_entityId,
  591. [&hc, &closestDistance, &rayIntersection, &preciseSelectionRequired, viewportId](
  592. AzToolsFramework::EditorComponentSelectionRequests* handler) -> bool
  593. {
  594. AZ_PROFILE_FUNCTION(Entity);
  595. if (handler->SupportsEditorRayIntersect())
  596. {
  597. float distance = std::numeric_limits<float>::max();
  598. preciseSelectionRequired = true;
  599. const bool intersection = handler->EditorSelectionIntersectRayViewport(
  600. { viewportId }, LYVec3ToAZVec3(hc.raySrc), LYVec3ToAZVec3(hc.rayDir), distance);
  601. rayIntersection = rayIntersection || intersection;
  602. if (intersection && distance < closestDistance)
  603. {
  604. closestDistance = distance;
  605. }
  606. }
  607. return true; // iterate over all handlers
  608. });
  609. hc.object = this;
  610. if (preciseSelectionRequired)
  611. {
  612. hc.dist = closestDistance;
  613. return rayIntersection;
  614. }
  615. hc.dist = (hitPos - hc.raySrc).GetLength();
  616. return true;
  617. }
  618. return false;
  619. }
  620. }
  621. const Vec3 origin = GetWorldPos();
  622. const float radius = GetRadius();
  623. Vec3 w = origin - hc.raySrc;
  624. Vec3 wcross = hc.rayDir.Cross(w);
  625. const float d = wcross.GetLengthSquared();
  626. if (d < square(radius) + hc.distanceTolerance &&
  627. w.GetLengthSquared() > square(radius))
  628. {
  629. Vec3 i0;
  630. hc.object = this;
  631. if (Intersect::Ray_SphereFirst(Ray(hc.raySrc, hc.rayDir), ::Sphere(origin, radius), i0))
  632. {
  633. hc.dist = hc.raySrc.GetDistance(i0);
  634. return true;
  635. }
  636. hc.dist = hc.raySrc.GetDistance(origin);
  637. return true;
  638. }
  639. return false;
  640. }
  641. void CComponentEntityObject::GetBoundBox(AABB& box)
  642. {
  643. AZ_PROFILE_FUNCTION(Entity);
  644. box.Reset();
  645. const AZ::EntityId entityId = m_entityId;
  646. if (entityId.IsValid())
  647. {
  648. CViewport* gameViewport = GetIEditor()->GetViewManager()->GetGameViewport();
  649. const int viewportId = gameViewport ? gameViewport->GetViewportId() : -1;
  650. if (const AZ::Aabb bound =
  651. AzToolsFramework::CalculateEditorEntitySelectionBounds(entityId, AzFramework::ViewportInfo{viewportId});
  652. bound.IsValid())
  653. {
  654. box.Add(AZVec3ToLYVec3(bound.GetMin()));
  655. box.Add(AZVec3ToLYVec3(bound.GetMax()));
  656. return;
  657. }
  658. }
  659. CBaseObject::GetBoundBox(box);
  660. }
  661. void CComponentEntityObject::GetLocalBounds(AABB& box)
  662. {
  663. box.Reset();
  664. float r = GetRadius();
  665. box.min = -Vec3(r, r, r);
  666. box.max = Vec3(r, r, r);
  667. }
  668. XmlNodeRef CComponentEntityObject::Export([[maybe_unused]] const QString& levelPath, [[maybe_unused]] XmlNodeRef& xmlNode)
  669. {
  670. // All component entities are serialized out in a separate pass, so they can be
  671. // loaded en-masse rather than individually. As such, we don't export them
  672. // alongside Cry Entities.
  673. return XmlNodeRef();
  674. }
  675. CComponentEntityObject* CComponentEntityObject::FindObjectForEntity(AZ::EntityId id)
  676. {
  677. CEntityObject* object = nullptr;
  678. EBUS_EVENT_ID_RESULT(object, id, AzToolsFramework::ComponentEntityEditorRequestBus, GetSandboxObject);
  679. if (object && (object->GetType() == OBJTYPE_AZENTITY))
  680. {
  681. return static_cast<CComponentEntityObject*>(object);
  682. }
  683. return nullptr;
  684. }
  685. void CComponentEntityObject::Display(DisplayContext& dc)
  686. {
  687. if (!(dc.flags & DISPLAY_2D))
  688. {
  689. m_entityIconVisible = false;
  690. }
  691. bool displaySelectionHelper = false;
  692. if (!CanBeDrawn(dc, displaySelectionHelper))
  693. {
  694. return;
  695. }
  696. DrawDefault(dc);
  697. bool showIcons = m_hasIcon;
  698. if (showIcons)
  699. {
  700. SEditorSettings* editorSettings = GetIEditor()->GetEditorSettings();
  701. if (!editorSettings->viewports.bShowIcons && !editorSettings->viewports.bShowSizeBasedIcons)
  702. {
  703. showIcons = false;
  704. }
  705. }
  706. if (m_entityId.IsValid())
  707. {
  708. // Draw link to parent if this or the parent object are selected.
  709. {
  710. AZ::EntityId parentId;
  711. EBUS_EVENT_ID_RESULT(parentId, m_entityId, AZ::TransformBus, GetParentId);
  712. if (parentId.IsValid())
  713. {
  714. bool isParentVisible = false;
  715. AzToolsFramework::EditorEntityInfoRequestBus::EventResult(isParentVisible, parentId, &AzToolsFramework::EditorEntityInfoRequestBus::Events::IsVisible);
  716. CComponentEntityObject* parentObject = CComponentEntityObject::FindObjectForEntity(parentId);
  717. if (isParentVisible && (IsSelected() || (parentObject && parentObject->IsSelected())))
  718. {
  719. const QColor kLinkColorParent(0, 255, 255);
  720. const QColor kLinkColorChild(0, 0, 255);
  721. AZ::Vector3 parentTranslation;
  722. EBUS_EVENT_ID_RESULT(parentTranslation, parentId, AZ::TransformBus, GetWorldTranslation);
  723. dc.DrawLine(AZVec3ToLYVec3(parentTranslation), GetWorldTM().GetTranslation(), kLinkColorParent, kLinkColorChild);
  724. }
  725. }
  726. }
  727. // Don't draw icons if we have an ancestor in the same location that has an icon - makes sure
  728. // ancestor icons draw on top and are able to be selected over children. Also check if a descendant
  729. // is selected at the same location. In cases of entity hierarchies where numerous ancestors have
  730. // no position offset, we need this so the ancestors don't draw over us when we're selected
  731. if (showIcons)
  732. {
  733. if ((dc.flags & DISPLAY_2D) ||
  734. IsSelected() ||
  735. IsAncestorIconDrawingAtSameLocation() ||
  736. IsDescendantSelectedAtSameLocation())
  737. {
  738. showIcons = false;
  739. }
  740. }
  741. // Allow components to override in-editor visualization.
  742. {
  743. const AzFramework::DisplayContextRequestGuard displayContextGuard(dc);
  744. AzFramework::DebugDisplayRequestBus::BusPtr debugDisplayBus;
  745. AzFramework::DebugDisplayRequestBus::Bind(
  746. debugDisplayBus, AzFramework::g_defaultSceneEntityDebugDisplayId);
  747. AZ_Assert(debugDisplayBus, "Invalid DebugDisplayRequestBus.");
  748. AzFramework::DebugDisplayRequests* debugDisplay =
  749. AzFramework::DebugDisplayRequestBus::FindFirstHandler(debugDisplayBus);
  750. AzFramework::EntityDebugDisplayEventBus::Event(
  751. m_entityId, &AzFramework::EntityDebugDisplayEvents::DisplayEntityViewport,
  752. AzFramework::ViewportInfo{ dc.GetView()->asCViewport()->GetViewportId() },
  753. *debugDisplay);
  754. }
  755. }
  756. }
  757. void CComponentEntityObject::DrawDefault(DisplayContext& dc, const QColor& labelColor)
  758. {
  759. CEntityObject::DrawDefault(dc, labelColor);
  760. DrawAccent(dc);
  761. }
  762. IStatObj* CComponentEntityObject::GetIStatObj()
  763. {
  764. return nullptr;
  765. }
  766. bool CComponentEntityObject::IsIsolated() const
  767. {
  768. return m_isIsolated;
  769. }
  770. bool CComponentEntityObject::IsSelected() const
  771. {
  772. return AzToolsFramework::IsSelected(m_entityId);
  773. }
  774. bool CComponentEntityObject::IsSelectable() const
  775. {
  776. return AzToolsFramework::IsSelectableInViewport(m_entityId);
  777. }
  778. void CComponentEntityObject::SetWorldPos(const Vec3& pos, int flags)
  779. {
  780. // Layers, by design, are not supposed to be moveable. Layers are intended to just be a grouping
  781. // mechanism to allow teams to cleanly split their level into working zones, and a moveable position
  782. // complicates that behavior more than it helps.
  783. // Unfortunately component entity objects have a position under the hood, so prevent layers from moving here.
  784. bool isLayerEntity = false;
  785. AzToolsFramework::Layers::EditorLayerComponentRequestBus::EventResult(
  786. isLayerEntity,
  787. m_entityId,
  788. &AzToolsFramework::Layers::EditorLayerComponentRequestBus::Events::HasLayer);
  789. bool isAzEditorTransformLocked = false;
  790. AzToolsFramework::Components::TransformComponentMessages::Bus::EventResult(isAzEditorTransformLocked, m_entityId,
  791. &AzToolsFramework::Components::TransformComponentMessages::IsTransformLocked);
  792. bool lockTransformOnUserInput = isAzEditorTransformLocked && (flags & eObjectUpdateFlags_UserInput);
  793. if (isLayerEntity || lockTransformOnUserInput)
  794. {
  795. return;
  796. }
  797. CEntityObject::SetWorldPos(pos, flags);
  798. }
  799. void CComponentEntityObject::OnContextMenu(QMenu* /*pMenu*/)
  800. {
  801. // Deliberately bypass the base class implementation (CEntityObject::OnContextMenu()).
  802. }
  803. void CComponentEntityObject::SetupEntityIcon()
  804. {
  805. bool hideIconInViewport = false;
  806. m_hasIcon = false;
  807. AzToolsFramework::EditorEntityIconComponentRequestBus::EventResult(hideIconInViewport, m_entityId, &AzToolsFramework::EditorEntityIconComponentRequestBus::Events::IsEntityIconHiddenInViewport);
  808. if (!hideIconInViewport)
  809. {
  810. AzToolsFramework::EditorEntityIconComponentRequestBus::EventResult(m_icon, m_entityId, &AzToolsFramework::EditorEntityIconComponentRequestBus::Events::GetEntityIconPath);
  811. if (!m_icon.empty())
  812. {
  813. m_hasIcon = true;
  814. // ToDo: Get from Atom?
  815. // int textureId = GetIEditor()->GetIconManager()->GetIconTexture(m_icon.c_str());
  816. m_iconTexture = nullptr;
  817. }
  818. }
  819. }
  820. void CComponentEntityObject::DrawAccent(DisplayContext& dc)
  821. {
  822. if (!m_drawAccents)
  823. {
  824. return;
  825. }
  826. switch (m_accentType)
  827. {
  828. case AzToolsFramework::EntityAccentType::None:
  829. {
  830. if (dc.flags & DISPLAY_2D)
  831. {
  832. dc.SetColor(0.941f, 0.764f, 0.176f); // Yellow
  833. }
  834. else
  835. {
  836. return;
  837. }
  838. break;
  839. }
  840. case AzToolsFramework::EntityAccentType::Hover:
  841. {
  842. dc.SetColor(0, 1, 0); // Green
  843. break;
  844. }
  845. case AzToolsFramework::EntityAccentType::Selected:
  846. {
  847. dc.SetColor(1, 0, 0); // Red
  848. break;
  849. }
  850. case AzToolsFramework::EntityAccentType::ParentSelected:
  851. {
  852. dc.SetColor(1, 0.549f, 0); // Orange
  853. break;
  854. }
  855. case AzToolsFramework::EntityAccentType::SliceSelected:
  856. {
  857. dc.SetColor(0.117f, 0.565f, 1); // Blue
  858. break;
  859. }
  860. default:
  861. {
  862. dc.SetColor(1, 0.0784f, 0.576f); // Pink
  863. break;
  864. }
  865. }
  866. // if there are no explicit handlers, default to show the aabb when the mouse is over or the entity is selected.
  867. // this will be the case with newly added entities without explicit handlers attached (no components).
  868. if (!AzToolsFramework::EditorComponentSelectionRequestsBus::HasHandlers(m_entityId))
  869. {
  870. AABB box;
  871. GetBoundBox(box);
  872. dc.DrawWireBox(box.min, box.max);
  873. }
  874. }