NetworkRandomComponent.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
  3. *
  4. * SPDX-License-Identifier: Apache-2.0 OR MIT
  5. *
  6. */
  7. #include <AzCore/Math/Random.h>
  8. #include <Source/Components/NetworkRandomComponent.h>
  9. namespace MultiplayerSample
  10. {
  11. uint64_t NetworkRandomComponentController::GetRandomUint64()
  12. {
  13. // Reimplements SimpleLcgRandom's rand int with a synchronized seed
  14. uint64_t& seed = ModifySeed();
  15. seed = (GetSeed() * 0x5DEECE66DLL + 0xBLL) & ((1LL << 48) - 1);
  16. return seed;
  17. }
  18. int NetworkRandomComponentController::GetRandomInt()
  19. {
  20. // Reimplements SimpleLcgRandom's rand int with a synchronized seed
  21. return static_cast<unsigned int>(GetRandomUint64() >> 16);
  22. }
  23. float NetworkRandomComponentController::GetRandomFloat()
  24. {
  25. // Reimplements SimpleLcgRandom's rand float with a synchronized seed
  26. unsigned int r = GetRandomInt();
  27. r &= 0x007fffff; //sets mantissa to random bits
  28. r |= 0x3f800000; //result is in [1,2), uniformly distributed
  29. union
  30. {
  31. float f;
  32. unsigned int i;
  33. } u;
  34. u.i = r;
  35. return u.f - 1.0f;
  36. }
  37. NetworkRandomComponentController::NetworkRandomComponentController(NetworkRandomComponent& parent)
  38. : NetworkRandomComponentControllerBase(parent)
  39. {
  40. #if AZ_TRAIT_SERVER
  41. if (IsNetEntityRoleAuthority())
  42. {
  43. // Setup seed on authority for proxies to pull
  44. AZ::BetterPseudoRandom seedGenerator;
  45. uint64_t seed = 0;
  46. seedGenerator.GetRandom(seed);
  47. SetSeed(seed);
  48. };
  49. #endif
  50. }
  51. void NetworkRandomComponentController::OnActivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  52. {
  53. ;
  54. }
  55. void NetworkRandomComponentController::OnDeactivate([[maybe_unused]] Multiplayer::EntityIsMigrating entityIsMigrating)
  56. {
  57. ;
  58. }
  59. }