AtomicPlayer.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  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 deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // 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 FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include <Atomic/Atomic.h>
  23. #include <Atomic/Engine/Engine.h>
  24. #include <Atomic/IO/FileSystem.h>
  25. #include <Atomic/IO/Log.h>
  26. #include <Atomic/Core/Main.h>
  27. #include <Atomic/Core/ProcessUtils.h>
  28. #include <Atomic/Resource/ResourceCache.h>
  29. #include <Atomic/Resource/ResourceEvents.h>
  30. // Move me
  31. #include <Atomic/Environment/Environment.h>
  32. #include <Atomic/Javascript/Javascript.h>
  33. #include <Atomic/Javascript/JSFile.h>
  34. #include "AtomicPlayer.h"
  35. #include <Atomic/DebugNew.h>
  36. #include <Atomic/UI/TBUI.h>
  37. #ifdef EMSCRIPTEN
  38. #include "emscripten.h"
  39. class EmscriptenApp
  40. {
  41. public:
  42. Atomic::SharedPtr<Atomic::Context> context_;
  43. Atomic::SharedPtr<AtomicPlayer> application_;
  44. static EmscriptenApp* sInstance_;
  45. EmscriptenApp() : context_(new Atomic::Context()), application_(new AtomicPlayer(context_))
  46. {
  47. sInstance_ = this;
  48. }
  49. };
  50. EmscriptenApp* EmscriptenApp::sInstance_ = NULL;
  51. static void RunFrame()
  52. {
  53. Engine* engine = EmscriptenApp::sInstance_->application_->GetSubsystem<Engine>();
  54. if (engine->IsInitialized())
  55. engine->RunFrame();
  56. else
  57. printf("ENGINE NOT INITIALIZED\n");
  58. }
  59. int main(int argc, char** argv)
  60. {
  61. Atomic::ParseArguments(argc, argv);
  62. // leak
  63. new EmscriptenApp();
  64. EmscriptenApp::sInstance_->application_->Run();
  65. int firefox = EM_ASM_INT ( return ((navigator.userAgent.toLowerCase().indexOf('firefox') > -1) ? 1 : 0), 0);
  66. if (firefox)
  67. emscripten_set_main_loop(RunFrame, 0, 1);
  68. else
  69. emscripten_set_main_loop(RunFrame, 60, 1);
  70. return 0;
  71. }
  72. #else
  73. DEFINE_APPLICATION_MAIN(AtomicPlayer);
  74. #endif
  75. // fixme
  76. static JSVM* vm = NULL;
  77. static Javascript* javascript = NULL;
  78. AtomicPlayer::AtomicPlayer(Context* context) :
  79. Application(context)
  80. {
  81. RegisterEnvironmenttLibrary(context_);
  82. }
  83. void AtomicPlayer::Setup()
  84. {
  85. FileSystem* filesystem = GetSubsystem<FileSystem>();
  86. // On Android and iOS, read command line from a file as parameters can not otherwise be easily given
  87. #if defined(ANDROID) || defined(IOS)
  88. SharedPtr<File> commandFile(new File(context_, filesystem->GetProgramDir() + "Data/CommandLine.txt",
  89. FILE_READ));
  90. String commandLine = commandFile->ReadLine();
  91. commandFile->Close();
  92. ParseArguments(commandLine, false);
  93. // Reparse engine startup parameters now
  94. engineParameters_ = Engine::ParseParameters(GetArguments());
  95. #endif
  96. // Check for script file name
  97. const Vector<String>& arguments = GetArguments();
  98. for (unsigned i = 0; i < arguments.Size(); ++i)
  99. {
  100. if (arguments[i][0] != '-')
  101. {
  102. scriptFileName_ = GetInternalPath(arguments[i]);
  103. break;
  104. }
  105. }
  106. #ifdef EMSCRIPTEN
  107. engineParameters_["WindowWidth"] = 1280;
  108. engineParameters_["WindowHeight"] = 720;
  109. engineParameters_["FullScreen"] = false;
  110. scriptFileName_ = "PhysicsPlatformer.js";
  111. #else
  112. // TODO: FIX!
  113. #if !defined(ANDROID)
  114. //GetSubsystem<TBUI>()->SetInputDisabled(true);
  115. //GetSubsystem<TBUI>()->FadeOut(.1f);
  116. #else
  117. scriptFileName_ = "PhysicsPlatformer.js";
  118. #endif
  119. #endif
  120. scriptFileName_ = "Script/Main.js";
  121. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  122. engineParameters_["ResourcePaths"] = "AtomicResources";
  123. engineParameters_["WindowTitle"] = "AtomicPlayer";
  124. engineParameters_["FullScreen"] = false;
  125. engineParameters_["WindowWidth"] = 1280;
  126. engineParameters_["WindowHeight"] = 720;
  127. #ifdef __APPLE__
  128. engineParameters_["ResourcePrefixPath"] = "../Resources";
  129. #endif
  130. // Show usage if not found
  131. if (scriptFileName_.Empty())
  132. {
  133. ErrorExit("Usage: AtomicPlayer <scriptfile> [options]\n\n"
  134. "The script file should implement the function void Start() for initializing the "
  135. "application and subscribing to all necessary events, such as the frame update.\n"
  136. #ifndef WIN32
  137. "\nCommand line options:\n"
  138. "-x <res> Horizontal resolution\n"
  139. "-y <res> Vertical resolution\n"
  140. "-m <level> Enable hardware multisampling\n"
  141. "-v Enable vertical sync\n"
  142. "-t Enable triple buffering\n"
  143. "-w Start in windowed mode\n"
  144. "-s Enable resizing when in windowed mode\n"
  145. "-q Enable quiet mode which does not log to standard output stream\n"
  146. "-b <length> Sound buffer length in milliseconds\n"
  147. "-r <freq> Sound mixing frequency in Hz\n"
  148. "-p <paths> Resource path(s) to use, separated by semicolons\n"
  149. "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n"
  150. "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n"
  151. "-ds <file> Dump used shader variations to a file for precaching\n"
  152. "-mq <level> Material quality level, default 2 (high)\n"
  153. "-tq <level> Texture quality level, default 2 (high)\n"
  154. "-tf <level> Texture filter mode, default 2 (trilinear)\n"
  155. "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n"
  156. "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D9\n"
  157. "-borderless Borderless window mode\n"
  158. "-headless Headless mode. No application window will be created\n"
  159. "-landscape Use landscape orientations (iOS only, default)\n"
  160. "-portrait Use portrait orientations (iOS only)\n"
  161. "-prepass Use light pre-pass rendering\n"
  162. "-deferred Use deferred rendering\n"
  163. "-lqshadows Use low-quality (1-sample) shadow filtering\n"
  164. "-noshadows Disable shadow rendering\n"
  165. "-nolimit Disable frame limiter\n"
  166. "-nothreads Disable worker threads\n"
  167. "-nosound Disable sound output\n"
  168. "-noip Disable sound mixing interpolation\n"
  169. "-sm2 Force SM2.0 rendering\n"
  170. "-touch Touch emulation on desktop platform\n"
  171. #endif
  172. );
  173. }
  174. else
  175. {
  176. // Use the script file name as the base name for the log file
  177. engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log";
  178. }
  179. }
  180. void AtomicPlayer::Start()
  181. {
  182. String extension = GetExtension(scriptFileName_);
  183. if (extension == ".js")
  184. {
  185. // Instantiate and register the Javascript subsystem
  186. javascript = new Javascript(context_);
  187. context_->RegisterSubsystem(javascript);
  188. vm = javascript->InstantiateVM("MainVM");
  189. vm->SetModuleSearchPath("Modules");
  190. duk_eval_string_noresult(vm->GetJSContext(), "require(\"AtomicGame\");");
  191. // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
  192. jsFile_ = GetSubsystem<ResourceCache>()->GetResource<JSFile>(scriptFileName_);
  193. // TODO: Live Reload
  194. // Subscribe to script's reload event to allow live-reload of the application
  195. //SubscribeToEvent(jsFile_, E_RELOADSTARTED, HANDLER(AtomicPlayer, HandleScriptReloadStarted));
  196. //SubscribeToEvent(jsFile_, E_RELOADFINISHED, HANDLER(AtomicPlayer, HandleScriptReloadFinished));
  197. //SubscribeToEvent(jsFile_, E_RELOADFAILED, HANDLER(AtomicPlayer, HandleScriptReloadFailed));
  198. if (jsFile_)
  199. {
  200. bool ok = vm->ExecuteFile(jsFile_);
  201. if (!ok)
  202. {
  203. ErrorExit("Error executing Javascript file");
  204. return;
  205. }
  206. LOGINFOF("Starting %s", scriptFileName_.CString());
  207. vm->ExecuteFunction("Start");
  208. }
  209. else
  210. {
  211. ErrorExit("Error loading Javascript file");
  212. return;
  213. }
  214. return;
  215. //javascript->ShutdownVM("MainVM");
  216. }
  217. // The script was not successfully loaded. Show the last error message and do not run the main loop
  218. ErrorExit();
  219. }
  220. void AtomicPlayer::Stop()
  221. {
  222. context_->RemoveSubsystem<Javascript>();
  223. /*
  224. LuaScript* luaScript = GetSubsystem<LuaScript>();
  225. if (luaScript && luaScript->GetFunction("Stop", true))
  226. luaScript->ExecuteFunction("Stop");
  227. */
  228. }
  229. void AtomicPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)
  230. {
  231. }
  232. void AtomicPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)
  233. {
  234. }
  235. void AtomicPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)
  236. {
  237. ErrorExit();
  238. }