Urho3DPlayer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #ifdef URHO3D_ANGELSCRIPT
  4. #include <Urho3D/AngelScript/ScriptFile.h>
  5. #include <Urho3D/AngelScript/Script.h>
  6. #endif
  7. #include <Urho3D/Core/Main.h>
  8. #include <Urho3D/Engine/Engine.h>
  9. #include <Urho3D/Engine/EngineDefs.h>
  10. #include <Urho3D/IO/FileSystem.h>
  11. #include <Urho3D/IO/Log.h>
  12. #ifdef URHO3D_LUA
  13. #include <Urho3D/LuaScript/LuaScript.h>
  14. #endif
  15. #include <Urho3D/Resource/ResourceCache.h>
  16. #include <Urho3D/Resource/ResourceEvents.h>
  17. #include "Urho3DPlayer.h"
  18. #include <Urho3D/DebugNew.h>
  19. URHO3D_DEFINE_APPLICATION_MAIN(Urho3DPlayer);
  20. Urho3DPlayer::Urho3DPlayer(Context* context) :
  21. Application(context),
  22. commandLineRead_(false)
  23. {
  24. }
  25. void Urho3DPlayer::Setup()
  26. {
  27. // Web platform depends on the resource system to read any data files. Skip parsing the command line file now
  28. // and try later when the resource system is live
  29. #ifndef __EMSCRIPTEN__
  30. // Read command line from a file if no arguments given. This is primarily intended for mobile platforms.
  31. // Note that the command file name uses a hardcoded path that does not utilize the resource system
  32. // properly (including resource path prefix), as the resource system is not yet initialized at this point
  33. auto* filesystem = GetSubsystem<FileSystem>();
  34. const String commandFileName = filesystem->GetProgramDir() + "Data/CommandLine.txt";
  35. if (GetArguments().Empty() && filesystem->FileExists(commandFileName))
  36. {
  37. SharedPtr<File> commandFile(new File(context_, commandFileName));
  38. if (commandFile->IsOpen())
  39. {
  40. commandLineRead_ = true;
  41. String commandLine = commandFile->ReadLine();
  42. commandFile->Close();
  43. ParseArguments(commandLine, false);
  44. // Reparse engine startup parameters now
  45. engineParameters_ = Engine::ParseParameters(GetArguments());
  46. }
  47. }
  48. #endif
  49. // Check for script file name from the arguments
  50. GetScriptFileName();
  51. #ifndef __EMSCRIPTEN__
  52. // Show usage if not found
  53. if ((GetArguments().Size() || commandLineRead_) && scriptFileName_.Empty())
  54. {
  55. ErrorExit("Usage: Urho3DPlayer <scriptfile> [options]\n\n"
  56. "The script file should implement the function void Start() for initializing the "
  57. "application and subscribing to all necessary events, such as the frame update.\n"
  58. #ifndef _WIN32
  59. "\nCommand line options:\n"
  60. "-x <res> Horizontal resolution\n"
  61. "-y <res> Vertical resolution\n"
  62. "-m <level> Enable hardware multisampling\n"
  63. "-v Enable vertical sync\n"
  64. "-t Enable triple buffering\n"
  65. "-w Start in windowed mode\n"
  66. "-s Enable resizing when in windowed mode\n"
  67. "-q Enable quiet mode which does not log to standard output stream\n"
  68. "-b <length> Sound buffer length in milliseconds\n"
  69. "-r <freq> Sound mixing frequency in Hz\n"
  70. "-pp <paths> Resource prefix path(s), separated by semicolons, default to executable path\n"
  71. "The resource prefix paths can also be defined using URHO3D_PREFIX_PATH env - var\n"
  72. "When both are defined, the paths set by -pp takes higher precedence\n"
  73. "-p <paths> Resource path(s) to use, separated by semicolons, default to 'Data;CoreData'\n"
  74. "-pf <files> Resource package file to use, separated by semicolons, default to none\n"
  75. "-ap <paths> Resource autoload path(s), separated by semicolons, default to 'AutoLoad'\n"
  76. "-log <level> Change the log level, valid 'level' values: 'debug', 'info', 'warning', 'error'\n"
  77. "-ds <file> Dump used shader variations to a file for precaching\n"
  78. "-mq <level> Material quality level, default 2 (high)\n"
  79. "-tq <level> Texture quality level, default 2 (high)\n"
  80. "-tf <level> Texture filter mode, default 2 (trilinear)\n"
  81. "-af <level> Texture anisotropy level, default 4. Also sets anisotropic filter mode\n"
  82. "-gl2 Force OpenGL 2 use even if OpenGL 3 is available\n"
  83. "-flushgpu Flush GPU command queue each frame. Effective only on Direct3D\n"
  84. "-borderless Borderless window mode\n"
  85. "-lowdpi Force low DPI mode on Retina display\n"
  86. "-headless Headless mode. No application window will be created\n"
  87. "-landscape Use landscape orientations (iOS only, default)\n"
  88. "-portrait Use portrait orientations (iOS only)\n"
  89. "-monitor <num> Monitor number to use\n"
  90. "-hz <freq> Monitor refresh rate to use\n"
  91. "-prepass Use light pre-pass rendering\n"
  92. "-deferred Use deferred rendering\n"
  93. "-renderpath <name> Use the named renderpath (must enter full resource name)\n"
  94. "-lqshadows Use low-quality (1-sample) shadow filtering\n"
  95. "-noshadows Disable shadow rendering\n"
  96. "-nolimit Disable frame limiter\n"
  97. "-nothreads Disable worker threads\n"
  98. "-nosound Disable sound output\n"
  99. "-noip Disable sound mixing interpolation\n"
  100. "-touch Touch emulation on desktop platform\n"
  101. #endif
  102. );
  103. }
  104. else
  105. {
  106. // Use the script file name as the base name for the log file
  107. engineParameters_[EP_LOG_NAME] = filesystem->GetAppPreferencesDir("urho3d", "logs") + GetFileNameAndExtension(scriptFileName_) + ".log";
  108. }
  109. #else
  110. // On Web platform setup a default windowed resolution similar to the executable samples
  111. engineParameters_[EP_FULL_SCREEN] = false;
  112. #endif
  113. // Construct a search path to find the resource prefix with two entries:
  114. // The first entry is an empty path which will be substituted with program/bin directory -- this entry is for binary when it is still in build tree
  115. // The second and third entries are possible relative paths from the installed program/bin directory to the asset directory -- these entries are for binary when it is in the Urho3D SDK installation location
  116. if (!engineParameters_.Contains(EP_RESOURCE_PREFIX_PATHS))
  117. engineParameters_[EP_RESOURCE_PREFIX_PATHS] = ";../share/Resources;../share/Urho3D/Resources";
  118. }
  119. void Urho3DPlayer::Start()
  120. {
  121. // Reattempt reading the command line from the resource system now if not read before
  122. // Note that the engine can not be reconfigured at this point; only the script name can be specified
  123. if (GetArguments().Empty() && !commandLineRead_)
  124. {
  125. SharedPtr<File> commandFile = GetSubsystem<ResourceCache>()->GetFile("CommandLine.txt", false);
  126. if (commandFile)
  127. {
  128. String commandLine = commandFile->ReadLine();
  129. commandFile->Close();
  130. ParseArguments(commandLine, false);
  131. }
  132. GetScriptFileName();
  133. }
  134. if (scriptFileName_.Empty())
  135. {
  136. ErrorExit("Script file name not specified; cannot proceed");
  137. return;
  138. }
  139. String extension = GetExtension(scriptFileName_);
  140. if (extension != ".lua" && extension != ".luc")
  141. {
  142. #ifdef URHO3D_ANGELSCRIPT
  143. // Instantiate and register the AngelScript subsystem
  144. context_->RegisterSubsystem(new Script(context_));
  145. // Hold a shared pointer to the script file to make sure it is not unloaded during runtime
  146. scriptFile_ = GetSubsystem<ResourceCache>()->GetResource<ScriptFile>(scriptFileName_);
  147. /// \hack If we are running the editor, also instantiate Lua subsystem to enable editing Lua ScriptInstances
  148. #ifdef URHO3D_LUA
  149. if (scriptFileName_.Contains("Editor.as", false))
  150. context_->RegisterSubsystem(new LuaScript(context_));
  151. #endif
  152. // If script loading is successful, proceed to main loop
  153. if (scriptFile_ && scriptFile_->Execute("void Start()"))
  154. {
  155. // Subscribe to script's reload event to allow live-reload of the application
  156. SubscribeToEvent(scriptFile_, E_RELOADSTARTED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadStarted));
  157. SubscribeToEvent(scriptFile_, E_RELOADFINISHED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFinished));
  158. SubscribeToEvent(scriptFile_, E_RELOADFAILED, URHO3D_HANDLER(Urho3DPlayer, HandleScriptReloadFailed));
  159. return;
  160. }
  161. #else
  162. ErrorExit("AngelScript is not enabled!");
  163. return;
  164. #endif
  165. }
  166. else
  167. {
  168. #ifdef URHO3D_LUA
  169. // Instantiate and register the Lua script subsystem
  170. auto* luaScript = new LuaScript(context_);
  171. context_->RegisterSubsystem(luaScript);
  172. // If script loading is successful, proceed to main loop
  173. if (luaScript->ExecuteFile(scriptFileName_))
  174. {
  175. luaScript->ExecuteFunction("Start");
  176. return;
  177. }
  178. #else
  179. ErrorExit("Lua is not enabled!");
  180. return;
  181. #endif
  182. }
  183. // The script was not successfully loaded. Show the last error message and do not run the main loop
  184. ErrorExit();
  185. }
  186. void Urho3DPlayer::Stop()
  187. {
  188. #ifdef URHO3D_ANGELSCRIPT
  189. if (scriptFile_)
  190. {
  191. // Execute the optional stop function
  192. if (scriptFile_->GetFunction("void Stop()"))
  193. scriptFile_->Execute("void Stop()");
  194. }
  195. #else
  196. if (false)
  197. {
  198. }
  199. #endif
  200. #ifdef URHO3D_LUA
  201. else
  202. {
  203. auto* luaScript = GetSubsystem<LuaScript>();
  204. if (luaScript && luaScript->GetFunction("Stop", true))
  205. luaScript->ExecuteFunction("Stop");
  206. }
  207. #endif
  208. }
  209. void Urho3DPlayer::HandleScriptReloadStarted(StringHash eventType, VariantMap& eventData)
  210. {
  211. #ifdef URHO3D_ANGELSCRIPT
  212. if (scriptFile_->GetFunction("void Stop()"))
  213. scriptFile_->Execute("void Stop()");
  214. #endif
  215. }
  216. void Urho3DPlayer::HandleScriptReloadFinished(StringHash eventType, VariantMap& eventData)
  217. {
  218. #ifdef URHO3D_ANGELSCRIPT
  219. // Restart the script application after reload
  220. if (!scriptFile_->Execute("void Start()"))
  221. {
  222. scriptFile_.Reset();
  223. ErrorExit();
  224. }
  225. #endif
  226. }
  227. void Urho3DPlayer::HandleScriptReloadFailed(StringHash eventType, VariantMap& eventData)
  228. {
  229. #ifdef URHO3D_ANGELSCRIPT
  230. scriptFile_.Reset();
  231. ErrorExit();
  232. #endif
  233. }
  234. void Urho3DPlayer::GetScriptFileName()
  235. {
  236. const Vector<String>& arguments = GetArguments();
  237. if (arguments.Size() && arguments[0][0] != '-')
  238. scriptFileName_ = GetInternalPath(arguments[0]);
  239. }