activeobjectmgr.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2018 nerzhul, Loic BLOT <loic.blot@unix-experience.fr>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #pragma once
  17. #include <unordered_map>
  18. #include "irrlichttypes.h"
  19. class TestClientActiveObjectMgr;
  20. class TestServerActiveObjectMgr;
  21. template <typename T>
  22. class ActiveObjectMgr
  23. {
  24. friend class ::TestClientActiveObjectMgr;
  25. friend class ::TestServerActiveObjectMgr;
  26. public:
  27. virtual void step(float dtime, const std::function<void(T *)> &f) = 0;
  28. virtual bool registerObject(T *obj) = 0;
  29. virtual void removeObject(u16 id) = 0;
  30. T *getActiveObject(u16 id)
  31. {
  32. typename std::unordered_map<u16, T *>::const_iterator n =
  33. m_active_objects.find(id);
  34. return (n != m_active_objects.end() ? n->second : nullptr);
  35. }
  36. protected:
  37. u16 getFreeId() const
  38. {
  39. // try to reuse id's as late as possible
  40. static thread_local u16 last_used_id = 0;
  41. u16 startid = last_used_id;
  42. while (!isFreeId(++last_used_id)) {
  43. if (last_used_id == startid)
  44. return 0;
  45. }
  46. return last_used_id;
  47. }
  48. bool isFreeId(u16 id) const
  49. {
  50. return id != 0 && m_active_objects.find(id) == m_active_objects.end();
  51. }
  52. std::unordered_map<u16, T *> m_active_objects;
  53. };