scene_tree.cpp 65 KB

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