SimulationEntitiesManager.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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 "SimulationEntitiesManager.h"
  9. #include <SimulationInterfaces/SimulationInterfacesTypeIds.h>
  10. #include "Clients/SimulationFeaturesAggregator.h"
  11. #include "CommonUtilities.h"
  12. #include "ConsoleCommands.inl"
  13. #include "SimulationInterfaces/SimulationFeatures.h"
  14. #include "SimulationInterfaces/SimulationFeaturesAggregatorRequestBus.h"
  15. #include <AzCore/Asset/AssetManager.h>
  16. #include <AzCore/Asset/AssetManagerBus.h>
  17. #include <AzCore/Component/ComponentApplicationBus.h>
  18. #include <AzCore/Component/TransformBus.h>
  19. #include <AzCore/Console/IConsole.h>
  20. #include <AzCore/Serialization/SerializeContext.h>
  21. #include <AzCore/std/containers/vector.h>
  22. #include <AzCore/std/string/regex.h>
  23. #include <AzFramework/Components/TransformComponent.h>
  24. #include <AzFramework/Physics/PhysicsSystem.h>
  25. #include <AzFramework/Physics/RigidBodyBus.h>
  26. #include <AzFramework/Physics/SimulatedBodies/RigidBody.h>
  27. #include <AzFramework/Spawnable/Spawnable.h>
  28. #include <AzFramework/Spawnable/SpawnableEntitiesInterface.h>
  29. namespace SimulationInterfaces
  30. {
  31. void SetRigidBodyVelocities(AzPhysics::RigidBody* rigidBody, const EntityState& state)
  32. {
  33. if (!state.m_twist_angular.IsClose(AZ::Vector3::CreateZero(), AZ::Constants::FloatEpsilon))
  34. {
  35. // get transform
  36. AZ::Vector3 angularVelWorld = rigidBody->GetTransform().TransformVector(state.m_twist_angular);
  37. rigidBody->SetAngularVelocity(angularVelWorld);
  38. }
  39. if (!state.m_twist_linear.IsClose(AZ::Vector3::CreateZero(), AZ::Constants::FloatEpsilon))
  40. {
  41. // get transform
  42. AZ::Vector3 linearVelWorld = rigidBody->GetTransform().TransformVector(state.m_twist_linear);
  43. rigidBody->SetLinearVelocity(linearVelWorld);
  44. }
  45. }
  46. AZ_COMPONENT_IMPL(SimulationEntitiesManager, "SimulationEntitiesManager", SimulationEntitiesManagerTypeId);
  47. void SimulationEntitiesManager::Reflect(AZ::ReflectContext* context)
  48. {
  49. if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(context))
  50. {
  51. serializeContext->Class<SimulationEntitiesManager, AZ::Component>()->Version(0);
  52. }
  53. }
  54. void SimulationEntitiesManager::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided)
  55. {
  56. provided.push_back(AZ_CRC_CE("SimulationInterfacesService"));
  57. }
  58. void SimulationEntitiesManager::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible)
  59. {
  60. incompatible.push_back(AZ_CRC_CE("SimulationInterfacesService"));
  61. }
  62. void SimulationEntitiesManager::GetRequiredServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& required)
  63. {
  64. required.push_back(AZ_CRC_CE("AssetCatalogService"));
  65. required.push_back(AZ_CRC_CE("SimulationFeaturesAggregator"));
  66. }
  67. void SimulationEntitiesManager::GetDependentServices([[maybe_unused]] AZ::ComponentDescriptor::DependencyArrayType& dependent)
  68. {
  69. dependent.push_back(AZ_CRC_CE("PhysicsService"));
  70. dependent.push_back(AZ_CRC_CE("SimulationFeaturesAggregator"));
  71. }
  72. SimulationEntitiesManager::SimulationEntitiesManager()
  73. {
  74. if (SimulationEntityManagerInterface::Get() == nullptr)
  75. {
  76. SimulationEntityManagerInterface::Register(this);
  77. }
  78. }
  79. SimulationEntitiesManager::~SimulationEntitiesManager()
  80. {
  81. if (SimulationEntityManagerInterface::Get() == this)
  82. {
  83. SimulationEntityManagerInterface::Unregister(this);
  84. }
  85. }
  86. void SimulationEntitiesManager::Init()
  87. {
  88. }
  89. AzPhysics::Scene* GetSceneHelper(AzPhysics::SceneHandle sceneHandle)
  90. {
  91. AzPhysics::SystemInterface* physicsSystem = AZ::Interface<AzPhysics::SystemInterface>::Get();
  92. AZ_Assert(physicsSystem, "Physics system is not available.");
  93. AzPhysics::Scene* scene = physicsSystem->GetScene(sceneHandle);
  94. return scene;
  95. }
  96. void SimulationEntitiesManager::Activate()
  97. {
  98. m_simulationBodyAddedHandler = AzPhysics::SceneEvents::OnSimulationBodyAdded::Handler(
  99. [this](AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle)
  100. {
  101. auto* scene = GetSceneHelper(sceneHandle);
  102. if (scene == nullptr)
  103. {
  104. return;
  105. }
  106. auto* body = scene->GetSimulatedBodyFromHandle(bodyHandle);
  107. AZ_Assert(body, "Simulated body is not available.");
  108. auto* rigidBody = azdynamic_cast<AzPhysics::RigidBody*>(body);
  109. if (rigidBody != nullptr)
  110. {
  111. [[maybe_unused]] auto shapeCount = rigidBody->GetShapeCount();
  112. AZ_Warning(
  113. "SimulationInterfaces",
  114. shapeCount > 0,
  115. "Entity %s has no collider shapes, it won't be available by bound search",
  116. rigidBody->GetEntityId().ToString().c_str());
  117. }
  118. const AZ::EntityId entityId = body->GetEntityId();
  119. AZ::Entity* entity = nullptr;
  120. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId);
  121. AZ_Assert(entity, "Entity is not available.");
  122. // check if entity is not spawned by this component
  123. const auto ticketId = entity->GetEntitySpawnTicketId();
  124. AZStd::string proposedName{};
  125. // check if ticket is in the unregistered list
  126. auto spawnData = m_spawnCompletedCallbacks.find(ticketId);
  127. if (spawnData != m_spawnCompletedCallbacks.end())
  128. {
  129. proposedName = spawnData->second.m_userProposedName;
  130. }
  131. const AZStd::string registeredName = this->AddSimulatedEntity(entityId, proposedName);
  132. // call the callback
  133. if (spawnData != m_spawnCompletedCallbacks.end())
  134. {
  135. // call and remove the callback
  136. spawnData->second.m_completedCb(AZ::Success(registeredName));
  137. m_spawnCompletedCallbacks.erase(spawnData);
  138. }
  139. });
  140. m_simulationBodyRemovedHandler = AzPhysics::SceneEvents::OnSimulationBodyRemoved::Handler(
  141. [this](AzPhysics::SceneHandle sceneHandle, AzPhysics::SimulatedBodyHandle bodyHandle)
  142. {
  143. auto* scene = GetSceneHelper(sceneHandle);
  144. if (scene == nullptr)
  145. {
  146. return;
  147. }
  148. const auto* body = scene->GetSimulatedBodyFromHandle(bodyHandle);
  149. AZ_Assert(body, "Simulated body is not available.");
  150. const AZ::EntityId entityId = body->GetEntityId();
  151. // remove simulated entity
  152. this->RemoveSimulatedEntity(entityId);
  153. });
  154. m_sceneAddedHandler = AzPhysics::SystemEvents::OnSceneAddedEvent::Handler(
  155. [this](AzPhysics::SceneHandle sceneHandle)
  156. {
  157. AZ_Warning("SimulationInterfaces", m_physicsScenesHandle == AzPhysics::InvalidSceneHandle, "Hmm, we already have a scene");
  158. auto* scene = GetSceneHelper(sceneHandle);
  159. AZ_Assert(scene, "Scene is not available.");
  160. if (scene == nullptr)
  161. {
  162. return;
  163. }
  164. scene->RegisterSimulationBodyAddedHandler(m_simulationBodyAddedHandler);
  165. scene->RegisterSimulationBodyRemovedHandler(m_simulationBodyRemovedHandler);
  166. AZ_Printf("SimulationInterfaces", "Registered simulation body added handler\n");
  167. m_physicsScenesHandle = sceneHandle;
  168. });
  169. m_sceneRemovedHandler = AzPhysics::SystemEvents::OnSceneRemovedEvent::Handler(
  170. [this](AzPhysics::SceneHandle sceneHandle)
  171. {
  172. if (m_physicsScenesHandle == sceneHandle)
  173. {
  174. m_entityIdToSimulatedEntityMap.clear();
  175. m_simulatedEntityToEntityIdMap.clear();
  176. m_simulationBodyAddedHandler.Disconnect();
  177. m_simulationBodyRemovedHandler.Disconnect();
  178. m_physicsScenesHandle = AzPhysics::InvalidSceneHandle;
  179. }
  180. });
  181. AzPhysics::SystemInterface* physicsSystem = AZ::Interface<AzPhysics::SystemInterface>::Get();
  182. if (physicsSystem)
  183. {
  184. physicsSystem->RegisterSceneAddedEvent(m_sceneAddedHandler);
  185. physicsSystem->RegisterSceneRemovedEvent(m_sceneRemovedHandler);
  186. SimulationEntityManagerRequestBus::Handler::BusConnect();
  187. }
  188. SimulationFeaturesAggregatorRequestBus::Broadcast(
  189. &SimulationFeaturesAggregatorRequests::AddSimulationFeatures,
  190. AZStd::unordered_set<SimulationFeatures>{ SimulationFeatures::ENTITY_TAGS,
  191. SimulationFeatures::ENTITY_BOUNDS_BOX,
  192. SimulationFeatures::ENTITY_BOUNDS_CONVEX,
  193. SimulationFeatures::ENTITY_CATEGORIES,
  194. SimulationFeatures::ENTITY_STATE_GETTING,
  195. SimulationFeatures::ENTITY_STATE_SETTING,
  196. SimulationFeatures::DELETING,
  197. SimulationFeatures::SPAWNABLES,
  198. SimulationFeatures::SPAWNING });
  199. }
  200. void SimulationEntitiesManager::Deactivate()
  201. {
  202. SimulationEntityManagerRequestBus::Handler::BusDisconnect();
  203. if (m_simulationBodyAddedHandler.IsConnected())
  204. {
  205. m_simulationBodyAddedHandler.Disconnect();
  206. }
  207. if (m_simulationBodyRemovedHandler.IsConnected())
  208. {
  209. m_simulationBodyRemovedHandler.Disconnect();
  210. }
  211. m_physicsScenesHandle = AzPhysics::InvalidSceneHandle;
  212. if (m_sceneAddedHandler.IsConnected())
  213. {
  214. m_sceneAddedHandler.Disconnect();
  215. }
  216. if (m_sceneAddedHandler.IsConnected())
  217. {
  218. m_sceneAddedHandler.Disconnect();
  219. }
  220. }
  221. AZStd::string SimulationEntitiesManager::AddSimulatedEntity(AZ::EntityId entityId, const AZStd::string& userProposedName)
  222. {
  223. if (!entityId.IsValid())
  224. {
  225. return "";
  226. }
  227. // check if entity is already registered
  228. auto findIt = m_entityIdToSimulatedEntityMap.find(entityId);
  229. if (findIt != m_entityIdToSimulatedEntityMap.end())
  230. {
  231. return findIt->second;
  232. }
  233. // register entity under unique name
  234. AZStd::string simulatedEntityName = GetSimulatedEntityName(entityId, userProposedName);
  235. m_simulatedEntityToEntityIdMap[simulatedEntityName] = entityId;
  236. m_entityIdToSimulatedEntityMap[entityId] = simulatedEntityName;
  237. AZ_Printf("SimulationInterfaces", "Registered entity %s\n", simulatedEntityName.c_str());
  238. return simulatedEntityName;
  239. }
  240. void SimulationEntitiesManager::RemoveSimulatedEntity(AZ::EntityId entityId)
  241. {
  242. auto findIt = m_entityIdToSimulatedEntityMap.find(entityId);
  243. if (findIt != m_entityIdToSimulatedEntityMap.end())
  244. {
  245. const auto& simulatedEntityName = findIt->second;
  246. m_entityIdToSimulatedEntityMap.erase(findIt);
  247. m_simulatedEntityToEntityIdMap.erase(simulatedEntityName);
  248. }
  249. }
  250. AZ::Outcome<EntityNameList, FailedResult> SimulationEntitiesManager::GetEntities(const EntityFilters& filter)
  251. {
  252. if (!filter.m_tags_filter.m_tags.empty())
  253. {
  254. AZ_Warning("SimulationInterfaces", false, "Tags filter is not implemented yet");
  255. return AZ::Failure(FailedResult(ErrorCode::RESULT_FEATURE_UNSUPPORTED, "Tags filter is not implemented yet"));
  256. }
  257. const bool reFilter = !filter.m_filter.empty();
  258. const bool shapeCastFilter = filter.m_bounds_shape != nullptr;
  259. AZStd::vector<AZStd::string> entities;
  260. if (!shapeCastFilter)
  261. {
  262. // get all entities from the map
  263. entities.reserve(m_entityIdToSimulatedEntityMap.size());
  264. AZStd::transform(
  265. m_entityIdToSimulatedEntityMap.begin(),
  266. m_entityIdToSimulatedEntityMap.end(),
  267. AZStd::back_inserter(entities),
  268. [](const auto& pair)
  269. {
  270. return pair.second;
  271. });
  272. }
  273. else
  274. {
  275. auto* sceneInterface = AZ::Interface<AzPhysics::SceneInterface>::Get();
  276. AZ_Assert(sceneInterface, "Physics scene interface is not available.");
  277. if (m_physicsScenesHandle == AzPhysics::InvalidSceneHandle)
  278. {
  279. return AZ::Failure(FailedResult(ErrorCode::RESULT_OPERATION_FAILED, "Physics scene interface is not available."));
  280. }
  281. AzPhysics::OverlapRequest request;
  282. request.m_shapeConfiguration = filter.m_bounds_shape;
  283. request.m_pose = filter.m_bounds_pose;
  284. request.m_maxResults = AZStd::numeric_limits<AZ::u32>::max();
  285. AzPhysics::SceneQueryHits result = sceneInterface->QueryScene(m_physicsScenesHandle, &request);
  286. for (const auto& hit : result.m_hits)
  287. {
  288. const AZ::EntityId entityId = hit.m_entityId;
  289. auto findIt = m_entityIdToSimulatedEntityMap.find(entityId);
  290. if (findIt != m_entityIdToSimulatedEntityMap.end())
  291. {
  292. entities.push_back(findIt->second);
  293. }
  294. }
  295. }
  296. if (reFilter)
  297. {
  298. const AZStd::vector<AZStd::string> prefilteredEntities = AZStd::move(entities);
  299. entities.clear();
  300. const AZStd::regex regex(filter.m_filter);
  301. if (!regex.Valid())
  302. {
  303. AZ_Warning("SimulationInterfaces", false, "Invalid regex filter");
  304. return AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, "Invalid regex filter"));
  305. }
  306. AZStd::ranges::copy_if(
  307. prefilteredEntities,
  308. AZStd::back_inserter(entities),
  309. [&regex](const AZStd::string& entityName)
  310. {
  311. return AZStd::regex_search(entityName, regex);
  312. });
  313. }
  314. return AZ::Success(entities);
  315. }
  316. AZ::Outcome<EntityState, FailedResult> SimulationEntitiesManager::GetEntityState(const AZStd::string& name)
  317. {
  318. const auto findIt = m_simulatedEntityToEntityIdMap.find(name);
  319. if (findIt == m_simulatedEntityToEntityIdMap.end())
  320. {
  321. AZ_Warning("SimulationInterfaces", findIt != m_simulatedEntityToEntityIdMap.end(), "Entity %s not found", name.c_str());
  322. return AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, "Entity not found"));
  323. }
  324. EntityState entityState{};
  325. const AZ::EntityId entityId = findIt->second;
  326. AZ_Assert(entityId.IsValid(), "EntityId is not valid");
  327. AZ::TransformBus::EventResult(entityState.m_pose, entityId, &AZ::TransformBus::Events::GetWorldTM);
  328. AZ::Vector3 linearVelocity = AZ::Vector3::CreateZero();
  329. Physics::RigidBodyRequestBus::EventResult(linearVelocity, entityId, &Physics::RigidBodyRequests::GetLinearVelocity);
  330. AZ::Vector3 angularVelocity = AZ::Vector3::CreateZero();
  331. Physics::RigidBodyRequestBus::EventResult(angularVelocity, entityId, &Physics::RigidBodyRequests::GetAngularVelocity);
  332. // transform linear and angular velocities to entity frame
  333. const AZ::Transform entityTransformInv = entityState.m_pose.GetInverse();
  334. entityState.m_twist_linear = entityTransformInv.TransformVector(linearVelocity);
  335. entityState.m_twist_angular = entityTransformInv.TransformVector(angularVelocity);
  336. return AZ::Success(entityState);
  337. }
  338. AZ::Outcome<MultipleEntitiesStates, FailedResult> SimulationEntitiesManager::GetEntitiesStates(const EntityFilters& filter)
  339. {
  340. if (!filter.m_tags_filter.m_tags.empty())
  341. {
  342. AZ_Warning("SimulationInterfaces", false, "Tags filter is not implemented yet");
  343. return AZ::Failure(FailedResult(ErrorCode::RESULT_FEATURE_UNSUPPORTED, "Tags filter is not implemented yet"));
  344. }
  345. MultipleEntitiesStates entitiesStates;
  346. const auto& entities = GetEntities(filter);
  347. if (!entities.IsSuccess())
  348. {
  349. return AZ::Failure(entities.GetError());
  350. }
  351. for (const auto& entity : entities.GetValue())
  352. {
  353. auto state = GetEntityState(entity);
  354. if (!state.IsSuccess())
  355. {
  356. return AZ::Failure(state.GetError());
  357. }
  358. entitiesStates.emplace(AZStd::make_pair(entity, state.GetValue()));
  359. }
  360. return entitiesStates;
  361. }
  362. AZ::Outcome<void, FailedResult> SimulationEntitiesManager::SetEntityState(const AZStd::string& name, const EntityState& state)
  363. {
  364. const auto findIt = m_simulatedEntityToEntityIdMap.find(name);
  365. if (findIt == m_simulatedEntityToEntityIdMap.end())
  366. {
  367. AZ_Warning("SimulationInterfaces", false, "Entity %s not found", name.c_str());
  368. return AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, "Entity not found"));
  369. }
  370. const AZ::EntityId entityId = findIt->second;
  371. AZ_Assert(entityId.IsValid(), "EntityId is not valid");
  372. // get entity and all descendants
  373. AZStd::vector<AZ::EntityId> entityAndDescendants;
  374. AZ::TransformBus::EventResult(entityAndDescendants, entityId, &AZ::TransformBus::Events::GetEntityAndAllDescendants);
  375. if (state.m_pose.IsOrthogonal())
  376. {
  377. // disable simulation for all entities
  378. AZStd::map<AZ::EntityId, AZ::Transform> entityTransforms;
  379. for (const auto& descendant : entityAndDescendants)
  380. {
  381. // get name
  382. AZStd::string entityName = "Unknown";
  383. AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, descendant);
  384. AZ_Printf("SimulationInterfaces", "Disable physics for entity %s\n", entityName.c_str());
  385. Physics::RigidBodyRequestBus::Event(descendant, &Physics::RigidBodyRequests::DisablePhysics);
  386. }
  387. AZ::TransformBus::Event(entityId, &AZ::TransformBus::Events::SetLocalTM, state.m_pose);
  388. for (const auto& descendant : entityAndDescendants)
  389. {
  390. Physics::RigidBodyRequestBus::Event(descendant, &Physics::RigidBodyRequests::EnablePhysics);
  391. Physics::RigidBodyRequestBus::Event(descendant, &Physics::RigidBodyRequests::SetAngularVelocity, AZ::Vector3::CreateZero());
  392. Physics::RigidBodyRequestBus::Event(descendant, &Physics::RigidBodyRequests::SetLinearVelocity, AZ::Vector3::CreateZero());
  393. }
  394. }
  395. if (!state.m_twist_linear.IsZero(AZ::Constants::FloatEpsilon) || !state.m_twist_angular.IsZero(AZ::Constants::FloatEpsilon))
  396. {
  397. // get rigid body
  398. AzPhysics::RigidBody* rigidBody = nullptr;
  399. Physics::RigidBodyRequestBus::EventResult(rigidBody, entityId, &Physics::RigidBodyRequests::GetRigidBody);
  400. if (rigidBody != nullptr)
  401. {
  402. SetRigidBodyVelocities(rigidBody, state);
  403. }
  404. }
  405. return AZ::Success();
  406. }
  407. void SimulationEntitiesManager::DeleteEntity(const AZStd::string& name, DeletionCompletedCb completedCb)
  408. {
  409. const auto findIt = m_simulatedEntityToEntityIdMap.find(name);
  410. if (findIt == m_simulatedEntityToEntityIdMap.end())
  411. {
  412. completedCb(AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, "Entity not found")));
  413. return;
  414. }
  415. const AZ::EntityId entityId = findIt->second;
  416. AZ_Assert(entityId.IsValid(), "EntityId is not valid");
  417. // get entity
  418. AZ::Entity* entity = nullptr;
  419. AZ::ComponentApplicationBus::BroadcastResult(entity, &AZ::ComponentApplicationRequests::FindEntity, entityId);
  420. AZ_Assert(entity, "Entity is not available.");
  421. if (entity == nullptr)
  422. {
  423. AZ_Error("SimulationInterfaces", false, "Entity %s (%s) not found", name.c_str(), entityId.ToString().c_str());
  424. completedCb(AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, "Entity not found")));
  425. return;
  426. }
  427. // check if entity is spawned by this component
  428. const auto ticketId = entity->GetEntitySpawnTicketId();
  429. if (m_spawnedTickets.find(ticketId) != m_spawnedTickets.end())
  430. {
  431. // remove the ticket
  432. // m_spawnedTickets.erase(ticketId);
  433. /// get spawner
  434. auto spawner = AZ::Interface<AzFramework::SpawnableEntitiesDefinition>::Get();
  435. AZ_Assert(spawner, "SpawnableEntitiesDefinition is not available.");
  436. // get ticket
  437. auto ticket = m_spawnedTickets[ticketId];
  438. // remove ticket
  439. AzFramework::DespawnAllEntitiesOptionalArgs optionalArgs;
  440. optionalArgs.m_completionCallback = [this, completedCb](AzFramework::EntitySpawnTicket::Id ticketId)
  441. {
  442. m_spawnedTickets.erase(ticketId);
  443. completedCb(AZ::Success());
  444. };
  445. spawner->DespawnAllEntities(ticket, optionalArgs);
  446. }
  447. else
  448. {
  449. const auto msg = AZStd::string::format("Entity %s was not spawned by this component, wont delete it", name.c_str());
  450. completedCb(AZ::Failure(FailedResult(ErrorCode::RESULT_OPERATION_FAILED, msg)));
  451. }
  452. #ifdef POTENTIALY_UNSAFE
  453. if (findIt != m_simulatedEntityToEntityIdMap.end())
  454. {
  455. const AZ::EntityId entityId = findIt->second;
  456. AZ_Assert(entityId.IsValid(), "EntityId is not valid");
  457. // get all descendants
  458. AZStd::vector<AZ::EntityId> entityAndDescendants;
  459. AZ::TransformBus::EventResult(entityAndDescendants, entityId, &AZ::TransformBus::Events::GetEntityAndAllDescendants);
  460. for (const auto& descendant : entityAndDescendants)
  461. {
  462. // I am not sure if this is the safe way to delete an entity
  463. AZ::ComponentApplicationBus::Broadcast(&AZ::ComponentApplicationRequests::DeleteEntity, descendant);
  464. }
  465. return true;
  466. }
  467. #endif
  468. }
  469. void SimulationEntitiesManager::DeleteAllEntities(DeletionCompletedCb completedCb)
  470. {
  471. if (m_spawnedTickets.empty())
  472. {
  473. // early return for empty scene
  474. completedCb(AZ::Success());
  475. return;
  476. }
  477. for (auto m_spawnedTicket : m_spawnedTickets)
  478. {
  479. auto spawner = AZ::Interface<AzFramework::SpawnableEntitiesDefinition>::Get();
  480. AZ_Assert(spawner, "SpawnableEntitiesDefinition is not available.");
  481. // get ticket
  482. auto ticket = m_spawnedTickets[m_spawnedTicket.first];
  483. // despawn
  484. AzFramework::DespawnAllEntitiesOptionalArgs optionalArgs;
  485. optionalArgs.m_completionCallback = [this, completedCb](AzFramework::EntitySpawnTicket::Id ticketId)
  486. {
  487. m_spawnedTickets.erase(ticketId);
  488. if (completedCb && m_spawnedTickets.empty())
  489. {
  490. completedCb(AZ::Success());
  491. }
  492. };
  493. spawner->DespawnAllEntities(ticket, optionalArgs);
  494. }
  495. }
  496. AZ::Outcome<SpawnableList, FailedResult> SimulationEntitiesManager::GetSpawnables()
  497. {
  498. AZStd::vector<Spawnable> spawnables;
  499. const auto enumCallback = [&spawnables](const AZ::Data::AssetId assetId, const AZ::Data::AssetInfo& assetInfo)
  500. {
  501. bool isSpawnable = false;
  502. AZ::Data::AssetCatalogRequestBus::BroadcastResult(
  503. isSpawnable, &AZ::Data::AssetCatalogRequests::DoesAssetIdMatchWildcardPattern, assetId, "*.spawnable");
  504. if (isSpawnable)
  505. {
  506. Spawnable spawnable;
  507. spawnable.m_uri = Utils::RelPathToUri(assetInfo.m_relativePath);
  508. spawnables.push_back(spawnable);
  509. }
  510. };
  511. AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequests::EnumerateAssets, nullptr, enumCallback, nullptr);
  512. return AZ::Success(spawnables);
  513. }
  514. void SimulationEntitiesManager::SpawnEntity(
  515. const AZStd::string& name,
  516. const AZStd::string& uri,
  517. const AZStd::string& entityNamespace,
  518. const AZ::Transform& initialPose,
  519. const bool allowRename,
  520. SpawnCompletedCb completedCb)
  521. {
  522. if (!allowRename)
  523. {
  524. // If API user does not allow renaming, check if name is unique
  525. if (m_simulatedEntityToEntityIdMap.contains(name))
  526. {
  527. const auto msg = AZStd::string::format("Entity name %s is not unique", name.c_str());
  528. completedCb(AZ::Failure(FailedResult(ErrorCode::RESULT_INCORRECT_STATE, msg)));
  529. return;
  530. }
  531. }
  532. if (!entityNamespace.empty())
  533. {
  534. // TODO: Mpelka - remove this error when ROS 2 namespace is implemented
  535. AZ_Error("SimulationInterfaces", false, "ROS 2 namespace is not implemented yet in spawning");
  536. completedCb(AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, "This feature is not implemented yet in spawning entities")));
  537. return;
  538. }
  539. // get rel path from uri
  540. const AZStd::string relPath = Utils::UriToRelPath(uri);
  541. // create spawnable
  542. AZ::Data::AssetId assetId;
  543. AZ::Data::AssetCatalogRequestBus::BroadcastResult(
  544. assetId,
  545. &AZ::Data::AssetCatalogRequestBus::Events::GetAssetIdByPath,
  546. relPath.c_str(),
  547. azrtti_typeid<AZ::Data::AssetData>(),
  548. false);
  549. AZ_Warning("SimulationInterfaces", assetId.IsValid(), "AssetId is not valid, relative path %s", relPath.c_str());
  550. auto spawner = AZ::Interface<AzFramework::SpawnableEntitiesDefinition>::Get();
  551. AZ_Assert(spawner, "SpawnableEntitiesDefinition is not available.");
  552. AZ::Data::Asset<AzFramework::Spawnable> spawnableAsset =
  553. AZ::Data::AssetManager::Instance().GetAsset<AzFramework::Spawnable>(assetId, AZ::Data::AssetLoadBehavior::NoLoad);
  554. if (!spawnableAsset)
  555. {
  556. const auto msg = AZStd::string::format("Spawnable asset %s not found", uri.c_str());
  557. completedCb(AZ::Failure(FailedResult(ErrorCode::RESULT_NOT_FOUND, msg)));
  558. return;
  559. }
  560. auto ticket = AzFramework::EntitySpawnTicket(spawnableAsset);
  561. AzFramework::SpawnAllEntitiesOptionalArgs optionalArgs;
  562. optionalArgs.m_preInsertionCallback = [initialPose, entityNamespace, name](auto id, auto view)
  563. {
  564. if (view.empty())
  565. {
  566. return;
  567. }
  568. const AZ::Entity* root = *view.begin();
  569. // change names for all entites
  570. for (auto* entity : view)
  571. {
  572. AZStd::string entityName = AZStd::string::format("%s_%s", name.c_str(), entity->GetName().c_str());
  573. entity->SetName(entityName);
  574. }
  575. auto* transformInterface = root->FindComponent<AzFramework::TransformComponent>();
  576. if (transformInterface)
  577. {
  578. transformInterface->SetWorldTM(initialPose);
  579. }
  580. };
  581. optionalArgs.m_completionCallback =
  582. [this, uri](AzFramework::EntitySpawnTicket::Id ticketId, AzFramework::SpawnableConstEntityContainerView view)
  583. {
  584. // at this point the entities are spawned and should be registered in simulation interface and callback should be called
  585. // if that is not a case, it means that the AZFramework::Physics::OnSimulationBodyAdded event was not called.
  586. // That means the prefab has no physics component or the physics component is not enabled - we need to call the callback here
  587. // and return the error.
  588. auto spawnData = m_spawnCompletedCallbacks.find(ticketId);
  589. if (spawnData != m_spawnCompletedCallbacks.end())
  590. {
  591. // call and remove the callback
  592. const auto msg = AZStd::string::format(
  593. "Entity %s (uri : %s) was not registered in simulation interface - "
  594. "no physics component or physics component is not enabled in source prefab.\n"
  595. "Entity will be in simulation, but not available in simulation interface.\n"
  596. "Please add some physics component (at least one static rigid body component) to the prefab.\n"
  597. "Technically, it is a memory leak.\n",
  598. spawnData->second.m_userProposedName.c_str(),
  599. uri.c_str());
  600. AZ_Error("SimulationInterfaces", false, msg.c_str());
  601. spawnData->second.m_completedCb(msg);
  602. m_spawnCompletedCallbacks.erase(spawnData);
  603. }
  604. };
  605. spawner->SpawnAllEntities(ticket, optionalArgs);
  606. auto ticketId = ticket.GetId();
  607. AZ_Printf("SimulationInterfaces", "Spawning uri %s with ticket id %d\n", uri.c_str(), ticketId);
  608. SpawnCompletedCbData data;
  609. data.m_userProposedName = name;
  610. data.m_completedCb = completedCb;
  611. m_spawnCompletedCallbacks[ticketId] = data;
  612. m_spawnedTickets[ticketId] = ticket;
  613. }
  614. AZStd::string SimulationEntitiesManager::GetSimulatedEntityName(AZ::EntityId entityId, const AZStd::string& proposedName) const
  615. {
  616. // Get O3DE entity name
  617. AZStd::string entityName = proposedName;
  618. if (entityName.empty())
  619. {
  620. AZ::ComponentApplicationBus::BroadcastResult(entityName, &AZ::ComponentApplicationRequests::GetEntityName, entityId);
  621. }
  622. // Generate unique simulated entity name
  623. AZStd::string simulatedEntityName = entityName;
  624. // check if name is unique
  625. auto otherEntityIt = m_simulatedEntityToEntityIdMap.find(simulatedEntityName);
  626. if (otherEntityIt != m_simulatedEntityToEntityIdMap.end())
  627. {
  628. // name is not unique, add entityId to name
  629. simulatedEntityName = AZStd::string::format("%s_%s", entityName.c_str(), entityId.ToString().c_str());
  630. }
  631. return simulatedEntityName;
  632. }
  633. } // namespace SimulationInterfaces