PageRenderTime 37ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/main/main.cpp

https://github.com/zzyclark/godot
C++ | 1450 lines | 982 code | 399 blank | 69 comment | 316 complexity | 38e2785cc95018546c4a8005f5e62d8f MD5 | raw file
  1. /*************************************************************************/
  2. /* main.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  9. /* */
  10. /* Permission is hereby granted, free of charge, to any person obtaining */
  11. /* a copy of this software and associated documentation files (the */
  12. /* "Software"), to deal in the Software without restriction, including */
  13. /* without limitation the rights to use, copy, modify, merge, publish, */
  14. /* distribute, sublicense, and/or sell copies of the Software, and to */
  15. /* permit persons to whom the Software is furnished to do so, subject to */
  16. /* the following conditions: */
  17. /* */
  18. /* The above copyright notice and this permission notice shall be */
  19. /* included in all copies or substantial portions of the Software. */
  20. /* */
  21. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  22. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  23. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  24. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  25. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  26. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  27. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  28. /*************************************************************************/
  29. #include "main.h"
  30. #include "os/os.h"
  31. #include "globals.h"
  32. #include "splash.h"
  33. #include "core/register_core_types.h"
  34. #include "scene/register_scene_types.h"
  35. #include "drivers/register_driver_types.h"
  36. #include "servers/register_server_types.h"
  37. #include "modules/register_module_types.h"
  38. #include "script_debugger_local.h"
  39. #include "script_debugger_remote.h"
  40. #include "message_queue.h"
  41. #include "path_remap.h"
  42. #include "input_map.h"
  43. #include "io/resource_loader.h"
  44. #include "scene/main/scene_main_loop.h"
  45. #include "scene/io/scene_loader.h"
  46. #include "script_language.h"
  47. #include "io/resource_loader.h"
  48. #include "bin/tests/test_main.h"
  49. #include "os/dir_access.h"
  50. #include "core/io/ip.h"
  51. #include "scene/resources/packed_scene.h"
  52. #include "scene/main/viewport.h"
  53. #ifdef TOOLS_ENABLED
  54. #include "tools/editor/editor_node.h"
  55. #include "tools/editor/project_manager.h"
  56. #include "tools/editor/console.h"
  57. #endif
  58. #include "io/file_access_network.h"
  59. #include "tools/doc/doc_data.h"
  60. #include "servers/spatial_sound_server.h"
  61. #include "servers/spatial_sound_2d_server.h"
  62. #include "servers/physics_2d_server.h"
  63. #include "core/io/stream_peer_tcp.h"
  64. #include "core/os/thread.h"
  65. #include "core/io/file_access_pack.h"
  66. #include "core/io/file_access_zip.h"
  67. #include "translation.h"
  68. #include "version.h"
  69. #include "performance.h"
  70. static Globals *globals=NULL;
  71. static InputMap *input_map=NULL;
  72. static bool _start_success=false;
  73. static ScriptDebugger *script_debugger=NULL;
  74. static MessageQueue *message_queue=NULL;
  75. static Performance *performance = NULL;
  76. static PathRemap *path_remap;
  77. static PackedData *packed_data=NULL;
  78. static FileAccessNetworkClient *file_access_network_client=NULL;
  79. static TranslationServer *translation_server = NULL;
  80. static OS::VideoMode video_mode;
  81. static int video_driver_idx=-1;
  82. static int audio_driver_idx=-1;
  83. static String locale;
  84. static String unescape_cmdline(const String& p_str) {
  85. return p_str.replace("%20"," ");
  86. }
  87. //#define DEBUG_INIT
  88. #ifdef DEBUG_INIT
  89. #define MAIN_PRINT(m_txt) print_line(m_txt)
  90. #else
  91. #define MAIN_PRINT(m_txt)
  92. #endif
  93. void Main::print_help(const char* p_binary) {
  94. OS::get_singleton()->print(VERSION_FULL_NAME" (c) 2008-2010 Juan Linietsky, Ariel Manzur.\n");
  95. OS::get_singleton()->print("Usage: %s [options] [scene]\n",p_binary);
  96. OS::get_singleton()->print("Options:\n");
  97. OS::get_singleton()->print("\t-path [dir] : Path to a game, containing engine.cfg\n");
  98. #ifdef TOOLS_ENABLED
  99. OS::get_singleton()->print("\t-e,-editor : Bring up the editor instead of running the scene.\n");
  100. #endif
  101. OS::get_singleton()->print("\t-test [test] : Run a test.\n");
  102. OS::get_singleton()->print("\t\t(");
  103. const char **test_names=tests_get_names();
  104. const char* coma = "";
  105. while(*test_names) {
  106. OS::get_singleton()->print("%s%s", coma, *test_names);
  107. test_names++;
  108. coma = ", ";
  109. }
  110. OS::get_singleton()->print(")\n");
  111. OS::get_singleton()->print("\t-r WIDTHxHEIGHT\t : Request Screen Resolution\n");
  112. OS::get_singleton()->print("\t-f\t\t : Request Fullscreen\n");
  113. OS::get_singleton()->print("\t-vd DRIVER\t : Video Driver (");
  114. for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {
  115. if (i!=0)
  116. OS::get_singleton()->print(", ");
  117. OS::get_singleton()->print("%s",OS::get_singleton()->get_video_driver_name(i));
  118. }
  119. OS::get_singleton()->print(")\n");
  120. OS::get_singleton()->print("\t-ad DRIVER\t : Audio Driver (");
  121. for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
  122. if (i!=0)
  123. OS::get_singleton()->print(", ");
  124. OS::get_singleton()->print("%s",OS::get_singleton()->get_audio_driver_name(i));
  125. }
  126. OS::get_singleton()->print("\t-rthread <mode>\t : Render Thread Mode ('unsafe', 'safe', 'separate).");
  127. OS::get_singleton()->print(")\n");
  128. OS::get_singleton()->print("\t-s,-script [script] : Run a script.\n");
  129. OS::get_singleton()->print("\t-d,-debug : Debug (local stdout debugger).\n");
  130. OS::get_singleton()->print("\t-rdebug ADDRESS : Remote debug (<ip>:<port> host address).\n");
  131. OS::get_singleton()->print("\t-fdelay [msec]: Simulate high CPU load (delay each frame by [msec]).\n");
  132. OS::get_singleton()->print("\t-bp : breakpoint list as source::line comma separated pairs, no spaces (%%20,%%2C,etc instead).\n");
  133. OS::get_singleton()->print("\t-v : Verbose stdout mode\n");
  134. OS::get_singleton()->print("\t-lang [locale]: Use a specific locale\n");
  135. OS::get_singleton()->print("\t-rfs <host/ip>[:<port>] : Remote FileSystem.\n");
  136. OS::get_singleton()->print("\t-rfs_pass <password> : Password for Remote FileSystem.\n");
  137. #ifdef TOOLS_ENABLED
  138. OS::get_singleton()->print("\t-doctool FILE: Dump the whole engine api to FILE in XML format. If FILE exists, it will be merged.\n");
  139. OS::get_singleton()->print("\t-nodocbase: Disallow dump the base types (used with -doctool).\n");
  140. OS::get_singleton()->print("\t-optimize FILE Save an optimized copy of scene to FILE.\n");
  141. OS::get_singleton()->print("\t-optimize_preset [preset] Use a given preset for optimization.\n");
  142. OS::get_singleton()->print("\t-export [target] Export the project using given export target.\n");
  143. #endif
  144. }
  145. Error Main::setup(const char *execpath,int argc, char *argv[],bool p_second_phase) {
  146. RID_OwnerBase::init_rid();
  147. OS::get_singleton()->initialize_core();
  148. ObjectTypeDB::init();
  149. MAIN_PRINT("Main: Initialize CORE");
  150. register_core_types();
  151. register_core_driver_types();
  152. MAIN_PRINT("Main: Initialize Globals");
  153. Thread::_main_thread_id = Thread::get_caller_ID();
  154. globals = memnew( Globals );
  155. input_map = memnew( InputMap );
  156. path_remap = memnew( PathRemap );
  157. translation_server = memnew( TranslationServer );
  158. performance = memnew( Performance );
  159. globals->add_singleton(Globals::Singleton("Performance",performance));
  160. MAIN_PRINT("Main: Parse CMDLine");
  161. /* argument parsing and main creation */
  162. List<String> args;
  163. List<String> main_args;
  164. for(int i=0;i<argc;i++) {
  165. args.push_back(String::utf8(argv[i]));
  166. }
  167. List<String>::Element *I=args.front();
  168. I=args.front();
  169. while (I) {
  170. I->get()=unescape_cmdline(I->get().strip_escapes());
  171. // print_line("CMD: "+I->get());
  172. I=I->next();
  173. }
  174. I=args.front();
  175. video_mode = OS::get_singleton()->get_default_video_mode();
  176. String video_driver="";
  177. String audio_driver="";
  178. String game_path=".";
  179. String debug_mode;
  180. String debug_host;
  181. String main_pack;
  182. int rtm=-1;
  183. String remotefs;
  184. String remotefs_pass;
  185. String screen = "";
  186. List<String> pack_list;
  187. Vector<String> breakpoints;
  188. bool use_custom_res=true;
  189. bool force_res=false;
  190. I=args.front();
  191. packed_data = PackedData::get_singleton();
  192. if (!packed_data)
  193. packed_data = memnew(PackedData);
  194. #ifdef MINIZIP_ENABLED
  195. packed_data->add_pack_source(ZipArchive::get_singleton());
  196. #endif
  197. bool editor=false;
  198. while(I) {
  199. List<String>::Element *N=I->next();
  200. if (I->get() == "-noop") {
  201. // no op
  202. } else if (I->get()=="-h" || I->get()=="--help" || I->get()=="/?") { // resolution
  203. goto error;
  204. } else if (I->get()=="-r") { // resolution
  205. if (I->next()) {
  206. String vm=I->next()->get();
  207. if (vm.find("x")==-1) { // invalid parameter format
  208. goto error;
  209. }
  210. int w=vm.get_slice("x",0).to_int();
  211. int h=vm.get_slice("x",1).to_int();
  212. if (w==0 || h==0) {
  213. goto error;
  214. }
  215. video_mode.width=w;
  216. video_mode.height=h;
  217. force_res=true;
  218. N=I->next()->next();
  219. } else {
  220. goto error;
  221. }
  222. } else if (I->get()=="-vd") { // video driver
  223. if (I->next()) {
  224. video_driver=I->next()->get();
  225. N=I->next()->next();
  226. } else {
  227. goto error;
  228. }
  229. } else if (I->get()=="-lang") { // language
  230. if (I->next()) {
  231. locale=I->next()->get();
  232. N=I->next()->next();
  233. } else {
  234. goto error;
  235. }
  236. } else if (I->get()=="-rfs") { // language
  237. if (I->next()) {
  238. remotefs=I->next()->get();
  239. N=I->next()->next();
  240. } else {
  241. goto error;
  242. }
  243. } else if (I->get()=="-rfs_pass") { // language
  244. if (I->next()) {
  245. remotefs_pass=I->next()->get();
  246. N=I->next()->next();
  247. } else {
  248. goto error;
  249. }
  250. } else if (I->get()=="-rthread") { // language
  251. if (I->next()) {
  252. if (I->next()->get()=="safe")
  253. rtm=OS::RENDER_THREAD_SAFE;
  254. else if (I->next()->get()=="unsafe")
  255. rtm=OS::RENDER_THREAD_UNSAFE;
  256. else if (I->next()->get()=="separate")
  257. rtm=OS::RENDER_SEPARATE_THREAD;
  258. N=I->next()->next();
  259. } else {
  260. goto error;
  261. }
  262. } else if (I->get()=="-ad") { // video driver
  263. if (I->next()) {
  264. audio_driver=I->next()->get();
  265. N=I->next()->next();
  266. } else {
  267. goto error;
  268. }
  269. } else if (I->get()=="-f") { // fullscreen
  270. video_mode.fullscreen=true;
  271. } else if (I->get()=="-e" || I->get()=="-editor") { // fonud editor
  272. editor=true;
  273. } else if (I->get()=="-nowindow") { // fullscreen
  274. OS::get_singleton()->set_no_window_mode(true);
  275. } else if (I->get()=="-v") { // fullscreen
  276. OS::get_singleton()->_verbose_stdout=true;
  277. } else if (I->get()=="-path") { // resolution
  278. if (I->next()) {
  279. String p = I->next()->get();
  280. if (OS::get_singleton()->set_cwd(p)==OK) {
  281. //nothing
  282. } else {
  283. game_path=I->next()->get(); //use game_path instead
  284. }
  285. N=I->next()->next();
  286. } else {
  287. goto error;
  288. }
  289. } else if (I->get()=="-bp") { // /breakpoints
  290. if (I->next()) {
  291. String bplist = I->next()->get();
  292. breakpoints= bplist.split(",");
  293. N=I->next()->next();
  294. } else {
  295. goto error;
  296. }
  297. } else if (I->get()=="-fdelay") { // resolution
  298. if (I->next()) {
  299. OS::get_singleton()->set_frame_delay(I->next()->get().to_int());
  300. N=I->next()->next();
  301. } else {
  302. goto error;
  303. }
  304. } else if (I->get() == "-pack") {
  305. if (I->next()) {
  306. pack_list.push_back(I->next()->get());
  307. N = I->next()->next();
  308. } else {
  309. goto error;
  310. };
  311. } else if (I->get() == "-main_pack") {
  312. if (I->next()) {
  313. main_pack=I->next()->get();
  314. N = I->next()->next();
  315. } else {
  316. goto error;
  317. };
  318. } else if (I->get()=="-debug" || I->get()=="-d") {
  319. debug_mode="local";
  320. } else if (I->get()=="-editor_scene") {
  321. if (I->next()) {
  322. Globals::get_singleton()->set("editor_scene",game_path=I->next()->get());
  323. } else {
  324. goto error;
  325. }
  326. } else if (I->get()=="-rdebug") {
  327. if (I->next()) {
  328. debug_mode="remote";
  329. debug_host=I->next()->get();
  330. if (debug_host.find(":")==-1) //wrong host
  331. goto error;
  332. N=I->next()->next();
  333. } else {
  334. goto error;
  335. }
  336. } else {
  337. //test for game path
  338. bool gpfound=false;
  339. if (!I->get().begins_with("-") && game_path=="") {
  340. DirAccess* da = DirAccess::open(I->get());
  341. if (da!=NULL) {
  342. game_path=I->get();
  343. gpfound=true;
  344. memdelete(da);
  345. }
  346. }
  347. if (!gpfound) {
  348. main_args.push_back(I->get());
  349. }
  350. }
  351. I=N;
  352. }
  353. if (debug_mode == "remote") {
  354. ScriptDebuggerRemote *sdr = memnew( ScriptDebuggerRemote );
  355. uint16_t debug_port = GLOBAL_DEF("debug/remote_port",6007);
  356. if (debug_host.find(":")!=-1) {
  357. debug_port=debug_host.get_slice(":",1).to_int();
  358. debug_host=debug_host.get_slice(":",0);
  359. }
  360. Error derr = sdr->connect_to_host(debug_host,debug_port);
  361. if (derr!=OK) {
  362. memdelete(sdr);
  363. } else {
  364. script_debugger=sdr;
  365. }
  366. } else if (debug_mode=="local") {
  367. script_debugger = memnew( ScriptDebuggerLocal );
  368. }
  369. if (remotefs!="") {
  370. file_access_network_client=memnew(FileAccessNetworkClient);
  371. int port;
  372. if (remotefs.find(":")!=-1) {
  373. port=remotefs.get_slice(":",1).to_int();
  374. remotefs=remotefs.get_slice(":",0);
  375. } else {
  376. port=6010;
  377. }
  378. Error err = file_access_network_client->connect(remotefs,port,remotefs_pass);
  379. if (err) {
  380. OS::get_singleton()->printerr("Could not connect to remotefs: %s:%i\n",remotefs.utf8().get_data(),port);
  381. goto error;
  382. }
  383. FileAccess::make_default<FileAccessNetwork>(FileAccess::ACCESS_RESOURCES);
  384. }
  385. if (script_debugger) {
  386. //there is a debugger, parse breakpoints
  387. for(int i=0;i<breakpoints.size();i++) {
  388. String bp = breakpoints[i];
  389. int sp=bp.find_last(":");
  390. if (sp==-1) {
  391. ERR_EXPLAIN("Invalid breakpoint: '"+bp+"', expected file:line format.");
  392. ERR_CONTINUE(sp==-1);
  393. }
  394. script_debugger->insert_breakpoint(bp.substr(sp+1,bp.length()).to_int(),bp.substr(0,sp));
  395. }
  396. }
  397. #ifdef TOOLS_ENABLED
  398. if (editor) {
  399. packed_data->set_disabled(true);
  400. globals->set_disable_platform_override(true);
  401. }
  402. #endif
  403. if (globals->setup(game_path,main_pack)!=OK) {
  404. #ifdef TOOLS_ENABLED
  405. editor=false;
  406. #else
  407. OS::get_singleton()->print("error: Couldn't load game path '%s'\n",game_path.ascii().get_data());
  408. goto error;
  409. #endif
  410. }
  411. if (editor) {
  412. main_args.push_back("-editor");
  413. use_custom_res=false;
  414. }
  415. OS::get_singleton()->set_cmdline(execpath, main_args);
  416. #ifdef TOOLS_ENABLED
  417. if (main_args.size()==0 && (!Globals::get_singleton()->has("application/main_loop_type")) && (!Globals::get_singleton()->has("application/main_scene") || String(Globals::get_singleton()->get("application/main_scene"))==""))
  418. use_custom_res=false; //project manager (run without arguments)
  419. #endif
  420. input_map->load_from_globals();
  421. if (video_driver=="") // specified in engine.cfg
  422. video_driver=_GLOBAL_DEF("display/driver",Variant((const char*)OS::get_singleton()->get_video_driver_name(0)));
  423. if (!force_res && use_custom_res && globals->has("display/width"))
  424. video_mode.width=globals->get("display/width");
  425. if (!force_res &&use_custom_res && globals->has("display/height"))
  426. video_mode.height=globals->get("display/height");
  427. if (use_custom_res && globals->has("display/fullscreen"))
  428. video_mode.fullscreen=globals->get("display/fullscreen");
  429. if (use_custom_res && globals->has("display/resizable"))
  430. video_mode.resizable=globals->get("display/resizable");
  431. GLOBAL_DEF("display/width",video_mode.width);
  432. GLOBAL_DEF("display/height",video_mode.height);
  433. GLOBAL_DEF("display/fullscreen",video_mode.fullscreen);
  434. GLOBAL_DEF("display/resizable",video_mode.resizable);
  435. if (rtm==-1) {
  436. rtm=GLOBAL_DEF("render/thread_model",OS::RENDER_THREAD_SAFE);
  437. }
  438. if (rtm>=0 && rtm<3)
  439. OS::get_singleton()->_render_thread_mode=OS::RenderThreadMode(rtm);
  440. /* Determine Video Driver */
  441. if (audio_driver=="") // specified in engine.cfg
  442. audio_driver=GLOBAL_DEF("audio/driver",OS::get_singleton()->get_audio_driver_name(0));
  443. for (int i=0;i<OS::get_singleton()->get_video_driver_count();i++) {
  444. if (video_driver==OS::get_singleton()->get_video_driver_name(i)) {
  445. video_driver_idx=i;
  446. break;
  447. }
  448. }
  449. if (video_driver_idx<0) {
  450. OS::get_singleton()->alert( "Invalid Video Driver: "+video_driver );
  451. video_driver_idx = 0;
  452. //goto error;
  453. }
  454. for (int i=0;i<OS::get_singleton()->get_audio_driver_count();i++) {
  455. if (audio_driver==OS::get_singleton()->get_audio_driver_name(i)) {
  456. audio_driver_idx=i;
  457. break;
  458. }
  459. }
  460. if (audio_driver_idx<0) {
  461. OS::get_singleton()->alert( "Invalid Audio Driver: "+audio_driver );
  462. goto error;
  463. }
  464. {
  465. String orientation = GLOBAL_DEF("display/orientation","landscape");
  466. if (orientation=="portrait")
  467. OS::get_singleton()->set_screen_orientation(OS::SCREEN_PORTRAIT);
  468. else if (orientation=="reverse_landscape")
  469. OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_LANDSCAPE);
  470. else if (orientation=="reverse_portrait")
  471. OS::get_singleton()->set_screen_orientation(OS::SCREEN_REVERSE_PORTRAIT);
  472. else if (orientation=="sensor_landscape")
  473. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_LANDSCAPE);
  474. else if (orientation=="sensor_portrait")
  475. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR_PORTRAIT);
  476. else if (orientation=="sensor")
  477. OS::get_singleton()->set_screen_orientation(OS::SCREEN_SENSOR);
  478. else
  479. OS::get_singleton()->set_screen_orientation(OS::SCREEN_LANDSCAPE);
  480. }
  481. OS::get_singleton()->set_iterations_per_second(GLOBAL_DEF("physics/fixed_fps",60));
  482. OS::get_singleton()->set_target_fps(GLOBAL_DEF("application/target_fps",0));
  483. if (!OS::get_singleton()->_verbose_stdout) //overrided
  484. OS::get_singleton()->_verbose_stdout=GLOBAL_DEF("debug/verbose_stdout",false);
  485. message_queue = memnew( MessageQueue );
  486. Globals::get_singleton()->register_global_defaults();
  487. if (p_second_phase)
  488. return setup2();
  489. return OK;
  490. error:
  491. video_driver="";
  492. audio_driver="";
  493. game_path="";
  494. args.clear();
  495. main_args.clear();
  496. print_help(execpath);
  497. if (performance)
  498. memdelete(performance);
  499. if (input_map)
  500. memdelete(input_map);
  501. if (translation_server)
  502. memdelete( translation_server );
  503. if (globals)
  504. memdelete(globals);
  505. if (script_debugger)
  506. memdelete(script_debugger);
  507. if (packed_data)
  508. memdelete(packed_data);
  509. if (file_access_network_client)
  510. memdelete(file_access_network_client);
  511. unregister_core_types();
  512. OS::get_singleton()->_cmdline.clear();
  513. if (message_queue)
  514. memdelete( message_queue);
  515. OS::get_singleton()->finalize_core();
  516. locale=String();
  517. return ERR_INVALID_PARAMETER;
  518. }
  519. Error Main::setup2() {
  520. OS::get_singleton()->initialize(video_mode,video_driver_idx,audio_driver_idx);
  521. register_core_singletons();
  522. MAIN_PRINT("Main: Setup Logo");
  523. bool show_logo=true;
  524. #ifdef JAVASCRIPT_ENABLED
  525. show_logo=false;
  526. #endif
  527. if (show_logo) { //boot logo!
  528. Image boot_logo=GLOBAL_DEF("application/boot_logo",Image());
  529. if (!boot_logo.empty()) {
  530. Color clear = GLOBAL_DEF("render/default_clear_color",Color(0.3,0.3,0.3));
  531. VisualServer::get_singleton()->set_default_clear_color(clear);
  532. Color boot_bg = GLOBAL_DEF("application/boot_bg_color", clear);
  533. VisualServer::get_singleton()->set_boot_image(boot_logo, boot_bg);
  534. #ifndef TOOLS_ENABLED
  535. //no tools, so free the boot logo (no longer needed)
  536. Globals::get_singleton()->set("application/boot_logo",Image());
  537. #endif
  538. } else {
  539. #ifndef NO_DEFAULT_BOOT_LOGO
  540. MAIN_PRINT("Main: Create botsplash");
  541. Image splash(boot_splash_png);
  542. MAIN_PRINT("Main: ClearColor");
  543. VisualServer::get_singleton()->set_default_clear_color(boot_splash_bg_color);
  544. MAIN_PRINT("Main: Image");
  545. VisualServer::get_singleton()->set_boot_image(splash, boot_splash_bg_color);
  546. #endif
  547. MAIN_PRINT("Main: DCC");
  548. VisualServer::get_singleton()->set_default_clear_color(GLOBAL_DEF("render/default_clear_color",Color(0.3,0.3,0.3)));
  549. MAIN_PRINT("Main: END");
  550. }
  551. Image icon(app_icon_png);
  552. OS::get_singleton()->set_icon(icon);
  553. }
  554. GLOBAL_DEF("application/icon",String());
  555. Globals::get_singleton()->set_custom_property_info("application/icon",PropertyInfo(Variant::STRING,"application/icon",PROPERTY_HINT_FILE,"*.png,*.webp"));
  556. MAIN_PRINT("Main: Load Remaps");
  557. path_remap->load_remaps();
  558. MAIN_PRINT("Main: Load Scene Types");
  559. register_scene_types();
  560. register_server_types();
  561. #ifdef TOOLS_ENABLED
  562. EditorNode::register_editor_types();
  563. #endif
  564. MAIN_PRINT("Main: Load Scripts, Modules, Drivers");
  565. register_module_types();
  566. register_driver_types();
  567. MAIN_PRINT("Main: Load Translations");
  568. translation_server->setup(); //register translations, load them, etc.
  569. if (locale!="") {
  570. translation_server->set_locale(locale);
  571. }
  572. translation_server->load_translations();
  573. _start_success=true;
  574. locale=String();
  575. MAIN_PRINT("Main: Done");
  576. return OK;
  577. }
  578. bool Main::start() {
  579. ERR_FAIL_COND_V(!_start_success,false);
  580. bool editor=false;
  581. String doc_tool;
  582. bool doc_base=true;
  583. String game_path;
  584. String script;
  585. String test;
  586. String screen;
  587. String optimize;
  588. String optimize_preset;
  589. String _export_platform;
  590. String _import;
  591. String _import_script;
  592. String dumpstrings;
  593. bool noquit=false;
  594. bool convert_old=false;
  595. bool export_debug=false;
  596. List<String> args = OS::get_singleton()->get_cmdline_args();
  597. for (int i=0;i<args.size();i++) {
  598. if (args[i]=="-doctool" && i <(args.size()-1)) {
  599. doc_tool=args[i+1];
  600. i++;
  601. }else if (args[i]=="-nodocbase") {
  602. doc_base=false;
  603. } else if ((args[i]=="-script" || args[i]=="-s") && i <(args.size()-1)) {
  604. script=args[i+1];
  605. i++;
  606. } else if ((args[i]=="-level" || args[i]=="-l") && i <(args.size()-1)) {
  607. OS::get_singleton()->_custom_level=args[i+1];
  608. i++;
  609. } else if (args[i]=="-test" && i <(args.size()-1)) {
  610. test=args[i+1];
  611. i++;
  612. } else if (args[i]=="-optimize" && i <(args.size()-1)) {
  613. optimize=args[i+1];
  614. i++;
  615. } else if (args[i]=="-optimize_preset" && i <(args.size()-1)) {
  616. optimize_preset=args[i+1];
  617. i++;
  618. } else if (args[i]=="-export" && i <(args.size()-1)) {
  619. editor=true; //needs editor
  620. _export_platform=args[i+1];
  621. i++;
  622. } else if (args[i]=="-export_debug" && i <(args.size()-1)) {
  623. editor=true; //needs editor
  624. _export_platform=args[i+1];
  625. export_debug=true;
  626. i++;
  627. } else if (args[i]=="-import" && i <(args.size()-1)) {
  628. editor=true; //needs editor
  629. _import=args[i+1];
  630. i++;
  631. } else if (args[i]=="-import_script" && i <(args.size()-1)) {
  632. editor=true; //needs editor
  633. _import_script=args[i+1];
  634. i++;
  635. } else if (args[i]=="-noquit" ) {
  636. noquit=true;
  637. } else if (args[i]=="-dumpstrings" && i <(args.size()-1)) {
  638. editor=true; //needs editor
  639. dumpstrings=args[i+1];
  640. i++;
  641. } else if (args[i]=="-editor" || args[i]=="-e") {
  642. editor=true;
  643. } else if (args[i]=="-convert_old") {
  644. convert_old=true;
  645. } else if (args[i].length() && args[i][0] != '-' && game_path == "") {
  646. game_path=args[i];
  647. }
  648. }
  649. if (editor)
  650. Globals::get_singleton()->set("editor_active",true);
  651. String main_loop_type;
  652. #ifdef TOOLS_ENABLED
  653. if(doc_tool!="") {
  654. DocData doc;
  655. doc.generate(doc_base);
  656. DocData docsrc;
  657. if (docsrc.load(doc_tool)==OK) {
  658. print_line("Doc exists. Merging..");
  659. doc.merge_from(docsrc);
  660. } else {
  661. print_line("No Doc exists. Generating empty.");
  662. }
  663. doc.save(doc_tool);
  664. return false;
  665. }
  666. if (optimize!="")
  667. editor=true; //need editor
  668. #endif
  669. if(script=="" && game_path=="" && !editor && String(GLOBAL_DEF("application/main_scene",""))!="") {
  670. game_path=GLOBAL_DEF("application/main_scene","");
  671. }
  672. MainLoop *main_loop=NULL;
  673. if (editor) {
  674. main_loop = memnew(SceneMainLoop);
  675. };
  676. if (test!="") {
  677. #ifdef DEBUG_ENABLED
  678. main_loop = test_main(test,args);
  679. if (!main_loop)
  680. return false;
  681. #endif
  682. } else if (script!="") {
  683. Ref<Script> script_res = ResourceLoader::load(script);
  684. ERR_EXPLAIN("Can't load script: "+script);
  685. ERR_FAIL_COND_V(script_res.is_null(),false);
  686. if( script_res->can_instance() /*&& script_res->inherits_from("SceneMainLoopScripted")*/) {
  687. StringName instance_type=script_res->get_instance_base_type();
  688. Object *obj = ObjectTypeDB::instance(instance_type);
  689. MainLoop *script_loop = obj?obj->cast_to<MainLoop>():NULL;
  690. if (!script_loop) {
  691. if (obj)
  692. memdelete(obj);
  693. ERR_EXPLAIN("Can't load script '"+script+"', it does not inherit from a MainLoop type");
  694. ERR_FAIL_COND_V(!script_loop,false);
  695. }
  696. script_loop->set_init_script(script_res);
  697. main_loop=script_loop;
  698. } else {
  699. return false;
  700. }
  701. } else {
  702. main_loop_type=GLOBAL_DEF("application/main_loop_type","");
  703. }
  704. if (!main_loop && main_loop_type=="")
  705. main_loop_type="SceneMainLoop";
  706. if (!main_loop) {
  707. if (!ObjectTypeDB::type_exists(main_loop_type)) {
  708. OS::get_singleton()->alert("godot: error: MainLoop type doesn't exist: "+main_loop_type);
  709. return false;
  710. } else {
  711. Object *ml = ObjectTypeDB::instance(main_loop_type);
  712. if (!ml) {
  713. ERR_EXPLAIN("Can't instance MainLoop type");
  714. ERR_FAIL_V(false);
  715. }
  716. main_loop=ml->cast_to<MainLoop>();
  717. if (!main_loop) {
  718. memdelete(ml);
  719. ERR_EXPLAIN("Invalid MainLoop type");
  720. ERR_FAIL_V(false);
  721. }
  722. }
  723. }
  724. if (main_loop->is_type("SceneMainLoop")) {
  725. SceneMainLoop *sml = main_loop->cast_to<SceneMainLoop>();
  726. #ifdef TOOLS_ENABLED
  727. EditorNode *editor_node=NULL;
  728. if (editor) {
  729. editor_node = memnew( EditorNode );
  730. sml->get_root()->add_child(editor_node);
  731. //root_node->set_editor(editor);
  732. //startup editor
  733. if (_export_platform!="") {
  734. editor_node->export_platform(_export_platform,game_path,export_debug,"",true);
  735. game_path=""; //no load anything
  736. }
  737. }
  738. #endif
  739. if (!editor) {
  740. //standard helpers that can be changed from main config
  741. String stretch_mode = GLOBAL_DEF("display/stretch_mode","disabled");
  742. String stretch_aspect = GLOBAL_DEF("display/stretch_aspect","ignore");
  743. Size2i stretch_size = Size2(GLOBAL_DEF("display/width",0),GLOBAL_DEF("display/height",0));
  744. SceneMainLoop::StretchMode sml_sm=SceneMainLoop::STRETCH_MODE_DISABLED;
  745. if (stretch_mode=="2d")
  746. sml_sm=SceneMainLoop::STRETCH_MODE_2D;
  747. else if (stretch_mode=="viewport")
  748. sml_sm=SceneMainLoop::STRETCH_MODE_VIEWPORT;
  749. SceneMainLoop::StretchAspect sml_aspect=SceneMainLoop::STRETCH_ASPECT_IGNORE;
  750. if (stretch_aspect=="keep")
  751. sml_aspect=SceneMainLoop::STRETCH_ASPECT_KEEP;
  752. else if (stretch_aspect=="keep_width")
  753. sml_aspect=SceneMainLoop::STRETCH_ASPECT_KEEP_WIDTH;
  754. else if (stretch_aspect=="keep_height")
  755. sml_aspect=SceneMainLoop::STRETCH_ASPECT_KEEP_HEIGHT;
  756. sml->set_screen_stretch(sml_sm,sml_aspect,stretch_size);
  757. sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
  758. String appname = Globals::get_singleton()->get("application/name");
  759. appname = TranslationServer::get_singleton()->translate(appname);
  760. OS::get_singleton()->set_window_title(appname);
  761. } else {
  762. GLOBAL_DEF("display/stretch_mode","disabled");
  763. Globals::get_singleton()->set_custom_property_info("display/stretch_mode",PropertyInfo(Variant::STRING,"display/stretch_mode",PROPERTY_HINT_ENUM,"disabled,2d,viewport"));
  764. GLOBAL_DEF("display/stretch_aspect","ignore");
  765. Globals::get_singleton()->set_custom_property_info("display/stretch_aspect",PropertyInfo(Variant::STRING,"display/stretch_aspect",PROPERTY_HINT_ENUM,"ignore,keep,keep_width,keep_height"));
  766. sml->set_auto_accept_quit(GLOBAL_DEF("application/auto_accept_quit",true));
  767. }
  768. if (game_path!="") {
  769. String local_game_path=game_path.replace("\\","/");
  770. if (!local_game_path.begins_with("res://")) {
  771. bool absolute=(local_game_path.size()>1) && (local_game_path[0]=='/' || local_game_path[1]==':');
  772. if (!absolute) {
  773. if (Globals::get_singleton()->is_using_datapack()) {
  774. local_game_path="res://"+local_game_path;
  775. } else {
  776. int sep=local_game_path.find_last("/");
  777. if (sep==-1) {
  778. DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  779. local_game_path=da->get_current_dir()+"/"+local_game_path;
  780. memdelete(da) ;
  781. } else {
  782. DirAccess *da = DirAccess::open(local_game_path.substr(0,sep));
  783. if (da) {
  784. local_game_path=da->get_current_dir()+"/"+local_game_path.substr(sep+1,local_game_path.length());;
  785. memdelete(da);
  786. }
  787. }
  788. }
  789. }
  790. }
  791. local_game_path=Globals::get_singleton()->localize_path(local_game_path);
  792. #ifdef TOOLS_ENABLED
  793. if (editor) {
  794. #ifdef OLD_SCENE_FORMAT_ENABLED
  795. if (convert_old)
  796. editor_node->set_convert_old_scene(true);
  797. #endif
  798. if (_import!="") {
  799. //editor_node->import_scene(_import,local_game_path,_import_script);
  800. if (!noquit)
  801. sml->quit();
  802. game_path=""; //no load anything
  803. } else {
  804. Error serr = editor_node->load_scene(local_game_path);
  805. if (serr==OK) {
  806. if (optimize!="") {
  807. editor_node->save_optimized_copy(optimize,optimize_preset);
  808. if (!noquit)
  809. sml->quit();
  810. }
  811. if (dumpstrings!="") {
  812. editor_node->save_translatable_strings(dumpstrings);
  813. if (!noquit)
  814. sml->quit();
  815. }
  816. }
  817. }
  818. //editor_node->set_edited_scene(game);
  819. } else {
  820. #endif
  821. {
  822. //autoload
  823. List<PropertyInfo> props;
  824. Globals::get_singleton()->get_property_list(&props);
  825. for(List<PropertyInfo>::Element *E=props.front();E;E=E->next()) {
  826. String s = E->get().name;
  827. if (!s.begins_with("autoload/"))
  828. continue;
  829. String name = s.get_slice("/",1);
  830. String path = Globals::get_singleton()->get(s);
  831. RES res = ResourceLoader::load(path);
  832. ERR_EXPLAIN("Can't autoload: "+path);
  833. ERR_CONTINUE(res.is_null());
  834. Node *n=NULL;
  835. if (res->is_type("PackedScene")) {
  836. Ref<PackedScene> ps = res;
  837. n=ps->instance();
  838. } else if (res->is_type("Script")) {
  839. Ref<Script> s = res;
  840. StringName ibt = s->get_instance_base_type();
  841. ERR_EXPLAIN("Script does not inherit a Node: "+path);
  842. ERR_CONTINUE( !ObjectTypeDB::is_type(ibt,"Node") );
  843. Object *obj = ObjectTypeDB::instance(ibt);
  844. ERR_EXPLAIN("Cannot instance node for autoload type: "+String(ibt));
  845. ERR_CONTINUE( obj==NULL );
  846. n = obj->cast_to<Node>();
  847. n->set_script(s.get_ref_ptr());
  848. }
  849. ERR_EXPLAIN("Path in autoload not a node or script: "+path);
  850. ERR_CONTINUE(!n);
  851. n->set_name(name);
  852. sml->get_root()->add_child(n);
  853. }
  854. }
  855. Node *scene=NULL;
  856. Ref<PackedScene> scenedata = ResourceLoader::load(local_game_path);
  857. if (scenedata.is_valid())
  858. scene=scenedata->instance();
  859. #ifdef OLD_SCENE_FORMAT_ENABLED
  860. if (!scene) {
  861. scene = SceneLoader::load(local_game_path,true);
  862. }
  863. #endif
  864. ERR_EXPLAIN("Failed loading scene: "+local_game_path);
  865. ERR_FAIL_COND_V(!scene,false)
  866. sml->get_root()->add_child(scene);
  867. String iconpath = GLOBAL_DEF("application/icon","Variant()""");
  868. if (iconpath!="") {
  869. Image icon;
  870. if (icon.load(iconpath)==OK)
  871. OS::get_singleton()->set_icon(icon);
  872. }
  873. //singletons
  874. #ifdef TOOLS_ENABLED
  875. }
  876. #endif
  877. }
  878. #ifdef TOOLS_ENABLED
  879. /*if (_export_platform!="") {
  880. sml->quit();
  881. }*/
  882. /*
  883. if (sml->get_root_node()) {
  884. Console *console = memnew( Console );
  885. sml->get_root_node()->cast_to<RootNode>()->set_console(console);
  886. if (GLOBAL_DEF("console/visible_default",false).operator bool()) {
  887. console->show();
  888. } else {P
  889. console->hide();
  890. };
  891. }
  892. */
  893. if (script=="" && test=="" && game_path=="" && !editor) {
  894. ProjectManager *pmanager = memnew( ProjectManager );
  895. sml->get_root()->add_child(pmanager);
  896. }
  897. #endif
  898. }
  899. OS::get_singleton()->set_main_loop( main_loop );
  900. return true;
  901. }
  902. uint64_t Main::last_ticks=0;
  903. uint64_t Main::target_ticks=0;
  904. float Main::time_accum=0;
  905. uint32_t Main::frames=0;
  906. uint32_t Main::frame=0;
  907. bool Main::force_redraw_requested = false;
  908. static uint64_t fixed_process_max=0;
  909. static uint64_t idle_process_max=0;
  910. bool Main::iteration() {
  911. uint64_t ticks=OS::get_singleton()->get_ticks_usec();
  912. uint64_t ticks_elapsed=ticks-last_ticks;
  913. frame+=ticks_elapsed;
  914. last_ticks=ticks;
  915. double step=(double)ticks_elapsed / 1000000.0;
  916. float frame_slice=1.0/OS::get_singleton()->get_iterations_per_second();
  917. if (step>frame_slice*8)
  918. step=frame_slice*8;
  919. time_accum+=step;
  920. bool exit=false;
  921. int iters = 0;
  922. while(time_accum>frame_slice) {
  923. uint64_t fixed_begin = OS::get_singleton()->get_ticks_usec();
  924. PhysicsServer::get_singleton()->sync();
  925. PhysicsServer::get_singleton()->flush_queries();
  926. Physics2DServer::get_singleton()->sync();
  927. Physics2DServer::get_singleton()->flush_queries();
  928. if (OS::get_singleton()->get_main_loop()->iteration( frame_slice )) {
  929. exit=true;
  930. break;
  931. }
  932. message_queue->flush();
  933. PhysicsServer::get_singleton()->step(frame_slice);
  934. Physics2DServer::get_singleton()->step(frame_slice);
  935. time_accum-=frame_slice;
  936. message_queue->flush();
  937. //if (AudioServer::get_singleton())
  938. // AudioServer::get_singleton()->update();
  939. fixed_process_max=MAX(OS::get_singleton()->get_ticks_usec()-fixed_begin,fixed_process_max);
  940. iters++;
  941. }
  942. uint64_t idle_begin = OS::get_singleton()->get_ticks_usec();
  943. OS::get_singleton()->get_main_loop()->idle( step );
  944. message_queue->flush();
  945. if (SpatialSoundServer::get_singleton())
  946. SpatialSoundServer::get_singleton()->update( step );
  947. if (SpatialSound2DServer::get_singleton())
  948. SpatialSound2DServer::get_singleton()->update( step );
  949. if (OS::get_singleton()->can_draw()) {
  950. if ((!force_redraw_requested) && OS::get_singleton()->is_in_low_processor_usage_mode()) {
  951. if (VisualServer::get_singleton()->has_changed()) {
  952. VisualServer::get_singleton()->draw(); // flush visual commands
  953. OS::get_singleton()->frames_drawn++;
  954. }
  955. } else {
  956. VisualServer::get_singleton()->draw(); // flush visual commands
  957. OS::get_singleton()->frames_drawn++;
  958. force_redraw_requested = false;
  959. }
  960. } else {
  961. VisualServer::get_singleton()->flush(); // flush visual commands
  962. }
  963. if (AudioServer::get_singleton())
  964. AudioServer::get_singleton()->update();
  965. for(int i=0;i<ScriptServer::get_language_count();i++) {
  966. ScriptServer::get_language(i)->frame();
  967. }
  968. idle_process_max=MAX(OS::get_singleton()->get_ticks_usec()-idle_begin,idle_process_max);
  969. if (script_debugger)
  970. script_debugger->idle_poll();
  971. // x11_delay_usec(10000);
  972. frames++;
  973. if (frame>1000000) {
  974. if (GLOBAL_DEF("debug/print_fps", OS::get_singleton()->is_stdout_verbose())) {
  975. print_line("FPS: "+itos(frames));
  976. };
  977. OS::get_singleton()->_fps=frames;
  978. performance->set_process_time(idle_process_max/1000000.0);
  979. performance->set_fixed_process_time(fixed_process_max/1000000.0);
  980. idle_process_max=0;
  981. fixed_process_max=0;
  982. if (GLOBAL_DEF("debug/print_metrics", false)) {
  983. //PerformanceMetrics::print();
  984. };
  985. frame%=1000000;
  986. frames=0;
  987. }
  988. if (OS::get_singleton()->is_in_low_processor_usage_mode() || !OS::get_singleton()->can_draw())
  989. OS::get_singleton()->delay_usec(25000); //apply some delay to force idle time
  990. else {
  991. uint32_t frame_delay = OS::get_singleton()->get_frame_delay();
  992. if (frame_delay)
  993. OS::get_singleton()->delay_usec( OS::get_singleton()->get_frame_delay()*1000 );
  994. }
  995. int taret_fps = OS::get_singleton()->get_target_fps();
  996. if (taret_fps>0) {
  997. uint64_t time_step = 1000000L/taret_fps;
  998. target_ticks += time_step;
  999. uint64_t current_ticks = OS::get_singleton()->get_ticks_usec();
  1000. if (current_ticks<target_ticks) OS::get_singleton()->delay_usec(target_ticks-current_ticks);
  1001. current_ticks = OS::get_singleton()->get_ticks_usec();
  1002. target_ticks = MIN(MAX(target_ticks,current_ticks-time_step),current_ticks+time_step);
  1003. }
  1004. return exit;
  1005. }
  1006. void Main::force_redraw() {
  1007. force_redraw_requested = true;
  1008. };
  1009. void Main::cleanup() {
  1010. ERR_FAIL_COND(!_start_success);
  1011. if (script_debugger)
  1012. memdelete(script_debugger);
  1013. OS::get_singleton()->delete_main_loop();
  1014. OS::get_singleton()->_cmdline.clear();
  1015. OS::get_singleton()->_execpath="";
  1016. OS::get_singleton()->_local_clipboard="";
  1017. #ifdef TOOLS_ENABLED
  1018. EditorNode::unregister_editor_types();
  1019. #endif
  1020. unregister_driver_types();
  1021. unregister_module_types();
  1022. unregister_scene_types();
  1023. unregister_server_types();
  1024. OS::get_singleton()->finalize();
  1025. if (packed_data)
  1026. memdelete(packed_data);
  1027. if (file_access_network_client)
  1028. memdelete(file_access_network_client);
  1029. if (performance)
  1030. memdelete(performance);
  1031. if (input_map)
  1032. memdelete(input_map);
  1033. if (translation_server)
  1034. memdelete( translation_server );
  1035. if (path_remap)
  1036. memdelete(path_remap);
  1037. if (globals)
  1038. memdelete(globals);
  1039. memdelete( message_queue );
  1040. unregister_core_driver_types();
  1041. unregister_core_types();
  1042. //PerformanceMetrics::finish();
  1043. OS::get_singleton()->clear_last_error();
  1044. OS::get_singleton()->finalize_core();
  1045. }