scene_tree.cpp 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385
  1. /*************************************************************************/
  2. /* scene_tree.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */
  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 "editor/editor_node.h"
  32. #include "io/marshalls.h"
  33. #include "io/resource_loader.h"
  34. #include "message_queue.h"
  35. #include "node.h"
  36. #include "os/keyboard.h"
  37. #include "os/os.h"
  38. #include "print_string.h"
  39. #include "project_settings.h"
  40. #include "scene/resources/material.h"
  41. #include "scene/resources/mesh.h"
  42. #include "scene/resources/packed_scene.h"
  43. #include "scene/scene_string_names.h"
  44. #include "servers/physics_2d_server.h"
  45. #include "servers/physics_server.h"
  46. #include "viewport.h"
  47. #include <stdio.h>
  48. void SceneTreeTimer::_bind_methods() {
  49. ClassDB::bind_method(D_METHOD("set_time_left", "time"), &SceneTreeTimer::set_time_left);
  50. ClassDB::bind_method(D_METHOD("get_time_left"), &SceneTreeTimer::get_time_left);
  51. ADD_SIGNAL(MethodInfo("timeout"));
  52. }
  53. void SceneTreeTimer::set_time_left(float p_time) {
  54. time_left = p_time;
  55. }
  56. float SceneTreeTimer::get_time_left() const {
  57. return time_left;
  58. }
  59. void SceneTreeTimer::set_pause_mode_process(bool p_pause_mode_process) {
  60. if (process_pause != p_pause_mode_process) {
  61. process_pause = p_pause_mode_process;
  62. }
  63. }
  64. bool SceneTreeTimer::is_pause_mode_process() {
  65. return process_pause;
  66. }
  67. SceneTreeTimer::SceneTreeTimer() {
  68. time_left = 0;
  69. process_pause = true;
  70. }
  71. void SceneTree::tree_changed() {
  72. tree_version++;
  73. emit_signal(tree_changed_name);
  74. }
  75. void SceneTree::node_added(Node *p_node) {
  76. emit_signal(node_added_name, p_node);
  77. }
  78. void SceneTree::node_removed(Node *p_node) {
  79. if (current_scene == p_node) {
  80. current_scene = NULL;
  81. }
  82. emit_signal(node_removed_name, p_node);
  83. if (call_lock > 0)
  84. call_skip.insert(p_node);
  85. }
  86. SceneTree::Group *SceneTree::add_to_group(const StringName &p_group, Node *p_node) {
  87. Map<StringName, Group>::Element *E = group_map.find(p_group);
  88. if (!E) {
  89. E = group_map.insert(p_group, Group());
  90. }
  91. if (E->get().nodes.find(p_node) != -1) {
  92. ERR_EXPLAIN("Already in group: " + p_group);
  93. ERR_FAIL_V(&E->get());
  94. }
  95. E->get().nodes.push_back(p_node);
  96. //E->get().last_tree_version=0;
  97. E->get().changed = true;
  98. return &E->get();
  99. }
  100. void SceneTree::remove_from_group(const StringName &p_group, Node *p_node) {
  101. Map<StringName, Group>::Element *E = group_map.find(p_group);
  102. ERR_FAIL_COND(!E);
  103. E->get().nodes.erase(p_node);
  104. if (E->get().nodes.empty())
  105. group_map.erase(E);
  106. }
  107. void SceneTree::_flush_transform_notifications() {
  108. SelfList<Node> *n = xform_change_list.first();
  109. while (n) {
  110. Node *node = n->self();
  111. SelfList<Node> *nx = n->next();
  112. xform_change_list.remove(n);
  113. n = nx;
  114. node->notification(NOTIFICATION_TRANSFORM_CHANGED);
  115. }
  116. }
  117. void SceneTree::_flush_ugc() {
  118. ugc_locked = true;
  119. while (unique_group_calls.size()) {
  120. Map<UGCall, Vector<Variant> >::Element *E = unique_group_calls.front();
  121. Variant v[VARIANT_ARG_MAX];
  122. for (int i = 0; i < E->get().size(); i++)
  123. v[i] = E->get()[i];
  124. call_group_flags(GROUP_CALL_REALTIME, E->key().group, E->key().call, v[0], v[1], v[2], v[3], v[4]);
  125. unique_group_calls.erase(E);
  126. }
  127. ugc_locked = false;
  128. }
  129. void SceneTree::_update_group_order(Group &g) {
  130. if (!g.changed)
  131. return;
  132. if (g.nodes.empty())
  133. return;
  134. Node **nodes = &g.nodes[0];
  135. int node_count = g.nodes.size();
  136. SortArray<Node *, Node::Comparator> node_sort;
  137. node_sort.sort(nodes, node_count);
  138. g.changed = false;
  139. }
  140. void SceneTree::call_group_flags(uint32_t p_call_flags, const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) {
  141. Map<StringName, Group>::Element *E = group_map.find(p_group);
  142. if (!E)
  143. return;
  144. Group &g = E->get();
  145. if (g.nodes.empty())
  146. return;
  147. if (p_call_flags & GROUP_CALL_UNIQUE && !(p_call_flags & GROUP_CALL_REALTIME)) {
  148. ERR_FAIL_COND(ugc_locked);
  149. UGCall ug;
  150. ug.call = p_function;
  151. ug.group = p_group;
  152. if (unique_group_calls.has(ug))
  153. return;
  154. VARIANT_ARGPTRS;
  155. Vector<Variant> args;
  156. for (int i = 0; i < VARIANT_ARG_MAX; i++) {
  157. if (argptr[i]->get_type() == Variant::NIL)
  158. break;
  159. args.push_back(*argptr[i]);
  160. }
  161. unique_group_calls[ug] = args;
  162. return;
  163. }
  164. _update_group_order(g);
  165. Vector<Node *> nodes_copy = g.nodes;
  166. Node **nodes = &nodes_copy[0];
  167. int node_count = nodes_copy.size();
  168. call_lock++;
  169. if (p_call_flags & GROUP_CALL_REVERSE) {
  170. for (int i = node_count - 1; i >= 0; i--) {
  171. if (call_lock && call_skip.has(nodes[i]))
  172. continue;
  173. if (p_call_flags & GROUP_CALL_REALTIME) {
  174. if (p_call_flags & GROUP_CALL_MULTILEVEL)
  175. nodes[i]->call_multilevel(p_function, VARIANT_ARG_PASS);
  176. else
  177. nodes[i]->call(p_function, VARIANT_ARG_PASS);
  178. } else
  179. MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS);
  180. }
  181. } else {
  182. for (int i = 0; i < node_count; i++) {
  183. if (call_lock && call_skip.has(nodes[i]))
  184. continue;
  185. if (p_call_flags & GROUP_CALL_REALTIME) {
  186. if (p_call_flags & GROUP_CALL_MULTILEVEL)
  187. nodes[i]->call_multilevel(p_function, VARIANT_ARG_PASS);
  188. else
  189. nodes[i]->call(p_function, VARIANT_ARG_PASS);
  190. } else
  191. MessageQueue::get_singleton()->push_call(nodes[i], p_function, VARIANT_ARG_PASS);
  192. }
  193. }
  194. call_lock--;
  195. if (call_lock == 0)
  196. call_skip.clear();
  197. }
  198. void SceneTree::notify_group_flags(uint32_t p_call_flags, const StringName &p_group, int p_notification) {
  199. Map<StringName, Group>::Element *E = group_map.find(p_group);
  200. if (!E)
  201. return;
  202. Group &g = E->get();
  203. if (g.nodes.empty())
  204. return;
  205. _update_group_order(g);
  206. Vector<Node *> nodes_copy = g.nodes;
  207. Node **nodes = &nodes_copy[0];
  208. int node_count = nodes_copy.size();
  209. call_lock++;
  210. if (p_call_flags & GROUP_CALL_REVERSE) {
  211. for (int i = node_count - 1; i >= 0; i--) {
  212. if (call_lock && call_skip.has(nodes[i]))
  213. continue;
  214. if (p_call_flags & GROUP_CALL_REALTIME)
  215. nodes[i]->notification(p_notification);
  216. else
  217. MessageQueue::get_singleton()->push_notification(nodes[i], p_notification);
  218. }
  219. } else {
  220. for (int i = 0; i < node_count; i++) {
  221. if (call_lock && call_skip.has(nodes[i]))
  222. continue;
  223. if (p_call_flags & GROUP_CALL_REALTIME)
  224. nodes[i]->notification(p_notification);
  225. else
  226. MessageQueue::get_singleton()->push_notification(nodes[i], p_notification);
  227. }
  228. }
  229. call_lock--;
  230. if (call_lock == 0)
  231. call_skip.clear();
  232. }
  233. void SceneTree::set_group_flags(uint32_t p_call_flags, const StringName &p_group, const String &p_name, const Variant &p_value) {
  234. Map<StringName, Group>::Element *E = group_map.find(p_group);
  235. if (!E)
  236. return;
  237. Group &g = E->get();
  238. if (g.nodes.empty())
  239. return;
  240. _update_group_order(g);
  241. Vector<Node *> nodes_copy = g.nodes;
  242. Node **nodes = &nodes_copy[0];
  243. int node_count = nodes_copy.size();
  244. call_lock++;
  245. if (p_call_flags & GROUP_CALL_REVERSE) {
  246. for (int i = node_count - 1; i >= 0; i--) {
  247. if (call_lock && call_skip.has(nodes[i]))
  248. continue;
  249. if (p_call_flags & GROUP_CALL_REALTIME)
  250. nodes[i]->set(p_name, p_value);
  251. else
  252. MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value);
  253. }
  254. } else {
  255. for (int i = 0; i < node_count; i++) {
  256. if (call_lock && call_skip.has(nodes[i]))
  257. continue;
  258. if (p_call_flags & GROUP_CALL_REALTIME)
  259. nodes[i]->set(p_name, p_value);
  260. else
  261. MessageQueue::get_singleton()->push_set(nodes[i], p_name, p_value);
  262. }
  263. }
  264. call_lock--;
  265. if (call_lock == 0)
  266. call_skip.clear();
  267. }
  268. void SceneTree::call_group(const StringName &p_group, const StringName &p_function, VARIANT_ARG_DECLARE) {
  269. call_group_flags(0, p_group, VARIANT_ARG_PASS);
  270. }
  271. void SceneTree::notify_group(const StringName &p_group, int p_notification) {
  272. notify_group_flags(0, p_group, p_notification);
  273. }
  274. void SceneTree::set_group(const StringName &p_group, const String &p_name, const Variant &p_value) {
  275. set_group_flags(0, p_group, p_name, p_value);
  276. }
  277. void SceneTree::set_input_as_handled() {
  278. input_handled = true;
  279. }
  280. void SceneTree::input_text(const String &p_text) {
  281. root_lock++;
  282. call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_input_text", p_text); //special one for GUI, as controls use their own process check
  283. root_lock--;
  284. }
  285. bool SceneTree::is_input_handled() {
  286. return input_handled;
  287. }
  288. void SceneTree::input_event(const Ref<InputEvent> &p_event) {
  289. if (Engine::get_singleton()->is_editor_hint() && (Object::cast_to<InputEventJoypadButton>(p_event.ptr()) || Object::cast_to<InputEventJoypadMotion>(*p_event)))
  290. return; //avoid joy input on editor
  291. root_lock++;
  292. //last_id=p_event.ID;
  293. input_handled = false;
  294. Ref<InputEvent> ev = p_event;
  295. ev->set_id(++last_id); //this should work better
  296. MainLoop::input_event(ev);
  297. call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_input", ev); //special one for GUI, as controls use their own process check
  298. if (ScriptDebugger::get_singleton() && ScriptDebugger::get_singleton()->is_remote()) {
  299. //quit from game window using F8
  300. Ref<InputEventKey> k = ev;
  301. if (k.is_valid() && k->is_pressed() && !k->is_echo() && k->get_scancode() == KEY_F8) {
  302. ScriptDebugger::get_singleton()->request_quit();
  303. }
  304. }
  305. _flush_ugc();
  306. root_lock--;
  307. //MessageQueue::get_singleton()->flush(); //flushing here causes UI and other places slowness
  308. root_lock++;
  309. if (!input_handled) {
  310. call_group_flags(GROUP_CALL_REALTIME, "_viewports", "_vp_unhandled_input", ev); //special one for GUI, as controls use their own process check
  311. input_handled = true;
  312. _flush_ugc();
  313. root_lock--;
  314. //MessageQueue::get_singleton()->flush(); //flushing here causes UI and other places slowness
  315. } else {
  316. input_handled = true;
  317. root_lock--;
  318. }
  319. _call_idle_callbacks();
  320. }
  321. void SceneTree::init() {
  322. //_quit=false;
  323. initialized = true;
  324. input_handled = false;
  325. pause = false;
  326. root->_set_tree(this);
  327. MainLoop::init();
  328. }
  329. bool SceneTree::iteration(float p_time) {
  330. root_lock++;
  331. current_frame++;
  332. _flush_transform_notifications();
  333. MainLoop::iteration(p_time);
  334. physics_process_time = p_time;
  335. emit_signal("physics_frame");
  336. _notify_group_pause("physics_process_internal", Node::NOTIFICATION_INTERNAL_PHYSICS_PROCESS);
  337. _notify_group_pause("physics_process", Node::NOTIFICATION_PHYSICS_PROCESS);
  338. _flush_ugc();
  339. MessageQueue::get_singleton()->flush(); //small little hack
  340. _flush_transform_notifications();
  341. call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds");
  342. root_lock--;
  343. _flush_delete_queue();
  344. _call_idle_callbacks();
  345. return _quit;
  346. }
  347. bool SceneTree::idle(float p_time) {
  348. //print_line("ram: "+itos(OS::get_singleton()->get_static_memory_usage())+" sram: "+itos(OS::get_singleton()->get_dynamic_memory_usage()));
  349. //print_line("node count: "+itos(get_node_count()));
  350. //print_line("TEXTURE RAM: "+itos(VS::get_singleton()->get_render_info(VS::INFO_TEXTURE_MEM_USED)));
  351. root_lock++;
  352. MainLoop::idle(p_time);
  353. idle_process_time = p_time;
  354. _network_poll();
  355. emit_signal("idle_frame");
  356. MessageQueue::get_singleton()->flush(); //small little hack
  357. _flush_transform_notifications();
  358. _notify_group_pause("idle_process_internal", Node::NOTIFICATION_INTERNAL_PROCESS);
  359. _notify_group_pause("idle_process", Node::NOTIFICATION_PROCESS);
  360. Size2 win_size = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
  361. if (win_size != last_screen_size) {
  362. last_screen_size = win_size;
  363. _update_root_rect();
  364. emit_signal("screen_resized");
  365. }
  366. _flush_ugc();
  367. MessageQueue::get_singleton()->flush(); //small little hack
  368. _flush_transform_notifications(); //transforms after world update, to avoid unnecessary enter/exit notifications
  369. call_group_flags(GROUP_CALL_REALTIME, "_viewports", "update_worlds");
  370. root_lock--;
  371. _flush_delete_queue();
  372. //go through timers
  373. for (List<Ref<SceneTreeTimer> >::Element *E = timers.front(); E;) {
  374. List<Ref<SceneTreeTimer> >::Element *N = E->next();
  375. if (pause && !E->get()->is_pause_mode_process()) {
  376. E = N;
  377. continue;
  378. }
  379. float time_left = E->get()->get_time_left();
  380. time_left -= p_time;
  381. E->get()->set_time_left(time_left);
  382. if (time_left < 0) {
  383. E->get()->emit_signal("timeout");
  384. timers.erase(E);
  385. }
  386. E = N;
  387. }
  388. _call_idle_callbacks();
  389. #ifdef TOOLS_ENABLED
  390. if (Engine::get_singleton()->is_editor_hint()) {
  391. //simple hack to reload fallback environment if it changed from editor
  392. String env_path = ProjectSettings::get_singleton()->get("rendering/environment/default_environment");
  393. env_path = env_path.strip_edges(); //user may have added a space or two
  394. String cpath;
  395. Ref<Environment> fallback = get_root()->get_world()->get_fallback_environment();
  396. if (fallback.is_valid()) {
  397. cpath = fallback->get_path();
  398. }
  399. if (cpath != env_path) {
  400. if (env_path != String()) {
  401. fallback = ResourceLoader::load(env_path);
  402. if (fallback.is_null()) {
  403. //could not load fallback, set as empty
  404. ProjectSettings::get_singleton()->set("rendering/environment/default_environment", "");
  405. }
  406. } else {
  407. fallback.unref();
  408. }
  409. get_root()->get_world()->set_fallback_environment(fallback);
  410. }
  411. }
  412. #endif
  413. return _quit;
  414. }
  415. void SceneTree::finish() {
  416. _flush_delete_queue();
  417. _flush_ugc();
  418. initialized = false;
  419. MainLoop::finish();
  420. if (root) {
  421. root->_set_tree(NULL);
  422. memdelete(root); //delete root
  423. }
  424. }
  425. void SceneTree::quit() {
  426. _quit = true;
  427. }
  428. void SceneTree::_notification(int p_notification) {
  429. switch (p_notification) {
  430. case NOTIFICATION_WM_QUIT_REQUEST: {
  431. get_root()->propagate_notification(p_notification);
  432. if (accept_quit) {
  433. _quit = true;
  434. break;
  435. }
  436. } break;
  437. case NOTIFICATION_WM_GO_BACK_REQUEST: {
  438. get_root()->propagate_notification(p_notification);
  439. if (quit_on_go_back) {
  440. _quit = true;
  441. break;
  442. }
  443. } break;
  444. case NOTIFICATION_OS_MEMORY_WARNING:
  445. case NOTIFICATION_WM_FOCUS_IN:
  446. case NOTIFICATION_WM_FOCUS_OUT: {
  447. get_root()->propagate_notification(p_notification);
  448. } break;
  449. case NOTIFICATION_TRANSLATION_CHANGED: {
  450. if (!Engine::get_singleton()->is_editor_hint()) {
  451. get_root()->propagate_notification(Node::NOTIFICATION_TRANSLATION_CHANGED);
  452. }
  453. } break;
  454. case NOTIFICATION_WM_UNFOCUS_REQUEST: {
  455. notify_group_flags(GROUP_CALL_REALTIME | GROUP_CALL_MULTILEVEL, "input", NOTIFICATION_WM_UNFOCUS_REQUEST);
  456. } break;
  457. case NOTIFICATION_WM_ABOUT: {
  458. #ifdef TOOLS_ENABLED
  459. if (EditorNode::get_singleton()) {
  460. EditorNode::get_singleton()->show_about();
  461. } else {
  462. #endif
  463. get_root()->propagate_notification(p_notification);
  464. #ifdef TOOLS_ENABLED
  465. }
  466. #endif
  467. } break;
  468. default:
  469. break;
  470. };
  471. };
  472. void SceneTree::set_auto_accept_quit(bool p_enable) {
  473. accept_quit = p_enable;
  474. }
  475. void SceneTree::set_quit_on_go_back(bool p_enable) {
  476. quit_on_go_back = p_enable;
  477. }
  478. #ifdef TOOLS_ENABLED
  479. bool SceneTree::is_node_being_edited(const Node *p_node) const {
  480. return Engine::get_singleton()->is_editor_hint() && edited_scene_root && (edited_scene_root->is_a_parent_of(p_node) || edited_scene_root == p_node);
  481. }
  482. #endif
  483. #ifdef DEBUG_ENABLED
  484. void SceneTree::set_debug_collisions_hint(bool p_enabled) {
  485. debug_collisions_hint = p_enabled;
  486. }
  487. bool SceneTree::is_debugging_collisions_hint() const {
  488. return debug_collisions_hint;
  489. }
  490. void SceneTree::set_debug_navigation_hint(bool p_enabled) {
  491. debug_navigation_hint = p_enabled;
  492. }
  493. bool SceneTree::is_debugging_navigation_hint() const {
  494. return debug_navigation_hint;
  495. }
  496. #endif
  497. void SceneTree::set_debug_collisions_color(const Color &p_color) {
  498. debug_collisions_color = p_color;
  499. }
  500. Color SceneTree::get_debug_collisions_color() const {
  501. return debug_collisions_color;
  502. }
  503. void SceneTree::set_debug_collision_contact_color(const Color &p_color) {
  504. debug_collision_contact_color = p_color;
  505. }
  506. Color SceneTree::get_debug_collision_contact_color() const {
  507. return debug_collision_contact_color;
  508. }
  509. void SceneTree::set_debug_navigation_color(const Color &p_color) {
  510. debug_navigation_color = p_color;
  511. }
  512. Color SceneTree::get_debug_navigation_color() const {
  513. return debug_navigation_color;
  514. }
  515. void SceneTree::set_debug_navigation_disabled_color(const Color &p_color) {
  516. debug_navigation_disabled_color = p_color;
  517. }
  518. Color SceneTree::get_debug_navigation_disabled_color() const {
  519. return debug_navigation_disabled_color;
  520. }
  521. Ref<Material> SceneTree::get_debug_navigation_material() {
  522. if (navigation_material.is_valid())
  523. return navigation_material;
  524. Ref<SpatialMaterial> line_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  525. line_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  526. line_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  527. line_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  528. line_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  529. line_material->set_albedo(get_debug_navigation_color());
  530. navigation_material = line_material;
  531. return navigation_material;
  532. }
  533. Ref<Material> SceneTree::get_debug_navigation_disabled_material() {
  534. if (navigation_disabled_material.is_valid())
  535. return navigation_disabled_material;
  536. Ref<SpatialMaterial> line_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  537. line_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  538. line_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  539. line_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  540. line_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  541. line_material->set_albedo(get_debug_navigation_disabled_color());
  542. navigation_disabled_material = line_material;
  543. return navigation_disabled_material;
  544. }
  545. Ref<Material> SceneTree::get_debug_collision_material() {
  546. if (collision_material.is_valid())
  547. return collision_material;
  548. Ref<SpatialMaterial> line_material = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  549. line_material->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  550. line_material->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  551. line_material->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  552. line_material->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  553. line_material->set_albedo(get_debug_collisions_color());
  554. collision_material = line_material;
  555. return collision_material;
  556. }
  557. Ref<ArrayMesh> SceneTree::get_debug_contact_mesh() {
  558. if (debug_contact_mesh.is_valid())
  559. return debug_contact_mesh;
  560. debug_contact_mesh = Ref<ArrayMesh>(memnew(ArrayMesh));
  561. Ref<SpatialMaterial> mat = Ref<SpatialMaterial>(memnew(SpatialMaterial));
  562. mat->set_flag(SpatialMaterial::FLAG_UNSHADED, true);
  563. mat->set_feature(SpatialMaterial::FEATURE_TRANSPARENT, true);
  564. mat->set_flag(SpatialMaterial::FLAG_SRGB_VERTEX_COLOR, true);
  565. mat->set_flag(SpatialMaterial::FLAG_ALBEDO_FROM_VERTEX_COLOR, true);
  566. mat->set_albedo(get_debug_collision_contact_color());
  567. Vector3 diamond[6] = {
  568. Vector3(-1, 0, 0),
  569. Vector3(1, 0, 0),
  570. Vector3(0, -1, 0),
  571. Vector3(0, 1, 0),
  572. Vector3(0, 0, -1),
  573. Vector3(0, 0, 1)
  574. };
  575. int diamond_faces[8 * 3] = {
  576. 0, 2, 4,
  577. 0, 3, 4,
  578. 1, 2, 4,
  579. 1, 3, 4,
  580. 0, 2, 5,
  581. 0, 3, 5,
  582. 1, 2, 5,
  583. 1, 3, 5,
  584. };
  585. PoolVector<int> indices;
  586. for (int i = 0; i < 8 * 3; i++)
  587. indices.push_back(diamond_faces[i]);
  588. PoolVector<Vector3> vertices;
  589. for (int i = 0; i < 6; i++)
  590. vertices.push_back(diamond[i] * 0.1);
  591. Array arr;
  592. arr.resize(Mesh::ARRAY_MAX);
  593. arr[Mesh::ARRAY_VERTEX] = vertices;
  594. arr[Mesh::ARRAY_INDEX] = indices;
  595. debug_contact_mesh->add_surface_from_arrays(Mesh::PRIMITIVE_TRIANGLES, arr);
  596. debug_contact_mesh->surface_set_material(0, mat);
  597. return debug_contact_mesh;
  598. }
  599. void SceneTree::set_pause(bool p_enabled) {
  600. if (p_enabled == pause)
  601. return;
  602. pause = p_enabled;
  603. PhysicsServer::get_singleton()->set_active(!p_enabled);
  604. Physics2DServer::get_singleton()->set_active(!p_enabled);
  605. if (get_root())
  606. get_root()->propagate_notification(p_enabled ? Node::NOTIFICATION_PAUSED : Node::NOTIFICATION_UNPAUSED);
  607. }
  608. bool SceneTree::is_paused() const {
  609. return pause;
  610. }
  611. void SceneTree::_call_input_pause(const StringName &p_group, const StringName &p_method, const Ref<InputEvent> &p_input) {
  612. Map<StringName, Group>::Element *E = group_map.find(p_group);
  613. if (!E)
  614. return;
  615. Group &g = E->get();
  616. if (g.nodes.empty())
  617. return;
  618. _update_group_order(g);
  619. //copy, so copy on write happens in case something is removed from process while being called
  620. //performance is not lost because only if something is added/removed the vector is copied.
  621. Vector<Node *> nodes_copy = g.nodes;
  622. int node_count = nodes_copy.size();
  623. Node **nodes = &nodes_copy[0];
  624. Variant arg = p_input;
  625. const Variant *v[1] = { &arg };
  626. call_lock++;
  627. for (int i = node_count - 1; i >= 0; i--) {
  628. if (input_handled)
  629. break;
  630. Node *n = nodes[i];
  631. if (call_lock && call_skip.has(n))
  632. continue;
  633. if (!n->can_process())
  634. continue;
  635. n->call_multilevel(p_method, (const Variant **)v, 1);
  636. //ERR_FAIL_COND(node_count != g.nodes.size());
  637. }
  638. call_lock--;
  639. if (call_lock == 0)
  640. call_skip.clear();
  641. }
  642. void SceneTree::_notify_group_pause(const StringName &p_group, int p_notification) {
  643. Map<StringName, Group>::Element *E = group_map.find(p_group);
  644. if (!E)
  645. return;
  646. Group &g = E->get();
  647. if (g.nodes.empty())
  648. return;
  649. _update_group_order(g);
  650. //copy, so copy on write happens in case something is removed from process while being called
  651. //performance is not lost because only if something is added/removed the vector is copied.
  652. Vector<Node *> nodes_copy = g.nodes;
  653. int node_count = nodes_copy.size();
  654. Node **nodes = &nodes_copy[0];
  655. call_lock++;
  656. for (int i = 0; i < node_count; i++) {
  657. Node *n = nodes[i];
  658. if (call_lock && call_skip.has(n))
  659. continue;
  660. if (!n->can_process())
  661. continue;
  662. n->notification(p_notification);
  663. //ERR_FAIL_COND(node_count != g.nodes.size());
  664. }
  665. call_lock--;
  666. if (call_lock == 0)
  667. call_skip.clear();
  668. }
  669. /*
  670. void SceneMainLoop::_update_listener_2d() {
  671. if (listener_2d.is_valid()) {
  672. SpatialSound2DServer::get_singleton()->listener_set_space( listener_2d, world_2d->get_sound_space() );
  673. }
  674. }
  675. */
  676. uint32_t SceneTree::get_last_event_id() const {
  677. return last_id;
  678. }
  679. Variant SceneTree::_call_group_flags(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  680. r_error.error = Variant::CallError::CALL_OK;
  681. ERR_FAIL_COND_V(p_argcount < 3, Variant());
  682. ERR_FAIL_COND_V(!p_args[0]->is_num(), Variant());
  683. ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING, Variant());
  684. ERR_FAIL_COND_V(p_args[2]->get_type() != Variant::STRING, Variant());
  685. int flags = *p_args[0];
  686. StringName group = *p_args[1];
  687. StringName method = *p_args[2];
  688. Variant v[VARIANT_ARG_MAX];
  689. for (int i = 0; i < MIN(p_argcount - 3, 5); i++) {
  690. v[i] = *p_args[i + 3];
  691. }
  692. call_group_flags(flags, group, method, v[0], v[1], v[2], v[3], v[4]);
  693. return Variant();
  694. }
  695. Variant SceneTree::_call_group(const Variant **p_args, int p_argcount, Variant::CallError &r_error) {
  696. r_error.error = Variant::CallError::CALL_OK;
  697. ERR_FAIL_COND_V(p_argcount < 2, Variant());
  698. ERR_FAIL_COND_V(p_args[0]->get_type() != Variant::STRING, Variant());
  699. ERR_FAIL_COND_V(p_args[1]->get_type() != Variant::STRING, Variant());
  700. StringName group = *p_args[0];
  701. StringName method = *p_args[1];
  702. Variant v[VARIANT_ARG_MAX];
  703. for (int i = 0; i < MIN(p_argcount - 2, 5); i++) {
  704. v[i] = *p_args[i + 2];
  705. }
  706. call_group_flags(0, group, method, v[0], v[1], v[2], v[3], v[4]);
  707. return Variant();
  708. }
  709. int64_t SceneTree::get_frame() const {
  710. return current_frame;
  711. }
  712. Array SceneTree::_get_nodes_in_group(const StringName &p_group) {
  713. Array ret;
  714. Map<StringName, Group>::Element *E = group_map.find(p_group);
  715. if (!E)
  716. return ret;
  717. _update_group_order(E->get()); //update order just in case
  718. int nc = E->get().nodes.size();
  719. if (nc == 0)
  720. return ret;
  721. ret.resize(nc);
  722. Node **ptr = E->get().nodes.ptr();
  723. for (int i = 0; i < nc; i++) {
  724. ret[i] = ptr[i];
  725. }
  726. return ret;
  727. }
  728. bool SceneTree::has_group(const StringName &p_identifier) const {
  729. return group_map.has(p_identifier);
  730. }
  731. void SceneTree::get_nodes_in_group(const StringName &p_group, List<Node *> *p_list) {
  732. Map<StringName, Group>::Element *E = group_map.find(p_group);
  733. if (!E)
  734. return;
  735. _update_group_order(E->get()); //update order just in case
  736. int nc = E->get().nodes.size();
  737. if (nc == 0)
  738. return;
  739. Node **ptr = E->get().nodes.ptr();
  740. for (int i = 0; i < nc; i++) {
  741. p_list->push_back(ptr[i]);
  742. }
  743. }
  744. static void _fill_array(Node *p_node, Array &array, int p_level) {
  745. array.push_back(p_level);
  746. array.push_back(p_node->get_name());
  747. array.push_back(p_node->get_class());
  748. array.push_back(p_node->get_instance_id());
  749. for (int i = 0; i < p_node->get_child_count(); i++) {
  750. _fill_array(p_node->get_child(i), array, p_level + 1);
  751. }
  752. }
  753. void SceneTree::_debugger_request_tree(void *self) {
  754. SceneTree *sml = (SceneTree *)self;
  755. Array arr;
  756. _fill_array(sml->root, arr, 0);
  757. ScriptDebugger::get_singleton()->send_message("scene_tree", arr);
  758. }
  759. void SceneTree::_flush_delete_queue() {
  760. _THREAD_SAFE_METHOD_
  761. while (delete_queue.size()) {
  762. Object *obj = ObjectDB::get_instance(delete_queue.front()->get());
  763. if (obj) {
  764. memdelete(obj);
  765. }
  766. delete_queue.pop_front();
  767. }
  768. }
  769. void SceneTree::queue_delete(Object *p_object) {
  770. _THREAD_SAFE_METHOD_
  771. ERR_FAIL_NULL(p_object);
  772. p_object->_is_queued_for_deletion = true;
  773. delete_queue.push_back(p_object->get_instance_id());
  774. }
  775. int SceneTree::get_node_count() const {
  776. return node_count;
  777. }
  778. void SceneTree::_update_root_rect() {
  779. if (stretch_mode == STRETCH_MODE_DISABLED) {
  780. root->set_size((last_screen_size / stretch_shrink).floor());
  781. root->set_attach_to_screen_rect(Rect2(Point2(), last_screen_size));
  782. root->set_size_override_stretch(false);
  783. root->set_size_override(false, Size2());
  784. return; //user will take care
  785. }
  786. //actual screen video mode
  787. Size2 video_mode = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
  788. Size2 desired_res = stretch_min;
  789. Size2 viewport_size;
  790. Size2 screen_size;
  791. float viewport_aspect = desired_res.aspect();
  792. float video_mode_aspect = video_mode.aspect();
  793. if (stretch_aspect == STRETCH_ASPECT_IGNORE || ABS(viewport_aspect - video_mode_aspect) < CMP_EPSILON) {
  794. //same aspect or ignore aspect
  795. viewport_size = desired_res;
  796. screen_size = video_mode;
  797. } else if (viewport_aspect < video_mode_aspect) {
  798. // screen ratio is smaller vertically
  799. if (stretch_aspect == STRETCH_ASPECT_KEEP_HEIGHT || stretch_aspect == STRETCH_ASPECT_EXPAND) {
  800. //will stretch horizontally
  801. viewport_size.x = desired_res.y * video_mode_aspect;
  802. viewport_size.y = desired_res.y;
  803. screen_size = video_mode;
  804. } else {
  805. //will need black bars
  806. viewport_size = desired_res;
  807. screen_size.x = video_mode.y * viewport_aspect;
  808. screen_size.y = video_mode.y;
  809. }
  810. } else {
  811. //screen ratio is smaller horizontally
  812. if (stretch_aspect == STRETCH_ASPECT_KEEP_WIDTH || stretch_aspect == STRETCH_ASPECT_EXPAND) {
  813. //will stretch horizontally
  814. viewport_size.x = desired_res.x;
  815. viewport_size.y = desired_res.x / video_mode_aspect;
  816. screen_size = video_mode;
  817. } else {
  818. //will need black bars
  819. viewport_size = desired_res;
  820. screen_size.x = video_mode.x;
  821. screen_size.y = video_mode.x / viewport_aspect;
  822. }
  823. }
  824. screen_size = screen_size.floor();
  825. viewport_size = viewport_size.floor();
  826. Size2 margin;
  827. Size2 offset;
  828. //black bars and margin
  829. if (stretch_aspect != STRETCH_ASPECT_EXPAND && screen_size.x < video_mode.x) {
  830. margin.x = Math::round((video_mode.x - screen_size.x) / 2.0);
  831. VisualServer::get_singleton()->black_bars_set_margins(margin.x, 0, margin.x, 0);
  832. offset.x = Math::round(margin.x * viewport_size.y / screen_size.y);
  833. } else if (stretch_aspect != STRETCH_ASPECT_EXPAND && screen_size.y < video_mode.y) {
  834. margin.y = Math::round((video_mode.y - screen_size.y) / 2.0);
  835. VisualServer::get_singleton()->black_bars_set_margins(0, margin.y, 0, margin.y);
  836. offset.y = Math::round(margin.y * viewport_size.x / screen_size.x);
  837. } else {
  838. VisualServer::get_singleton()->black_bars_set_margins(0, 0, 0, 0);
  839. }
  840. //print_line("VP SIZE: "+viewport_size+" OFFSET: "+offset+" = "+(offset*2+viewport_size));
  841. //print_line("SS: "+video_mode);
  842. switch (stretch_mode) {
  843. case STRETCH_MODE_2D: {
  844. root->set_size((screen_size / stretch_shrink).floor());
  845. root->set_attach_to_screen_rect(Rect2(margin, screen_size));
  846. root->set_size_override_stretch(true);
  847. root->set_size_override(true, (viewport_size / stretch_shrink).floor());
  848. } break;
  849. case STRETCH_MODE_VIEWPORT: {
  850. root->set_size((viewport_size / stretch_shrink).floor());
  851. root->set_attach_to_screen_rect(Rect2(margin, screen_size));
  852. root->set_size_override_stretch(false);
  853. root->set_size_override(false, Size2());
  854. } break;
  855. }
  856. }
  857. void SceneTree::set_screen_stretch(StretchMode p_mode, StretchAspect p_aspect, const Size2 p_minsize, real_t p_shrink) {
  858. stretch_mode = p_mode;
  859. stretch_aspect = p_aspect;
  860. stretch_min = p_minsize;
  861. stretch_shrink = p_shrink;
  862. _update_root_rect();
  863. }
  864. #ifdef TOOLS_ENABLED
  865. void SceneTree::set_edited_scene_root(Node *p_node) {
  866. edited_scene_root = p_node;
  867. }
  868. Node *SceneTree::get_edited_scene_root() const {
  869. return edited_scene_root;
  870. }
  871. #endif
  872. void SceneTree::set_current_scene(Node *p_scene) {
  873. ERR_FAIL_COND(p_scene && p_scene->get_parent() != root);
  874. current_scene = p_scene;
  875. }
  876. Node *SceneTree::get_current_scene() const {
  877. return current_scene;
  878. }
  879. void SceneTree::_change_scene(Node *p_to) {
  880. if (current_scene) {
  881. memdelete(current_scene);
  882. current_scene = NULL;
  883. }
  884. if (p_to) {
  885. current_scene = p_to;
  886. root->add_child(p_to);
  887. }
  888. }
  889. Error SceneTree::change_scene(const String &p_path) {
  890. Ref<PackedScene> new_scene = ResourceLoader::load(p_path);
  891. if (new_scene.is_null())
  892. return ERR_CANT_OPEN;
  893. return change_scene_to(new_scene);
  894. }
  895. Error SceneTree::change_scene_to(const Ref<PackedScene> &p_scene) {
  896. Node *new_scene = NULL;
  897. if (p_scene.is_valid()) {
  898. new_scene = p_scene->instance();
  899. ERR_FAIL_COND_V(!new_scene, ERR_CANT_CREATE);
  900. }
  901. call_deferred("_change_scene", new_scene);
  902. return OK;
  903. }
  904. Error SceneTree::reload_current_scene() {
  905. ERR_FAIL_COND_V(!current_scene, ERR_UNCONFIGURED);
  906. String fname = current_scene->get_filename();
  907. return change_scene(fname);
  908. }
  909. void SceneTree::add_current_scene(Node *p_current) {
  910. current_scene = p_current;
  911. root->add_child(p_current);
  912. }
  913. #ifdef DEBUG_ENABLED
  914. void SceneTree::_live_edit_node_path_func(const NodePath &p_path, int p_id) {
  915. live_edit_node_path_cache[p_id] = p_path;
  916. }
  917. void SceneTree::_live_edit_res_path_func(const String &p_path, int p_id) {
  918. live_edit_resource_cache[p_id] = p_path;
  919. }
  920. void SceneTree::_live_edit_node_set_func(int p_id, const StringName &p_prop, const Variant &p_value) {
  921. if (!live_edit_node_path_cache.has(p_id))
  922. return;
  923. NodePath np = live_edit_node_path_cache[p_id];
  924. Node *base = NULL;
  925. if (root->has_node(live_edit_root))
  926. base = root->get_node(live_edit_root);
  927. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  928. if (!E)
  929. return; //scene not editable
  930. for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
  931. Node *n = F->get();
  932. if (base && !base->is_a_parent_of(n))
  933. continue;
  934. if (!n->has_node(np))
  935. continue;
  936. Node *n2 = n->get_node(np);
  937. n2->set(p_prop, p_value);
  938. }
  939. }
  940. void SceneTree::_live_edit_node_set_res_func(int p_id, const StringName &p_prop, const String &p_value) {
  941. RES r = ResourceLoader::load(p_value);
  942. if (!r.is_valid())
  943. return;
  944. _live_edit_node_set_func(p_id, p_prop, r);
  945. }
  946. void SceneTree::_live_edit_node_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
  947. if (!live_edit_node_path_cache.has(p_id))
  948. return;
  949. NodePath np = live_edit_node_path_cache[p_id];
  950. Node *base = NULL;
  951. if (root->has_node(live_edit_root))
  952. base = root->get_node(live_edit_root);
  953. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  954. if (!E)
  955. return; //scene not editable
  956. for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
  957. Node *n = F->get();
  958. if (base && !base->is_a_parent_of(n))
  959. continue;
  960. if (!n->has_node(np))
  961. continue;
  962. Node *n2 = n->get_node(np);
  963. n2->call(p_method, VARIANT_ARG_PASS);
  964. }
  965. }
  966. void SceneTree::_live_edit_res_set_func(int p_id, const StringName &p_prop, const Variant &p_value) {
  967. if (!live_edit_resource_cache.has(p_id))
  968. return;
  969. String resp = live_edit_resource_cache[p_id];
  970. if (!ResourceCache::has(resp))
  971. return;
  972. RES r = ResourceCache::get(resp);
  973. if (!r.is_valid())
  974. return;
  975. r->set(p_prop, p_value);
  976. }
  977. void SceneTree::_live_edit_res_set_res_func(int p_id, const StringName &p_prop, const String &p_value) {
  978. RES r = ResourceLoader::load(p_value);
  979. if (!r.is_valid())
  980. return;
  981. _live_edit_res_set_func(p_id, p_prop, r);
  982. }
  983. void SceneTree::_live_edit_res_call_func(int p_id, const StringName &p_method, VARIANT_ARG_DECLARE) {
  984. if (!live_edit_resource_cache.has(p_id))
  985. return;
  986. String resp = live_edit_resource_cache[p_id];
  987. if (!ResourceCache::has(resp))
  988. return;
  989. RES r = ResourceCache::get(resp);
  990. if (!r.is_valid())
  991. return;
  992. r->call(p_method, VARIANT_ARG_PASS);
  993. }
  994. void SceneTree::_live_edit_root_func(const NodePath &p_scene_path, const String &p_scene_from) {
  995. live_edit_root = p_scene_path;
  996. live_edit_scene = p_scene_from;
  997. }
  998. void SceneTree::_live_edit_create_node_func(const NodePath &p_parent, const String &p_type, const String &p_name) {
  999. Node *base = NULL;
  1000. if (root->has_node(live_edit_root))
  1001. base = root->get_node(live_edit_root);
  1002. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1003. if (!E)
  1004. return; //scene not editable
  1005. for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
  1006. Node *n = F->get();
  1007. if (base && !base->is_a_parent_of(n))
  1008. continue;
  1009. if (!n->has_node(p_parent))
  1010. continue;
  1011. Node *n2 = n->get_node(p_parent);
  1012. Node *no = Object::cast_to<Node>(ClassDB::instance(p_type));
  1013. if (!no) {
  1014. continue;
  1015. }
  1016. no->set_name(p_name);
  1017. n2->add_child(no);
  1018. }
  1019. }
  1020. void SceneTree::_live_edit_instance_node_func(const NodePath &p_parent, const String &p_path, const String &p_name) {
  1021. Ref<PackedScene> ps = ResourceLoader::load(p_path);
  1022. if (!ps.is_valid())
  1023. return;
  1024. Node *base = NULL;
  1025. if (root->has_node(live_edit_root))
  1026. base = root->get_node(live_edit_root);
  1027. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1028. if (!E)
  1029. return; //scene not editable
  1030. for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
  1031. Node *n = F->get();
  1032. if (base && !base->is_a_parent_of(n))
  1033. continue;
  1034. if (!n->has_node(p_parent))
  1035. continue;
  1036. Node *n2 = n->get_node(p_parent);
  1037. Node *no = ps->instance();
  1038. no->set_name(p_name);
  1039. n2->add_child(no);
  1040. }
  1041. }
  1042. void SceneTree::_live_edit_remove_node_func(const NodePath &p_at) {
  1043. Node *base = NULL;
  1044. if (root->has_node(live_edit_root))
  1045. base = root->get_node(live_edit_root);
  1046. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1047. if (!E)
  1048. return; //scene not editable
  1049. for (Set<Node *>::Element *F = E->get().front(); F;) {
  1050. Set<Node *>::Element *N = F->next();
  1051. Node *n = F->get();
  1052. if (base && !base->is_a_parent_of(n))
  1053. continue;
  1054. if (!n->has_node(p_at))
  1055. continue;
  1056. Node *n2 = n->get_node(p_at);
  1057. memdelete(n2);
  1058. F = N;
  1059. }
  1060. }
  1061. void SceneTree::_live_edit_remove_and_keep_node_func(const NodePath &p_at, ObjectID p_keep_id) {
  1062. Node *base = NULL;
  1063. if (root->has_node(live_edit_root))
  1064. base = root->get_node(live_edit_root);
  1065. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1066. if (!E)
  1067. return; //scene not editable
  1068. for (Set<Node *>::Element *F = E->get().front(); F;) {
  1069. Set<Node *>::Element *N = F->next();
  1070. Node *n = F->get();
  1071. if (base && !base->is_a_parent_of(n))
  1072. continue;
  1073. if (!n->has_node(p_at))
  1074. continue;
  1075. Node *n2 = n->get_node(p_at);
  1076. n2->get_parent()->remove_child(n2);
  1077. live_edit_remove_list[n][p_keep_id] = n2;
  1078. F = N;
  1079. }
  1080. }
  1081. void SceneTree::_live_edit_restore_node_func(ObjectID p_id, const NodePath &p_at, int p_at_pos) {
  1082. Node *base = NULL;
  1083. if (root->has_node(live_edit_root))
  1084. base = root->get_node(live_edit_root);
  1085. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1086. if (!E)
  1087. return; //scene not editable
  1088. for (Set<Node *>::Element *F = E->get().front(); F;) {
  1089. Set<Node *>::Element *N = F->next();
  1090. Node *n = F->get();
  1091. if (base && !base->is_a_parent_of(n))
  1092. continue;
  1093. if (!n->has_node(p_at))
  1094. continue;
  1095. Node *n2 = n->get_node(p_at);
  1096. Map<Node *, Map<ObjectID, Node *> >::Element *EN = live_edit_remove_list.find(n);
  1097. if (!EN)
  1098. continue;
  1099. Map<ObjectID, Node *>::Element *FN = EN->get().find(p_id);
  1100. if (!FN)
  1101. continue;
  1102. n2->add_child(FN->get());
  1103. EN->get().erase(FN);
  1104. if (EN->get().size() == 0) {
  1105. live_edit_remove_list.erase(EN);
  1106. }
  1107. F = N;
  1108. }
  1109. }
  1110. void SceneTree::_live_edit_duplicate_node_func(const NodePath &p_at, const String &p_new_name) {
  1111. Node *base = NULL;
  1112. if (root->has_node(live_edit_root))
  1113. base = root->get_node(live_edit_root);
  1114. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1115. if (!E)
  1116. return; //scene not editable
  1117. for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
  1118. Node *n = F->get();
  1119. if (base && !base->is_a_parent_of(n))
  1120. continue;
  1121. if (!n->has_node(p_at))
  1122. continue;
  1123. Node *n2 = n->get_node(p_at);
  1124. Node *dup = n2->duplicate(true);
  1125. if (!dup)
  1126. continue;
  1127. dup->set_name(p_new_name);
  1128. n2->get_parent()->add_child(dup);
  1129. }
  1130. }
  1131. void SceneTree::_live_edit_reparent_node_func(const NodePath &p_at, const NodePath &p_new_place, const String &p_new_name, int p_at_pos) {
  1132. Node *base = NULL;
  1133. if (root->has_node(live_edit_root))
  1134. base = root->get_node(live_edit_root);
  1135. Map<String, Set<Node *> >::Element *E = live_scene_edit_cache.find(live_edit_scene);
  1136. if (!E)
  1137. return; //scene not editable
  1138. for (Set<Node *>::Element *F = E->get().front(); F; F = F->next()) {
  1139. Node *n = F->get();
  1140. if (base && !base->is_a_parent_of(n))
  1141. continue;
  1142. if (!n->has_node(p_at))
  1143. continue;
  1144. Node *nfrom = n->get_node(p_at);
  1145. if (!n->has_node(p_new_place))
  1146. continue;
  1147. Node *nto = n->get_node(p_new_place);
  1148. nfrom->get_parent()->remove_child(nfrom);
  1149. nfrom->set_name(p_new_name);
  1150. nto->add_child(nfrom);
  1151. if (p_at_pos >= 0)
  1152. nto->move_child(nfrom, p_at_pos);
  1153. }
  1154. }
  1155. #endif
  1156. void SceneTree::drop_files(const Vector<String> &p_files, int p_from_screen) {
  1157. emit_signal("files_dropped", p_files, p_from_screen);
  1158. MainLoop::drop_files(p_files, p_from_screen);
  1159. }
  1160. Ref<SceneTreeTimer> SceneTree::create_timer(float p_delay_sec, bool p_process_pause) {
  1161. Ref<SceneTreeTimer> stt;
  1162. stt.instance();
  1163. stt->set_pause_mode_process(p_process_pause);
  1164. stt->set_time_left(p_delay_sec);
  1165. timers.push_back(stt);
  1166. return stt;
  1167. }
  1168. void SceneTree::_network_peer_connected(int p_id) {
  1169. connected_peers.insert(p_id);
  1170. path_get_cache.insert(p_id, PathGetCache());
  1171. emit_signal("network_peer_connected", p_id);
  1172. }
  1173. void SceneTree::_network_peer_disconnected(int p_id) {
  1174. connected_peers.erase(p_id);
  1175. path_get_cache.erase(p_id); //I no longer need your cache, sorry
  1176. emit_signal("network_peer_disconnected", p_id);
  1177. }
  1178. void SceneTree::_connected_to_server() {
  1179. emit_signal("connected_to_server");
  1180. }
  1181. void SceneTree::_connection_failed() {
  1182. emit_signal("connection_failed");
  1183. }
  1184. void SceneTree::_server_disconnected() {
  1185. emit_signal("server_disconnected");
  1186. }
  1187. void SceneTree::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_network_peer) {
  1188. if (network_peer.is_valid()) {
  1189. network_peer->disconnect("peer_connected", this, "_network_peer_connected");
  1190. network_peer->disconnect("peer_disconnected", this, "_network_peer_disconnected");
  1191. network_peer->disconnect("connection_succeeded", this, "_connected_to_server");
  1192. network_peer->disconnect("connection_failed", this, "_connection_failed");
  1193. network_peer->disconnect("server_disconnected", this, "_server_disconnected");
  1194. connected_peers.clear();
  1195. path_get_cache.clear();
  1196. path_send_cache.clear();
  1197. last_send_cache_id = 1;
  1198. }
  1199. ERR_EXPLAIN("Supplied NetworkedNetworkPeer must be connecting or connected.");
  1200. ERR_FAIL_COND(p_network_peer.is_valid() && p_network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED);
  1201. network_peer = p_network_peer;
  1202. if (network_peer.is_valid()) {
  1203. network_peer->connect("peer_connected", this, "_network_peer_connected");
  1204. network_peer->connect("peer_disconnected", this, "_network_peer_disconnected");
  1205. network_peer->connect("connection_succeeded", this, "_connected_to_server");
  1206. network_peer->connect("connection_failed", this, "_connection_failed");
  1207. network_peer->connect("server_disconnected", this, "_server_disconnected");
  1208. }
  1209. }
  1210. bool SceneTree::is_network_server() const {
  1211. ERR_FAIL_COND_V(!network_peer.is_valid(), false);
  1212. return network_peer->is_server();
  1213. }
  1214. bool SceneTree::has_network_peer() const {
  1215. return network_peer.is_valid();
  1216. }
  1217. int SceneTree::get_network_unique_id() const {
  1218. ERR_FAIL_COND_V(!network_peer.is_valid(), 0);
  1219. return network_peer->get_unique_id();
  1220. }
  1221. Vector<int> SceneTree::get_network_connected_peers() const {
  1222. ERR_FAIL_COND_V(!network_peer.is_valid(), Vector<int>());
  1223. Vector<int> ret;
  1224. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  1225. ret.push_back(E->get());
  1226. }
  1227. return ret;
  1228. }
  1229. int SceneTree::get_rpc_sender_id() const {
  1230. return rpc_sender_id;
  1231. }
  1232. void SceneTree::set_refuse_new_network_connections(bool p_refuse) {
  1233. ERR_FAIL_COND(!network_peer.is_valid());
  1234. network_peer->set_refuse_new_connections(p_refuse);
  1235. }
  1236. bool SceneTree::is_refusing_new_network_connections() const {
  1237. ERR_FAIL_COND_V(!network_peer.is_valid(), false);
  1238. return network_peer->is_refusing_new_connections();
  1239. }
  1240. void SceneTree::_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  1241. if (network_peer.is_null()) {
  1242. ERR_EXPLAIN("Attempt to remote call/set when networking is not active in SceneTree.");
  1243. ERR_FAIL();
  1244. }
  1245. if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING) {
  1246. ERR_EXPLAIN("Attempt to remote call/set when networking is not connected yet in SceneTree.");
  1247. ERR_FAIL();
  1248. }
  1249. if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
  1250. ERR_EXPLAIN("Attempt to remote call/set when networking is disconnected.");
  1251. ERR_FAIL();
  1252. }
  1253. if (p_argcount > 255) {
  1254. ERR_EXPLAIN("Too many arguments >255.");
  1255. ERR_FAIL();
  1256. }
  1257. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  1258. if (p_to == get_network_unique_id()) {
  1259. ERR_EXPLAIN("Attempt to remote call/set yourself! unique ID: " + itos(get_network_unique_id()));
  1260. } else {
  1261. ERR_EXPLAIN("Attempt to remote call unexisting ID: " + itos(p_to));
  1262. }
  1263. ERR_FAIL();
  1264. }
  1265. NodePath from_path = p_from->get_path();
  1266. ERR_FAIL_COND(from_path.is_empty());
  1267. //see if the path is cached
  1268. PathSentCache *psc = path_send_cache.getptr(from_path);
  1269. if (!psc) {
  1270. //path is not cached, create
  1271. path_send_cache[from_path] = PathSentCache();
  1272. psc = path_send_cache.getptr(from_path);
  1273. psc->id = last_send_cache_id++;
  1274. }
  1275. //create base packet, lots of harcode because it must be tight
  1276. int ofs = 0;
  1277. #define MAKE_ROOM(m_amount) \
  1278. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  1279. //encode type
  1280. MAKE_ROOM(1);
  1281. packet_cache[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  1282. ofs += 1;
  1283. //encode ID
  1284. MAKE_ROOM(ofs + 4);
  1285. encode_uint32(psc->id, &packet_cache[ofs]);
  1286. ofs += 4;
  1287. //encode function name
  1288. CharString name = String(p_name).utf8();
  1289. int len = encode_cstring(name.get_data(), NULL);
  1290. MAKE_ROOM(ofs + len);
  1291. encode_cstring(name.get_data(), &packet_cache[ofs]);
  1292. ofs += len;
  1293. if (p_set) {
  1294. //set argument
  1295. Error err = encode_variant(*p_arg[0], NULL, len);
  1296. ERR_FAIL_COND(err != OK);
  1297. MAKE_ROOM(ofs + len);
  1298. encode_variant(*p_arg[0], &packet_cache[ofs], len);
  1299. ofs += len;
  1300. } else {
  1301. //call arguments
  1302. MAKE_ROOM(ofs + 1);
  1303. packet_cache[ofs] = p_argcount;
  1304. ofs += 1;
  1305. for (int i = 0; i < p_argcount; i++) {
  1306. Error err = encode_variant(*p_arg[i], NULL, len);
  1307. ERR_FAIL_COND(err != OK);
  1308. MAKE_ROOM(ofs + len);
  1309. encode_variant(*p_arg[i], &packet_cache[ofs], len);
  1310. ofs += len;
  1311. }
  1312. }
  1313. //see if all peers have cached path (is so, call can be fast)
  1314. bool has_all_peers = true;
  1315. List<int> peers_to_add; //if one is missing, take note to add it
  1316. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  1317. if (p_to < 0 && E->get() == -p_to)
  1318. continue; //continue, excluded
  1319. if (p_to > 0 && E->get() != p_to)
  1320. continue; //continue, not for this peer
  1321. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  1322. if (!F || F->get() == false) {
  1323. //path was not cached, or was cached but is unconfirmed
  1324. if (!F) {
  1325. //not cached at all, take note
  1326. peers_to_add.push_back(E->get());
  1327. }
  1328. has_all_peers = false;
  1329. }
  1330. }
  1331. //those that need to be added, send a message for this
  1332. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  1333. //encode function name
  1334. CharString pname = String(from_path).utf8();
  1335. int len = encode_cstring(pname.get_data(), NULL);
  1336. Vector<uint8_t> packet;
  1337. packet.resize(1 + 4 + len);
  1338. packet[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
  1339. encode_uint32(psc->id, &packet[1]);
  1340. encode_cstring(pname.get_data(), &packet[5]);
  1341. network_peer->set_target_peer(E->get()); //to all of you
  1342. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  1343. network_peer->put_packet(packet.ptr(), packet.size());
  1344. psc->confirmed_peers.insert(E->get(), false); //insert into confirmed, but as false since it was not confirmed
  1345. }
  1346. //take chance and set transfer mode, since all send methods will use it
  1347. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  1348. if (has_all_peers) {
  1349. //they all have verified paths, so send fast
  1350. network_peer->set_target_peer(p_to); //to all of you
  1351. network_peer->put_packet(packet_cache.ptr(), ofs); //a message with love
  1352. } else {
  1353. //not all verified path, so send one by one
  1354. //apend path at the end, since we will need it for some packets
  1355. CharString pname = String(from_path).utf8();
  1356. int path_len = encode_cstring(pname.get_data(), NULL);
  1357. MAKE_ROOM(ofs + path_len);
  1358. encode_cstring(pname.get_data(), &packet_cache[ofs]);
  1359. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  1360. if (p_to < 0 && E->get() == -p_to)
  1361. continue; //continue, excluded
  1362. if (p_to > 0 && E->get() != p_to)
  1363. continue; //continue, not for this peer
  1364. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  1365. ERR_CONTINUE(!F); //should never happen
  1366. network_peer->set_target_peer(E->get()); //to this one specifically
  1367. if (F->get() == true) {
  1368. //this one confirmed path, so use id
  1369. encode_uint32(psc->id, &packet_cache[1]);
  1370. network_peer->put_packet(packet_cache.ptr(), ofs);
  1371. } else {
  1372. //this one did not confirm path yet, so use entire path (sorry!)
  1373. encode_uint32(0x80000000 | ofs, &packet_cache[1]); //offset to path and flag
  1374. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  1375. }
  1376. }
  1377. }
  1378. }
  1379. void SceneTree::_network_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  1380. ERR_FAIL_COND(p_packet_len < 5);
  1381. uint8_t packet_type = p_packet[0];
  1382. switch (packet_type) {
  1383. case NETWORK_COMMAND_REMOTE_CALL:
  1384. case NETWORK_COMMAND_REMOTE_SET: {
  1385. ERR_FAIL_COND(p_packet_len < 5);
  1386. uint32_t target = decode_uint32(&p_packet[1]);
  1387. Node *node = NULL;
  1388. if (target & 0x80000000) {
  1389. //use full path (not cached yet)
  1390. int ofs = target & 0x7FFFFFFF;
  1391. ERR_FAIL_COND(ofs >= p_packet_len);
  1392. String paths;
  1393. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  1394. NodePath np = paths;
  1395. node = get_root()->get_node(np);
  1396. if (node == NULL) {
  1397. ERR_EXPLAIN("Failed to get path from RPC: " + String(np));
  1398. ERR_FAIL_COND(node == NULL);
  1399. }
  1400. } else {
  1401. //use cached path
  1402. int id = target;
  1403. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  1404. ERR_FAIL_COND(!E);
  1405. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  1406. ERR_FAIL_COND(!F);
  1407. PathGetCache::NodeInfo *ni = &F->get();
  1408. //do proper caching later
  1409. node = get_root()->get_node(ni->path);
  1410. if (node == NULL) {
  1411. ERR_EXPLAIN("Failed to get cached path from RPC: " + String(ni->path));
  1412. ERR_FAIL_COND(node == NULL);
  1413. }
  1414. }
  1415. ERR_FAIL_COND(p_packet_len < 6);
  1416. //detect cstring end
  1417. int len_end = 5;
  1418. for (; len_end < p_packet_len; len_end++) {
  1419. if (p_packet[len_end] == 0) {
  1420. break;
  1421. }
  1422. }
  1423. ERR_FAIL_COND(len_end >= p_packet_len);
  1424. StringName name = String::utf8((const char *)&p_packet[5]);
  1425. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  1426. if (!node->can_call_rpc(name, p_from))
  1427. return;
  1428. int ofs = len_end + 1;
  1429. ERR_FAIL_COND(ofs >= p_packet_len);
  1430. int argc = p_packet[ofs];
  1431. Vector<Variant> args;
  1432. Vector<const Variant *> argp;
  1433. args.resize(argc);
  1434. argp.resize(argc);
  1435. ofs++;
  1436. for (int i = 0; i < argc; i++) {
  1437. ERR_FAIL_COND(ofs >= p_packet_len);
  1438. int vlen;
  1439. Error err = decode_variant(args[i], &p_packet[ofs], p_packet_len - ofs, &vlen);
  1440. ERR_FAIL_COND(err != OK);
  1441. //args[i]=p_packet[3+i];
  1442. argp[i] = &args[i];
  1443. ofs += vlen;
  1444. }
  1445. Variant::CallError ce;
  1446. node->call(name, argp.ptr(), argc, ce);
  1447. if (ce.error != Variant::CallError::CALL_OK) {
  1448. String error = Variant::get_call_error_text(node, name, argp.ptr(), argc, ce);
  1449. error = "RPC - " + error;
  1450. ERR_PRINTS(error);
  1451. }
  1452. } else {
  1453. if (!node->can_call_rset(name, p_from))
  1454. return;
  1455. int ofs = len_end + 1;
  1456. ERR_FAIL_COND(ofs >= p_packet_len);
  1457. Variant value;
  1458. decode_variant(value, &p_packet[ofs], p_packet_len - ofs);
  1459. bool valid;
  1460. node->set(name, value, &valid);
  1461. if (!valid) {
  1462. String error = "Error setting remote property '" + String(name) + "', not found in object of type " + node->get_class();
  1463. ERR_PRINTS(error);
  1464. }
  1465. }
  1466. } break;
  1467. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  1468. ERR_FAIL_COND(p_packet_len < 5);
  1469. int id = decode_uint32(&p_packet[1]);
  1470. String paths;
  1471. paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
  1472. NodePath path = paths;
  1473. if (!path_get_cache.has(p_from)) {
  1474. path_get_cache[p_from] = PathGetCache();
  1475. }
  1476. PathGetCache::NodeInfo ni;
  1477. ni.path = path;
  1478. ni.instance = 0;
  1479. path_get_cache[p_from].nodes[id] = ni;
  1480. {
  1481. //send ack
  1482. //encode path
  1483. CharString pname = String(path).utf8();
  1484. int len = encode_cstring(pname.get_data(), NULL);
  1485. Vector<uint8_t> packet;
  1486. packet.resize(1 + len);
  1487. packet[0] = NETWORK_COMMAND_CONFIRM_PATH;
  1488. encode_cstring(pname.get_data(), &packet[1]);
  1489. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  1490. network_peer->set_target_peer(p_from);
  1491. network_peer->put_packet(packet.ptr(), packet.size());
  1492. }
  1493. } break;
  1494. case NETWORK_COMMAND_CONFIRM_PATH: {
  1495. String paths;
  1496. paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
  1497. NodePath path = paths;
  1498. PathSentCache *psc = path_send_cache.getptr(path);
  1499. ERR_FAIL_COND(!psc);
  1500. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  1501. ERR_FAIL_COND(!E);
  1502. E->get() = true;
  1503. } break;
  1504. }
  1505. }
  1506. void SceneTree::_network_poll() {
  1507. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
  1508. return;
  1509. network_peer->poll();
  1510. if (!network_peer.is_valid()) //it's possible that polling might have resulted in a disconnection, so check here
  1511. return;
  1512. while (network_peer->get_available_packet_count()) {
  1513. int sender = network_peer->get_packet_peer();
  1514. const uint8_t *packet;
  1515. int len;
  1516. Error err = network_peer->get_packet(&packet, len);
  1517. if (err != OK) {
  1518. ERR_PRINT("Error getting packet!");
  1519. }
  1520. rpc_sender_id = sender;
  1521. _network_process_packet(sender, packet, len);
  1522. rpc_sender_id = 0;
  1523. if (!network_peer.is_valid()) {
  1524. break; //it's also possible that a packet or RPC caused a disconnection, so also check here
  1525. }
  1526. }
  1527. }
  1528. void SceneTree::_bind_methods() {
  1529. //ClassDB::bind_method(D_METHOD("call_group","call_flags","group","method","arg1","arg2"),&SceneMainLoop::_call_group,DEFVAL(Variant()),DEFVAL(Variant()));
  1530. ClassDB::bind_method(D_METHOD("get_root"), &SceneTree::get_root);
  1531. ClassDB::bind_method(D_METHOD("has_group", "name"), &SceneTree::has_group);
  1532. ClassDB::bind_method(D_METHOD("set_auto_accept_quit", "enabled"), &SceneTree::set_auto_accept_quit);
  1533. ClassDB::bind_method(D_METHOD("set_debug_collisions_hint", "enable"), &SceneTree::set_debug_collisions_hint);
  1534. ClassDB::bind_method(D_METHOD("is_debugging_collisions_hint"), &SceneTree::is_debugging_collisions_hint);
  1535. ClassDB::bind_method(D_METHOD("set_debug_navigation_hint", "enable"), &SceneTree::set_debug_navigation_hint);
  1536. ClassDB::bind_method(D_METHOD("is_debugging_navigation_hint"), &SceneTree::is_debugging_navigation_hint);
  1537. #ifdef TOOLS_ENABLED
  1538. ClassDB::bind_method(D_METHOD("set_edited_scene_root", "scene"), &SceneTree::set_edited_scene_root);
  1539. ClassDB::bind_method(D_METHOD("get_edited_scene_root"), &SceneTree::get_edited_scene_root);
  1540. #endif
  1541. ClassDB::bind_method(D_METHOD("set_pause", "enable"), &SceneTree::set_pause);
  1542. ClassDB::bind_method(D_METHOD("is_paused"), &SceneTree::is_paused);
  1543. ClassDB::bind_method(D_METHOD("set_input_as_handled"), &SceneTree::set_input_as_handled);
  1544. ClassDB::bind_method(D_METHOD("is_input_handled"), &SceneTree::is_input_handled);
  1545. ClassDB::bind_method(D_METHOD("create_timer", "time_sec", "pause_mode_process"), &SceneTree::create_timer, DEFVAL(true));
  1546. ClassDB::bind_method(D_METHOD("get_node_count"), &SceneTree::get_node_count);
  1547. ClassDB::bind_method(D_METHOD("get_frame"), &SceneTree::get_frame);
  1548. ClassDB::bind_method(D_METHOD("quit"), &SceneTree::quit);
  1549. ClassDB::bind_method(D_METHOD("set_screen_stretch", "mode", "aspect", "minsize", "shrink"), &SceneTree::set_screen_stretch, DEFVAL(1));
  1550. ClassDB::bind_method(D_METHOD("queue_delete", "obj"), &SceneTree::queue_delete);
  1551. MethodInfo mi;
  1552. mi.name = "call_group_flags";
  1553. mi.arguments.push_back(PropertyInfo(Variant::INT, "flags"));
  1554. mi.arguments.push_back(PropertyInfo(Variant::STRING, "group"));
  1555. mi.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
  1556. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group_flags", &SceneTree::_call_group_flags, mi);
  1557. ClassDB::bind_method(D_METHOD("notify_group_flags", "call_flags", "group", "notification"), &SceneTree::notify_group_flags);
  1558. ClassDB::bind_method(D_METHOD("set_group_flags", "call_flags", "group", "property", "value"), &SceneTree::set_group_flags);
  1559. MethodInfo mi2;
  1560. mi2.name = "call_group";
  1561. mi2.arguments.push_back(PropertyInfo(Variant::STRING, "group"));
  1562. mi2.arguments.push_back(PropertyInfo(Variant::STRING, "method"));
  1563. ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "call_group", &SceneTree::_call_group, mi2);
  1564. ClassDB::bind_method(D_METHOD("notify_group", "group", "notification"), &SceneTree::notify_group);
  1565. ClassDB::bind_method(D_METHOD("set_group", "group", "property", "value"), &SceneTree::set_group);
  1566. ClassDB::bind_method(D_METHOD("get_nodes_in_group", "group"), &SceneTree::_get_nodes_in_group);
  1567. ClassDB::bind_method(D_METHOD("set_current_scene", "child_node"), &SceneTree::set_current_scene);
  1568. ClassDB::bind_method(D_METHOD("get_current_scene"), &SceneTree::get_current_scene);
  1569. ClassDB::bind_method(D_METHOD("change_scene", "path"), &SceneTree::change_scene);
  1570. ClassDB::bind_method(D_METHOD("change_scene_to", "packed_scene"), &SceneTree::change_scene_to);
  1571. ClassDB::bind_method(D_METHOD("reload_current_scene"), &SceneTree::reload_current_scene);
  1572. ClassDB::bind_method(D_METHOD("_change_scene"), &SceneTree::_change_scene);
  1573. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &SceneTree::set_network_peer);
  1574. ClassDB::bind_method(D_METHOD("is_network_server"), &SceneTree::is_network_server);
  1575. ClassDB::bind_method(D_METHOD("has_network_peer"), &SceneTree::has_network_peer);
  1576. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &SceneTree::get_network_connected_peers);
  1577. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &SceneTree::get_network_unique_id);
  1578. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &SceneTree::get_rpc_sender_id);
  1579. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &SceneTree::set_refuse_new_network_connections);
  1580. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &SceneTree::is_refusing_new_network_connections);
  1581. ClassDB::bind_method(D_METHOD("_network_peer_connected"), &SceneTree::_network_peer_connected);
  1582. ClassDB::bind_method(D_METHOD("_network_peer_disconnected"), &SceneTree::_network_peer_disconnected);
  1583. ClassDB::bind_method(D_METHOD("_connected_to_server"), &SceneTree::_connected_to_server);
  1584. ClassDB::bind_method(D_METHOD("_connection_failed"), &SceneTree::_connection_failed);
  1585. ClassDB::bind_method(D_METHOD("_server_disconnected"), &SceneTree::_server_disconnected);
  1586. ADD_SIGNAL(MethodInfo("tree_changed"));
  1587. ADD_SIGNAL(MethodInfo("node_added", PropertyInfo(Variant::OBJECT, "node")));
  1588. ADD_SIGNAL(MethodInfo("node_removed", PropertyInfo(Variant::OBJECT, "node")));
  1589. ADD_SIGNAL(MethodInfo("screen_resized"));
  1590. ADD_SIGNAL(MethodInfo("node_configuration_warning_changed", PropertyInfo(Variant::OBJECT, "node")));
  1591. ADD_SIGNAL(MethodInfo("idle_frame"));
  1592. ADD_SIGNAL(MethodInfo("physics_frame"));
  1593. ADD_SIGNAL(MethodInfo("files_dropped", PropertyInfo(Variant::POOL_STRING_ARRAY, "files"), PropertyInfo(Variant::INT, "screen")));
  1594. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  1595. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  1596. ADD_SIGNAL(MethodInfo("connected_to_server"));
  1597. ADD_SIGNAL(MethodInfo("connection_failed"));
  1598. ADD_SIGNAL(MethodInfo("server_disconnected"));
  1599. BIND_ENUM_CONSTANT(GROUP_CALL_DEFAULT);
  1600. BIND_ENUM_CONSTANT(GROUP_CALL_REVERSE);
  1601. BIND_ENUM_CONSTANT(GROUP_CALL_REALTIME);
  1602. BIND_ENUM_CONSTANT(GROUP_CALL_UNIQUE);
  1603. BIND_ENUM_CONSTANT(STRETCH_MODE_DISABLED);
  1604. BIND_ENUM_CONSTANT(STRETCH_MODE_2D);
  1605. BIND_ENUM_CONSTANT(STRETCH_MODE_VIEWPORT);
  1606. BIND_ENUM_CONSTANT(STRETCH_ASPECT_IGNORE);
  1607. BIND_ENUM_CONSTANT(STRETCH_ASPECT_KEEP);
  1608. BIND_ENUM_CONSTANT(STRETCH_ASPECT_KEEP_WIDTH);
  1609. BIND_ENUM_CONSTANT(STRETCH_ASPECT_KEEP_HEIGHT);
  1610. BIND_ENUM_CONSTANT(STRETCH_ASPECT_EXPAND);
  1611. }
  1612. SceneTree *SceneTree::singleton = NULL;
  1613. SceneTree::IdleCallback SceneTree::idle_callbacks[SceneTree::MAX_IDLE_CALLBACKS];
  1614. int SceneTree::idle_callback_count = 0;
  1615. void SceneTree::_call_idle_callbacks() {
  1616. for (int i = 0; i < idle_callback_count; i++) {
  1617. idle_callbacks[i]();
  1618. }
  1619. }
  1620. void SceneTree::add_idle_callback(IdleCallback p_callback) {
  1621. ERR_FAIL_COND(idle_callback_count >= MAX_IDLE_CALLBACKS);
  1622. idle_callbacks[idle_callback_count++] = p_callback;
  1623. }
  1624. SceneTree::SceneTree() {
  1625. singleton = this;
  1626. _quit = false;
  1627. accept_quit = true;
  1628. quit_on_go_back = true;
  1629. initialized = false;
  1630. #ifdef DEBUG_ENABLED
  1631. debug_collisions_hint = false;
  1632. debug_navigation_hint = false;
  1633. #endif
  1634. debug_collisions_color = GLOBAL_DEF("debug/shapes/collision/shape_color", Color(0.0, 0.6, 0.7, 0.5));
  1635. debug_collision_contact_color = GLOBAL_DEF("debug/shapes/collision/contact_color", Color(1.0, 0.2, 0.1, 0.8));
  1636. debug_navigation_color = GLOBAL_DEF("debug/shapes/navigation/geometry_color", Color(0.1, 1.0, 0.7, 0.4));
  1637. debug_navigation_disabled_color = GLOBAL_DEF("debug/shapes/navigation/disabled_geometry_color", Color(1.0, 0.7, 0.1, 0.4));
  1638. collision_debug_contacts = GLOBAL_DEF("debug/shapes/collision/max_contacts_displayed", 10000);
  1639. tree_version = 1;
  1640. physics_process_time = 1;
  1641. idle_process_time = 1;
  1642. last_id = 1;
  1643. root = NULL;
  1644. current_frame = 0;
  1645. tree_changed_name = "tree_changed";
  1646. node_added_name = "node_added";
  1647. node_removed_name = "node_removed";
  1648. ugc_locked = false;
  1649. call_lock = 0;
  1650. root_lock = 0;
  1651. node_count = 0;
  1652. rpc_sender_id = 0;
  1653. //create with mainloop
  1654. root = memnew(Viewport);
  1655. root->set_name("root");
  1656. if (!root->get_world().is_valid())
  1657. root->set_world(Ref<World>(memnew(World)));
  1658. //root->set_world_2d( Ref<World2D>( memnew( World2D )));
  1659. root->set_as_audio_listener(true);
  1660. root->set_as_audio_listener_2d(true);
  1661. current_scene = NULL;
  1662. int ref_atlas_size = GLOBAL_DEF("rendering/quality/reflections/atlas_size", 2048);
  1663. int ref_atlas_subdiv = GLOBAL_DEF("rendering/quality/reflections/atlas_subdiv", 8);
  1664. int msaa_mode = GLOBAL_DEF("rendering/quality/filters/msaa", 0);
  1665. ProjectSettings::get_singleton()->set_custom_property_info("rendering/quality/filters/msaa", PropertyInfo(Variant::INT, "rendering/quality/filters/msaa", PROPERTY_HINT_ENUM, "Disabled,2x,4x,8x,16x"));
  1666. root->set_msaa(Viewport::MSAA(msaa_mode));
  1667. GLOBAL_DEF("rendering/quality/depth/hdr", true);
  1668. GLOBAL_DEF("rendering/quality/depth/hdr.mobile", false);
  1669. bool hdr = GLOBAL_GET("rendering/quality/depth/hdr");
  1670. root->set_hdr(hdr);
  1671. VS::get_singleton()->scenario_set_reflection_atlas_size(root->get_world()->get_scenario(), ref_atlas_size, ref_atlas_subdiv);
  1672. { //load default fallback environment
  1673. //get possible extensions
  1674. List<String> exts;
  1675. ResourceLoader::get_recognized_extensions_for_type("Environment", &exts);
  1676. String ext_hint;
  1677. for (List<String>::Element *E = exts.front(); E; E = E->next()) {
  1678. if (ext_hint != String())
  1679. ext_hint += ",";
  1680. ext_hint += "*." + E->get();
  1681. }
  1682. //get path
  1683. String env_path = GLOBAL_DEF("rendering/environment/default_environment", "");
  1684. //setup property
  1685. ProjectSettings::get_singleton()->set_custom_property_info("rendering/environment/default_environment", PropertyInfo(Variant::STRING, "rendering/viewport/default_environment", PROPERTY_HINT_FILE, ext_hint));
  1686. env_path = env_path.strip_edges();
  1687. if (env_path != String()) {
  1688. Ref<Environment> env = ResourceLoader::load(env_path);
  1689. if (env.is_valid()) {
  1690. root->get_world()->set_fallback_environment(env);
  1691. } else {
  1692. if (Engine::get_singleton()->is_editor_hint()) {
  1693. //file was erased, clear the field.
  1694. ProjectSettings::get_singleton()->set("rendering/environment/default_environment", "");
  1695. } else {
  1696. //file was erased, notify user.
  1697. ERR_PRINTS(RTR("Default Environment as specified in Project Setings (Rendering -> Viewport -> Default Environment) could not be loaded."));
  1698. }
  1699. }
  1700. }
  1701. }
  1702. stretch_mode = STRETCH_MODE_DISABLED;
  1703. stretch_aspect = STRETCH_ASPECT_IGNORE;
  1704. stretch_shrink = 1;
  1705. last_screen_size = Size2(OS::get_singleton()->get_video_mode().width, OS::get_singleton()->get_video_mode().height);
  1706. _update_root_rect();
  1707. if (ScriptDebugger::get_singleton()) {
  1708. ScriptDebugger::get_singleton()->set_request_scene_tree_message_func(_debugger_request_tree, this);
  1709. }
  1710. root->set_physics_object_picking(GLOBAL_DEF("physics/common/enable_object_picking", true));
  1711. #ifdef TOOLS_ENABLED
  1712. edited_scene_root = NULL;
  1713. #endif
  1714. #ifdef DEBUG_ENABLED
  1715. live_edit_funcs.udata = this;
  1716. live_edit_funcs.node_path_func = _live_edit_node_path_funcs;
  1717. live_edit_funcs.res_path_func = _live_edit_res_path_funcs;
  1718. live_edit_funcs.node_set_func = _live_edit_node_set_funcs;
  1719. live_edit_funcs.node_set_res_func = _live_edit_node_set_res_funcs;
  1720. live_edit_funcs.node_call_func = _live_edit_node_call_funcs;
  1721. live_edit_funcs.res_set_func = _live_edit_res_set_funcs;
  1722. live_edit_funcs.res_set_res_func = _live_edit_res_set_res_funcs;
  1723. live_edit_funcs.res_call_func = _live_edit_res_call_funcs;
  1724. live_edit_funcs.root_func = _live_edit_root_funcs;
  1725. live_edit_funcs.tree_create_node_func = _live_edit_create_node_funcs;
  1726. live_edit_funcs.tree_instance_node_func = _live_edit_instance_node_funcs;
  1727. live_edit_funcs.tree_remove_node_func = _live_edit_remove_node_funcs;
  1728. live_edit_funcs.tree_remove_and_keep_node_func = _live_edit_remove_and_keep_node_funcs;
  1729. live_edit_funcs.tree_restore_node_func = _live_edit_restore_node_funcs;
  1730. live_edit_funcs.tree_duplicate_node_func = _live_edit_duplicate_node_funcs;
  1731. live_edit_funcs.tree_reparent_node_func = _live_edit_reparent_node_funcs;
  1732. if (ScriptDebugger::get_singleton()) {
  1733. ScriptDebugger::get_singleton()->set_live_edit_funcs(&live_edit_funcs);
  1734. }
  1735. live_edit_root = NodePath("/root");
  1736. last_send_cache_id = 1;
  1737. #endif
  1738. }
  1739. SceneTree::~SceneTree() {
  1740. }