scene_tree.cpp 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  1. /**************************************************************************/
  2. /* scene_tree.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "scene_tree.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/debugger/engine_debugger.h"
  33. #include "core/input/input.h"
  34. #include "core/io/dir_access.h"
  35. #include "core/io/image_loader.h"
  36. #include "core/io/marshalls.h"
  37. #include "core/io/resource_loader.h"
  38. #include "core/object/message_queue.h"
  39. #include "core/object/worker_thread_pool.h"
  40. #include "core/os/keyboard.h"
  41. #include "core/os/os.h"
  42. #include "core/string/print_string.h"
  43. #include "node.h"
  44. #include "scene/animation/tween.h"
  45. #include "scene/debugger/scene_debugger.h"
  46. #include "scene/gui/control.h"
  47. #include "scene/main/multiplayer_api.h"
  48. #include "scene/main/viewport.h"
  49. #include "scene/resources/environment.h"
  50. #include "scene/resources/font.h"
  51. #include "scene/resources/image_texture.h"
  52. #include "scene/resources/material.h"
  53. #include "scene/resources/mesh.h"
  54. #include "scene/resources/packed_scene.h"
  55. #include "scene/resources/world_2d.h"
  56. #include "scene/resources/world_3d.h"
  57. #include "scene/scene_string_names.h"
  58. #include "servers/display_server.h"
  59. #include "servers/navigation_server_3d.h"
  60. #include "servers/physics_server_2d.h"
  61. #include "servers/physics_server_3d.h"
  62. #include "window.h"
  63. #include <stdio.h>
  64. #include <stdlib.h>
  65. void SceneTreeTimer::_bind_methods() {
  66. ClassDB::bind_method(D_METHOD("set_time_left", "time"), &SceneTreeTimer::set_time_left);
  67. ClassDB::bind_method(D_METHOD("get_time_left"), &SceneTreeTimer::get_time_left);
  68. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "time_left", PROPERTY_HINT_NONE, "suffix:s"), "set_time_left", "get_time_left");
  69. ADD_SIGNAL(MethodInfo("timeout"));
  70. }
  71. void SceneTreeTimer::set_time_left(double p_time) {
  72. time_left = p_time;
  73. }
  74. double SceneTreeTimer::get_time_left() const {
  75. return MAX(time_left, 0.0);
  76. }
  77. void SceneTreeTimer::set_process_always(bool p_process_always) {
  78. process_always = p_process_always;
  79. }
  80. bool SceneTreeTimer::is_process_always() {
  81. return process_always;
  82. }
  83. void SceneTreeTimer::set_process_in_physics(bool p_process_in_physics) {
  84. process_in_physics = p_process_in_physics;
  85. }
  86. bool SceneTreeTimer::is_process_in_physics() {
  87. return process_in_physics;
  88. }
  89. void SceneTreeTimer::set_ignore_time_scale(bool p_ignore) {
  90. ignore_time_scale = p_ignore;
  91. }
  92. bool SceneTreeTimer::is_ignore_time_scale() {
  93. return ignore_time_scale;
  94. }
  95. void SceneTreeTimer::release_connections() {
  96. List<Connection> signal_connections;
  97. get_all_signal_connections(&signal_connections);
  98. for (const Connection &connection : signal_connections) {
  99. disconnect(connection.signal.get_name(), connection.callable);
  100. }
  101. }
  102. SceneTreeTimer::SceneTreeTimer() {}
  103. void SceneTree::tree_changed() {
  104. tree_version++;
  105. emit_signal(tree_changed_name);
  106. }
  107. void SceneTree::node_added(Node *p_node) {
  108. emit_signal(node_added_name, p_node);
  109. }
  110. void SceneTree::node_removed(Node *p_node) {
  111. // Nodes can only be removed from the main thread.
  112. if (current_scene == p_node) {
  113. current_scene = nullptr;
  114. }
  115. emit_signal(node_removed_name, p_node);
  116. if (nodes_removed_on_group_call_lock) {
  117. nodes_removed_on_group_call.insert(p_node);
  118. }
  119. }
  120. void SceneTree::node_renamed(Node *p_node) {
  121. emit_signal(node_renamed_name, p_node);
  122. }
  123. SceneTree::Group *SceneTree::add_to_group(const StringName &p_group, Node *p_node) {
  124. _THREAD_SAFE_METHOD_
  125. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  126. if (!E) {
  127. E = group_map.insert(p_group, Group());
  128. }
  129. ERR_FAIL_COND_V_MSG(E->value.nodes.has(p_node), &E->value, "Already in group: " + p_group + ".");
  130. E->value.nodes.push_back(p_node);
  131. //E->value.last_tree_version=0;
  132. E->value.changed = true;
  133. return &E->value;
  134. }
  135. void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) {
  136. _THREAD_SAFE_METHOD_
  137. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  138. ERR_FAIL_COND(!E);
  139. E->value.nodes.erase(p_node);
  140. if (E->value.nodes.is_empty()) {
  141. group_map.remove(E);
  142. }
  143. }
  144. void SceneTree::make_group_changed(const StringName &p_group) {
  145. _THREAD_SAFE_METHOD_
  146. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  147. if (E) {
  148. E->value.changed = true;
  149. }
  150. }
  151. void SceneTree::flush_transform_notifications() {
  152. _THREAD_SAFE_METHOD_
  153. SelfList<Node> *n = xform_change_list.first();
  154. while (n) {
  155. Node *node = n->self();
  156. SelfList<Node> *nx = n->next();
  157. xform_change_list.remove(n);
  158. n = nx;
  159. node->notification(NOTIFICATION_TRANSFORM_CHANGED);
  160. }
  161. }
  162. void SceneTree::_flush_ugc() {
  163. ugc_locked = true;
  164. while (unique_group_calls.size()) {
  165. HashMap<UGCall, Vector<Variant>, UGCall>::Iterator E = unique_group_calls.begin();
  166. const Variant **argptrs = (const Variant **)alloca(E->value.size() * sizeof(Variant *));
  167. for (int i = 0; i < E->value.size(); i++) {
  168. argptrs[i] = &E->value[i];
  169. }
  170. call_group_flagsp(GROUP_CALL_DEFAULT, E->key.group, E->key.call, argptrs, E->value.size());
  171. unique_group_calls.remove(E);
  172. }
  173. ugc_locked = false;
  174. }
  175. void SceneTree::_update_group_order(Group &g) {
  176. if (!g.changed) {
  177. return;
  178. }
  179. if (g.nodes.is_empty()) {
  180. return;
  181. }
  182. Node **gr_nodes = g.nodes.ptrw();
  183. int gr_node_count = g.nodes.size();
  184. SortArray<Node *, Node::Comparator> node_sort;
  185. node_sort.sort(gr_nodes, gr_node_count);
  186. g.changed = false;
  187. }
  188. void SceneTree::call_group_flagsp(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, const Variant **p_args, int p_argcount) {
  189. Vector<Node *> nodes_copy;
  190. {
  191. _THREAD_SAFE_METHOD_
  192. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  193. if (!E) {
  194. return;
  195. }
  196. Group &g = E->value;
  197. if (g.nodes.is_empty()) {
  198. return;
  199. }
  200. if (p_call_flags & GROUP_CALL_UNIQUE && p_call_flags & GROUP_CALL_DEFERRED) {
  201. ERR_FAIL_COND(ugc_locked);
  202. UGCall ug;
  203. ug.call = p_function;
  204. ug.group = p_group;
  205. if (unique_group_calls.has(ug)) {
  206. return;
  207. }
  208. Vector<Variant> args;
  209. for (int i = 0; i < p_argcount; i++) {
  210. args.push_back(*p_args[i]);
  211. }
  212. unique_group_calls[ug] = args;
  213. return;
  214. }
  215. _update_group_order(g);
  216. nodes_copy = g.nodes;
  217. }
  218. Node **gr_nodes = nodes_copy.ptrw();
  219. int gr_node_count = nodes_copy.size();
  220. {
  221. _THREAD_SAFE_METHOD_
  222. nodes_removed_on_group_call_lock++;
  223. }
  224. if (p_call_flags & GROUP_CALL_REVERSE) {
  225. for (int i = gr_node_count - 1; i >= 0; i--) {
  226. if (nodes_removed_on_group_call_lock && nodes_removed_on_group_call.has(gr_nodes[i])) {
  227. continue;
  228. }
  229. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  230. Callable::CallError ce;
  231. gr_nodes[i]->callp(p_function, p_args, p_argcount, ce);
  232. } else {
  233. MessageQueue::get_singleton()->push_callp(gr_nodes[i], p_function, p_args, p_argcount);
  234. }
  235. }
  236. } else {
  237. for (int i = 0; i < gr_node_count; i++) {
  238. if (nodes_removed_on_group_call_lock && nodes_removed_on_group_call.has(gr_nodes[i])) {
  239. continue;
  240. }
  241. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  242. Callable::CallError ce;
  243. gr_nodes[i]->callp(p_function, p_args, p_argcount, ce);
  244. } else {
  245. MessageQueue::get_singleton()->push_callp(gr_nodes[i], p_function, p_args, p_argcount);
  246. }
  247. }
  248. }
  249. {
  250. _THREAD_SAFE_METHOD_
  251. nodes_removed_on_group_call_lock--;
  252. if (nodes_removed_on_group_call_lock == 0) {
  253. nodes_removed_on_group_call.clear();
  254. }
  255. }
  256. }
  257. void SceneTree::notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification) {
  258. Vector<Node *> nodes_copy;
  259. {
  260. _THREAD_SAFE_METHOD_
  261. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  262. if (!E) {
  263. return;
  264. }
  265. Group &g = E->value;
  266. if (g.nodes.is_empty()) {
  267. return;
  268. }
  269. _update_group_order(g);
  270. nodes_copy = g.nodes;
  271. }
  272. Node **gr_nodes = nodes_copy.ptrw();
  273. int gr_node_count = nodes_copy.size();
  274. {
  275. _THREAD_SAFE_METHOD_
  276. nodes_removed_on_group_call_lock++;
  277. }
  278. if (p_call_flags & GROUP_CALL_REVERSE) {
  279. for (int i = gr_node_count - 1; i >= 0; i--) {
  280. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  281. continue;
  282. }
  283. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  284. gr_nodes[i]->notification(p_notification, true);
  285. } else {
  286. MessageQueue::get_singleton()->push_notification(gr_nodes[i], p_notification);
  287. }
  288. }
  289. } else {
  290. for (int i = 0; i < gr_node_count; i++) {
  291. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  292. continue;
  293. }
  294. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  295. gr_nodes[i]->notification(p_notification);
  296. } else {
  297. MessageQueue::get_singleton()->push_notification(gr_nodes[i], p_notification);
  298. }
  299. }
  300. }
  301. {
  302. _THREAD_SAFE_METHOD_
  303. nodes_removed_on_group_call_lock--;
  304. if (nodes_removed_on_group_call_lock == 0) {
  305. nodes_removed_on_group_call.clear();
  306. }
  307. }
  308. }
  309. void SceneTree::set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value) {
  310. Vector<Node *> nodes_copy;
  311. {
  312. _THREAD_SAFE_METHOD_
  313. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  314. if (!E) {
  315. return;
  316. }
  317. Group &g = E->value;
  318. if (g.nodes.is_empty()) {
  319. return;
  320. }
  321. _update_group_order(g);
  322. nodes_copy = g.nodes;
  323. }
  324. Node **gr_nodes = nodes_copy.ptrw();
  325. int gr_node_count = nodes_copy.size();
  326. {
  327. _THREAD_SAFE_METHOD_
  328. nodes_removed_on_group_call_lock++;
  329. }
  330. if (p_call_flags & GROUP_CALL_REVERSE) {
  331. for (int i = gr_node_count - 1; i >= 0; i--) {
  332. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  333. continue;
  334. }
  335. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  336. gr_nodes[i]->set(p_name, p_value);
  337. } else {
  338. MessageQueue::get_singleton()->push_set(gr_nodes[i], p_name, p_value);
  339. }
  340. }
  341. } else {
  342. for (int i = 0; i < gr_node_count; i++) {
  343. if (nodes_removed_on_group_call.has(gr_nodes[i])) {
  344. continue;
  345. }
  346. if (!(p_call_flags & GROUP_CALL_DEFERRED)) {
  347. gr_nodes[i]->set(p_name, p_value);
  348. } else {
  349. MessageQueue::get_singleton()->push_set(gr_nodes[i], p_name, p_value);
  350. }
  351. }
  352. }
  353. {
  354. _THREAD_SAFE_METHOD_
  355. nodes_removed_on_group_call_lock--;
  356. if (nodes_removed_on_group_call_lock == 0) {
  357. nodes_removed_on_group_call.clear();
  358. }
  359. }
  360. }
  361. void SceneTree::notify_group(const StringName &p_group, int p_notification) {
  362. notify_group_flags(GROUP_CALL_DEFAULT, p_group, p_notification);
  363. }
  364. void SceneTree::set_group(const StringName &p_group, const String &p_name, const Variant &p_value) {
  365. set_group_flags(GROUP_CALL_DEFAULT, p_group, p_name, p_value);
  366. }
  367. void SceneTree::initialize() {
  368. ERR_FAIL_NULL(root);
  369. MainLoop::initialize();
  370. root->_set_tree(this);
  371. }
  372. bool SceneTree::physics_process(double p_time) {
  373. root_lock++;
  374. current_frame++;
  375. flush_transform_notifications();
  376. if (MainLoop::physics_process(p_time)) {
  377. _quit = true;
  378. }
  379. physics_process_time = p_time;
  380. emit_signal(SNAME("physics_frame"));
  381. call_group(SNAME("_picking_viewports"), SNAME("_process_picking"));
  382. _process(true);
  383. _flush_ugc();
  384. MessageQueue::get_singleton()->flush(); //small little hack
  385. process_timers(p_time, true); //go through timers
  386. process_tweens(p_time, true);
  387. flush_transform_notifications();
  388. root_lock--;
  389. _flush_delete_queue();
  390. _call_idle_callbacks();
  391. return _quit;
  392. }
  393. bool SceneTree::process(double p_time) {
  394. root_lock++;
  395. if (MainLoop::process(p_time)) {
  396. _quit = true;
  397. }
  398. process_time = p_time;
  399. if (multiplayer_poll) {
  400. multiplayer->poll();
  401. for (KeyValue<NodePath, Ref<MultiplayerAPI>> &E : custom_multiplayers) {
  402. E.value->poll();
  403. }
  404. }
  405. emit_signal(SNAME("process_frame"));
  406. MessageQueue::get_singleton()->flush(); //small little hack
  407. flush_transform_notifications();
  408. _process(false);
  409. _flush_ugc();
  410. MessageQueue::get_singleton()->flush(); //small little hack
  411. flush_transform_notifications(); //transforms after world update, to avoid unnecessary enter/exit notifications
  412. root_lock--;
  413. _flush_delete_queue();
  414. if (unlikely(pending_new_scene)) {
  415. _flush_scene_change();
  416. }
  417. process_timers(p_time, false); //go through timers
  418. process_tweens(p_time, false);
  419. flush_transform_notifications(); //additional transforms after timers update
  420. _call_idle_callbacks();
  421. #ifdef TOOLS_ENABLED
  422. #ifndef _3D_DISABLED
  423. if (Engine::get_singleton()->is_editor_hint()) {
  424. //simple hack to reload fallback environment if it changed from editor
  425. String env_path = GLOBAL_GET(SNAME("rendering/environment/defaults/default_environment"));
  426. env_path = env_path.strip_edges(); //user may have added a space or two
  427. String cpath;
  428. Ref<Environment> fallback = get_root()->get_world_3d()->get_fallback_environment();
  429. if (fallback.is_valid()) {
  430. cpath = fallback->get_path();
  431. }
  432. if (cpath != env_path) {
  433. if (!env_path.is_empty()) {
  434. fallback = ResourceLoader::load(env_path);
  435. if (fallback.is_null()) {
  436. //could not load fallback, set as empty
  437. ProjectSettings::get_singleton()->set("rendering/environment/defaults/default_environment", "");
  438. }
  439. } else {
  440. fallback.unref();
  441. }
  442. get_root()->get_world_3d()->set_fallback_environment(fallback);
  443. }
  444. }
  445. #endif // _3D_DISABLED
  446. #endif // TOOLS_ENABLED
  447. return _quit;
  448. }
  449. void SceneTree::process_timers(double p_delta, bool p_physics_frame) {
  450. _THREAD_SAFE_METHOD_
  451. List<Ref<SceneTreeTimer>>::Element *L = timers.back(); //last element
  452. for (List<Ref<SceneTreeTimer>>::Element *E = timers.front(); E;) {
  453. List<Ref<SceneTreeTimer>>::Element *N = E->next();
  454. if ((paused && !E->get()->is_process_always()) || (E->get()->is_process_in_physics() != p_physics_frame)) {
  455. if (E == L) {
  456. break; //break on last, so if new timers were added during list traversal, ignore them.
  457. }
  458. E = N;
  459. continue;
  460. }
  461. double time_left = E->get()->get_time_left();
  462. if (E->get()->is_ignore_time_scale()) {
  463. time_left -= Engine::get_singleton()->get_process_step();
  464. } else {
  465. time_left -= p_delta;
  466. }
  467. E->get()->set_time_left(time_left);
  468. if (time_left <= 0) {
  469. E->get()->emit_signal(SNAME("timeout"));
  470. timers.erase(E);
  471. }
  472. if (E == L) {
  473. break; //break on last, so if new timers were added during list traversal, ignore them.
  474. }
  475. E = N;
  476. }
  477. }
  478. void SceneTree::process_tweens(double p_delta, bool p_physics) {
  479. _THREAD_SAFE_METHOD_
  480. // This methods works similarly to how SceneTreeTimers are handled.
  481. List<Ref<Tween>>::Element *L = tweens.back();
  482. for (List<Ref<Tween>>::Element *E = tweens.front(); E;) {
  483. List<Ref<Tween>>::Element *N = E->next();
  484. // Don't process if paused or process mode doesn't match.
  485. if (!E->get()->can_process(paused) || (p_physics == (E->get()->get_process_mode() == Tween::TWEEN_PROCESS_IDLE))) {
  486. if (E == L) {
  487. break;
  488. }
  489. E = N;
  490. continue;
  491. }
  492. if (!E->get()->step(p_delta)) {
  493. E->get()->clear();
  494. tweens.erase(E);
  495. }
  496. if (E == L) {
  497. break;
  498. }
  499. E = N;
  500. }
  501. }
  502. void SceneTree::finalize() {
  503. _flush_delete_queue();
  504. _flush_ugc();
  505. if (root) {
  506. root->_set_tree(nullptr);
  507. root->_propagate_after_exit_tree();
  508. memdelete(root); //delete root
  509. root = nullptr;
  510. // In case deletion of some objects was queued when destructing the `root`.
  511. // E.g. if `queue_free()` was called for some node outside the tree when handling NOTIFICATION_PREDELETE for some node in the tree.
  512. _flush_delete_queue();
  513. }
  514. MainLoop::finalize();
  515. // Cleanup timers.
  516. for (Ref<SceneTreeTimer> &timer : timers) {
  517. timer->release_connections();
  518. }
  519. timers.clear();
  520. // Cleanup tweens.
  521. for (Ref<Tween> &tween : tweens) {
  522. tween->clear();
  523. }
  524. tweens.clear();
  525. }
  526. void SceneTree::quit(int p_exit_code) {
  527. _THREAD_SAFE_METHOD_
  528. OS::get_singleton()->set_exit_code(p_exit_code);
  529. _quit = true;
  530. }
  531. void SceneTree::_main_window_close() {
  532. if (accept_quit) {
  533. _quit = true;
  534. }
  535. }
  536. void SceneTree::_main_window_go_back() {
  537. if (quit_on_go_back) {
  538. _quit = true;
  539. }
  540. }
  541. void SceneTree::_main_window_focus_in() {
  542. Input *id = Input::get_singleton();
  543. if (id) {
  544. id->ensure_touch_mouse_raised();
  545. }
  546. }
  547. void SceneTree::_notification(int p_notification) {
  548. switch (p_notification) {
  549. case NOTIFICATION_TRANSLATION_CHANGED: {
  550. if (!Engine::get_singleton()->is_editor_hint()) {
  551. get_root()->propagate_notification(p_notification);
  552. }
  553. } break;
  554. case NOTIFICATION_OS_MEMORY_WARNING:
  555. case NOTIFICATION_OS_IME_UPDATE:
  556. case NOTIFICATION_WM_ABOUT:
  557. case NOTIFICATION_CRASH:
  558. case NOTIFICATION_APPLICATION_RESUMED:
  559. case NOTIFICATION_APPLICATION_PAUSED:
  560. case NOTIFICATION_APPLICATION_FOCUS_IN:
  561. case NOTIFICATION_APPLICATION_FOCUS_OUT: {
  562. // Pass these to nodes, since they are mirrored.
  563. get_root()->propagate_notification(p_notification);
  564. } break;
  565. }
  566. }
  567. bool SceneTree::is_auto_accept_quit() const {
  568. return accept_quit;
  569. }
  570. void SceneTree::set_auto_accept_quit(bool p_enable) {
  571. accept_quit = p_enable;
  572. }
  573. bool SceneTree::is_quit_on_go_back() const {
  574. return quit_on_go_back;
  575. }
  576. void SceneTree::set_quit_on_go_back(bool p_enable) {
  577. quit_on_go_back = p_enable;
  578. }
  579. #ifdef TOOLS_ENABLED
  580. bool SceneTree::is_node_being_edited(const Node *p_node) const {
  581. return Engine::get_singleton()->is_editor_hint() && edited_scene_root && (edited_scene_root->is_ancestor_of(p_node) || edited_scene_root == p_node);
  582. }
  583. #endif
  584. #ifdef DEBUG_ENABLED
  585. void SceneTree::set_debug_collisions_hint(bool p_enabled) {
  586. debug_collisions_hint = p_enabled;
  587. }
  588. bool SceneTree::is_debugging_collisions_hint() const {
  589. return debug_collisions_hint;
  590. }
  591. void SceneTree::set_debug_paths_hint(bool p_enabled) {
  592. debug_paths_hint = p_enabled;
  593. }
  594. bool SceneTree::is_debugging_paths_hint() const {
  595. return debug_paths_hint;
  596. }
  597. void SceneTree::set_debug_navigation_hint(bool p_enabled) {
  598. debug_navigation_hint = p_enabled;
  599. }
  600. bool SceneTree::is_debugging_navigation_hint() const {
  601. return debug_navigation_hint;
  602. }
  603. #endif
  604. void SceneTree::set_debug_collisions_color(const Color &p_color) {
  605. debug_collisions_color = p_color;
  606. }
  607. Color SceneTree::get_debug_collisions_color() const {
  608. return debug_collisions_color;
  609. }
  610. void SceneTree::set_debug_collision_contact_color(const Color &p_color) {
  611. debug_collision_contact_color = p_color;
  612. }
  613. Color SceneTree::get_debug_collision_contact_color() const {
  614. return debug_collision_contact_color;
  615. }
  616. void SceneTree::set_debug_paths_color(const Color &p_color) {
  617. debug_paths_color = p_color;
  618. }
  619. Color SceneTree::get_debug_paths_color() const {
  620. return debug_paths_color;
  621. }
  622. void SceneTree::set_debug_paths_width(float p_width) {
  623. debug_paths_width = p_width;
  624. }
  625. float SceneTree::get_debug_paths_width() const {
  626. return debug_paths_width;
  627. }
  628. Ref<Material> SceneTree::get_debug_paths_material() {
  629. _THREAD_SAFE_METHOD_
  630. if (debug_paths_material.is_valid()) {
  631. return debug_paths_material;
  632. }
  633. Ref<StandardMaterial3D> _debug_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  634. _debug_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  635. _debug_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  636. _debug_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  637. _debug_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  638. _debug_material->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  639. _debug_material->set_albedo(get_debug_paths_color());
  640. debug_paths_material = _debug_material;
  641. return debug_paths_material;
  642. }
  643. Ref<Material> SceneTree::get_debug_collision_material() {
  644. _THREAD_SAFE_METHOD_
  645. if (collision_material.is_valid()) {
  646. return collision_material;
  647. }
  648. Ref<StandardMaterial3D> line_material = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  649. line_material->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  650. line_material->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  651. line_material->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  652. line_material->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  653. line_material->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  654. line_material->set_albedo(get_debug_collisions_color());
  655. collision_material = line_material;
  656. return collision_material;
  657. }
  658. Ref<ArrayMesh> SceneTree::get_debug_contact_mesh() {
  659. _THREAD_SAFE_METHOD_
  660. if (debug_contact_mesh.is_valid()) {
  661. return debug_contact_mesh;
  662. }
  663. debug_contact_mesh = Ref<ArrayMesh>(memnew(ArrayMesh));
  664. Ref<StandardMaterial3D> mat = Ref<StandardMaterial3D>(memnew(StandardMaterial3D));
  665. mat->set_shading_mode(StandardMaterial3D::SHADING_MODE_UNSHADED);
  666. mat->set_transparency(StandardMaterial3D::TRANSPARENCY_ALPHA);
  667. mat->set_flag(StandardMaterial3D::FLAG_SRGB_VERTEX_COLOR, true);
  668. mat->set_flag(StandardMaterial3D::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  669. mat->set_flag(StandardMaterial3D::FLAG_DISABLE_FOG, true);
  670. mat->set_albedo(get_debug_collision_contact_color());
  671. Vector3 diamond[6] = {
  672. Vector3(-1, 0, 0),
  673. Vector3(1, 0, 0),
  674. Vector3(0, -1, 0),
  675. Vector3(0, 1, 0),
  676. Vector3(0, 0, -1),
  677. Vector3(0, 0, 1)
  678. };
  679. /* clang-format off */
  680. int diamond_faces[8 * 3] = {
  681. 0, 2, 4,
  682. 0, 3, 4,
  683. 1, 2, 4,
  684. 1, 3, 4,
  685. 0, 2, 5,
  686. 0, 3, 5,
  687. 1, 2, 5,
  688. 1, 3, 5,
  689. };
  690. /* clang-format on */
  691. Vector<int> indices;
  692. for (int i = 0; i < 8 * 3; i++) {
  693. indices.push_back(diamond_faces[i]);
  694. }
  695. Vector<Vector3> vertices;
  696. for (int i = 0; i < 6; i++) {
  697. vertices.push_back(diamond[i] * 0.1);
  698. }
  699. Array arr;
  700. arr.resize(Mesh::ARRAY_MAX);
  701. arr[Mesh::ARRAY_VERTEX] = vertices;
  702. arr[Mesh::ARRAY_INDEX] = indices;
  703. debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  704. debug_contact_mesh->surface_set_material(0, mat);
  705. return debug_contact_mesh;
  706. }
  707. void SceneTree::set_pause(bool p_enabled) {
  708. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Pause can only be set from the main thread.");
  709. if (p_enabled == paused) {
  710. return;
  711. }
  712. paused = p_enabled;
  713. PhysicsServer3D::get_singleton()->set_active(!p_enabled);
  714. PhysicsServer2D::get_singleton()->set_active(!p_enabled);
  715. if (get_root()) {
  716. get_root()->_propagate_pause_notification(p_enabled);
  717. }
  718. }
  719. bool SceneTree::is_paused() const {
  720. return paused;
  721. }
  722. void SceneTree::_process_group(ProcessGroup *p_group, bool p_physics) {
  723. // When reading this function, keep in mind that this code must work in a way where
  724. // if any node is removed, this needs to continue working.
  725. p_group->call_queue.flush(); // Flush messages before processing.
  726. Vector<Node *> &nodes = p_physics ? p_group->physics_nodes : p_group->nodes;
  727. if (nodes.is_empty()) {
  728. return;
  729. }
  730. if (p_physics) {
  731. if (p_group->physics_node_order_dirty) {
  732. nodes.sort_custom<Node::ComparatorWithPhysicsPriority>();
  733. p_group->physics_node_order_dirty = false;
  734. }
  735. } else {
  736. if (p_group->node_order_dirty) {
  737. nodes.sort_custom<Node::ComparatorWithPriority>();
  738. p_group->node_order_dirty = false;
  739. }
  740. }
  741. // Make a copy, so if nodes are added/removed from process, this does not break
  742. Vector<Node *> nodes_copy = nodes;
  743. uint32_t node_count = nodes_copy.size();
  744. Node **nodes_ptr = (Node **)nodes_copy.ptr(); // Force cast, pointer will not change.
  745. for (uint32_t i = 0; i < node_count; i++) {
  746. Node *n = nodes_ptr[i];
  747. if (nodes_removed_on_group_call.has(n)) {
  748. // Node may have been removed during process, skip it.
  749. // Keep in mind removals can only happen on the main thread.
  750. continue;
  751. }
  752. if (!n->can_process() || !n->is_inside_tree()) {
  753. continue;
  754. }
  755. if (p_physics) {
  756. if (n->is_physics_processing_internal()) {
  757. n->notification(Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS);
  758. }
  759. if (n->is_physics_processing()) {
  760. n->notification(Node::NOTIFICATION_PHYSICS_PROCESS);
  761. }
  762. } else {
  763. if (n->is_processing_internal()) {
  764. n->notification(Node::NOTIFICATION_INTERNAL_PROCESS);
  765. }
  766. if (n->is_processing()) {
  767. n->notification(Node::NOTIFICATION_PROCESS);
  768. }
  769. }
  770. }
  771. p_group->call_queue.flush(); // Flush messages also after processing (for potential deferred calls).
  772. }
  773. void SceneTree::_process_groups_thread(uint32_t p_index, bool p_physics) {
  774. Node::current_process_thread_group = local_process_group_cache[p_index]->owner;
  775. _process_group(local_process_group_cache[p_index], p_physics);
  776. Node::current_process_thread_group = nullptr;
  777. }
  778. void SceneTree::_process(bool p_physics) {
  779. if (process_groups_dirty) {
  780. {
  781. // First, remove dirty groups.
  782. // This needs to be done when not processing to avoid problems.
  783. ProcessGroup **pg_ptr = (ProcessGroup **)process_groups.ptr(); // discard constness.
  784. uint32_t pg_count = process_groups.size();
  785. for (uint32_t i = 0; i < pg_count; i++) {
  786. if (pg_ptr[i]->removed) {
  787. // Replace removed with last.
  788. pg_ptr[i] = pg_ptr[pg_count - 1];
  789. // Retry
  790. i--;
  791. pg_count--;
  792. }
  793. }
  794. if (pg_count != process_groups.size()) {
  795. process_groups.resize(pg_count);
  796. }
  797. }
  798. {
  799. // Then, re-sort groups.
  800. process_groups.sort_custom<ProcessGroupSort>();
  801. }
  802. process_groups_dirty = false;
  803. }
  804. // Cache the group count, because during processing new groups may be added.
  805. // They will be added at the end, hence for consistency they will be ignored by this process loop.
  806. // No group will be removed from the array during processing (this is done earlier in this function by marking the groups dirty).
  807. uint32_t group_count = process_groups.size();
  808. if (group_count == 0) {
  809. return;
  810. }
  811. process_last_pass++; // Increment pass
  812. uint32_t from = 0;
  813. uint32_t process_count = 0;
  814. nodes_removed_on_group_call_lock++;
  815. int current_order = process_groups[0]->owner ? process_groups[0]->owner->data.process_thread_group_order : 0;
  816. bool current_threaded = process_groups[0]->owner ? process_groups[0]->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD : false;
  817. for (uint32_t i = 0; i <= group_count; i++) {
  818. int order = i < group_count && process_groups[i]->owner ? process_groups[i]->owner->data.process_thread_group_order : 0;
  819. bool threaded = i < group_count && process_groups[i]->owner ? process_groups[i]->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD : false;
  820. if (i == group_count || current_order != order || current_threaded != threaded) {
  821. if (process_count > 0) {
  822. // Proceed to process the group.
  823. bool using_threads = process_groups[from]->owner && process_groups[from]->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD && !node_threading_disabled;
  824. if (using_threads) {
  825. local_process_group_cache.clear();
  826. }
  827. for (uint32_t j = from; j < i; j++) {
  828. if (process_groups[j]->last_pass == process_last_pass) {
  829. if (using_threads) {
  830. local_process_group_cache.push_back(process_groups[j]);
  831. } else {
  832. _process_group(process_groups[j], p_physics);
  833. }
  834. }
  835. }
  836. if (using_threads) {
  837. WorkerThreadPool::GroupID id = WorkerThreadPool::get_singleton()->add_template_group_task(this, &SceneTree::_process_groups_thread, p_physics, local_process_group_cache.size(), -1, true);
  838. WorkerThreadPool::get_singleton()->wait_for_group_task_completion(id);
  839. }
  840. }
  841. if (i == group_count) {
  842. // This one is invalid, no longer process
  843. break;
  844. }
  845. from = i;
  846. current_threaded = threaded;
  847. current_order = order;
  848. }
  849. if (process_groups[i]->removed) {
  850. continue;
  851. }
  852. ProcessGroup *pg = process_groups[i];
  853. // Validate group for processing
  854. bool process_valid = false;
  855. if (p_physics) {
  856. if (!pg->physics_nodes.is_empty()) {
  857. process_valid = true;
  858. } else if ((pg == &default_process_group || (pg->owner != nullptr && pg->owner->data.process_thread_messages.has_flag(Node::FLAG_PROCESS_THREAD_MESSAGES_PHYSICS))) && pg->call_queue.has_messages()) {
  859. process_valid = true;
  860. }
  861. } else {
  862. if (!pg->nodes.is_empty()) {
  863. process_valid = true;
  864. } else if ((pg == &default_process_group || (pg->owner != nullptr && pg->owner->data.process_thread_messages.has_flag(Node::FLAG_PROCESS_THREAD_MESSAGES))) && pg->call_queue.has_messages()) {
  865. process_valid = true;
  866. }
  867. }
  868. if (process_valid) {
  869. pg->last_pass = process_last_pass; // Enable for processing
  870. process_count++;
  871. }
  872. }
  873. nodes_removed_on_group_call_lock--;
  874. if (nodes_removed_on_group_call_lock == 0) {
  875. nodes_removed_on_group_call.clear();
  876. }
  877. }
  878. bool SceneTree::ProcessGroupSort::operator()(const ProcessGroup *p_left, const ProcessGroup *p_right) const {
  879. int left_order = p_left->owner ? p_left->owner->data.process_thread_group_order : 0;
  880. int right_order = p_right->owner ? p_right->owner->data.process_thread_group_order : 0;
  881. if (left_order == right_order) {
  882. int left_threaded = p_left->owner != nullptr && p_left->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD ? 0 : 1;
  883. int right_threaded = p_right->owner != nullptr && p_right->owner->data.process_thread_group == Node::PROCESS_THREAD_GROUP_SUB_THREAD ? 0 : 1;
  884. return left_threaded < right_threaded;
  885. } else {
  886. return left_order < right_order;
  887. }
  888. }
  889. void SceneTree::_remove_process_group(Node *p_node) {
  890. _THREAD_SAFE_METHOD_
  891. ProcessGroup *pg = (ProcessGroup *)p_node->data.process_group;
  892. ERR_FAIL_NULL(pg);
  893. ERR_FAIL_COND(pg->removed);
  894. pg->removed = true;
  895. pg->owner = nullptr;
  896. p_node->data.process_group = nullptr;
  897. process_groups_dirty = true;
  898. }
  899. void SceneTree::_add_process_group(Node *p_node) {
  900. _THREAD_SAFE_METHOD_
  901. ERR_FAIL_NULL(p_node);
  902. ProcessGroup *pg = memnew(ProcessGroup);
  903. pg->owner = p_node;
  904. p_node->data.process_group = pg;
  905. process_groups.push_back(pg);
  906. process_groups_dirty = true;
  907. }
  908. void SceneTree::_remove_node_from_process_group(Node *p_node, Node *p_owner) {
  909. _THREAD_SAFE_METHOD_
  910. ProcessGroup *pg = p_owner ? (ProcessGroup *)p_owner->data.process_group : &default_process_group;
  911. if (p_node->is_processing() || p_node->is_processing_internal()) {
  912. bool found = pg->nodes.erase(p_node);
  913. ERR_FAIL_COND(!found);
  914. }
  915. if (p_node->is_physics_processing() || p_node->is_physics_processing_internal()) {
  916. bool found = pg->physics_nodes.erase(p_node);
  917. ERR_FAIL_COND(!found);
  918. }
  919. }
  920. void SceneTree::_add_node_to_process_group(Node *p_node, Node *p_owner) {
  921. _THREAD_SAFE_METHOD_
  922. ProcessGroup *pg = p_owner ? (ProcessGroup *)p_owner->data.process_group : &default_process_group;
  923. if (p_node->is_processing() || p_node->is_processing_internal()) {
  924. pg->nodes.push_back(p_node);
  925. pg->node_order_dirty = true;
  926. }
  927. if (p_node->is_physics_processing() || p_node->is_physics_processing_internal()) {
  928. pg->physics_nodes.push_back(p_node);
  929. pg->physics_node_order_dirty = true;
  930. }
  931. }
  932. void SceneTree::_call_input_pause(const StringName &p_group, CallInputType p_call_type, const Ref<InputEvent> &p_input, Viewport *p_viewport) {
  933. Vector<Node *> nodes_copy;
  934. {
  935. _THREAD_SAFE_METHOD_
  936. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  937. if (!E) {
  938. return;
  939. }
  940. Group &g = E->value;
  941. if (g.nodes.is_empty()) {
  942. return;
  943. }
  944. _update_group_order(g);
  945. //copy, so copy on write happens in case something is removed from process while being called
  946. //performance is not lost because only if something is added/removed the vector is copied.
  947. nodes_copy = g.nodes;
  948. }
  949. int gr_node_count = nodes_copy.size();
  950. Node **gr_nodes = nodes_copy.ptrw();
  951. {
  952. _THREAD_SAFE_METHOD_
  953. nodes_removed_on_group_call_lock++;
  954. }
  955. Vector<ObjectID> no_context_node_ids; // Nodes may be deleted due to this shortcut input.
  956. for (int i = gr_node_count - 1; i >= 0; i--) {
  957. if (p_viewport->is_input_handled()) {
  958. break;
  959. }
  960. Node *n = gr_nodes[i];
  961. if (nodes_removed_on_group_call.has(n)) {
  962. continue;
  963. }
  964. if (!n->can_process()) {
  965. continue;
  966. }
  967. switch (p_call_type) {
  968. case CALL_INPUT_TYPE_INPUT:
  969. n->_call_input(p_input);
  970. break;
  971. case CALL_INPUT_TYPE_SHORTCUT_INPUT: {
  972. const Control *c = Object::cast_to<Control>(n);
  973. if (c) {
  974. // If calling shortcut input on a control, ensure it respects the shortcut context.
  975. // Shortcut context (based on focus) only makes sense for controls (UI), so don't need to worry about it for nodes
  976. if (c->get_shortcut_context() == nullptr) {
  977. no_context_node_ids.append(n->get_instance_id());
  978. continue;
  979. }
  980. if (!c->is_focus_owner_in_shortcut_context()) {
  981. continue;
  982. }
  983. }
  984. n->_call_shortcut_input(p_input);
  985. break;
  986. }
  987. case CALL_INPUT_TYPE_UNHANDLED_INPUT:
  988. n->_call_unhandled_input(p_input);
  989. break;
  990. case CALL_INPUT_TYPE_UNHANDLED_KEY_INPUT:
  991. n->_call_unhandled_key_input(p_input);
  992. break;
  993. }
  994. }
  995. for (const ObjectID &id : no_context_node_ids) {
  996. if (p_viewport->is_input_handled()) {
  997. break;
  998. }
  999. Node *n = Object::cast_to<Node>(ObjectDB::get_instance(id));
  1000. if (n) {
  1001. n->_call_shortcut_input(p_input);
  1002. }
  1003. }
  1004. {
  1005. _THREAD_SAFE_METHOD_
  1006. nodes_removed_on_group_call_lock--;
  1007. if (nodes_removed_on_group_call_lock == 0) {
  1008. nodes_removed_on_group_call.clear();
  1009. }
  1010. }
  1011. }
  1012. void SceneTree::_call_group_flags(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1013. r_error.error = Callable::CallError::CALL_OK;
  1014. ERR_FAIL_COND(p_argcount < 3);
  1015. ERR_FAIL_COND(!p_args[0]->is_num());
  1016. ERR_FAIL_COND(p_args[1]->get_type() != Variant::STRING_NAME && p_args[1]->get_type() != Variant::STRING);
  1017. ERR_FAIL_COND(p_args[2]->get_type() != Variant::STRING_NAME && p_args[2]->get_type() != Variant::STRING);
  1018. int flags = *p_args[0];
  1019. StringName group = *p_args[1];
  1020. StringName method = *p_args[2];
  1021. call_group_flagsp(flags, group, method, p_args + 3, p_argcount - 3);
  1022. }
  1023. void SceneTree::_call_group(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
  1024. r_error.error = Callable::CallError::CALL_OK;
  1025. ERR_FAIL_COND(p_argcount < 2);
  1026. ERR_FAIL_COND(p_args[0]->get_type() != Variant::STRING_NAME && p_args[0]->get_type() != Variant::STRING);
  1027. ERR_FAIL_COND(p_args[1]->get_type() != Variant::STRING_NAME && p_args[1]->get_type() != Variant::STRING);
  1028. StringName group = *p_args[0];
  1029. StringName method = *p_args[1];
  1030. call_group_flagsp(GROUP_CALL_DEFAULT, group, method, p_args + 2, p_argcount - 2);
  1031. }
  1032. int64_t SceneTree::get_frame() const {
  1033. return current_frame;
  1034. }
  1035. TypedArray<Node> SceneTree::_get_nodes_in_group(const StringName &p_group) {
  1036. _THREAD_SAFE_METHOD_
  1037. TypedArray<Node> ret;
  1038. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1039. if (!E) {
  1040. return ret;
  1041. }
  1042. _update_group_order(E->value); //update order just in case
  1043. int nc = E->value.nodes.size();
  1044. if (nc == 0) {
  1045. return ret;
  1046. }
  1047. ret.resize(nc);
  1048. Node **ptr = E->value.nodes.ptrw();
  1049. for (int i = 0; i < nc; i++) {
  1050. ret[i] = ptr[i];
  1051. }
  1052. return ret;
  1053. }
  1054. bool SceneTree::has_group(const StringName &p_identifier) const {
  1055. _THREAD_SAFE_METHOD_
  1056. return group_map.has(p_identifier);
  1057. }
  1058. Node *SceneTree::get_first_node_in_group(const StringName &p_group) {
  1059. _THREAD_SAFE_METHOD_
  1060. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1061. if (!E) {
  1062. return nullptr; // No group.
  1063. }
  1064. _update_group_order(E->value); // Update order just in case.
  1065. if (E->value.nodes.is_empty()) {
  1066. return nullptr;
  1067. }
  1068. return E->value.nodes[0];
  1069. }
  1070. void SceneTree::get_nodes_in_group(const StringName &p_group, List<Node *> *p_list) {
  1071. _THREAD_SAFE_METHOD_
  1072. HashMap<StringName, Group>::Iterator E = group_map.find(p_group);
  1073. if (!E) {
  1074. return;
  1075. }
  1076. _update_group_order(E->value); //update order just in case
  1077. int nc = E->value.nodes.size();
  1078. if (nc == 0) {
  1079. return;
  1080. }
  1081. Node **ptr = E->value.nodes.ptrw();
  1082. for (int i = 0; i < nc; i++) {
  1083. p_list->push_back(ptr[i]);
  1084. }
  1085. }
  1086. void SceneTree::_flush_delete_queue() {
  1087. _THREAD_SAFE_METHOD_
  1088. while (delete_queue.size()) {
  1089. Object *obj = ObjectDB::get_instance(delete_queue.front()->get());
  1090. if (obj) {
  1091. memdelete(obj);
  1092. }
  1093. delete_queue.pop_front();
  1094. }
  1095. }
  1096. void SceneTree::queue_delete(Object *p_object) {
  1097. _THREAD_SAFE_METHOD_
  1098. ERR_FAIL_NULL(p_object);
  1099. p_object->_is_queued_for_deletion = true;
  1100. delete_queue.push_back(p_object->get_instance_id());
  1101. }
  1102. int SceneTree::get_node_count() const {
  1103. return nodes_in_tree_count;
  1104. }
  1105. void SceneTree::set_edited_scene_root(Node *p_node) {
  1106. #ifdef TOOLS_ENABLED
  1107. edited_scene_root = p_node;
  1108. #endif
  1109. }
  1110. Node *SceneTree::get_edited_scene_root() const {
  1111. #ifdef TOOLS_ENABLED
  1112. return edited_scene_root;
  1113. #else
  1114. return nullptr;
  1115. #endif
  1116. }
  1117. void SceneTree::set_current_scene(Node *p_scene) {
  1118. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Changing scene can only be done from the main thread.");
  1119. ERR_FAIL_COND(p_scene && p_scene->get_parent() != root);
  1120. current_scene = p_scene;
  1121. }
  1122. Node *SceneTree::get_current_scene() const {
  1123. return current_scene;
  1124. }
  1125. void SceneTree::_flush_scene_change() {
  1126. if (prev_scene) {
  1127. memdelete(prev_scene);
  1128. prev_scene = nullptr;
  1129. }
  1130. current_scene = pending_new_scene;
  1131. root->add_child(pending_new_scene);
  1132. pending_new_scene = nullptr;
  1133. // Update display for cursor instantly.
  1134. root->update_mouse_cursor_state();
  1135. }
  1136. Error SceneTree::change_scene_to_file(const String &p_path) {
  1137. ERR_FAIL_COND_V_MSG(!Thread::is_main_thread(), ERR_INVALID_PARAMETER, "Changing scene can only be done from the main thread.");
  1138. Ref<PackedScene> new_scene = ResourceLoader::load(p_path);
  1139. if (new_scene.is_null()) {
  1140. return ERR_CANT_OPEN;
  1141. }
  1142. return change_scene_to_packed(new_scene);
  1143. }
  1144. Error SceneTree::change_scene_to_packed(const Ref<PackedScene> &p_scene) {
  1145. ERR_FAIL_COND_V_MSG(p_scene.is_null(), ERR_INVALID_PARAMETER, "Can't change to a null scene. Use unload_current_scene() if you wish to unload it.");
  1146. Node *new_scene = p_scene->instantiate();
  1147. ERR_FAIL_NULL_V(new_scene, ERR_CANT_CREATE);
  1148. // If called again while a change is pending.
  1149. if (pending_new_scene) {
  1150. queue_delete(pending_new_scene);
  1151. pending_new_scene = nullptr;
  1152. }
  1153. prev_scene = current_scene;
  1154. if (current_scene) {
  1155. // Let as many side effects as possible happen or be queued now,
  1156. // so they are run before the scene is actually deleted.
  1157. root->remove_child(current_scene);
  1158. }
  1159. DEV_ASSERT(!current_scene);
  1160. pending_new_scene = new_scene;
  1161. return OK;
  1162. }
  1163. Error SceneTree::reload_current_scene() {
  1164. ERR_FAIL_COND_V_MSG(!Thread::is_main_thread(), ERR_INVALID_PARAMETER, "Reloading scene can only be done from the main thread.");
  1165. ERR_FAIL_NULL_V(current_scene, ERR_UNCONFIGURED);
  1166. String fname = current_scene->get_scene_file_path();
  1167. return change_scene_to_file(fname);
  1168. }
  1169. void SceneTree::unload_current_scene() {
  1170. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Unloading the current scene can only be done from the main thread.");
  1171. if (current_scene) {
  1172. memdelete(current_scene);
  1173. current_scene = nullptr;
  1174. }
  1175. }
  1176. void SceneTree::add_current_scene(Node *p_current) {
  1177. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Adding a current scene can only be done from the main thread.");
  1178. current_scene = p_current;
  1179. root->add_child(p_current);
  1180. }
  1181. Ref<SceneTreeTimer> SceneTree::create_timer(double p_delay_sec, bool p_process_always, bool p_process_in_physics, bool p_ignore_time_scale) {
  1182. _THREAD_SAFE_METHOD_
  1183. Ref<SceneTreeTimer> stt;
  1184. stt.instantiate();
  1185. stt->set_process_always(p_process_always);
  1186. stt->set_time_left(p_delay_sec);
  1187. stt->set_process_in_physics(p_process_in_physics);
  1188. stt->set_ignore_time_scale(p_ignore_time_scale);
  1189. timers.push_back(stt);
  1190. return stt;
  1191. }
  1192. Ref<Tween> SceneTree::create_tween() {
  1193. _THREAD_SAFE_METHOD_
  1194. Ref<Tween> tween = memnew(Tween(true));
  1195. tweens.push_back(tween);
  1196. return tween;
  1197. }
  1198. TypedArray<Tween> SceneTree::get_processed_tweens() {
  1199. _THREAD_SAFE_METHOD_
  1200. TypedArray<Tween> ret;
  1201. ret.resize(tweens.size());
  1202. int i = 0;
  1203. for (const Ref<Tween> &tween : tweens) {
  1204. ret[i] = tween;
  1205. i++;
  1206. }
  1207. return ret;
  1208. }
  1209. Ref<MultiplayerAPI> SceneTree::get_multiplayer(const NodePath &p_for_path) const {
  1210. ERR_FAIL_COND_V_MSG(!Thread::is_main_thread(), Ref<MultiplayerAPI>(), "Multiplayer can only be manipulated from the main thread.");
  1211. if (p_for_path.is_empty()) {
  1212. return multiplayer;
  1213. }
  1214. const Vector<StringName> tnames = p_for_path.get_names();
  1215. const StringName *nptr = tnames.ptr();
  1216. for (const KeyValue<NodePath, Ref<MultiplayerAPI>> &E : custom_multiplayers) {
  1217. const Vector<StringName> snames = E.key.get_names();
  1218. if (tnames.size() < snames.size()) {
  1219. continue;
  1220. }
  1221. const StringName *sptr = snames.ptr();
  1222. bool valid = true;
  1223. for (int i = 0; i < snames.size(); i++) {
  1224. if (sptr[i] != nptr[i]) {
  1225. valid = false;
  1226. break;
  1227. }
  1228. }
  1229. if (valid) {
  1230. return E.value;
  1231. }
  1232. }
  1233. return multiplayer;
  1234. }
  1235. void SceneTree::set_multiplayer(Ref<MultiplayerAPI> p_multiplayer, const NodePath &p_root_path) {
  1236. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Multiplayer can only be manipulated from the main thread.");
  1237. if (p_root_path.is_empty()) {
  1238. ERR_FAIL_COND(!p_multiplayer.is_valid());
  1239. if (multiplayer.is_valid()) {
  1240. multiplayer->object_configuration_remove(nullptr, NodePath("/" + root->get_name()));
  1241. }
  1242. multiplayer = p_multiplayer;
  1243. multiplayer->object_configuration_add(nullptr, NodePath("/" + root->get_name()));
  1244. } else {
  1245. if (custom_multiplayers.has(p_root_path)) {
  1246. custom_multiplayers[p_root_path]->object_configuration_remove(nullptr, p_root_path);
  1247. } else if (p_multiplayer.is_valid()) {
  1248. const Vector<StringName> tnames = p_root_path.get_names();
  1249. const StringName *nptr = tnames.ptr();
  1250. for (const KeyValue<NodePath, Ref<MultiplayerAPI>> &E : custom_multiplayers) {
  1251. const Vector<StringName> snames = E.key.get_names();
  1252. if (tnames.size() < snames.size()) {
  1253. continue;
  1254. }
  1255. const StringName *sptr = snames.ptr();
  1256. bool valid = true;
  1257. for (int i = 0; i < snames.size(); i++) {
  1258. if (sptr[i] != nptr[i]) {
  1259. valid = false;
  1260. break;
  1261. }
  1262. }
  1263. ERR_FAIL_COND_MSG(valid, "Multiplayer is already configured for a parent of this path: '" + p_root_path + "' in '" + E.key + "'.");
  1264. }
  1265. }
  1266. if (p_multiplayer.is_valid()) {
  1267. custom_multiplayers[p_root_path] = p_multiplayer;
  1268. p_multiplayer->object_configuration_add(nullptr, p_root_path);
  1269. } else {
  1270. custom_multiplayers.erase(p_root_path);
  1271. }
  1272. }
  1273. }
  1274. void SceneTree::set_multiplayer_poll_enabled(bool p_enabled) {
  1275. ERR_FAIL_COND_MSG(!Thread::is_main_thread(), "Multiplayer can only be manipulated from the main thread.");
  1276. multiplayer_poll = p_enabled;
  1277. }
  1278. bool SceneTree::is_multiplayer_poll_enabled() const {
  1279. return multiplayer_poll;
  1280. }
  1281. void SceneTree::_bind_methods() {
  1282. ClassDB::bind_method(D_METHOD("get_root"), &SceneTree::get_root);
  1283. ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group);
  1284. ClassDB::bind_method(D_METHOD("is_auto_accept_quit"), &SceneTree::is_auto_accept_quit);
  1285. ClassDB::bind_method(D_METHOD("set_auto_accept_quit", "enabled"), &SceneTree::set_auto_accept_quit);
  1286. ClassDB::bind_method(D_METHOD("is_quit_on_go_back"), &SceneTree::is_quit_on_go_back);
  1287. ClassDB::bind_method(D_METHOD("set_quit_on_go_back", "enabled"), &SceneTree::set_quit_on_go_back);
  1288. ClassDB::bind_method(D_METHOD("set_debug_collisions_hint", "enable"), &SceneTree::set_debug_collisions_hint);
  1289. ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"), &SceneTree::is_debugging_collisions_hint);
  1290. ClassDB::bind_method(D_METHOD("set_debug_paths_hint", "enable"), &SceneTree::set_debug_paths_hint);
  1291. ClassDB::bind_method(D_METHOD("is_debugging_paths_hint"), &SceneTree::is_debugging_paths_hint);
  1292. ClassDB::bind_method(D_METHOD("set_debug_navigation_hint", "enable"), &SceneTree::set_debug_navigation_hint);
  1293. ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"), &SceneTree::is_debugging_navigation_hint);
  1294. ClassDB::bind_method(D_METHOD("set_edited_scene_root", "scene"), &SceneTree::set_edited_scene_root);
  1295. ClassDB::bind_method(D_METHOD("get_edited_scene_root"), &SceneTree::get_edited_scene_root);
  1296. ClassDB::bind_method(D_METHOD("set_pause", "enable"), &SceneTree::set_pause);
  1297. ClassDB::bind_method(D_METHOD("is_paused"), &SceneTree::is_paused);
  1298. ClassDB::bind_method(D_METHOD("create_timer", "time_sec", "process_always", "process_in_physics", "ignore_time_scale"), &SceneTree::create_timer, DEFVAL(true), DEFVAL(false), DEFVAL(false));
  1299. ClassDB::bind_method(D_METHOD("create_tween"), &SceneTree::create_tween);
  1300. ClassDB::bind_method(D_METHOD("get_processed_tweens"), &SceneTree::get_processed_tweens);
  1301. ClassDB::bind_method(D_METHOD("get_node_count"), &SceneTree::get_node_count);
  1302. ClassDB::bind_method(D_METHOD("get_frame"), &SceneTree::get_frame);
  1303. ClassDB::bind_method(D_METHOD("quit", "exit_code"), &SceneTree::quit, DEFVAL(EXIT_SUCCESS));
  1304. ClassDB::bind_method(D_METHOD("queue_delete", "obj"), &SceneTree::queue_delete);
  1305. MethodInfo mi;
  1306. mi.name = "call_group_flags";
  1307. mi.arguments.push_back(PropertyInfo(Variant::INT, "flags"));
  1308. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "group"));
  1309. mi.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1310. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group_flags", &SceneTree::_call_group_flags, mi);
  1311. ClassDB::bind_method(D_METHOD("notify_group_flags", "call_flags", "group", "notification"), &SceneTree::notify_group_flags);
  1312. ClassDB::bind_method(D_METHOD("set_group_flags", "call_flags", "group", "property", "value"), &SceneTree::set_group_flags);
  1313. MethodInfo mi2;
  1314. mi2.name = "call_group";
  1315. mi2.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "group"));
  1316. mi2.arguments.push_back(PropertyInfo(Variant::STRING_NAME, "method"));
  1317. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group", &SceneTree::_call_group, mi2);
  1318. ClassDB::bind_method(D_METHOD("notify_group", "group", "notification"), &SceneTree::notify_group);
  1319. ClassDB::bind_method(D_METHOD("set_group", "group", "property", "value"), &SceneTree::set_group);
  1320. ClassDB::bind_method(D_METHOD("get_nodes_in_group", "group"), &SceneTree::_get_nodes_in_group);
  1321. ClassDB::bind_method(D_METHOD("get_first_node_in_group", "group"), &SceneTree::get_first_node_in_group);
  1322. ClassDB::bind_method(D_METHOD("set_current_scene", "child_node"), &SceneTree::set_current_scene);
  1323. ClassDB::bind_method(D_METHOD("get_current_scene"), &SceneTree::get_current_scene);
  1324. ClassDB::bind_method(D_METHOD("change_scene_to_file", "path"), &SceneTree::change_scene_to_file);
  1325. ClassDB::bind_method(D_METHOD("change_scene_to_packed", "packed_scene"), &SceneTree::change_scene_to_packed);
  1326. ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene);
  1327. ClassDB::bind_method(D_METHOD("unload_current_scene"), &SceneTree::unload_current_scene);
  1328. ClassDB::bind_method(D_METHOD("set_multiplayer", "multiplayer", "root_path"), &SceneTree::set_multiplayer, DEFVAL(NodePath()));
  1329. ClassDB::bind_method(D_METHOD("get_multiplayer", "for_path"), &SceneTree::get_multiplayer, DEFVAL(NodePath()));
  1330. ClassDB::bind_method(D_METHOD("set_multiplayer_poll_enabled", "enabled"), &SceneTree::set_multiplayer_poll_enabled);
  1331. ClassDB::bind_method(D_METHOD("is_multiplayer_poll_enabled"), &SceneTree::is_multiplayer_poll_enabled);
  1332. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "auto_accept_quit"), "set_auto_accept_quit", "is_auto_accept_quit");
  1333. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "quit_on_go_back"), "set_quit_on_go_back", "is_quit_on_go_back");
  1334. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_collisions_hint"), "set_debug_collisions_hint", "is_debugging_collisions_hint");
  1335. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_paths_hint"), "set_debug_paths_hint", "is_debugging_paths_hint");
  1336. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "debug_navigation_hint"), "set_debug_navigation_hint", "is_debugging_navigation_hint");
  1337. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "paused"), "set_pause", "is_paused");
  1338. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "edited_scene_root", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_edited_scene_root", "get_edited_scene_root");
  1339. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "current_scene", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "set_current_scene", "get_current_scene");
  1340. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "root", PROPERTY_HINT_RESOURCE_TYPE, "Node", PROPERTY_USAGE_NONE), "", "get_root");
  1341. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "multiplayer_poll"), "set_multiplayer_poll_enabled", "is_multiplayer_poll_enabled");
  1342. ADD_SIGNAL(MethodInfo("tree_changed"));
  1343. ADD_SIGNAL(MethodInfo("tree_process_mode_changed")); //editor only signal, but due to API hash it can't be removed in run-time
  1344. ADD_SIGNAL(MethodInfo("node_added", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1345. ADD_SIGNAL(MethodInfo("node_removed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1346. ADD_SIGNAL(MethodInfo("node_renamed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1347. ADD_SIGNAL(MethodInfo("node_configuration_warning_changed", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
  1348. ADD_SIGNAL(MethodInfo("process_frame"));
  1349. ADD_SIGNAL(MethodInfo("physics_frame"));
  1350. BIND_ENUM_CONSTANT(GROUP_CALL_DEFAULT);
  1351. BIND_ENUM_CONSTANT(GROUP_CALL_REVERSE);
  1352. BIND_ENUM_CONSTANT(GROUP_CALL_DEFERRED);
  1353. BIND_ENUM_CONSTANT(GROUP_CALL_UNIQUE);
  1354. }
  1355. SceneTree *SceneTree::singleton = nullptr;
  1356. SceneTree::IdleCallback SceneTree::idle_callbacks[SceneTree::MAX_IDLE_CALLBACKS];
  1357. int SceneTree::idle_callback_count = 0;
  1358. void SceneTree::_call_idle_callbacks() {
  1359. for (int i = 0; i < idle_callback_count; i++) {
  1360. idle_callbacks[i]();
  1361. }
  1362. }
  1363. void SceneTree::add_idle_callback(IdleCallback p_callback) {
  1364. ERR_FAIL_COND(idle_callback_count >= MAX_IDLE_CALLBACKS);
  1365. idle_callbacks[idle_callback_count++] = p_callback;
  1366. }
  1367. void SceneTree::get_argument_options(const StringName &p_function, int p_idx, List<String> *r_options) const {
  1368. if (p_function == "change_scene_to_file") {
  1369. Ref<DirAccess> dir_access = DirAccess::create(DirAccess::ACCESS_RESOURCES);
  1370. List<String> directories;
  1371. directories.push_back(dir_access->get_current_dir());
  1372. while (!directories.is_empty()) {
  1373. dir_access->change_dir(directories.back()->get());
  1374. directories.pop_back();
  1375. dir_access->list_dir_begin();
  1376. String filename = dir_access->get_next();
  1377. while (!filename.is_empty()) {
  1378. if (filename == "." || filename == "..") {
  1379. filename = dir_access->get_next();
  1380. continue;
  1381. }
  1382. if (dir_access->dir_exists(filename)) {
  1383. directories.push_back(dir_access->get_current_dir().path_join(filename));
  1384. } else if (filename.ends_with(".tscn") || filename.ends_with(".scn")) {
  1385. r_options->push_back("\"" + dir_access->get_current_dir().path_join(filename) + "\"");
  1386. }
  1387. filename = dir_access->get_next();
  1388. }
  1389. }
  1390. }
  1391. MainLoop::get_argument_options(p_function, p_idx, r_options);
  1392. }
  1393. void SceneTree::set_disable_node_threading(bool p_disable) {
  1394. node_threading_disabled = p_disable;
  1395. }
  1396. SceneTree::SceneTree() {
  1397. if (singleton == nullptr) {
  1398. singleton = this;
  1399. }
  1400. debug_collisions_color = GLOBAL_DEF("debug/shapes/collision/shape_color", Color(0.0, 0.6, 0.7, 0.42));
  1401. debug_collision_contact_color = GLOBAL_DEF("debug/shapes/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8));
  1402. debug_paths_color = GLOBAL_DEF("debug/shapes/paths/geometry_color", Color(0.1, 1.0, 0.7, 0.4));
  1403. debug_paths_width = GLOBAL_DEF("debug/shapes/paths/geometry_width", 2.0);
  1404. collision_debug_contacts = GLOBAL_DEF(PropertyInfo(Variant::INT, "debug/shapes/collision/max_contacts_displayed", PROPERTY_HINT_RANGE, "0,20000,1"), 10000);
  1405. GLOBAL_DEF("debug/shapes/collision/draw_2d_outlines", true);
  1406. process_group_call_queue_allocator = memnew(CallQueue::Allocator(64));
  1407. Math::randomize();
  1408. // Create with mainloop.
  1409. root = memnew(Window);
  1410. root->set_min_size(Size2i(64, 64)); // Define a very small minimum window size to prevent bugs such as GH-37242.
  1411. root->set_process_mode(Node::PROCESS_MODE_PAUSABLE);
  1412. root->set_name("root");
  1413. root->set_title(GLOBAL_GET("application/config/name"));
  1414. if (Engine::get_singleton()->is_editor_hint()) {
  1415. root->set_wrap_controls(true);
  1416. }
  1417. #ifndef _3D_DISABLED
  1418. if (!root->get_world_3d().is_valid()) {
  1419. root->set_world_3d(Ref<World3D>(memnew(World3D)));
  1420. }
  1421. root->set_as_audio_listener_3d(true);
  1422. #endif // _3D_DISABLED
  1423. // Initialize network state.
  1424. set_multiplayer(MultiplayerAPI::create_default_interface());
  1425. root->set_as_audio_listener_2d(true);
  1426. current_scene = nullptr;
  1427. const int msaa_mode_2d = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_2d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), 0);
  1428. root->set_msaa_2d(Viewport::MSAA(msaa_mode_2d));
  1429. const int msaa_mode_3d = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/msaa_3d", PROPERTY_HINT_ENUM, String::utf8("Disabled (Fastest),2× (Average),4× (Slow),8× (Slowest)")), 0);
  1430. root->set_msaa_3d(Viewport::MSAA(msaa_mode_3d));
  1431. const bool transparent_background = GLOBAL_DEF("rendering/viewport/transparent_background", false);
  1432. root->set_transparent_background(transparent_background);
  1433. const bool use_hdr_2d = GLOBAL_DEF_RST_BASIC("rendering/viewport/hdr_2d", false);
  1434. root->set_use_hdr_2d(use_hdr_2d);
  1435. const int ssaa_mode = GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "rendering/anti_aliasing/quality/screen_space_aa", PROPERTY_HINT_ENUM, "Disabled (Fastest),FXAA (Fast)"), 0);
  1436. root->set_screen_space_aa(Viewport::ScreenSpaceAA(ssaa_mode));
  1437. const bool use_taa = GLOBAL_DEF_BASIC("rendering/anti_aliasing/quality/use_taa", false);
  1438. root->set_use_taa(use_taa);
  1439. const bool use_debanding = GLOBAL_DEF("rendering/anti_aliasing/quality/use_debanding", false);
  1440. root->set_use_debanding(use_debanding);
  1441. const bool use_occlusion_culling = GLOBAL_DEF("rendering/occlusion_culling/use_occlusion_culling", false);
  1442. root->set_use_occlusion_culling(use_occlusion_culling);
  1443. float mesh_lod_threshold = GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "rendering/mesh_lod/lod_change/threshold_pixels", PROPERTY_HINT_RANGE, "0,1024,0.1"), 1.0);
  1444. root->set_mesh_lod_threshold(mesh_lod_threshold);
  1445. bool snap_2d_transforms = GLOBAL_DEF("rendering/2d/snap/snap_2d_transforms_to_pixel", false);
  1446. root->set_snap_2d_transforms_to_pixel(snap_2d_transforms);
  1447. bool snap_2d_vertices = GLOBAL_DEF("rendering/2d/snap/snap_2d_vertices_to_pixel", false);
  1448. root->set_snap_2d_vertices_to_pixel(snap_2d_vertices);
  1449. // We setup VRS for the main viewport here, in the editor this will have little effect.
  1450. const int vrs_mode = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/vrs/mode", PROPERTY_HINT_ENUM, String::utf8("Disabled,Texture,XR")), 0);
  1451. root->set_vrs_mode(Viewport::VRSMode(vrs_mode));
  1452. const String vrs_texture_path = String(GLOBAL_DEF(PropertyInfo(Variant::STRING, "rendering/vrs/texture", PROPERTY_HINT_FILE, "*.bmp,*.png,*.tga,*.webp"), String())).strip_edges();
  1453. if (vrs_mode == 1 && !vrs_texture_path.is_empty()) {
  1454. Ref<Image> vrs_image;
  1455. vrs_image.instantiate();
  1456. Error load_err = ImageLoader::load_image(vrs_texture_path, vrs_image);
  1457. if (load_err) {
  1458. ERR_PRINT("Non-existing or invalid VRS texture at '" + vrs_texture_path + "'.");
  1459. } else {
  1460. Ref<ImageTexture> vrs_texture;
  1461. vrs_texture.instantiate();
  1462. vrs_texture->create_from_image(vrs_image);
  1463. root->set_vrs_texture(vrs_texture);
  1464. }
  1465. }
  1466. int shadowmap_size = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_size", PROPERTY_HINT_RANGE, "256,16384"), 4096);
  1467. GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_size.mobile", 2048);
  1468. bool shadowmap_16_bits = GLOBAL_DEF("rendering/lights_and_shadows/positional_shadow/atlas_16_bits", true);
  1469. int atlas_q0 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_0_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 2);
  1470. int atlas_q1 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_1_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 2);
  1471. int atlas_q2 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_2_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 3);
  1472. int atlas_q3 = GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/lights_and_shadows/positional_shadow/atlas_quadrant_3_subdiv", PROPERTY_HINT_ENUM, "Disabled,1 Shadow,4 Shadows,16 Shadows,64 Shadows,256 Shadows,1024 Shadows"), 4);
  1473. root->set_positional_shadow_atlas_size(shadowmap_size);
  1474. root->set_positional_shadow_atlas_16_bits(shadowmap_16_bits);
  1475. root->set_positional_shadow_atlas_quadrant_subdiv(0, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q0));
  1476. root->set_positional_shadow_atlas_quadrant_subdiv(1, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q1));
  1477. root->set_positional_shadow_atlas_quadrant_subdiv(2, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q2));
  1478. root->set_positional_shadow_atlas_quadrant_subdiv(3, Viewport::PositionalShadowAtlasQuadrantSubdiv(atlas_q3));
  1479. Viewport::SDFOversize sdf_oversize = Viewport::SDFOversize(int(GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/2d/sdf/oversize", PROPERTY_HINT_ENUM, "100%,120%,150%,200%"), 1)));
  1480. root->set_sdf_oversize(sdf_oversize);
  1481. Viewport::SDFScale sdf_scale = Viewport::SDFScale(int(GLOBAL_DEF(PropertyInfo(Variant::INT, "rendering/2d/sdf/scale", PROPERTY_HINT_ENUM, "100%,50%,25%"), 1)));
  1482. root->set_sdf_scale(sdf_scale);
  1483. #ifndef _3D_DISABLED
  1484. { // Load default fallback environment.
  1485. // Get possible extensions.
  1486. List<String> exts;
  1487. ResourceLoader::get_recognized_extensions_for_type("Environment", &exts);
  1488. String ext_hint;
  1489. for (const String &E : exts) {
  1490. if (!ext_hint.is_empty()) {
  1491. ext_hint += ",";
  1492. }
  1493. ext_hint += "*." + E;
  1494. }
  1495. // Get path.
  1496. String env_path = GLOBAL_DEF(PropertyInfo(Variant::STRING, "rendering/environment/defaults/default_environment", PROPERTY_HINT_FILE, ext_hint), "");
  1497. // Setup property.
  1498. env_path = env_path.strip_edges();
  1499. if (!env_path.is_empty()) {
  1500. Ref<Environment> env = ResourceLoader::load(env_path);
  1501. if (env.is_valid()) {
  1502. root->get_world_3d()->set_fallback_environment(env);
  1503. } else {
  1504. if (Engine::get_singleton()->is_editor_hint()) {
  1505. // File was erased, clear the field.
  1506. ProjectSettings::get_singleton()->set("rendering/environment/defaults/default_environment", "");
  1507. } else {
  1508. // File was erased, notify user.
  1509. ERR_PRINT("Default Environment as specified in the project setting \"rendering/environment/defaults/default_environment\" could not be loaded.");
  1510. }
  1511. }
  1512. }
  1513. }
  1514. #endif // _3D_DISABLED
  1515. root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking", true));
  1516. root->connect("close_requested", callable_mp(this, &SceneTree::_main_window_close));
  1517. root->connect("go_back_requested", callable_mp(this, &SceneTree::_main_window_go_back));
  1518. root->connect("focus_entered", callable_mp(this, &SceneTree::_main_window_focus_in));
  1519. #ifdef TOOLS_ENABLED
  1520. edited_scene_root = nullptr;
  1521. #endif
  1522. process_groups.push_back(&default_process_group);
  1523. }
  1524. SceneTree::~SceneTree() {
  1525. if (prev_scene) {
  1526. memdelete(prev_scene);
  1527. prev_scene = nullptr;
  1528. }
  1529. if (pending_new_scene) {
  1530. memdelete(pending_new_scene);
  1531. pending_new_scene = nullptr;
  1532. }
  1533. if (root) {
  1534. root->_set_tree(nullptr);
  1535. root->_propagate_after_exit_tree();
  1536. memdelete(root);
  1537. }
  1538. // Process groups are not deleted immediately, they may remain around. Delete them now.
  1539. for (uint32_t i = 0; i < process_groups.size(); i++) {
  1540. if (process_groups[i] != &default_process_group) {
  1541. memdelete(process_groups[i]);
  1542. }
  1543. }
  1544. memdelete(process_group_call_queue_allocator);
  1545. if (singleton == this) {
  1546. singleton = nullptr;
  1547. }
  1548. }