CmModule.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #pragma once
  2. #include "CmPrerequisitesUtil.h"
  3. #include "CmException.h"
  4. namespace CamelotEngine
  5. {
  6. /**
  7. * @brief Represents one engine module. Essentially it is a specialized type of singleton.
  8. */
  9. template <class T> // TODO - Make it thread safe
  10. class Module
  11. {
  12. public:
  13. static T& instance()
  14. {
  15. if(isShutDown)
  16. {
  17. CM_EXCEPT(InternalErrorException,
  18. "Trying to access a module but it hasn't been started up yet.");
  19. }
  20. if(isDestroyed)
  21. {
  22. CM_EXCEPT(InternalErrorException,
  23. "Trying to access a destroyed module.");
  24. }
  25. return *_instance;
  26. }
  27. static T* instancePtr()
  28. {
  29. if(isShutDown)
  30. {
  31. CM_EXCEPT(InternalErrorException,
  32. "Trying to access a module but it hasn't been started up yet.");
  33. }
  34. if(isDestroyed)
  35. {
  36. CM_EXCEPT(InternalErrorException,
  37. "Trying to access a destroyed module.");
  38. }
  39. return _instance;
  40. }
  41. /**
  42. * @brief Initializes the module.
  43. *
  44. * @param [in] moduleInstance Instantiated module. Module takes ownership of instance memory
  45. * and releases it when shutDown is called.
  46. */
  47. static void startUp(T* moduleInstance)
  48. {
  49. if(!isShutDown)
  50. {
  51. CM_EXCEPT(InternalErrorException,
  52. "Trying to start an already started module.");
  53. }
  54. _instance = moduleInstance;
  55. isShutDown = false;
  56. }
  57. /**
  58. * @brief Shuts down this module and frees any resources it is using.
  59. */
  60. static void shutDown()
  61. {
  62. if(isShutDown)
  63. {
  64. CM_EXCEPT(InternalErrorException,
  65. "Trying to shut down an already shut down module.");
  66. }
  67. delete _instance;
  68. isShutDown = true;
  69. }
  70. /**
  71. * @brief Query if this object has been started.
  72. */
  73. static bool isStarted()
  74. {
  75. return !isShutDown && !isDestroyed;
  76. }
  77. protected:
  78. Module()
  79. {
  80. }
  81. virtual ~Module()
  82. {
  83. _instance = nullptr;
  84. isDestroyed = true;
  85. }
  86. Module(const Module&) { }
  87. Module& operator=(const Module&) { return *this; }
  88. private:
  89. static T* _instance;
  90. static bool isShutDown;
  91. static bool isDestroyed;
  92. };
  93. template <class T>
  94. T* Module<T>::_instance = nullptr;
  95. template <class T>
  96. bool Module<T>::isShutDown = true;
  97. template <class T>
  98. bool Module<T>::isDestroyed = false;
  99. }