Slice.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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 "FileIOBaseTestTypes.h"
  9. #include <AzCore/IO/FileIO.h>
  10. #include <AzCore/IO/Streamer/Streamer.h>
  11. #include <AzCore/IO/Streamer/StreamerComponent.h>
  12. #include <AzCore/Jobs/JobManager.h>
  13. #include <AzCore/Jobs/JobContext.h>
  14. #include <AzCore/Slice/SliceComponent.h>
  15. #include <AzCore/Serialization/SerializeContext.h>
  16. #include <AzCore/Component/Entity.h>
  17. #include <AzCore/Component/Component.h>
  18. #include <AzCore/Component/ComponentApplication.h>
  19. #include <AzCore/Serialization/ObjectStream.h>
  20. #include <AzCore/Serialization/Utils.h>
  21. #include <AzCore/Slice/SliceAssetHandler.h>
  22. #include <AzCore/Asset/AssetManager.h>
  23. #include <AzCore/Math/Sfmt.h>
  24. #include <AzCore/Memory/PoolAllocator.h>
  25. #include <AzCore/Slice/SliceMetadataInfoComponent.h>
  26. #include <AzCore/UnitTest/TestTypes.h>
  27. #include <AZTestShared/Utils/Utils.h>
  28. #if defined(HAVE_BENCHMARK)
  29. #include <benchmark/benchmark.h>
  30. #endif
  31. namespace UnitTest
  32. {
  33. class MyTestComponent1
  34. : public AZ::Component
  35. {
  36. public:
  37. AZ_COMPONENT(MyTestComponent1, "{5D3B5B45-64DF-4F88-8003-271646B6CA27}");
  38. void Activate() override
  39. {
  40. }
  41. void Deactivate() override
  42. {
  43. }
  44. static void Reflect(AZ::ReflectContext* reflection)
  45. {
  46. auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection);
  47. if (serializeContext)
  48. {
  49. serializeContext->Class<MyTestComponent1, AZ::Component>()->
  50. Field("float", &MyTestComponent1::m_float)->
  51. Field("int", &MyTestComponent1::m_int);
  52. }
  53. }
  54. float m_float = 0.f;
  55. int m_int = 0;
  56. };
  57. class MyTestComponent2
  58. : public AZ::Component
  59. {
  60. public:
  61. AZ_COMPONENT(MyTestComponent2, "{ACD7B78D-0C30-46E8-A52E-61D4B33D5528}");
  62. void Activate() override
  63. {
  64. }
  65. void Deactivate() override
  66. {
  67. }
  68. static void Reflect(AZ::ReflectContext* reflection)
  69. {
  70. auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection);
  71. if (serializeContext)
  72. {
  73. serializeContext->Class<MyTestComponent2, AZ::Component>()->
  74. Field("entityId", &MyTestComponent2::m_entityId);
  75. }
  76. }
  77. AZ::EntityId m_entityId;
  78. };
  79. class SliceTest_MockCatalog
  80. : public AZ::Data::AssetCatalog
  81. , public AZ::Data::AssetCatalogRequestBus::Handler
  82. {
  83. private:
  84. AZ::Uuid randomUuid = AZ::Uuid::CreateRandom();
  85. AZStd::vector<AZ::Data::AssetId> m_mockAssetIds;
  86. public:
  87. AZ_CLASS_ALLOCATOR(SliceTest_MockCatalog, AZ::SystemAllocator);
  88. SliceTest_MockCatalog()
  89. {
  90. AZ::Data::AssetCatalogRequestBus::Handler::BusConnect();
  91. }
  92. ~SliceTest_MockCatalog() override
  93. {
  94. AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect();
  95. }
  96. AZ::Data::AssetId GenerateMockAssetId()
  97. {
  98. AZ::Data::AssetId assetId = AZ::Data::AssetId(AZ::Uuid::CreateRandom(), 0);
  99. m_mockAssetIds.push_back(assetId);
  100. return assetId;
  101. }
  102. //////////////////////////////////////////////////////////////////////////
  103. // AZ::Data::AssetCatalogRequestBus
  104. AZ::Data::AssetInfo GetAssetInfoById(const AZ::Data::AssetId& id) override
  105. {
  106. AZ::Data::AssetInfo result;
  107. result.m_assetType = AZ::AzTypeInfo<AZ::SliceAsset>::Uuid();
  108. for (const auto& assetId : m_mockAssetIds)
  109. {
  110. if (assetId == id)
  111. {
  112. result.m_assetId = id;
  113. break;
  114. }
  115. }
  116. return result;
  117. }
  118. //////////////////////////////////////////////////////////////////////////
  119. AZ::Data::AssetStreamInfo GetStreamInfoForLoad(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override
  120. {
  121. EXPECT_TRUE(type == AZ::AzTypeInfo<AZ::SliceAsset>::Uuid());
  122. AZ::Data::AssetStreamInfo info;
  123. info.m_dataOffset = 0;
  124. info.m_streamFlags = AZ::IO::OpenMode::ModeRead;
  125. for (int i = 0; i < m_mockAssetIds.size(); ++i)
  126. {
  127. if (m_mockAssetIds[i] == id)
  128. {
  129. info.m_streamName = AZStd::string::format("MockSliceAssetName%d", i);
  130. }
  131. }
  132. if (!info.m_streamName.empty())
  133. {
  134. // this ensures tha parallel running unit tests do not overlap their files that they use.
  135. AZ::IO::Path fullName = GetTestFolderPath() / AZStd::string::format("%s-%s", randomUuid.ToString<AZStd::string>().c_str(), info.m_streamName.c_str());
  136. info.m_streamName = AZStd::move(fullName.Native());
  137. info.m_dataLen = static_cast<size_t>(AZ::IO::SystemFile::Length(info.m_streamName.c_str()));
  138. }
  139. else
  140. {
  141. info.m_dataLen = 0;
  142. }
  143. return info;
  144. }
  145. AZ::Data::AssetStreamInfo GetStreamInfoForSave(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override
  146. {
  147. AZ::Data::AssetStreamInfo info;
  148. info = GetStreamInfoForLoad(id, type);
  149. info.m_streamFlags = AZ::IO::OpenMode::ModeWrite;
  150. return info;
  151. }
  152. bool SaveAsset(AZ::Data::Asset<AZ::SliceAsset>& asset)
  153. {
  154. volatile bool isDone = false;
  155. volatile bool succeeded = false;
  156. AZ::Data::AssetBusCallbacks callbacks;
  157. callbacks.SetCallbacks(nullptr, nullptr, nullptr,
  158. [&isDone, &succeeded](const AZ::Data::Asset<AZ::Data::AssetData>& /*asset*/, bool isSuccessful, AZ::Data::AssetBusCallbacks& /*callbacks*/)
  159. {
  160. isDone = true;
  161. succeeded = isSuccessful;
  162. }, nullptr, nullptr, nullptr);
  163. callbacks.BusConnect(asset.GetId());
  164. asset.Save();
  165. while (!isDone)
  166. {
  167. AZ::Data::AssetManager::Instance().DispatchEvents();
  168. }
  169. return succeeded;
  170. }
  171. };
  172. class SliceTest
  173. : public LeakDetectionFixture
  174. {
  175. public:
  176. void SetUp() override
  177. {
  178. LeakDetectionFixture::SetUp();
  179. m_serializeContext = aznew AZ::SerializeContext(true, true);
  180. m_sliceDescriptor = AZ::SliceComponent::CreateDescriptor();
  181. m_prevFileIO = AZ::IO::FileIOBase::GetInstance();
  182. AZ::IO::FileIOBase::SetInstance(&m_fileIO);
  183. m_streamer = aznew AZ::IO::Streamer(AZStd::thread_desc{}, AZ::StreamerComponent::CreateStreamerStack());
  184. AZ::Interface<AZ::IO::IStreamer>::Register(m_streamer);
  185. m_sliceDescriptor->Reflect(m_serializeContext);
  186. MyTestComponent1::Reflect(m_serializeContext);
  187. MyTestComponent2::Reflect(m_serializeContext);
  188. AZ::SliceMetadataInfoComponent::Reflect(m_serializeContext);
  189. AZ::Entity::Reflect(m_serializeContext);
  190. AZ::DataPatch::Reflect(m_serializeContext);
  191. // Create database
  192. AZ::Data::AssetManager::Descriptor desc;
  193. AZ::Data::AssetManager::Create(desc);
  194. AZ::Data::AssetManager::Instance().RegisterHandler(aznew AZ::SliceAssetHandler(m_serializeContext), AZ::AzTypeInfo<AZ::SliceAsset>::Uuid());
  195. m_catalog.reset(aznew SliceTest_MockCatalog());
  196. AZ::Data::AssetManager::Instance().RegisterCatalog(m_catalog.get(), AZ::AzTypeInfo<AZ::SliceAsset>::Uuid());
  197. }
  198. void TearDown() override
  199. {
  200. m_catalog->DisableCatalog();
  201. m_catalog.reset();
  202. AZ::Data::AssetManager::Destroy();
  203. delete m_sliceDescriptor;
  204. delete m_serializeContext;
  205. AZ::Interface<AZ::IO::IStreamer>::Unregister(m_streamer);
  206. delete m_streamer;
  207. AZ::IO::FileIOBase::SetInstance(m_prevFileIO);
  208. LeakDetectionFixture::TearDown();
  209. }
  210. AZ::IO::FileIOBase* m_prevFileIO{ nullptr };
  211. AZ::IO::Streamer* m_streamer{ nullptr };
  212. TestFileIOBase m_fileIO;
  213. AZStd::unique_ptr<SliceTest_MockCatalog> m_catalog;
  214. AZ::SerializeContext* m_serializeContext;
  215. AZ::ComponentDescriptor* m_sliceDescriptor;
  216. };
  217. TEST_F(SliceTest, UberTest)
  218. {
  219. AZ::SerializeContext& serializeContext = *m_serializeContext;
  220. AZStd::vector<char> binaryBuffer;
  221. AZ::Entity* sliceEntity = nullptr;
  222. AZ::SliceComponent* sliceComponent = nullptr;
  223. AZ::Entity* entity1 = nullptr;
  224. MyTestComponent1* component1 = nullptr;
  225. /////////////////////////////////////////////////////////////////////////////
  226. // Test prefab without base prefab - aka root prefab
  227. /////////////////////////////////////////////////////////////////////////////
  228. sliceEntity = aznew AZ::Entity();
  229. sliceComponent = aznew AZ::SliceComponent();
  230. sliceComponent->SetSerializeContext(&serializeContext);
  231. sliceEntity->AddComponent(sliceComponent);
  232. sliceEntity->Init();
  233. sliceEntity->Activate();
  234. // Create an entity with a component to be part of the prefab
  235. entity1 = aznew AZ::Entity();
  236. component1 = aznew MyTestComponent1();
  237. component1->m_float = 2.0f;
  238. component1->m_int = 11;
  239. entity1->AddComponent(component1);
  240. sliceComponent->AddEntity(entity1);
  241. // store to stream
  242. AZ::IO::ByteContainerStream<AZStd::vector<char> > binaryStream(&binaryBuffer);
  243. AZ::ObjectStream* binaryObjStream = AZ::ObjectStream::Create(&binaryStream, serializeContext, AZ::ObjectStream::ST_BINARY);
  244. binaryObjStream->WriteClass(sliceEntity);
  245. AZ_TEST_ASSERT(binaryObjStream->Finalize());
  246. // load from stream and check values
  247. binaryStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  248. AZ::Entity* sliceEntity2 = AZ::Utils::LoadObjectFromStream<AZ::Entity>(binaryStream, &serializeContext);
  249. AZ_TEST_ASSERT(sliceEntity2);
  250. AZ_TEST_ASSERT(sliceEntity2->FindComponent<AZ::SliceComponent>() != nullptr);
  251. AZ_TEST_ASSERT(sliceEntity2->FindComponent<AZ::SliceComponent>()->GetSlices().empty());
  252. const AZ::SliceComponent::EntityList& entityContainer = sliceEntity2->FindComponent<AZ::SliceComponent>()->GetNewEntities();
  253. AZ_TEST_ASSERT(entityContainer.size() == 1);
  254. AZ_TEST_ASSERT(entityContainer.front()->FindComponent<MyTestComponent1>());
  255. AZ_TEST_ASSERT(entityContainer.front()->FindComponent<MyTestComponent1>()->m_float == 2.0f);
  256. AZ_TEST_ASSERT(entityContainer.front()->FindComponent<MyTestComponent1>()->m_int == 11);
  257. delete sliceEntity2;
  258. sliceEntity2 = nullptr;
  259. /////////////////////////////////////////////////////////////////////////////
  260. /////////////////////////////////////////////////////////////////////////////
  261. // Test slice component with a single base prefab
  262. // Create "fake" asset - so we don't have to deal with the asset database, etc.
  263. AZ::Data::Asset<AZ::SliceAsset> sliceAssetHolder = AZ::Data::AssetManager::Instance().CreateAsset<AZ::SliceAsset>(m_catalog->GenerateMockAssetId(), AZ::Data::AssetLoadBehavior::Default);
  264. AZ::SliceAsset* sliceAsset1 = sliceAssetHolder.Get();
  265. sliceAsset1->SetData(sliceEntity, sliceComponent);
  266. // ASSERT_TRUE(m_catalog->SaveAsset(sliceAssetHolder));
  267. AZ::Data::AssetInfo assetInfo;
  268. AZ::Data::AssetCatalogRequestBus::BroadcastResult(assetInfo, &AZ::Data::AssetCatalogRequestBus::Events::GetAssetInfoById, sliceAssetHolder.GetId());
  269. ASSERT_TRUE(assetInfo.m_assetId.IsValid());
  270. sliceEntity2 = aznew AZ::Entity;
  271. AZ::SliceComponent* sliceComponent2 = sliceEntity2->CreateComponent<AZ::SliceComponent>();
  272. sliceComponent2->SetSerializeContext(&serializeContext);
  273. sliceComponent2->AddSlice(sliceAssetHolder);
  274. sliceEntity2->Init();
  275. sliceEntity2->Activate();
  276. AZ::SliceComponent::EntityList entities;
  277. sliceComponent2->GetEntities(entities); // get all entities (Instantiated if needed)
  278. AZ_TEST_ASSERT(entities.size() == 1);
  279. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>());
  280. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_float == 2.0f);
  281. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_int == 11);
  282. // Modify Component
  283. entities.front()->FindComponent<MyTestComponent1>()->m_float = 5.0f;
  284. // Add a new entity
  285. AZ::Entity* entity2 = aznew AZ::Entity();
  286. entity2->CreateComponent<MyTestComponent2>();
  287. sliceComponent2->AddEntity(entity2);
  288. // FindSlice test
  289. auto prefabFindResult = sliceComponent2->FindSlice(entity2);
  290. AZ_TEST_ASSERT(prefabFindResult.GetReference() == nullptr); // prefab reference
  291. AZ_TEST_ASSERT(prefabFindResult.GetInstance() == nullptr); // prefab instance
  292. prefabFindResult = sliceComponent2->FindSlice(entities.front());
  293. AZ_TEST_ASSERT(prefabFindResult.GetReference() != nullptr); // prefab reference
  294. AZ_TEST_ASSERT(prefabFindResult.GetInstance() != nullptr); // prefab instance
  295. // store to stream
  296. binaryBuffer.clear();
  297. binaryStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  298. binaryObjStream = AZ::ObjectStream::Create(&binaryStream, serializeContext, AZ::ObjectStream::ST_XML);
  299. binaryObjStream->WriteClass(sliceEntity2);
  300. AZ_TEST_ASSERT(binaryObjStream->Finalize());
  301. // load from stream and validate
  302. binaryStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  303. AZ::Entity* sliceEntity2Clone = AZ::Utils::LoadObjectFromStream<AZ::Entity>(binaryStream, &serializeContext);
  304. AZ_TEST_ASSERT(sliceEntity2Clone);
  305. AZ_TEST_ASSERT(sliceEntity2Clone->FindComponent<AZ::SliceComponent>() != nullptr);
  306. AZ_TEST_ASSERT(sliceEntity2Clone->FindComponent<AZ::SliceComponent>()->GetSlices().size() == 1);
  307. AZ_TEST_ASSERT(sliceEntity2Clone->FindComponent<AZ::SliceComponent>()->GetNewEntities().size() == 1);
  308. // instantiate the loaded component
  309. sliceEntity2Clone->FindComponent<AZ::SliceComponent>()->SetSerializeContext(&serializeContext);
  310. entities.clear();
  311. sliceEntity2Clone->FindComponent<AZ::SliceComponent>()->GetEntities(entities);
  312. AZ_TEST_ASSERT(entities.size() == 2); // original entity (prefab) plus the newly added one
  313. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>());
  314. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_float == 5.0f); // test modified field
  315. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_int == 11);
  316. AZ_TEST_ASSERT(entities.back()->FindComponent<MyTestComponent2>());
  317. ////////////////////////////////////////////////////////////////////////////
  318. /////////////////////////////////////////////////////////////////////////////
  319. // Test slice component 3 levels of customization
  320. AZ::Data::Asset<AZ::SliceAsset> sliceAssetHolder1 = AZ::Data::AssetManager::Instance().CreateAsset<AZ::SliceAsset>(m_catalog->GenerateMockAssetId(), AZ::Data::AssetLoadBehavior::Default);
  321. AZ::SliceAsset* sliceAsset2 = sliceAssetHolder1.Get();
  322. sliceAsset2->SetData(sliceEntity2, sliceComponent2);
  323. AZ::Entity* sliceEntity3 = aznew AZ::Entity();
  324. AZ::SliceComponent* sliceComponent3 = sliceEntity3->CreateComponent<AZ::SliceComponent>();
  325. sliceComponent3->SetSerializeContext(&serializeContext);
  326. sliceEntity3->Init();
  327. sliceEntity3->Activate();
  328. sliceComponent3->AddSlice(sliceAssetHolder1);
  329. entities.clear();
  330. sliceComponent3->GetEntities(entities);
  331. AZ_TEST_ASSERT(entities.size() == 2);
  332. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>());
  333. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_float == 5.0f);
  334. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_int == 11);
  335. AZ_TEST_ASSERT(entities.back()->FindComponent<MyTestComponent2>());
  336. // Modify Component
  337. entities.front()->FindComponent<MyTestComponent1>()->m_int = 22;
  338. // Remove a entity
  339. sliceComponent3->RemoveEntity(entities.back());
  340. // store to stream
  341. binaryBuffer.clear();
  342. binaryStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  343. binaryObjStream = AZ::ObjectStream::Create(&binaryStream, serializeContext, AZ::ObjectStream::ST_XML);
  344. binaryObjStream->WriteClass(sliceEntity3);
  345. AZ_TEST_ASSERT(binaryObjStream->Finalize());
  346. // modify root asset (to make sure that changes propgate properly), we have not overridden MyTestComponent1::m_float
  347. entities.clear();
  348. sliceComponent2->GetEntities(entities);
  349. entities.front()->FindComponent<MyTestComponent1>()->m_float = 15.0f;
  350. // load from stream and validate
  351. binaryStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  352. AZ::Entity* sliceEntity3Clone = AZ::Utils::LoadObjectFromStream<AZ::Entity>(binaryStream, &serializeContext);
  353. // instantiate the loaded component
  354. sliceEntity3Clone->FindComponent<AZ::SliceComponent>()->SetSerializeContext(&serializeContext);
  355. sliceEntity3Clone->Init();
  356. sliceEntity3Clone->Activate();
  357. entities.clear();
  358. sliceEntity3Clone->FindComponent<AZ::SliceComponent>()->GetEntities(entities);
  359. AZ_TEST_ASSERT(entities.size() == 1);
  360. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>());
  361. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_float == 15.0f); // this value was modified in the base prefab
  362. AZ_TEST_ASSERT(entities.front()->FindComponent<MyTestComponent1>()->m_int == 22);
  363. /////////////////////////////////////////////////////////////////////////////
  364. /////////////////////////////////////////////////////////////////////////////
  365. // Testing patching instance-owned entities in an existing prefab.
  366. {
  367. AZ::Entity rootEntity;
  368. AZ::SliceComponent* rootSlice = rootEntity.CreateComponent<AZ::SliceComponent>();
  369. rootSlice->SetSerializeContext(&serializeContext);
  370. rootEntity.Init();
  371. rootEntity.Activate();
  372. AZ::Data::Asset<AZ::SliceAsset> testAsset = AZ::Data::AssetManager::Instance().CreateAsset<AZ::SliceAsset>(m_catalog->GenerateMockAssetId(), AZ::Data::AssetLoadBehavior::Default);
  373. AZ::Entity* testAssetEntity = aznew AZ::Entity;
  374. AZ::SliceComponent* testAssetSlice = testAssetEntity->CreateComponent<AZ::SliceComponent>();
  375. testAssetSlice->SetSerializeContext(&serializeContext);
  376. // Add a couple test entities to the prefab asset.
  377. AZ::Entity* testEntity1 = aznew AZ::Entity();
  378. testEntity1->CreateComponent<MyTestComponent1>()->m_float = 15.f;
  379. testAssetSlice->AddEntity(testEntity1);
  380. AZ::Entity* testEntity2 = aznew AZ::Entity();
  381. testEntity2->CreateComponent<MyTestComponent1>()->m_float = 5.f;
  382. testAssetSlice->AddEntity(testEntity2);
  383. testAsset.Get()->SetData(testAssetEntity, testAssetSlice);
  384. // Test removing an entity from an existing prefab instance, cloning it, and re-adding it.
  385. // This emulates what's required for fast undo/redo entity restore for slice-owned entities.
  386. {
  387. rootSlice->AddSlice(testAsset);
  388. entities.clear();
  389. rootSlice->GetEntities(entities);
  390. // Grab one of the entities to remove, clone, and re-add.
  391. AZ::Entity* entity = entities.back();
  392. AZ_TEST_ASSERT(entity);
  393. AZ::SliceComponent::SliceInstanceAddress addr = rootSlice->FindSlice(entity);
  394. AZ_TEST_ASSERT(addr.IsValid());
  395. const AZ::SliceComponent::SliceInstanceId instanceId = addr.GetInstance()->GetId();
  396. AZ::SliceComponent::EntityAncestorList ancestors;
  397. addr.GetReference()->GetInstanceEntityAncestry(entity->GetId(), ancestors, 1);
  398. AZ_TEST_ASSERT(ancestors.size() == 1);
  399. AZ::SliceComponent::EntityRestoreInfo restoreInfo;
  400. AZ_TEST_ASSERT(rootSlice->GetEntityRestoreInfo(entity->GetId(), restoreInfo));
  401. // Duplicate the entity and make a data change we can validate later.
  402. AZ::Entity* clone = serializeContext.CloneObject(entity);
  403. clone->FindComponent<MyTestComponent1>()->m_float = 10.f;
  404. // Remove the original. We have two entities in the instance, so this will not wipe the instance.
  405. rootSlice->RemoveEntity(entity);
  406. // Patch it back into the prefab.
  407. rootSlice->RestoreEntity(clone, restoreInfo);
  408. // Re-retrieve the entity. We should find it, and it should match the data of the clone.
  409. addr = rootSlice->FindSlice(clone);
  410. ASSERT_TRUE(addr.IsValid());
  411. EXPECT_EQ(instanceId, addr.GetInstance()->GetId());
  412. entities.clear();
  413. rootSlice->GetEntities(entities);
  414. ASSERT_EQ(clone, entities.back());
  415. EXPECT_EQ(10.0f, entities.back()->FindComponent<MyTestComponent1>()->m_float);
  416. ancestors.clear();
  417. addr.GetReference()->GetInstanceEntityAncestry(clone->GetId(), ancestors, 1);
  418. EXPECT_EQ(1, ancestors.size());
  419. }
  420. // We also support re-adding when the reference no longer exists, so run the above
  421. // test, but such that the entity we remove is the last one, in turn destroying
  422. // the whole instance & reference.
  423. {
  424. rootSlice->RemoveSlice(testAsset);
  425. rootSlice->AddSlice(testAsset);
  426. entities.clear();
  427. rootSlice->GetEntities(entities);
  428. // Remove one of the entities.
  429. rootSlice->RemoveEntity(entities.front());
  430. AZ::Entity* entity = entities.back();
  431. AZ_TEST_ASSERT(entity);
  432. AZ::SliceComponent::SliceInstanceAddress addr = rootSlice->FindSlice(entity);
  433. AZ_TEST_ASSERT(addr.IsValid());
  434. const AZ::SliceComponent::SliceInstanceId instanceId = addr.GetInstance()->GetId();
  435. AZ::SliceComponent::EntityAncestorList ancestors;
  436. addr.GetReference()->GetInstanceEntityAncestry(entity->GetId(), ancestors, 1);
  437. AZ_TEST_ASSERT(ancestors.size() == 1);
  438. AZ::SliceComponent::EntityRestoreInfo restoreInfo;
  439. AZ_TEST_ASSERT(rootSlice->GetEntityRestoreInfo(entity->GetId(), restoreInfo));
  440. // Duplicate the entity and make a data change we can validate later.
  441. AZ::Entity* clone = serializeContext.CloneObject(entity);
  442. clone->FindComponent<MyTestComponent1>()->m_float = 10.f;
  443. // Remove the original. We have two entities in the instance, so this will not wipe the instance.
  444. rootSlice->RemoveEntity(entity);
  445. // Patch it back into the prefab.
  446. rootSlice->RestoreEntity(clone, restoreInfo);
  447. // Re-retrieve the entity. We should find it, and it should match the data of the clone.
  448. addr = rootSlice->FindSlice(clone);
  449. AZ_TEST_ASSERT(addr.IsValid());
  450. AZ_TEST_ASSERT(addr.GetInstance()->GetId() == instanceId);
  451. entities.clear();
  452. rootSlice->GetEntities(entities);
  453. AZ_TEST_ASSERT(entities.back() == clone);
  454. AZ_TEST_ASSERT(entities.back()->FindComponent<MyTestComponent1>()->m_float == 10.0f);
  455. ancestors.clear();
  456. addr.GetReference()->GetInstanceEntityAncestry(clone->GetId(), ancestors, 1);
  457. AZ_TEST_ASSERT(ancestors.size() == 1);
  458. }
  459. }
  460. /////////////////////////////////////////////////////////////////////////////
  461. // just reset the asset, don't delete the owned entity (we delete it later)
  462. sliceAsset1->SetData(nullptr, nullptr, false);
  463. sliceAsset2->SetData(nullptr, nullptr, false);
  464. delete sliceEntity;
  465. delete sliceEntity2;
  466. delete sliceEntity2Clone;
  467. delete sliceEntity3;
  468. delete sliceEntity3Clone;
  469. sliceAssetHolder.Reset(); // release asset
  470. sliceAssetHolder1.Reset();
  471. AZ::Data::AssetManager::Destroy();
  472. }
  473. /// a mock asset catalog which only contains two fixed assets.
  474. class SliceTest_RecursionDetection_Catalog
  475. : public AZ::Data::AssetCatalog
  476. , public AZ::Data::AssetCatalogRequestBus::Handler
  477. {
  478. public:
  479. AZ_CLASS_ALLOCATOR(SliceTest_RecursionDetection_Catalog, AZ::SystemAllocator);
  480. AZ::Uuid randomUuid = AZ::Uuid::CreateRandom();
  481. AZ::Data::AssetId m_assetIdSlice1 = AZ::Data::AssetId("{9DE6E611-CE12-4D78-90A5-53D106A50042}", 0);
  482. AZ::Data::AssetId m_assetIdSlice2 = AZ::Data::AssetId("{884C3DEE-3C86-4941-85E9-89103BAE314B}", 0);
  483. SliceTest_RecursionDetection_Catalog()
  484. {
  485. AZ::Data::AssetCatalogRequestBus::Handler::BusConnect();
  486. }
  487. ~SliceTest_RecursionDetection_Catalog() override
  488. {
  489. AZ::Data::AssetCatalogRequestBus::Handler::BusDisconnect();
  490. }
  491. //////////////////////////////////////////////////////////////////////////
  492. // AZ::Data::AssetCatalogRequestBus
  493. AZ::Data::AssetInfo GetAssetInfoById(const AZ::Data::AssetId& id) override
  494. {
  495. AZ::Data::AssetInfo result;
  496. result.m_assetType = azrtti_typeid<AZ::SliceAsset>();
  497. if (id == m_assetIdSlice1)
  498. {
  499. result.m_assetId = id;
  500. }
  501. else if (id == m_assetIdSlice2)
  502. {
  503. result.m_assetId = id;
  504. }
  505. return result;
  506. }
  507. //////////////////////////////////////////////////////////////////////////
  508. AZ::Data::AssetStreamInfo GetStreamInfoForLoad(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override
  509. {
  510. EXPECT_TRUE(type == AZ::AzTypeInfo<AZ::SliceAsset>::Uuid());
  511. AZ::Data::AssetStreamInfo info;
  512. info.m_dataOffset = 0;
  513. info.m_streamFlags = AZ::IO::OpenMode::ModeRead;
  514. if (m_assetIdSlice1 == id)
  515. {
  516. info.m_streamName = "MySliceAsset1.txt";
  517. }
  518. else if (m_assetIdSlice2 == id)
  519. {
  520. info.m_streamName = "MySliceAsset2.txt";
  521. }
  522. if (!info.m_streamName.empty())
  523. {
  524. // this ensures the parallel running unit tests do not overlap their files that they use.
  525. AZ::IO::Path fullName = GetTestFolderPath() / AZStd::string::format("%s-%s", randomUuid.ToString<AZStd::string>().c_str(), info.m_streamName.c_str());
  526. info.m_streamName = AZStd::move(fullName.Native());
  527. info.m_dataLen = static_cast<size_t>(AZ::IO::SystemFile::Length(info.m_streamName.c_str()));
  528. }
  529. else
  530. {
  531. info.m_dataLen = 0;
  532. }
  533. return info;
  534. }
  535. AZ::Data::AssetStreamInfo GetStreamInfoForSave(const AZ::Data::AssetId& id, const AZ::Data::AssetType& type) override
  536. {
  537. AZ::Data::AssetStreamInfo info;
  538. info = GetStreamInfoForLoad(id, type);
  539. info.m_streamFlags = AZ::IO::OpenMode::ModeWrite;
  540. return info;
  541. }
  542. };
  543. class DataFlags_CleanupTest
  544. : public LeakDetectionFixture
  545. {
  546. protected:
  547. void SetUp() override
  548. {
  549. auto allEntitiesValidFunction = [](AZ::EntityId) { return true; };
  550. m_dataFlags = AZStd::make_unique<AZ::SliceComponent::DataFlagsPerEntity>(allEntitiesValidFunction);
  551. m_addressOfSetFlag.push_back(AZ_CRC_CE("Components"));
  552. m_valueOfSetFlag = AZ::DataPatch::Flag::ForceOverrideSet;
  553. m_entityIdToGoMissing = AZ::Entity::MakeId();
  554. m_entityIdToRemain = AZ::Entity::MakeId();
  555. m_remainingEntity = AZStd::make_unique<AZ::Entity>(m_entityIdToRemain);
  556. m_remainingEntityList.push_back(m_remainingEntity.get());
  557. m_dataFlags->SetEntityDataFlagsAtAddress(m_entityIdToGoMissing, m_addressOfSetFlag, m_valueOfSetFlag);
  558. m_dataFlags->SetEntityDataFlagsAtAddress(m_entityIdToRemain, m_addressOfSetFlag, m_valueOfSetFlag);
  559. m_dataFlags->Cleanup(m_remainingEntityList);
  560. }
  561. void TearDown() override
  562. {
  563. m_remainingEntity.reset();
  564. m_dataFlags.reset();
  565. }
  566. AZStd::unique_ptr<AZ::SliceComponent::DataFlagsPerEntity> m_dataFlags;
  567. AZ::DataPatch::AddressType m_addressOfSetFlag;
  568. AZ::DataPatch::Flags m_valueOfSetFlag;
  569. AZ::EntityId m_entityIdToGoMissing;
  570. AZ::EntityId m_entityIdToRemain;
  571. AZStd::unique_ptr<AZ::Entity> m_remainingEntity;
  572. AZ::SliceComponent::EntityList m_remainingEntityList;
  573. };
  574. TEST_F(DataFlags_CleanupTest, MissingEntitiesPruned)
  575. {
  576. EXPECT_TRUE(m_dataFlags->GetEntityDataFlags(m_entityIdToGoMissing).empty());
  577. }
  578. TEST_F(DataFlags_CleanupTest, ValidEntitiesRemain)
  579. {
  580. EXPECT_EQ(m_dataFlags->GetEntityDataFlagsAtAddress(m_entityIdToRemain, m_addressOfSetFlag), m_valueOfSetFlag);
  581. }
  582. TEST_F(SliceTest, SliceMetadataInfoComponentV1ToV2Converter)
  583. {
  584. AZStd::string_view sliceAssociatedEntityIds = R"(<ObjectStream version="3">
  585. <Class name="SliceMetadataInfoComponent" field="element" version="1" type="{25EE4D75-8A17-4449-81F4-E561005BAABD}">
  586. <Class name="AZStd::unordered_set" field="AssociatedIds" type="{6C8F8E52-AB4A-5C1F-8E56-9AC390290B94}">
  587. <Class name="EntityId" field="element" version="1" type="{6383F1D3-BB27-4E6B-A49A-6409B2059EAA}">
  588. <Class name="AZ::u64" field="id" value="421626392978" type="{D6597933-47CD-4FC8-B911-63F3E2B0993A}"/>
  589. </Class>
  590. </Class>
  591. </Class>
  592. </ObjectStream>)";
  593. AZ::Entity* entity = aznew AZ::Entity("Slice");
  594. AZ::SliceMetadataInfoComponent* sliceMetadataInfoComponent = entity->CreateComponent<AZ::SliceMetadataInfoComponent>();
  595. AZ::IO::MemoryStream xmlStream(sliceAssociatedEntityIds.data(), sliceAssociatedEntityIds.size());
  596. AZ::Utils::LoadObjectFromStreamInPlace(xmlStream, *sliceMetadataInfoComponent, m_serializeContext);
  597. sliceMetadataInfoComponent->Activate();
  598. AZStd::set<AZ::EntityId> associatedEntities;
  599. AZ::SliceMetadataInfoRequestBus::Event(sliceMetadataInfoComponent->GetEntityId(), &AZ::SliceMetadataInfoRequestBus::Events::GetAssociatedEntities, associatedEntities);
  600. ASSERT_TRUE(associatedEntities.size() == 1);
  601. delete sliceMetadataInfoComponent;
  602. delete entity;
  603. }
  604. TEST_F(SliceTest, PreventOverrideOfPropertyinEntityFromSlice_InstancedSlicesCantOverrideProperty)
  605. {
  606. ////////////////////////////////////////////////////////////////////////
  607. // Create a root slice and make it an asset
  608. AZ::Entity* rootSliceEntity = aznew AZ::Entity();
  609. AZ::SliceComponent* rootSliceComponent = rootSliceEntity->CreateComponent<AZ::SliceComponent>();
  610. AZ::EntityId entityId1InRootSlice;
  611. AZ::ComponentId componentId1InRootSlice;
  612. AZ::Data::Asset<AZ::SliceAsset> rootSliceAssetRef;
  613. {
  614. rootSliceComponent->SetSerializeContext(m_serializeContext);
  615. rootSliceEntity->Init();
  616. rootSliceEntity->Activate();
  617. // put 1 entity in the root slice
  618. AZ::Entity* entity1InRootSlice = aznew AZ::Entity();
  619. entityId1InRootSlice = entity1InRootSlice->GetId();
  620. MyTestComponent1* component1InRootSlice = entity1InRootSlice->CreateComponent<MyTestComponent1>();
  621. componentId1InRootSlice = component1InRootSlice->GetId();
  622. rootSliceComponent->AddEntity(entity1InRootSlice);
  623. // create a "fake" slice asset
  624. rootSliceAssetRef = AZ::Data::AssetManager::Instance().CreateAsset<AZ::SliceAsset>(m_catalog->GenerateMockAssetId(), AZ::Data::AssetLoadBehavior::Default);
  625. rootSliceAssetRef.Get()->SetData(rootSliceEntity, rootSliceComponent);
  626. }
  627. ////////////////////////////////////////////////////////////////////////
  628. // Create slice2, which contains an instance of the first slice
  629. // store slice2 in stream
  630. AZStd::vector<AZ::u8> slice2Buffer;
  631. AZ::IO::ByteContainerStream<AZStd::vector<AZ::u8>> slice2Stream(&slice2Buffer);
  632. {
  633. AZ::Entity* slice2Entity = aznew AZ::Entity();
  634. AZ::SliceComponent* slice2Component = slice2Entity->CreateComponent<AZ::SliceComponent>();
  635. slice2Component->SetSerializeContext(m_serializeContext);
  636. slice2Component->AddSlice(rootSliceAssetRef);
  637. AZ::SliceComponent::EntityList entitiesInSlice2;
  638. slice2Component->GetEntities(entitiesInSlice2); // this instantiates slice2 and the rootSlice
  639. // change a property
  640. entitiesInSlice2[0]->FindComponent<MyTestComponent1>()->m_int = 43;
  641. auto slice2ObjectStream = AZ::ObjectStream::Create(&slice2Stream, *m_serializeContext, AZ::ObjectStream::ST_BINARY);
  642. EXPECT_TRUE(slice2ObjectStream->WriteClass(slice2Entity));
  643. EXPECT_TRUE(slice2ObjectStream->Finalize());
  644. delete slice2Entity;
  645. }
  646. ////////////////////////////////////////////////////////////////////////
  647. // Re-spawn slice2, the property should still be overridden
  648. {
  649. slice2Stream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  650. auto slice2Entity = AZ::Utils::LoadObjectFromStream<AZ::Entity>(slice2Stream, m_serializeContext);
  651. AZ::SliceComponent::EntityList entitiesInSlice2;
  652. slice2Entity->FindComponent<AZ::SliceComponent>()->GetEntities(entitiesInSlice2);
  653. EXPECT_EQ(43, entitiesInSlice2[0]->FindComponent<MyTestComponent1>()->m_int);
  654. delete slice2Entity;
  655. }
  656. ////////////////////////////////////////////////////////////////////////
  657. // Now modify the root slice to prevent override of the component's m_int value.
  658. {
  659. AZ::DataPatch::AddressType address;
  660. address.push_back(AZ_CRC_CE("Components"));
  661. address.push_back(componentId1InRootSlice);
  662. address.push_back(AZ_CRC_CE("int"));
  663. rootSliceComponent->SetEntityDataFlagsAtAddress(entityId1InRootSlice, address, AZ::DataPatch::Flag::PreventOverrideSet);
  664. // There are expectations that slice assets don't change after they're loaded,
  665. // so fake an "asset reload" by writing out the slice and reading it back in.
  666. AZStd::vector<char> rootSliceBuffer;
  667. AZ::IO::ByteContainerStream<AZStd::vector<char>> rootSliceStream(&rootSliceBuffer);
  668. auto rootSliceObjectStream = AZ::ObjectStream::Create(&rootSliceStream, *m_serializeContext, AZ::ObjectStream::ST_XML);
  669. EXPECT_TRUE(rootSliceObjectStream->WriteClass(rootSliceEntity));
  670. EXPECT_TRUE(rootSliceObjectStream->Finalize());
  671. rootSliceStream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  672. rootSliceEntity = AZ::Utils::LoadObjectFromStream<AZ::Entity>(rootSliceStream, m_serializeContext);
  673. rootSliceComponent = rootSliceEntity->FindComponent<AZ::SliceComponent>();
  674. rootSliceComponent->SetSerializeContext(m_serializeContext);
  675. rootSliceEntity->Init();
  676. rootSliceEntity->Activate();
  677. rootSliceAssetRef.Get()->SetData(rootSliceEntity, rootSliceComponent, true);
  678. }
  679. ////////////////////////////////////////////////////////////////////////
  680. // Re-spawn slice2, the property should NOT be overridden
  681. {
  682. slice2Stream.Seek(0, AZ::IO::GenericStream::ST_SEEK_BEGIN);
  683. auto slice2Entity = AZ::Utils::LoadObjectFromStream<AZ::Entity>(slice2Stream, m_serializeContext);
  684. AZ::SliceComponent::EntityList entitiesInSlice2;
  685. slice2Entity->FindComponent<AZ::SliceComponent>()->GetEntities(entitiesInSlice2);
  686. EXPECT_NE(43, entitiesInSlice2[0]->FindComponent<MyTestComponent1>()->m_int);
  687. delete slice2Entity;
  688. }
  689. }
  690. }
  691. #ifdef HAVE_BENCHMARK
  692. namespace Benchmark
  693. {
  694. static void BM_Slice_GenerateNewIdsAndFixRefs(benchmark::State& state)
  695. {
  696. AZ::ComponentApplication componentApp;
  697. AZ::ComponentApplication::Descriptor desc;
  698. desc.m_useExistingAllocator = true;
  699. AZ::ComponentApplication::StartupParameters startupParameters;
  700. startupParameters.m_loadSettingsRegistry = false;
  701. componentApp.Create(desc, startupParameters);
  702. UnitTest::MyTestComponent1::Reflect(componentApp.GetSerializeContext());
  703. UnitTest::MyTestComponent2::Reflect(componentApp.GetSerializeContext());
  704. // we use some randomness to set up this scenario,
  705. // seed the generator so we get the same results each time.
  706. AZ::u32 randSeed[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  707. AZ::Sfmt::GetInstance().Seed(randSeed, AZ_ARRAY_SIZE(randSeed));
  708. // setup a container with N entities
  709. AZ::SliceComponent::InstantiatedContainer container;
  710. for (int64_t entityI = 0; entityI < state.range(0); ++entityI)
  711. {
  712. auto entity = aznew AZ::Entity();
  713. // add components with nothing to remap, just to bulk up the volume of processed data
  714. entity->CreateComponent<UnitTest::MyTestComponent1>();
  715. entity->CreateComponent<UnitTest::MyTestComponent1>();
  716. entity->CreateComponent<UnitTest::MyTestComponent1>();
  717. // add component which references another EntityId
  718. auto component2 = entity->CreateComponent<UnitTest::MyTestComponent2>();
  719. if (entityI != 0)
  720. {
  721. component2->m_entityId = container.m_entities[AZ::Sfmt::GetInstance().Rand64() % container.m_entities.size()]->GetId();
  722. }
  723. container.m_entities.push_back(entity);
  724. }
  725. // shuffle entities so that some ID references are earlier in the data and some are later
  726. for (size_t i = container.m_entities.size() - 1; i > 0; --i)
  727. {
  728. AZStd::swap(container.m_entities[i], container.m_entities[AZ::Sfmt::GetInstance().Rand64() % (i+1)]);
  729. }
  730. AZStd::unordered_map<AZ::EntityId, AZ::EntityId> remappedIds;
  731. while (state.KeepRunning())
  732. {
  733. // Setup
  734. state.PauseTiming();
  735. AZ::SliceComponent::InstantiatedContainer* clonedContainer = componentApp.GetSerializeContext()->CloneObject(&container);
  736. state.ResumeTiming();
  737. // Timed Test
  738. AZ::IdUtils::Remapper<AZ::EntityId>::GenerateNewIdsAndFixRefs(clonedContainer, remappedIds, componentApp.GetSerializeContext());
  739. state.PauseTiming();
  740. delete clonedContainer;
  741. remappedIds.clear();
  742. state.ResumeTiming();
  743. }
  744. }
  745. BENCHMARK(BM_Slice_GenerateNewIdsAndFixRefs)->Arg(10)->Arg(1000);
  746. } // namespace Benchmark
  747. #endif // HAVE_BENCHMARK