scene_tree.cpp 65 KB

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