BsCoreApplication.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsCoreApplication.h"
  4. #include "BsRenderAPI.h"
  5. #include "BsRenderAPIManager.h"
  6. #include "BsPlatform.h"
  7. #include "BsHardwareBufferManager.h"
  8. #include "BsRenderWindow.h"
  9. #include "BsViewport.h"
  10. #include "BsVector2.h"
  11. #include "BsGpuProgram.h"
  12. #include "BsCoreObjectManager.h"
  13. #include "BsGameObjectManager.h"
  14. #include "BsDynLib.h"
  15. #include "BsDynLibManager.h"
  16. #include "BsCoreSceneManager.h"
  17. #include "BsImporter.h"
  18. #include "BsResources.h"
  19. #include "BsMesh.h"
  20. #include "BsSceneObject.h"
  21. #include "BsTime.h"
  22. #include "BsInput.h"
  23. #include "BsRendererManager.h"
  24. #include "BsGpuProgramManager.h"
  25. #include "BsMeshManager.h"
  26. #include "BsMaterialManager.h"
  27. #include "BsFontManager.h"
  28. #include "BsRenderWindowManager.h"
  29. #include "BsCoreRenderer.h"
  30. #include "BsDeferredCallManager.h"
  31. #include "BsCoreThread.h"
  32. #include "BsStringTableManager.h"
  33. #include "BsProfilingManager.h"
  34. #include "BsProfilerCPU.h"
  35. #include "BsProfilerGPU.h"
  36. #include "BsQueryManager.h"
  37. #include "BsThreadPool.h"
  38. #include "BsTaskScheduler.h"
  39. #include "BsRenderStats.h"
  40. #include "BsMessageHandler.h"
  41. #include "BsResourceListenerManager.h"
  42. #include "BsRenderStateManager.h"
  43. #include "BsShaderManager.h"
  44. #include "BsPhysicsManager.h"
  45. #include "BsPhysics.h"
  46. namespace BansheeEngine
  47. {
  48. CoreApplication::CoreApplication(START_UP_DESC desc)
  49. : mPrimaryWindow(nullptr), mStartUpDesc(desc), mFrameStep(16666), mLastFrameTime(0), mRendererPlugin(nullptr)
  50. , mIsFrameRenderingFinished(true), mSimThreadId(BS_THREAD_CURRENT_ID), mRunMainLoop(false)
  51. { }
  52. CoreApplication::~CoreApplication()
  53. {
  54. mPrimaryWindow->destroy();
  55. mPrimaryWindow = nullptr;
  56. Importer::shutDown();
  57. FontManager::shutDown();
  58. MaterialManager::shutDown();
  59. MeshManager::shutDown();
  60. ProfilerGPU::shutDown();
  61. CoreSceneManager::shutDown();
  62. Input::shutDown();
  63. StringTableManager::shutDown();
  64. Resources::shutDown();
  65. ResourceListenerManager::shutDown();
  66. GameObjectManager::shutDown();
  67. RenderStateManager::shutDown();
  68. // This must be done after all resources are released since it will unload the physics plugin, and some resources
  69. // might be instances of types from that plugin.
  70. PhysicsManager::shutDown();
  71. RendererManager::shutDown();
  72. // All CoreObject related modules should be shut down now. They have likely queued CoreObjects for destruction, so
  73. // we need to wait for those objects to get destroyed before continuing.
  74. CoreObjectManager::instance().clearDirty();
  75. gCoreThread().update();
  76. gCoreThread().submitAccessors(true);
  77. unloadPlugin(mRendererPlugin);
  78. RenderAPIManager::shutDown();
  79. GpuProgramCoreManager::shutDown();
  80. GpuProgramManager::shutDown();
  81. CoreObjectManager::shutDown(); // Must shut down before DynLibManager to ensure all objects are destroyed before unloading their libraries
  82. DynLibManager::shutDown();
  83. Time::shutDown();
  84. DeferredCallManager::shutDown();
  85. CoreThread::shutDown();
  86. RenderStats::shutDown();
  87. TaskScheduler::shutDown();
  88. ThreadPool::shutDown();
  89. ProfilingManager::shutDown();
  90. ProfilerCPU::shutDown();
  91. MessageHandler::shutDown();
  92. ShaderManager::shutDown();
  93. MemStack::endThread();
  94. Platform::_shutDown();
  95. }
  96. void CoreApplication::onStartUp()
  97. {
  98. UINT32 numWorkerThreads = BS_THREAD_HARDWARE_CONCURRENCY - 1; // Number of cores while excluding current thread.
  99. Platform::_startUp();
  100. MemStack::beginThread();
  101. ShaderManager::startUp(getShaderIncludeHandler());
  102. MessageHandler::startUp();
  103. ProfilerCPU::startUp();
  104. ProfilingManager::startUp();
  105. ThreadPool::startUp<TThreadPool<ThreadBansheePolicy>>((numWorkerThreads));
  106. TaskScheduler::startUp();
  107. TaskScheduler::instance().removeWorker();
  108. RenderStats::startUp();
  109. CoreThread::startUp();
  110. StringTableManager::startUp();
  111. DeferredCallManager::startUp();
  112. Time::startUp();
  113. DynLibManager::startUp();
  114. CoreObjectManager::startUp();
  115. GameObjectManager::startUp();
  116. Resources::startUp();
  117. ResourceListenerManager::startUp();
  118. GpuProgramManager::startUp();
  119. RenderStateManager::startUp();
  120. GpuProgramCoreManager::startUp();
  121. RenderAPIManager::startUp();
  122. mPrimaryWindow = RenderAPIManager::instance().initialize(mStartUpDesc.renderAPI, mStartUpDesc.primaryWindowDesc);
  123. Input::startUp();
  124. RendererManager::startUp();
  125. loadPlugin(mStartUpDesc.renderer, &mRendererPlugin);
  126. SceneManagerFactory::create();
  127. RendererManager::instance().setActive(mStartUpDesc.renderer);
  128. startUpRenderer();
  129. ProfilerGPU::startUp();
  130. MeshManager::startUp();
  131. MaterialManager::startUp();
  132. FontManager::startUp();
  133. Importer::startUp();
  134. PhysicsManager::startUp(mStartUpDesc.physics, isEditor());
  135. for (auto& importerName : mStartUpDesc.importers)
  136. loadPlugin(importerName);
  137. loadPlugin(mStartUpDesc.input, nullptr, mPrimaryWindow.get());
  138. }
  139. void CoreApplication::runMainLoop()
  140. {
  141. mRunMainLoop = true;
  142. gCoreThread().queueCommand(std::bind(&CoreApplication::beginCoreProfiling, this));
  143. while(mRunMainLoop)
  144. {
  145. // Limit FPS if needed
  146. if (mFrameStep > 0)
  147. {
  148. UINT64 currentTime = gTime().getTimePrecise();
  149. UINT64 nextFrameTime = mLastFrameTime + mFrameStep;
  150. while (nextFrameTime > currentTime)
  151. {
  152. UINT32 waitTime = (UINT32)(nextFrameTime - currentTime);
  153. // If waiting for longer, sleep
  154. if (waitTime >= 2000)
  155. {
  156. Platform::sleep(waitTime / 1000);
  157. currentTime = gTime().getTimePrecise();
  158. }
  159. else
  160. {
  161. // Otherwise we just spin, sleep timer granularity is too low and we might end up wasting a
  162. // millisecond otherwise.
  163. // Note: For mobiles where power might be more important than input latency, consider using sleep.
  164. while(nextFrameTime > currentTime)
  165. currentTime = gTime().getTimePrecise();
  166. }
  167. }
  168. mLastFrameTime = currentTime;
  169. }
  170. gProfilerCPU().beginThread("Sim");
  171. Platform::_update();
  172. DeferredCallManager::instance()._update();
  173. gTime()._update();
  174. gInput()._update();
  175. // RenderWindowManager::update needs to happen after Input::update and before Input::_triggerCallbacks,
  176. // so that all input is properly captured in case there is a focus change, and so that
  177. // focus change is registered before input events are sent out (mouse press can result in code
  178. // checking if a window is in focus, so it has to be up to date)
  179. RenderWindowManager::instance()._update();
  180. gInput()._triggerCallbacks();
  181. gDebug()._triggerCallbacks();
  182. preUpdate();
  183. PROFILE_CALL(gCoreSceneManager()._update(), "SceneManager");
  184. gPhysics().update();
  185. gCoreThread().queueCommand(std::bind(&RenderWindowCoreManager::_update, RenderWindowCoreManager::instancePtr()));
  186. gCoreThread().queueCommand(std::bind(&QueryManager::_update, QueryManager::instancePtr()));
  187. gCoreThread().queueCommand(std::bind(&CoreApplication::endCoreProfiling, this));
  188. // Update plugins
  189. for (auto& pluginUpdateFunc : mPluginUpdateFunctions)
  190. pluginUpdateFunc.second();
  191. postUpdate();
  192. // Send out resource events in case any were loaded/destroyed/modified
  193. ResourceListenerManager::instance().update();
  194. gCoreSceneManager()._updateCoreObjectTransforms();
  195. PROFILE_CALL(RendererManager::instance().getActive()->renderAll(), "Render");
  196. // Core and sim thread run in lockstep. This will result in a larger input latency than if I was
  197. // running just a single thread. Latency becomes worse if the core thread takes longer than sim
  198. // thread, in which case sim thread needs to wait. Optimal solution would be to get an average
  199. // difference between sim/core thread and start the sim thread a bit later so they finish at nearly the same time.
  200. {
  201. BS_LOCK_MUTEX_NAMED(mFrameRenderingFinishedMutex, lock);
  202. while(!mIsFrameRenderingFinished)
  203. {
  204. TaskScheduler::instance().addWorker();
  205. BS_THREAD_WAIT(mFrameRenderingFinishedCondition, mFrameRenderingFinishedMutex, lock);
  206. TaskScheduler::instance().removeWorker();
  207. }
  208. mIsFrameRenderingFinished = false;
  209. }
  210. gCoreThread().queueCommand(std::bind(&CoreApplication::beginCoreProfiling, this));
  211. gCoreThread().queueCommand(&Platform::_coreUpdate);
  212. gCoreThread().update();
  213. gCoreThread().submitAccessors();
  214. gCoreThread().queueCommand(std::bind(&CoreApplication::frameRenderingFinishedCallback, this));
  215. gProfilerCPU().endThread();
  216. gProfiler()._update();
  217. }
  218. gCoreThread().queueCommand(std::bind(&CoreApplication::endCoreProfiling, this));
  219. // Wait until last core frame is finished before exiting
  220. {
  221. BS_LOCK_MUTEX_NAMED(mFrameRenderingFinishedMutex, lock);
  222. while (!mIsFrameRenderingFinished)
  223. {
  224. TaskScheduler::instance().addWorker();
  225. BS_THREAD_WAIT(mFrameRenderingFinishedCondition, mFrameRenderingFinishedMutex, lock);
  226. TaskScheduler::instance().removeWorker();
  227. }
  228. }
  229. }
  230. void CoreApplication::preUpdate()
  231. {
  232. // Do nothing
  233. }
  234. void CoreApplication::postUpdate()
  235. {
  236. // Do nothing
  237. }
  238. void CoreApplication::stopMainLoop()
  239. {
  240. mRunMainLoop = false; // No sync primitives needed, in that rare case of
  241. // a race condition we might run the loop one extra iteration which is acceptable
  242. }
  243. void CoreApplication::quitRequested()
  244. {
  245. stopMainLoop();
  246. }
  247. void CoreApplication::setFPSLimit(UINT32 limit)
  248. {
  249. mFrameStep = (UINT64)1000000 / limit;
  250. }
  251. void CoreApplication::frameRenderingFinishedCallback()
  252. {
  253. BS_LOCK_MUTEX(mFrameRenderingFinishedMutex);
  254. mIsFrameRenderingFinished = true;
  255. BS_THREAD_NOTIFY_ONE(mFrameRenderingFinishedCondition);
  256. }
  257. void CoreApplication::startUpRenderer()
  258. {
  259. RendererManager::instance().initialize();
  260. }
  261. void CoreApplication::beginCoreProfiling()
  262. {
  263. gProfilerCPU().beginThread("Core");
  264. ProfilerGPU::instance().beginFrame();
  265. }
  266. void CoreApplication::endCoreProfiling()
  267. {
  268. ProfilerGPU::instance().endFrame();
  269. ProfilerGPU::instance()._update();
  270. gProfilerCPU().endThread();
  271. gProfiler()._updateCore();
  272. }
  273. void* CoreApplication::loadPlugin(const String& pluginName, DynLib** library, void* passThrough)
  274. {
  275. DynLib* loadedLibrary = gDynLibManager().load(pluginName);
  276. if(library != nullptr)
  277. *library = loadedLibrary;
  278. void* retVal = nullptr;
  279. if(loadedLibrary != nullptr)
  280. {
  281. if (passThrough == nullptr)
  282. {
  283. typedef void* (*LoadPluginFunc)();
  284. LoadPluginFunc loadPluginFunc = (LoadPluginFunc)loadedLibrary->getSymbol("loadPlugin");
  285. if (loadPluginFunc != nullptr)
  286. retVal = loadPluginFunc();
  287. }
  288. else
  289. {
  290. typedef void* (*LoadPluginFunc)(void*);
  291. LoadPluginFunc loadPluginFunc = (LoadPluginFunc)loadedLibrary->getSymbol("loadPlugin");
  292. if (loadPluginFunc != nullptr)
  293. retVal = loadPluginFunc(passThrough);
  294. }
  295. UpdatePluginFunc loadPluginFunc = (UpdatePluginFunc)loadedLibrary->getSymbol("updatePlugin");
  296. if (loadPluginFunc != nullptr)
  297. mPluginUpdateFunctions[loadedLibrary] = loadPluginFunc;
  298. }
  299. return retVal;
  300. }
  301. void CoreApplication::unloadPlugin(DynLib* library)
  302. {
  303. typedef void (*UnloadPluginFunc)();
  304. UnloadPluginFunc unloadPluginFunc = (UnloadPluginFunc)library->getSymbol("unloadPlugin");
  305. if(unloadPluginFunc != nullptr)
  306. unloadPluginFunc();
  307. mPluginUpdateFunctions.erase(library);
  308. gDynLibManager().unload(library);
  309. }
  310. SPtr<IShaderIncludeHandler> CoreApplication::getShaderIncludeHandler() const
  311. {
  312. return bs_shared_ptr_new<DefaultShaderIncludeHandler>();
  313. }
  314. CoreApplication& gCoreApplication()
  315. {
  316. return CoreApplication::instance();
  317. }
  318. }