scene_tree.cpp 67 KB

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