CmModule.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #pragma once
  2. #include "CmPrerequisitesUtil.h"
  3. #include "CmException.h"
  4. namespace CamelotFramework
  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. ((Module*)moduleInstance)->onStartUp();
  57. }
  58. /**
  59. * @brief Shuts down this module and frees any resources it is using.
  60. */
  61. static void shutDown()
  62. {
  63. if(isShutDown)
  64. {
  65. CM_EXCEPT(InternalErrorException,
  66. "Trying to shut down an already shut down module.");
  67. }
  68. ((Module*)_instance)->onShutDown();
  69. cm_delete(_instance);
  70. isShutDown = true;
  71. }
  72. /**
  73. * @brief Query if this object has been started.
  74. */
  75. static bool isStarted()
  76. {
  77. return !isShutDown && !isDestroyed;
  78. }
  79. protected:
  80. Module()
  81. {
  82. }
  83. virtual ~Module()
  84. {
  85. _instance = nullptr;
  86. isDestroyed = true;
  87. }
  88. Module(const Module&) { }
  89. Module& operator=(const Module&) { return *this; }
  90. virtual void onStartUp() {}
  91. virtual void onShutDown() {}
  92. private:
  93. static T* _instance;
  94. static bool isShutDown;
  95. static bool isDestroyed;
  96. };
  97. template <class T>
  98. T* Module<T>::_instance = nullptr;
  99. template <class T>
  100. bool Module<T>::isShutDown = true;
  101. template <class T>
  102. bool Module<T>::isDestroyed = false;
  103. }