CmModule.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  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>
  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. static void startUp(T* inst)
  42. {
  43. if(!isShutDown)
  44. CM_EXCEPT(InternalErrorException, "Trying to start an already started module.");
  45. _instance = inst;
  46. isShutDown = false;
  47. ((Module*)_instance)->onStartUp();
  48. }
  49. /**
  50. * @brief Shuts down this module and frees any resources it is using.
  51. */
  52. static void shutDown()
  53. {
  54. if(isShutDown)
  55. {
  56. CM_EXCEPT(InternalErrorException,
  57. "Trying to shut down an already shut down module.");
  58. }
  59. ((Module*)_instance)->onShutDown();
  60. cm_delete(_instance);
  61. isShutDown = true;
  62. }
  63. /**
  64. * @brief Query if this object has been started.
  65. */
  66. static bool isStarted()
  67. {
  68. return !isShutDown && !isDestroyed;
  69. }
  70. protected:
  71. Module()
  72. {
  73. }
  74. virtual ~Module()
  75. {
  76. _instance = nullptr;
  77. isDestroyed = true;
  78. }
  79. Module(const Module&) { }
  80. Module& operator=(const Module&) { return *this; }
  81. virtual void onStartUp() {}
  82. virtual void onShutDown() {}
  83. static T* _instance;
  84. static bool isShutDown;
  85. static bool isDestroyed;
  86. };
  87. template <class T>
  88. T* Module<T>::_instance = nullptr;
  89. template <class T>
  90. bool Module<T>::isShutDown = true;
  91. template <class T>
  92. bool Module<T>::isDestroyed = false;
  93. }