EditorWhiteBoxColliderComponent.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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 "EditorWhiteBoxColliderComponent.h"
  9. #include "EditorWhiteBoxComponent.h"
  10. #include "WhiteBoxColliderComponent.h"
  11. #include <AzCore/Component/TransformBus.h>
  12. #include <AzCore/Serialization/EditContext.h>
  13. #include <AzCore/std/smart_ptr/make_shared.h>
  14. #include <AzFramework/Physics/PhysicsScene.h>
  15. #include <AzFramework/Physics/SystemBus.h>
  16. #include <AzFramework/Physics/Configuration/StaticRigidBodyConfiguration.h>
  17. #include <WhiteBox/EditorWhiteBoxComponentBus.h>
  18. #include <numeric>
  19. namespace WhiteBox
  20. {
  21. void EditorWhiteBoxColliderComponent::Reflect(AZ::ReflectContext* context)
  22. {
  23. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  24. {
  25. serializeContext->Class<EditorWhiteBoxColliderComponent, EditorComponentBase>()
  26. ->Version(1)
  27. ->Field("Configuration", &EditorWhiteBoxColliderComponent::m_physicsColliderConfiguration)
  28. ->Field("MeshData", &EditorWhiteBoxColliderComponent::m_meshShapeConfiguration)
  29. ->Field("WhiteBoxConfiguration", &EditorWhiteBoxColliderComponent::m_whiteBoxColliderConfiguration);
  30. if (auto editContext = serializeContext->GetEditContext())
  31. {
  32. editContext
  33. ->Class<EditorWhiteBoxColliderComponent>(
  34. "White Box Collider", "Physics collider for White Box Component")
  35. ->ClassElement(AZ::Edit::ClassElements::EditorData, "")
  36. ->Attribute(AZ::Edit::Attributes::Category, "Shape")
  37. ->Attribute(AZ::Edit::Attributes::Icon, "Editor/Icons/Components/WhiteBox_collider.svg")
  38. ->Attribute(
  39. AZ::Edit::Attributes::ViewportIcon, "Editor/Icons/Components/Viewport/WhiteBox_collider.png")
  40. ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC_CE("Game"))
  41. ->Attribute(
  42. AZ::Edit::Attributes::HelpPageURL,
  43. "https://o3de.org/docs/user-guide/components/reference/shape/white-box-collider/")
  44. ->Attribute(AZ::Edit::Attributes::AutoExpand, true)
  45. ->DataElement(
  46. AZ::Edit::UIHandlers::Default, &EditorWhiteBoxColliderComponent::m_physicsColliderConfiguration,
  47. "Configuration", "Collider configuration")
  48. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly)
  49. ->DataElement(
  50. AZ::Edit::UIHandlers::Default,
  51. &EditorWhiteBoxColliderComponent::m_whiteBoxColliderConfiguration,
  52. "White Box Collider Configuration", "White Box collider configuration properties")
  53. ->Attribute(AZ::Edit::Attributes::Visibility, AZ::Edit::PropertyVisibility::ShowChildrenOnly);
  54. }
  55. }
  56. }
  57. void EditorWhiteBoxColliderComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  58. {
  59. provided.push_back(AZ_CRC_CE("WhiteBoxColliderService"));
  60. }
  61. void EditorWhiteBoxColliderComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& required)
  62. {
  63. required.push_back(AZ_CRC_CE("TransformService"));
  64. required.push_back(AZ_CRC_CE("WhiteBoxService"));
  65. }
  66. void EditorWhiteBoxColliderComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  67. {
  68. incompatible.push_back(AZ_CRC_CE("NonUniformScaleService"));
  69. incompatible.push_back(AZ_CRC_CE("WhiteBoxColliderService"));
  70. // Incompatible with other rigid bodies because it handles its own rigid body
  71. // internally and it would conflict if another rigid body is added to the entity.
  72. incompatible.push_back(AZ_CRC_CE("PhysicsRigidBodyService"));
  73. }
  74. void EditorWhiteBoxColliderComponent::Activate()
  75. {
  76. AzToolsFramework::Components::EditorComponentBase::Activate();
  77. EditorWhiteBoxColliderRequestBus::Handler::BusConnect(GetEntityId());
  78. AZ::TransformNotificationBus::Handler::BusConnect(GetEntityId());
  79. // hide collider properties we do not care about for white box
  80. m_physicsColliderConfiguration.SetPropertyVisibility(Physics::ColliderConfiguration::Offset, false);
  81. m_physicsColliderConfiguration.SetPropertyVisibility(Physics::ColliderConfiguration::IsTrigger, false);
  82. m_sceneInterface = AZ::Interface<AzPhysics::SceneInterface>::Get();
  83. if (m_sceneInterface)
  84. {
  85. m_editorSceneHandle = m_sceneInterface->GetSceneHandle(AzPhysics::EditorPhysicsSceneName);
  86. }
  87. // can't use buses here as EditorWhiteBoxComponentBus is addressed using component id. How do get component id?
  88. if (auto whiteBoxComponent = GetEntity()->FindComponent<WhiteBox::EditorWhiteBoxComponent>())
  89. {
  90. if (auto whiteBoxMesh = whiteBoxComponent->GetWhiteBoxMesh())
  91. {
  92. CreatePhysics(*whiteBoxMesh);
  93. }
  94. }
  95. }
  96. void EditorWhiteBoxColliderComponent::Deactivate()
  97. {
  98. AZ::TransformNotificationBus::Handler::BusDisconnect();
  99. EditorWhiteBoxColliderRequestBus::Handler::BusDisconnect();
  100. AzToolsFramework::Components::EditorComponentBase::Deactivate();
  101. DestroyPhysics();
  102. m_sceneInterface = nullptr;
  103. m_editorSceneHandle = AzPhysics::InvalidSceneHandle;
  104. }
  105. void EditorWhiteBoxColliderComponent::BuildGameEntity(AZ::Entity* gameEntity)
  106. {
  107. gameEntity->CreateComponent<WhiteBoxColliderComponent>(
  108. m_meshShapeConfiguration, m_physicsColliderConfiguration, m_whiteBoxColliderConfiguration);
  109. }
  110. void EditorWhiteBoxColliderComponent::OnTransformChanged(
  111. [[maybe_unused]] const AZ::Transform& local, const AZ::Transform& world)
  112. {
  113. if (m_sceneInterface)
  114. {
  115. if (auto* rigidBody = m_sceneInterface->GetSimulatedBodyFromHandle(m_editorSceneHandle, m_rigidBodyHandle))
  116. {
  117. rigidBody->SetTransform(world);
  118. }
  119. }
  120. }
  121. void EditorWhiteBoxColliderComponent::CreatePhysics(const WhiteBoxMesh& whiteBox)
  122. {
  123. if (Api::MeshFaceCount(whiteBox) == 0)
  124. {
  125. return;
  126. }
  127. ConvertToPhysicsMesh(whiteBox);
  128. AzPhysics::StaticRigidBodyConfiguration bodyConfiguration;
  129. bodyConfiguration.m_debugName = GetEntity()->GetName().c_str();
  130. bodyConfiguration.m_entityId = GetEntityId();
  131. bodyConfiguration.m_orientation = GetTransform()->GetWorldRotationQuaternion();
  132. bodyConfiguration.m_position = GetTransform()->GetWorldTranslation();
  133. bodyConfiguration.m_colliderAndShapeData = AzPhysics::ShapeColliderPair(
  134. AZStd::make_shared<Physics::ColliderConfiguration>(m_physicsColliderConfiguration),
  135. AZStd::make_shared<Physics::CookedMeshShapeConfiguration>(m_meshShapeConfiguration));
  136. if (m_sceneInterface)
  137. {
  138. DestroyPhysics();
  139. m_rigidBodyHandle = m_sceneInterface->AddSimulatedBody(m_editorSceneHandle, &bodyConfiguration);
  140. }
  141. }
  142. void EditorWhiteBoxColliderComponent::DestroyPhysics()
  143. {
  144. if (m_sceneInterface && m_rigidBodyHandle != AzPhysics::InvalidSimulatedBodyHandle)
  145. {
  146. m_sceneInterface->RemoveSimulatedBody(m_editorSceneHandle, m_rigidBodyHandle);
  147. m_rigidBodyHandle = AzPhysics::InvalidSimulatedBodyHandle;
  148. }
  149. }
  150. static bool ConvertToTriangles(
  151. const WhiteBoxMesh& whiteBox, AZStd::vector<AZ::Vector3>& vertices, AZStd::vector<AZ::u32>& indices)
  152. {
  153. const auto triangleCount = Api::MeshFaceCount(whiteBox);
  154. if (triangleCount == 0)
  155. {
  156. return false;
  157. }
  158. const auto vertexCount = Api::MeshHalfedgeCount(whiteBox);
  159. vertices.resize(vertexCount);
  160. indices.resize(triangleCount * 3);
  161. // fill vertex position array
  162. size_t index = 0;
  163. const auto faceHandles = Api::MeshFaceHandles(whiteBox);
  164. for (const auto& faceHandle : faceHandles)
  165. {
  166. const auto faceHalfedgeHandles = Api::FaceHalfedgeHandles(whiteBox, faceHandle);
  167. for (const auto& halfEdgeHandle : faceHalfedgeHandles)
  168. {
  169. const auto vh = Api::HalfedgeVertexHandleAtTip(whiteBox, halfEdgeHandle);
  170. vertices[index] = Api::VertexPosition(whiteBox, vh);
  171. index++;
  172. }
  173. }
  174. // fill index array - this will have to change at some point probably
  175. std::iota(indices.begin(), indices.end(), 0);
  176. return true;
  177. }
  178. void EditorWhiteBoxColliderComponent::ConvertToPhysicsMesh(const WhiteBoxMesh& whiteBox)
  179. {
  180. AZStd::vector<AZ::Vector3> vertices;
  181. AZStd::vector<AZ::u32> indices;
  182. // convert white box mesh to vertices
  183. if (!ConvertToTriangles(whiteBox, vertices, indices))
  184. {
  185. // if there are no valid triangles then do not attempt to create a physics mesh
  186. return;
  187. }
  188. if (auto* physicsSystem = AZ::Interface<Physics::System>::Get())
  189. {
  190. AZStd::vector<AZ::u8> bytes;
  191. const bool result = physicsSystem->CookTriangleMeshToMemory(
  192. vertices.data(), (AZ::u32)vertices.size(), indices.data(), (AZ::u32)indices.size(), bytes);
  193. AZ_Warning("EditorWhiteBoxColliderComponent", result, "Failed to cook mesh data");
  194. if (result)
  195. {
  196. m_meshShapeConfiguration.SetCookedMeshData(
  197. bytes.data(), bytes.size(), Physics::CookedMeshShapeConfiguration::MeshType::TriangleMesh);
  198. }
  199. }
  200. else
  201. {
  202. AZ_Warning(
  203. "EditorWhiteBoxColliderComponent", false, "No physics backend enabled - please ensure one is provided");
  204. }
  205. }
  206. } // namespace WhiteBox