NetworkSpawnableLibrary.cpp 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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 <Source/NetworkEntity/NetworkSpawnableLibrary.h>
  9. #include <AzCore/Asset/AssetManagerBus.h>
  10. #include <AzCore/Component/ComponentApplicationLifecycle.h>
  11. #include <AzFramework/Spawnable/Spawnable.h>
  12. #include <AzCore/Interface/Interface.h>
  13. #include <Multiplayer/MultiplayerConstants.h>
  14. namespace Multiplayer
  15. {
  16. NetworkSpawnableLibrary::NetworkSpawnableLibrary()
  17. {
  18. AZ::Interface<INetworkSpawnableLibrary>::Register(this);
  19. if (auto settingsRegistry{ AZ::SettingsRegistry::Get() }; settingsRegistry != nullptr)
  20. {
  21. auto LifecycleCallback = [this](const AZ::SettingsRegistryInterface::NotifyEventArgs&)
  22. {
  23. BuildSpawnablesList();
  24. };
  25. AZ::ComponentApplicationLifecycle::RegisterHandler(*settingsRegistry, m_criticalAssetsHandler,
  26. AZStd::move(LifecycleCallback), "CriticalAssetsCompiled");
  27. }
  28. }
  29. NetworkSpawnableLibrary::~NetworkSpawnableLibrary()
  30. {
  31. m_criticalAssetsHandler = {};
  32. AZ::Interface<INetworkSpawnableLibrary>::Unregister(this);
  33. }
  34. void NetworkSpawnableLibrary::BuildSpawnablesList()
  35. {
  36. m_spawnables.clear();
  37. m_spawnablesReverseLookup.clear();
  38. auto enumerateCallback = [this](const AZ::Data::AssetId id, const AZ::Data::AssetInfo& info)
  39. {
  40. if (info.m_assetType == AZ::AzTypeInfo<AzFramework::Spawnable>::Uuid() &&
  41. info.m_relativePath.ends_with(NetworkSpawnableFileExtension))
  42. {
  43. ProcessSpawnableAsset(info.m_relativePath, id);
  44. }
  45. };
  46. AZ::Data::AssetCatalogRequestBus::Broadcast(&AZ::Data::AssetCatalogRequests::EnumerateAssets, nullptr,
  47. enumerateCallback, nullptr);
  48. }
  49. void NetworkSpawnableLibrary::ProcessSpawnableAsset(const AZStd::string& relativePath, const AZ::Data::AssetId id)
  50. {
  51. const AZ::Name name = AZ::Name(relativePath);
  52. m_spawnables[name] = id;
  53. m_spawnablesReverseLookup[id] = name;
  54. }
  55. AZ::Name NetworkSpawnableLibrary::GetSpawnableNameFromAssetId(AZ::Data::AssetId assetId)
  56. {
  57. if (assetId.IsValid())
  58. {
  59. auto it = m_spawnablesReverseLookup.find(assetId);
  60. if (it != m_spawnablesReverseLookup.end())
  61. {
  62. return it->second;
  63. }
  64. }
  65. return {};
  66. }
  67. AZ::Data::AssetId NetworkSpawnableLibrary::GetAssetIdByName(AZ::Name name)
  68. {
  69. auto it = m_spawnables.find(name);
  70. if (it != m_spawnables.end())
  71. {
  72. return it->second;
  73. }
  74. return {};
  75. }
  76. }