AtomicPlayer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. /*
  88. #if defined(ANDROID) || defined(IOS)
  89. SharedPtr<File> commandFile(new File(context_, filesystem->GetProgramDir() + "Data/CommandLine.txt",
  90. FILE_READ));
  91. String commandLine = commandFile->ReadLine();
  92. commandFile->Close();
  93. ParseArguments(commandLine, false);
  94. // Reparse engine startup parameters now
  95. engineParameters_ = Engine::ParseParameters(GetArguments());
  96. #endif
  97. */
  98. // Check for script file name
  99. const Vector<String>& arguments = GetArguments();
  100. for (unsigned i = 0; i < arguments.Size(); ++i)
  101. {
  102. if (arguments[i][0] != '-')
  103. {
  104. scriptFileName_ = GetInternalPath(arguments[i]);
  105. break;
  106. }
  107. }
  108. #ifdef EMSCRIPTEN
  109. engineParameters_["WindowWidth"] = 1280;
  110. engineParameters_["WindowHeight"] = 720;
  111. engineParameters_["FullScreen"] = false;
  112. scriptFileName_ = "PhysicsPlatformer.js";
  113. #endif
  114. scriptFileName_ = "Script/Main.js";
  115. FileSystem* fileSystem = GetSubsystem<FileSystem>();
  116. engineParameters_["WindowTitle"] = "AtomicPlayer";
  117. #if (ATOMIC_PLATFORM_ANDROID)
  118. engineParameters_["FullScreen"] = true;
  119. engineParameters_["ResourcePaths"] = "CoreData;Data;AtomicResources";
  120. #else
  121. engineParameters_["ResourcePaths"] = "AtomicResources";
  122. engineParameters_["FullScreen"] = false;
  123. engineParameters_["WindowWidth"] = 1280;
  124. engineParameters_["WindowHeight"] = 720;
  125. #endif
  126. #if ATOMIC_PLATFORM_WINDOWS
  127. engineParameters_["ResourcePrefixPath"] = "AtomicPlayer_Resources";
  128. #elif ATOMIC_PLATFORM_ANDROID
  129. //engineParameters_["ResourcePrefixPath"] = "assets";
  130. #elif ATOMIC_PLATFORM_OSX
  131. engineParameters_["ResourcePrefixPath"] = "../Resources";
  132. #endif
  133. // Show usage if not found
  134. if (scriptFileName_.Empty())
  135. {
  136. ErrorExit("Usage: AtomicPlayer <scriptfile> [options]\n\n"
  137. "The script file should implement the function void Start() for initializing the "
  138. "application and subscribing to all necessary events, such as the frame update.\n"
  139. #ifndef WIN32
  140. "\nCommand line options:\n"
  141. "-x <res> Horizontal resolution\n"
  142. "-y <res> Vertical resolution\n"
  143. "-m <level> Enable hardware multisampling\n"
  144. "-v Enable vertical sync\n"
  145. "-t Enable triple buffering\n"
  146. "-w Start in windowed mode\n"
  147. "-s Enable resizing when in windowed mode\n"
  148. "-q Enable quiet mode which does not log to standard output stream\n"
  149. "-b <length> Sound buffer length in milliseconds\n"
  150. "-r <freq> Sound mixing frequency in Hz\n"
  151. "-p <paths> Resource path(s) to use, separated by semicolons\n"
  152. "-ap <paths> Autoload resource path(s) to use, seperated by semicolons\n"
  153. "-log <level> Change the log level, valid 'level' values are 'debug', 'info', 'warning', 'error'\n"
  154. "-ds <file> Dump used shader variations to a file for precaching\n"
  155. "-mq <level> Material quality level, default 2 (high)\n"
  156. "-tq <level> Texture quality level, default 2 (high)\n"
  157. "-tf <level> Texture filter mode, default 2 (trilinear)\n"
  158. "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n"
  159. "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D9\n"
  160. "-borderless Borderless window mode\n"
  161. "-headless Headless mode. No application window will be created\n"
  162. "-landscape Use landscape orientations (iOS only, default)\n"
  163. "-portrait Use portrait orientations (iOS only)\n"
  164. "-prepass Use light pre-pass rendering\n"
  165. "-deferred Use deferred rendering\n"
  166. "-lqshadows Use low-quality (1-sample) shadow filtering\n"
  167. "-noshadows Disable shadow rendering\n"
  168. "-nolimit Disable frame limiter\n"
  169. "-nothreads Disable worker threads\n"
  170. "-nosound Disable sound output\n"
  171. "-noip Disable sound mixing interpolation\n"
  172. "-sm2 Force SM2.0 rendering\n"
  173. "-touch Touch emulation on desktop platform\n"
  174. #endif
  175. );
  176. }
  177. else
  178. {
  179. // Use the script file name as the base name for the log file
  180. engineParameters_["LogName"] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log";
  181. }
  182. }
  183. void AtomicPlayer::Start()
  184. {
  185. String extension = GetExtension(scriptFileName_);
  186. if (extension == ".js")
  187. {
  188. // Instantiate and register the Javascript subsystem
  189. javascript = new Javascript(context_);
  190. context_->RegisterSubsystem(javascript);
  191. vm = javascript->InstantiateVM("MainVM");
  192. vm->SetModuleSearchPath("Modules");
  193. duk_eval_string_noresult(vm->GetJSContext(), "require(\"AtomicGame\");");
  194. // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
  195. jsFile_ = GetSubsystem<ResourceCache>()->GetResource<JSFile>(scriptFileName_);
  196. // TODO: Live Reload
  197. // Subscribe to script's reload event to allow live-reload of the application
  198. //SubscribeToEvent(jsFile_, E_RELOADSTARTED, HANDLER(AtomicPlayer, HandleScriptReloadStarted));
  199. //SubscribeToEvent(jsFile_, E_RELOADFINISHED, HANDLER(AtomicPlayer, HandleScriptReloadFinished));
  200. //SubscribeToEvent(jsFile_, E_RELOADFAILED, HANDLER(AtomicPlayer, HandleScriptReloadFailed));
  201. if (jsFile_)
  202. {
  203. bool ok = vm->ExecuteFile(jsFile_);
  204. if (!ok)
  205. {
  206. ErrorExit("Error executing Javascript file");
  207. return;
  208. }
  209. LOGINFOF("Starting %s", scriptFileName_.CString());
  210. vm->ExecuteFunction("Start");
  211. }
  212. else
  213. {
  214. LOGERROR("Poop");
  215. ErrorExit("Error loading Javascript file");
  216. return;
  217. }
  218. return;
  219. //javascript->ShutdownVM("MainVM");
  220. }
  221. // The script was not successfully loaded. Show the last error message and do not run the main loop
  222. ErrorExit();
  223. }
  224. void AtomicPlayer::Stop()
  225. {
  226. context_->RemoveSubsystem<Javascript>();
  227. /*
  228. LuaScript* luaScript = GetSubsystem<LuaScript>();
  229. if (luaScript && luaScript->GetFunction("Stop", true))
  230. luaScript->ExecuteFunction("Stop");
  231. */
  232. }
  233. void AtomicPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)
  234. {
  235. }
  236. void AtomicPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)
  237. {
  238. }
  239. void AtomicPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)
  240. {
  241. ErrorExit();
  242. }