BsCoreApplication.cpp 12 KB

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