Engine.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 Lasse Öörni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #include "Precompiled.h"
  24. #include "Audio.h"
  25. #include "Console.h"
  26. #include "Context.h"
  27. #include "CoreEvents.h"
  28. #include "DebugHud.h"
  29. #include "Engine.h"
  30. #include "FileSystem.h"
  31. #include "Graphics.h"
  32. #include "Input.h"
  33. #include "Log.h"
  34. #include "Network.h"
  35. #include "PackageFile.h"
  36. #include "PhysicsWorld.h"
  37. #include "ProcessUtils.h"
  38. #include "Profiler.h"
  39. #include "Renderer.h"
  40. #include "ResourceCache.h"
  41. #include "Scene.h"
  42. #include "SceneEvents.h"
  43. #include "Script.h"
  44. #include "ScriptAPI.h"
  45. #include "StringUtils.h"
  46. #include "UI.h"
  47. #include "WorkQueue.h"
  48. #include "DebugNew.h"
  49. OBJECTTYPESTATIC(Engine);
  50. Engine::Engine(Context* context) :
  51. Object(context),
  52. minFps_(10),
  53. maxFps_(200),
  54. maxInactiveFps_(50),
  55. timeStep_(0),
  56. initialized_(false),
  57. exiting_(false),
  58. headless_(false)
  59. {
  60. }
  61. Engine::~Engine()
  62. {
  63. }
  64. bool Engine::Initialize(const String& windowTitle, const String& logName, const Vector<String>& arguments)
  65. {
  66. if (initialized_)
  67. return true;
  68. int width = 0;
  69. int height = 0;
  70. int multiSample = 1;
  71. int buffer = 100;
  72. int mixRate = 44100;
  73. bool fullscreen = true;
  74. bool vsync = false;
  75. bool tripleBuffer = false;
  76. bool forceSM2 = false;
  77. bool forceFallback = false;
  78. bool shadows = true;
  79. bool lqShadows = false;
  80. bool sound = true;
  81. bool stereo = true;
  82. bool interpolate = true;
  83. bool flush = true;
  84. for (unsigned i = 0; i < arguments.Size(); ++i)
  85. {
  86. if (arguments[i][0] == '-' && arguments[i].Length() >= 2)
  87. {
  88. String argument = arguments[i].Substring(1).ToLower();
  89. if (argument == "headless")
  90. headless_ = true;
  91. else if (argument == "nolimit")
  92. SetMaxFps(0);
  93. else if (argument == "nosound")
  94. sound = false;
  95. else if (argument == "noip")
  96. interpolate = false;
  97. else if (argument == "mono")
  98. stereo = false;
  99. else if (argument == "noshadows")
  100. shadows = false;
  101. else if (argument == "lqshadows")
  102. lqShadows = true;
  103. else if (argument == "noflush")
  104. flush = false;
  105. else if (argument == "sm2")
  106. forceSM2 = true;
  107. else if (argument == "fallback")
  108. forceFallback = true;
  109. else
  110. {
  111. switch (tolower(argument[0]))
  112. {
  113. case 'x':
  114. if (arguments[i].Length() > 1)
  115. width = ToInt(argument.Substring(1));
  116. break;
  117. case 'y':
  118. if (arguments[i].Length() > 1)
  119. height = ToInt(argument.Substring(1));
  120. break;
  121. case 'm':
  122. if (arguments[i].Length() > 1)
  123. multiSample = ToInt(argument.Substring(1));
  124. break;
  125. case 'b':
  126. if (arguments[i].Length() > 1)
  127. buffer = ToInt(argument.Substring(1));
  128. break;
  129. case 'r':
  130. if (arguments[i].Length() > 1)
  131. mixRate = ToInt(argument.Substring(1));
  132. break;
  133. case 'v':
  134. vsync = true;
  135. break;
  136. case 't':
  137. tripleBuffer = true;
  138. break;
  139. case 'f':
  140. fullscreen = true;
  141. break;
  142. case 'w':
  143. fullscreen = false;
  144. break;
  145. }
  146. }
  147. }
  148. }
  149. // Register object factories and attributes first, then subsystems
  150. RegisterObjects();
  151. RegisterSubsystems();
  152. // Start logging
  153. Log* log = GetSubsystem<Log>();
  154. log->Open(logName);
  155. // Add default resource paths: CoreData package or directory, Data package or directory
  156. ResourceCache* cache = GetSubsystem<ResourceCache>();
  157. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  158. String exePath = fileSystem->GetProgramDir();
  159. if (fileSystem->FileExists(exePath + "CoreData.pak"))
  160. {
  161. SharedPtr<PackageFile> package(new PackageFile(context_));
  162. package->Open(exePath + "CoreData.pak");
  163. cache->AddPackageFile(package);
  164. }
  165. else if (fileSystem->DirExists(exePath + "CoreData"))
  166. cache->AddResourceDir(exePath + "CoreData");
  167. if (fileSystem->FileExists(exePath + "Data.pak"))
  168. {
  169. SharedPtr<PackageFile> package(new PackageFile(context_));
  170. package->Open(exePath + "Data.pak");
  171. cache->AddPackageFile(package);
  172. }
  173. else if (fileSystem->DirExists(exePath + "Data"))
  174. cache->AddResourceDir(exePath + "Data");
  175. // Initialize graphics & audio output
  176. if (!headless_)
  177. {
  178. Graphics* graphics = GetSubsystem<Graphics>();
  179. Renderer* renderer = GetSubsystem<Renderer>();
  180. graphics->SetFlushGPU(flush);
  181. graphics->SetForceSM2(forceSM2);
  182. graphics->SetForceFallback(forceFallback);
  183. graphics->SetWindowTitle(windowTitle);
  184. if (!graphics->SetMode(width, height, fullscreen, vsync, tripleBuffer, multiSample))
  185. return false;
  186. if (!shadows)
  187. renderer->SetDrawShadows(false);
  188. else if (lqShadows)
  189. renderer->SetShadowQuality(SHADOWQUALITY_LOW_16BIT);
  190. if (sound)
  191. GetSubsystem<Audio>()->SetMode(buffer, mixRate, stereo, interpolate);
  192. }
  193. frameTimer_.Reset();
  194. initialized_ = true;
  195. return true;
  196. }
  197. bool Engine::InitializeScripting()
  198. {
  199. if (!initialized_)
  200. return false;
  201. // Check if scripting already initialized
  202. if (GetSubsystem<Script>())
  203. return true;
  204. RegisterScriptLibrary(context_);
  205. context_->RegisterSubsystem(new Script(context_));
  206. {
  207. PROFILE(RegisterScriptAPI);
  208. asIScriptEngine* engine = GetSubsystem<Script>()->GetScriptEngine();
  209. RegisterMathAPI(engine);
  210. RegisterCoreAPI(engine);
  211. RegisterIOAPI(engine);
  212. RegisterResourceAPI(engine);
  213. RegisterSceneAPI(engine);
  214. RegisterGraphicsAPI(engine);
  215. RegisterInputAPI(engine);
  216. RegisterAudioAPI(engine);
  217. RegisterUIAPI(engine);
  218. RegisterNetworkAPI(engine);
  219. RegisterPhysicsAPI(engine);
  220. RegisterScriptAPI(engine);
  221. RegisterEngineAPI(engine);
  222. }
  223. return true;
  224. }
  225. void Engine::RunFrame()
  226. {
  227. if (!initialized_ || exiting_)
  228. return;
  229. // Set exit flag if the window was closed
  230. if (!headless_ && !GetSubsystem<Graphics>()->IsInitialized())
  231. {
  232. exiting_ = true;
  233. return;
  234. }
  235. Time* time = GetSubsystem<Time>();
  236. time->BeginFrame(timeStep_);
  237. Render();
  238. ApplyFrameLimit();
  239. time->EndFrame();
  240. }
  241. Console* Engine::CreateConsole()
  242. {
  243. if (headless_ || !initialized_)
  244. return 0;
  245. context_->RegisterSubsystem(new Console(context_));
  246. return GetSubsystem<Console>();
  247. }
  248. DebugHud* Engine::CreateDebugHud()
  249. {
  250. if (headless_ || !initialized_)
  251. return 0;
  252. context_->RegisterSubsystem(new DebugHud(context_));
  253. return GetSubsystem<DebugHud>();
  254. }
  255. void Engine::SetMinFps(int fps)
  256. {
  257. minFps_ = Max(fps, 0);
  258. }
  259. void Engine::SetMaxFps(int fps)
  260. {
  261. maxFps_ = Max(fps, 0);
  262. }
  263. void Engine::SetMaxInactiveFps(int fps)
  264. {
  265. maxInactiveFps_ = Max(fps, 0);
  266. }
  267. void Engine::Exit()
  268. {
  269. Graphics* graphics = GetSubsystem<Graphics>();
  270. if (graphics)
  271. graphics->Close();
  272. exiting_ = true;
  273. }
  274. void Engine::DumpProfilingData()
  275. {
  276. Profiler* profiler = GetSubsystem<Profiler>();
  277. if (profiler)
  278. {
  279. profiler->EndFrame();
  280. LOGRAW(profiler->GetData(true, false, true) + "\n");
  281. }
  282. }
  283. void Engine::DumpResources()
  284. {
  285. ResourceCache* cache = GetSubsystem<ResourceCache>();
  286. const Map<ShortStringHash, ResourceGroup>& resourceGroups = cache->GetAllResources();
  287. LOGRAW("\n");
  288. for (Map<ShortStringHash, ResourceGroup>::ConstIterator i = resourceGroups.Begin();
  289. i != resourceGroups.End(); ++i)
  290. {
  291. unsigned num = i->second_.resources_.Size();
  292. unsigned memoryUse = i->second_.memoryUse_;
  293. if (num)
  294. {
  295. LOGRAW("Resource type " + i->second_.resources_.Begin()->second_->GetTypeName() +
  296. ": count " + String(num) + " memory use " + String(memoryUse) + "\n");
  297. }
  298. }
  299. LOGRAW("Total memory use of all resources " + String(cache->GetTotalMemoryUse()) + "\n\n");
  300. }
  301. void Engine::Render()
  302. {
  303. // Do not render if device lost
  304. Graphics* graphics = GetSubsystem<Graphics>();
  305. if (graphics && graphics->BeginFrame())
  306. {
  307. GetSubsystem<Renderer>()->Render();
  308. GetSubsystem<UI>()->Render();
  309. graphics->EndFrame();
  310. }
  311. }
  312. void Engine::ApplyFrameLimit()
  313. {
  314. if (!initialized_)
  315. return;
  316. int maxFps = maxFps_;
  317. Input* input = GetSubsystem<Input>();
  318. if (input && !input->IsActive())
  319. maxFps = maxInactiveFps_;
  320. int timeAcc = 0;
  321. if (maxFps)
  322. {
  323. PROFILE(ApplyFrameLimit);
  324. int targetMax = 1000 / maxFps;
  325. for (;;)
  326. {
  327. timeAcc += frameTimer_.GetMSec(true);
  328. if (timeAcc >= targetMax)
  329. break;
  330. unsigned wait = (targetMax - timeAcc);
  331. Time::Sleep(wait / 2);
  332. }
  333. }
  334. else
  335. timeAcc = frameTimer_.GetMSec(true);
  336. // If FPS lower than minimum, clamp elapsed time
  337. if (minFps_)
  338. {
  339. int targetMin = 1000 / minFps_;
  340. if (timeAcc > targetMin)
  341. timeAcc = targetMin;
  342. }
  343. timeStep_ = timeAcc;
  344. }
  345. void Engine::RegisterObjects()
  346. {
  347. RegisterResourceLibrary(context_);
  348. RegisterSceneLibrary(context_);
  349. RegisterNetworkLibrary(context_);
  350. RegisterGraphicsLibrary(context_);
  351. RegisterAudioLibrary(context_);
  352. RegisterUILibrary(context_);
  353. RegisterPhysicsLibrary(context_);
  354. }
  355. void Engine::RegisterSubsystems()
  356. {
  357. // Register self as a subsystem
  358. context_->RegisterSubsystem(this);
  359. // Create and register the rest of the subsystems
  360. context_->RegisterSubsystem(new Time(context_));
  361. context_->RegisterSubsystem(new WorkQueue(context_));
  362. #ifdef ENABLE_PROFILING
  363. context_->RegisterSubsystem(new Profiler(context_));
  364. #endif
  365. context_->RegisterSubsystem(new Log(context_));
  366. context_->RegisterSubsystem(new FileSystem(context_));
  367. context_->RegisterSubsystem(new ResourceCache(context_));
  368. context_->RegisterSubsystem(new Network(context_));
  369. if (!headless_)
  370. {
  371. context_->RegisterSubsystem(new Graphics(context_));
  372. context_->RegisterSubsystem(new Renderer(context_));
  373. }
  374. context_->RegisterSubsystem(new Input(context_));
  375. context_->RegisterSubsystem(new UI(context_));
  376. context_->RegisterSubsystem(new Audio(context_));
  377. }