BsCoreApplication.cpp 12 KB

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