mainLoop.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "app/mainLoop.h"
  23. #include "app/game.h"
  24. #include "platform/platformTimer.h"
  25. #include "platform/platformRedBook.h"
  26. #include "platform/platformVolume.h"
  27. #include "platform/platformMemory.h"
  28. #include "platform/platformTimer.h"
  29. #include "platform/platformNet.h"
  30. #include "platform/nativeDialogs/fileDialog.h"
  31. #include "platform/threads/thread.h"
  32. #include "core/module.h"
  33. #include "core/threadStatic.h"
  34. #include "core/iTickable.h"
  35. #include "core/stream/fileStream.h"
  36. #include "windowManager/platformWindowMgr.h"
  37. #include "core/util/journal/process.h"
  38. #include "util/fpsTracker.h"
  39. #include "console/debugOutputConsumer.h"
  40. #include "console/consoleTypes.h"
  41. #include "console/engineAPI.h"
  42. #include "gfx/bitmap/gBitmap.h"
  43. #include "gfx/gFont.h"
  44. #include "gfx/video/videoCapture.h"
  45. #include "gfx/gfxTextureManager.h"
  46. #include "sim/netStringTable.h"
  47. #include "sim/actionMap.h"
  48. #include "sim/netInterface.h"
  49. #include "util/sampler.h"
  50. #include "platform/threads/threadPool.h"
  51. // For the TickMs define... fix this for T2D...
  52. #include "T3D/gameBase/processList.h"
  53. #ifdef TORQUE_DEMO_PURCHASE
  54. #include "demo/pestTimer/pestTimer.h"
  55. #endif
  56. #ifdef TORQUE_ENABLE_VFS
  57. #include "platform/platformVFS.h"
  58. #endif
  59. DITTS( F32, gTimeScale, 1.0 );
  60. DITTS( U32, gTimeAdvance, 0 );
  61. DITTS( U32, gFrameSkip, 0 );
  62. extern S32 sgBackgroundProcessSleepTime;
  63. extern S32 sgTimeManagerProcessInterval;
  64. extern FPSTracker gFPS;
  65. TimeManager* tm = NULL;
  66. static bool gRequiresRestart = false;
  67. #ifdef TORQUE_DEBUG
  68. /// Temporary timer used to time startup times.
  69. static PlatformTimer* gStartupTimer;
  70. #endif
  71. #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE )
  72. StringTableEntry gMiniDumpDir;
  73. StringTableEntry gMiniDumpExec;
  74. StringTableEntry gMiniDumpParams;
  75. StringTableEntry gMiniDumpExecDir;
  76. #endif
  77. namespace engineAPI
  78. {
  79. // This is the magic switch for deciding which interop the engine
  80. // should use. It will go away when we drop the console system
  81. // entirely but for now it is necessary for several behaviors that
  82. // differ between the interops to decide what to do.
  83. bool gUseConsoleInterop = true;
  84. bool gIsInitialized = false;
  85. }
  86. // The following are some tricks to make the memory leak checker run after global
  87. // dtors have executed by placing some code in the termination segments.
  88. #if defined( TORQUE_DEBUG ) && !defined( TORQUE_DISABLE_MEMORY_MANAGER )
  89. #ifdef TORQUE_COMPILER_VISUALC
  90. # pragma data_seg( ".CRT$XTU" )
  91. static void* sCheckMemBeforeTermination = &Memory::ensureAllFreed;
  92. # pragma data_seg()
  93. #elif defined( TORQUE_COMPILER_GCC )
  94. __attribute__ ( ( destructor ) ) static void _ensureAllFreed()
  95. {
  96. Memory::ensureAllFreed();
  97. }
  98. #endif
  99. #endif
  100. // Process a time event and update all sub-processes
  101. void processTimeEvent(S32 elapsedTime)
  102. {
  103. PROFILE_START(ProcessTimeEvent);
  104. // If recording a video and not playinb back a journal, override the elapsedTime
  105. if (VIDCAP->isRecording() && !Journal::IsPlaying())
  106. elapsedTime = VIDCAP->getMsPerFrame();
  107. // cap the elapsed time to one second
  108. // if it's more than that we're probably in a bad catch-up situation
  109. if(elapsedTime > 1024)
  110. elapsedTime = 1024;
  111. U32 timeDelta;
  112. if(ATTS(gTimeAdvance))
  113. timeDelta = ATTS(gTimeAdvance);
  114. else
  115. timeDelta = (U32) (elapsedTime * ATTS(gTimeScale));
  116. Platform::advanceTime(elapsedTime);
  117. // Don't build up more time than a single tick... this makes the sim
  118. // frame rate dependent but is a useful hack for singleplayer.
  119. if ( ATTS(gFrameSkip) )
  120. if ( timeDelta > TickMs )
  121. timeDelta = TickMs;
  122. bool tickPass;
  123. PROFILE_START(ServerProcess);
  124. tickPass = serverProcess(timeDelta);
  125. PROFILE_END();
  126. PROFILE_START(ServerNetProcess);
  127. // only send packets if a tick happened
  128. if(tickPass)
  129. GNet->processServer();
  130. // Used to indicate if server was just ticked.
  131. Con::setBoolVariable( "$pref::hasServerTicked", tickPass );
  132. PROFILE_END();
  133. PROFILE_START(SimAdvanceTime);
  134. Sim::advanceTime(timeDelta);
  135. PROFILE_END();
  136. PROFILE_START(ClientProcess);
  137. tickPass = clientProcess(timeDelta);
  138. // Used to indicate if client was just ticked.
  139. Con::setBoolVariable( "$pref::hasClientTicked", tickPass );
  140. PROFILE_END_NAMED(ClientProcess);
  141. PROFILE_START(ClientNetProcess);
  142. if(tickPass)
  143. GNet->processClient();
  144. PROFILE_END();
  145. GNet->checkTimeouts();
  146. gFPS.update();
  147. // Give the texture manager a chance to cleanup any
  148. // textures that haven't been referenced for a bit.
  149. if( GFX )
  150. TEXMGR->cleanupCache( 5 );
  151. PROFILE_END();
  152. // Update the console time
  153. Con::setFloatVariable("Sim::Time",F32(Platform::getVirtualMilliseconds()) / 1000);
  154. }
  155. void StandardMainLoop::init()
  156. {
  157. #ifdef TORQUE_DEBUG
  158. gStartupTimer = PlatformTimer::create();
  159. #endif
  160. #ifdef TORQUE_DEBUG_GUARD
  161. Memory::flagCurrentAllocs( Memory::FLAG_Global );
  162. #endif
  163. Platform::setMathControlStateKnown();
  164. // Asserts should be created FIRST
  165. PlatformAssert::create();
  166. ManagedSingleton< ThreadManager >::createSingleton();
  167. FrameAllocator::init(TORQUE_FRAME_SIZE); // See comments in torqueConfig.h
  168. // Yell if we can't initialize the network.
  169. if(!Net::init())
  170. {
  171. AssertISV(false, "StandardMainLoop::initCore - could not initialize networking!");
  172. }
  173. _StringTable::create();
  174. // Set up the resource manager and get some basic file types in it.
  175. Con::init();
  176. Platform::initConsole();
  177. NetStringTable::create();
  178. // Use debug output logging on the Xbox and OSX builds
  179. #if defined( _XBOX ) || defined( TORQUE_OS_MAC )
  180. DebugOutputConsumer::init();
  181. #endif
  182. // init Filesystem first, so we can actually log errors for all components that follow
  183. Platform::FS::InstallFileSystems(); // install all drives for now until we have everything using the volume stuff
  184. Platform::FS::MountDefaults();
  185. // Set our working directory.
  186. Torque::FS::SetCwd( "game:/" );
  187. // Set our working directory.
  188. Platform::setCurrentDirectory( Platform::getMainDotCsDir() );
  189. Processor::init();
  190. Math::init();
  191. Platform::init(); // platform specific initialization
  192. RedBook::init();
  193. Platform::initConsole();
  194. ThreadPool::GlobalThreadPool::createSingleton();
  195. // Initialize modules.
  196. ModuleManager::initializeSystem();
  197. // Initialise ITickable.
  198. #ifdef TORQUE_TGB_ONLY
  199. ITickable::init( 4 );
  200. #endif
  201. #ifdef TORQUE_ENABLE_VFS
  202. // [tom, 10/28/2006] Load the VFS here so that it stays loaded
  203. Zip::ZipArchive *vfs = openEmbeddedVFSArchive();
  204. gResourceManager->addVFSRoot(vfs);
  205. #endif
  206. Con::addVariable("timeScale", TypeF32, &ATTS(gTimeScale), "Animation time scale.\n"
  207. "@ingroup platform");
  208. Con::addVariable("timeAdvance", TypeS32, &ATTS(gTimeAdvance), "The speed at which system processing time advances.\n"
  209. "@ingroup platform");
  210. Con::addVariable("frameSkip", TypeS32, &ATTS(gFrameSkip), "Sets the number of frames to skip while rendering the scene.\n"
  211. "@ingroup platform");
  212. Con::setVariable( "defaultGame", StringTable->insert("scripts") );
  213. Con::addVariable( "_forceAllMainThread", TypeBool, &ThreadPool::getForceAllMainThread(), "Force all work items to execute on main thread. turns this into a single-threaded system. Primarily useful to find whether malfunctions are caused by parallel execution or not.\n"
  214. "@ingroup platform" );
  215. #if defined( TORQUE_MINIDUMP ) && defined( TORQUE_RELEASE )
  216. Con::addVariable("MiniDump::Dir", TypeString, &gMiniDumpDir);
  217. Con::addVariable("MiniDump::Exec", TypeString, &gMiniDumpExec);
  218. Con::addVariable("MiniDump::Params", TypeString, &gMiniDumpParams);
  219. Con::addVariable("MiniDump::ExecDir", TypeString, &gMiniDumpExecDir);
  220. #endif
  221. ActionMap* globalMap = new ActionMap;
  222. globalMap->registerObject("GlobalActionMap");
  223. Sim::getActiveActionMapSet()->pushObject(globalMap);
  224. // Do this before we init the process so that process notifiees can get the time manager
  225. tm = new TimeManager;
  226. tm->timeEvent.notify(&::processTimeEvent);
  227. // Start up the Input Event Manager
  228. INPUTMGR->start();
  229. Sampler::init();
  230. // Hook in for UDP notification
  231. Net::smPacketReceive.notify(GNet, &NetInterface::processPacketReceiveEvent);
  232. #ifdef TORQUE_DEMO_PURCHASE
  233. PestTimerinit();
  234. #endif
  235. #ifdef TORQUE_DEBUG_GUARD
  236. Memory::flagCurrentAllocs( Memory::FLAG_Static );
  237. #endif
  238. }
  239. void StandardMainLoop::shutdown()
  240. {
  241. // Stop the Input Event Manager
  242. INPUTMGR->stop();
  243. delete tm;
  244. preShutdown();
  245. // Shut down modules.
  246. ModuleManager::shutdownSystem();
  247. ThreadPool::GlobalThreadPool::deleteSingleton();
  248. #ifdef TORQUE_ENABLE_VFS
  249. closeEmbeddedVFSArchive();
  250. #endif
  251. RedBook::destroy();
  252. Platform::shutdown();
  253. #if defined( _XBOX ) || defined( TORQUE_OS_MAC )
  254. DebugOutputConsumer::destroy();
  255. #endif
  256. NetStringTable::destroy();
  257. Con::shutdown();
  258. _StringTable::destroy();
  259. FrameAllocator::destroy();
  260. Net::shutdown();
  261. Sampler::destroy();
  262. ManagedSingleton< ThreadManager >::deleteSingleton();
  263. // asserts should be destroyed LAST
  264. PlatformAssert::destroy();
  265. #if defined( TORQUE_DEBUG ) && !defined( TORQUE_DISABLE_MEMORY_MANAGER )
  266. Memory::validate();
  267. #endif
  268. }
  269. void StandardMainLoop::preShutdown()
  270. {
  271. #ifdef TORQUE_TOOLS
  272. // Tools are given a chance to do pre-quit processing
  273. // - This is because for tools we like to do things such
  274. // as prompting to save changes before shutting down
  275. // and onExit is packaged which means we can't be sure
  276. // where in the shutdown namespace chain we are when using
  277. // onExit since some components of the tools may already be
  278. // destroyed that may be vital to saving changes to avoid
  279. // loss of work [1/5/2007 justind]
  280. if( Con::isFunction("onPreExit") )
  281. Con::executef( "onPreExit");
  282. #endif
  283. //exec the script onExit() function
  284. if ( Con::isFunction( "onExit" ) )
  285. Con::executef("onExit");
  286. }
  287. bool StandardMainLoop::handleCommandLine( S32 argc, const char **argv )
  288. {
  289. // Allow the window manager to process command line inputs; this is
  290. // done to let web plugin functionality happen in a fairly transparent way.
  291. PlatformWindowManager::get()->processCmdLineArgs(argc, argv);
  292. Process::handleCommandLine( argc, argv );
  293. // Set up the command line args for the console scripts...
  294. Con::setIntVariable("Game::argc", argc);
  295. U32 i;
  296. for (i = 0; i < argc; i++)
  297. Con::setVariable(avar("Game::argv%d", i), argv[i]);
  298. #ifdef TORQUE_PLAYER
  299. if(argc > 2 && dStricmp(argv[1], "-project") == 0)
  300. {
  301. char playerPath[1024];
  302. Platform::makeFullPathName(argv[2], playerPath, sizeof(playerPath));
  303. Platform::setCurrentDirectory(playerPath);
  304. argv += 2;
  305. argc -= 2;
  306. // Re-locate the game:/ asset mount.
  307. Torque::FS::Unmount( "game" );
  308. Torque::FS::Mount( "game", Platform::FS::createNativeFS( playerPath ) );
  309. }
  310. #endif
  311. // Executes an entry script file. This is "main.cs"
  312. // by default, but any file name (with no whitespace
  313. // in it) may be run if it is specified as the first
  314. // command-line parameter. The script used, default
  315. // or otherwise, is not compiled and is loaded here
  316. // directly because the resource system restricts
  317. // access to the "root" directory.
  318. #ifdef TORQUE_ENABLE_VFS
  319. Zip::ZipArchive *vfs = openEmbeddedVFSArchive();
  320. bool useVFS = vfs != NULL;
  321. #endif
  322. Stream *mainCsStream = NULL;
  323. // The working filestream.
  324. FileStream str;
  325. const char *defaultScriptName = "main.cs";
  326. bool useDefaultScript = true;
  327. // Check if any command-line parameters were passed (the first is just the app name).
  328. if (argc > 1)
  329. {
  330. // If so, check if the first parameter is a file to open.
  331. if ( (dStrcmp(argv[1], "") != 0 ) && (str.open(argv[1], Torque::FS::File::Read)) )
  332. {
  333. // If it opens, we assume it is the script to run.
  334. useDefaultScript = false;
  335. #ifdef TORQUE_ENABLE_VFS
  336. useVFS = false;
  337. #endif
  338. mainCsStream = &str;
  339. }
  340. }
  341. if (useDefaultScript)
  342. {
  343. bool success = false;
  344. #ifdef TORQUE_ENABLE_VFS
  345. if(useVFS)
  346. success = (mainCsStream = vfs->openFile(defaultScriptName, Zip::ZipArchive::Read)) != NULL;
  347. else
  348. #endif
  349. success = str.open(defaultScriptName, Torque::FS::File::Read);
  350. #if defined( TORQUE_DEBUG ) && defined (TORQUE_TOOLS) && !defined( _XBOX )
  351. if (!success)
  352. {
  353. OpenFileDialog ofd;
  354. FileDialogData &fdd = ofd.getData();
  355. fdd.mFilters = StringTable->insert("Main Entry Script (main.cs)|main.cs|");
  356. fdd.mTitle = StringTable->insert("Locate Game Entry Script");
  357. // Get the user's selection
  358. if( !ofd.Execute() )
  359. return false;
  360. // Process and update CWD so we can run the selected main.cs
  361. S32 pathLen = dStrlen( fdd.mFile );
  362. FrameTemp<char> szPathCopy( pathLen + 1);
  363. dStrcpy( szPathCopy, fdd.mFile );
  364. //forwardslash( szPathCopy );
  365. const char *path = dStrrchr(szPathCopy, '/');
  366. if(path)
  367. {
  368. U32 len = path - (const char*)szPathCopy;
  369. szPathCopy[len+1] = 0;
  370. Platform::setCurrentDirectory(szPathCopy);
  371. // Re-locate the game:/ asset mount.
  372. Torque::FS::Unmount( "game" );
  373. Torque::FS::Mount( "game", Platform::FS::createNativeFS( ( const char* ) szPathCopy ) );
  374. success = str.open(fdd.mFile, Torque::FS::File::Read);
  375. if(success)
  376. defaultScriptName = fdd.mFile;
  377. }
  378. }
  379. #endif
  380. if( !success )
  381. {
  382. char msg[1024];
  383. dSprintf(msg, sizeof(msg), "Failed to open \"%s\".", defaultScriptName);
  384. Platform::AlertOK("Error", msg);
  385. #ifdef TORQUE_ENABLE_VFS
  386. closeEmbeddedVFSArchive();
  387. #endif
  388. return false;
  389. }
  390. #ifdef TORQUE_ENABLE_VFS
  391. if(! useVFS)
  392. #endif
  393. mainCsStream = &str;
  394. }
  395. // This should rarely happen, but lets deal with
  396. // it gracefully if it does.
  397. if ( mainCsStream == NULL )
  398. return false;
  399. U32 size = mainCsStream->getStreamSize();
  400. char *script = new char[size + 1];
  401. mainCsStream->read(size, script);
  402. #ifdef TORQUE_ENABLE_VFS
  403. if(useVFS)
  404. vfs->closeFile(mainCsStream);
  405. else
  406. #endif
  407. str.close();
  408. script[size] = 0;
  409. char buffer[1024], *ptr;
  410. Platform::makeFullPathName(useDefaultScript ? defaultScriptName : argv[1], buffer, sizeof(buffer), Platform::getCurrentDirectory());
  411. ptr = dStrrchr(buffer, '/');
  412. if(ptr != NULL)
  413. *ptr = 0;
  414. Platform::setMainDotCsDir(buffer);
  415. Platform::setCurrentDirectory(buffer);
  416. Con::evaluate(script, false, useDefaultScript ? defaultScriptName : argv[1]);
  417. delete[] script;
  418. #ifdef TORQUE_ENABLE_VFS
  419. closeEmbeddedVFSArchive();
  420. #endif
  421. return true;
  422. }
  423. bool StandardMainLoop::doMainLoop()
  424. {
  425. #ifdef TORQUE_DEBUG
  426. if( gStartupTimer )
  427. {
  428. Con::printf( "Started up in %.2f seconds...",
  429. F32( gStartupTimer->getElapsedMs() ) / 1000.f );
  430. SAFE_DELETE( gStartupTimer );
  431. }
  432. #endif
  433. bool keepRunning = true;
  434. // while(keepRunning)
  435. {
  436. tm->setBackgroundThreshold(mClamp(sgBackgroundProcessSleepTime, 1, 200));
  437. tm->setForegroundThreshold(mClamp(sgTimeManagerProcessInterval, 1, 200));
  438. // update foreground/background status
  439. if(WindowManager->getFirstWindow())
  440. {
  441. static bool lastFocus = false;
  442. bool newFocus = ( WindowManager->getFocusedWindow() != NULL );
  443. if(lastFocus != newFocus)
  444. {
  445. #ifndef TORQUE_SHIPPING
  446. Con::printf("Window focus status changed: focus: %d", newFocus);
  447. if (!newFocus)
  448. Con::printf(" Using background sleep time: %u", Platform::getBackgroundSleepTime());
  449. #endif
  450. #ifdef TORQUE_OS_MAC
  451. if (newFocus)
  452. WindowManager->getFirstWindow()->show();
  453. #endif
  454. lastFocus = newFocus;
  455. }
  456. #ifndef TORQUE_OS_MAC
  457. // under the web plugin do not sleep the process when the child window loses focus as this will cripple the browser perfomance
  458. if (!Platform::getWebDeployment())
  459. tm->setBackground(!newFocus);
  460. else
  461. tm->setBackground(false);
  462. #else
  463. tm->setBackground(false);
  464. #endif
  465. }
  466. else
  467. {
  468. tm->setBackground(false);
  469. }
  470. PROFILE_START(MainLoop);
  471. Sampler::beginFrame();
  472. if(!Process::processEvents())
  473. keepRunning = false;
  474. ThreadPool::processMainThreadWorkItems();
  475. Sampler::endFrame();
  476. PROFILE_END_NAMED(MainLoop);
  477. #ifdef TORQUE_DEMO_PURCHASE
  478. CheckTimer();
  479. CheckBlocker();
  480. #endif
  481. }
  482. return keepRunning;
  483. }
  484. void StandardMainLoop::setRestart(bool restart )
  485. {
  486. gRequiresRestart = restart;
  487. }
  488. bool StandardMainLoop::requiresRestart()
  489. {
  490. return gRequiresRestart;
  491. }