CharacterID.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2025 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #pragma once
  5. #include <Jolt/Core/HashCombine.h>
  6. JPH_NAMESPACE_BEGIN
  7. /// ID of a character. Used primarily to identify deleted characters and to sort deterministically.
  8. class JPH_EXPORT CharacterID
  9. {
  10. public:
  11. JPH_OVERRIDE_NEW_DELETE
  12. static constexpr uint32 cInvalidCharacterID = 0xffffffff; ///< The value for an invalid character ID
  13. /// Construct invalid character ID
  14. CharacterID() :
  15. mID(cInvalidCharacterID)
  16. {
  17. }
  18. /// Construct with specific value, make sure you don't use the same value twice!
  19. explicit CharacterID(uint32 inID) :
  20. mID(inID)
  21. {
  22. }
  23. /// Get the numeric value of the ID
  24. inline uint32 GetValue() const
  25. {
  26. return mID;
  27. }
  28. /// Check if the ID is valid
  29. inline bool IsInvalid() const
  30. {
  31. return mID == cInvalidCharacterID;
  32. }
  33. /// Equals check
  34. inline bool operator == (const CharacterID &inRHS) const
  35. {
  36. return mID == inRHS.mID;
  37. }
  38. /// Not equals check
  39. inline bool operator != (const CharacterID &inRHS) const
  40. {
  41. return mID != inRHS.mID;
  42. }
  43. /// Smaller than operator, can be used for sorting characters
  44. inline bool operator < (const CharacterID &inRHS) const
  45. {
  46. return mID < inRHS.mID;
  47. }
  48. /// Greater than operator, can be used for sorting characters
  49. inline bool operator > (const CharacterID &inRHS) const
  50. {
  51. return mID > inRHS.mID;
  52. }
  53. /// Get the hash for this character ID
  54. inline uint64 GetHash() const
  55. {
  56. return Hash<uint32>{} (mID);
  57. }
  58. /// Generate the next available character ID
  59. static CharacterID sNextCharacterID()
  60. {
  61. for (;;)
  62. {
  63. uint32 next = sNextID.fetch_add(1, std::memory_order_relaxed);
  64. if (next != cInvalidCharacterID)
  65. return CharacterID(next);
  66. }
  67. }
  68. /// Set the next available character ID, can be used after destroying all character to prepare for a second deterministic run
  69. static void sSetNextCharacterID(uint32 inNextValue = 1)
  70. {
  71. sNextID.store(inNextValue, std::memory_order_relaxed);
  72. }
  73. private:
  74. /// Next character ID to be assigned
  75. inline static atomic<uint32> sNextID = 1;
  76. /// ID value
  77. uint32 mID;
  78. };
  79. JPH_NAMESPACE_END