activeobjectmgr.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Luanti
  2. // SPDX-License-Identifier: LGPL-2.1-or-later
  3. // Copyright (C) 2010-2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr>
  4. #pragma once
  5. #include <memory>
  6. #include "debug.h"
  7. #include "util/container.h"
  8. #include "irrlichttypes.h"
  9. #include "util/basic_macros.h"
  10. class TestClientActiveObjectMgr;
  11. class TestServerActiveObjectMgr;
  12. template <typename T>
  13. class ActiveObjectMgr
  14. {
  15. friend class ::TestServerActiveObjectMgr;
  16. public:
  17. ActiveObjectMgr() = default;
  18. DISABLE_CLASS_COPY(ActiveObjectMgr);
  19. virtual ~ActiveObjectMgr()
  20. {
  21. SANITY_CHECK(m_active_objects.empty());
  22. // Note: Do not call clear() here. The derived class is already half
  23. // destructed.
  24. }
  25. virtual void step(float dtime, const std::function<void(T *)> &f) = 0;
  26. virtual bool registerObject(std::unique_ptr<T> obj) = 0;
  27. virtual void removeObject(u16 id) = 0;
  28. void clear()
  29. {
  30. // on_destruct could add new objects so this has to be a loop
  31. do {
  32. for (auto &it : m_active_objects.iter()) {
  33. if (!it.second)
  34. continue;
  35. m_active_objects.remove(it.first);
  36. }
  37. } while (!m_active_objects.empty());
  38. }
  39. T *getActiveObject(u16 id)
  40. {
  41. return m_active_objects.get(id).get();
  42. }
  43. protected:
  44. u16 getFreeId() const
  45. {
  46. // try to reuse id's as late as possible
  47. static thread_local u16 last_used_id = 0;
  48. u16 startid = last_used_id;
  49. while (!isFreeId(++last_used_id)) {
  50. if (last_used_id == startid)
  51. return 0;
  52. }
  53. return last_used_id;
  54. }
  55. bool isFreeId(u16 id) const
  56. {
  57. return id != 0 && !m_active_objects.get(id);
  58. }
  59. // Note that this is ordered to fix #10985
  60. ModifySafeMap<u16, std::unique_ptr<T>> m_active_objects;
  61. };