multiplayer_api.cpp 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 "multiplayer_api.h"
  31. #include "core/debugger/engine_debugger.h"
  32. #include "core/io/marshalls.h"
  33. #include "scene/main/node.h"
  34. #include <stdint.h>
  35. #define NODE_ID_COMPRESSION_SHIFT 3
  36. #define NAME_ID_COMPRESSION_SHIFT 5
  37. #define BYTE_ONLY_OR_NO_ARGS_SHIFT 6
  38. #ifdef DEBUG_ENABLED
  39. #include "core/os/os.h"
  40. #endif
  41. _FORCE_INLINE_ bool _should_call_local(MultiplayerAPI::RPCMode mode, bool is_master, bool &r_skip_rpc) {
  42. switch (mode) {
  43. case MultiplayerAPI::RPC_MODE_DISABLED: {
  44. // Do nothing.
  45. } break;
  46. case MultiplayerAPI::RPC_MODE_REMOTE: {
  47. // Do nothing also. Remote cannot produce a local call.
  48. } break;
  49. case MultiplayerAPI::RPC_MODE_MASTERSYNC: {
  50. if (is_master) {
  51. r_skip_rpc = true; // I am the master, so skip remote call.
  52. }
  53. [[fallthrough]];
  54. }
  55. case MultiplayerAPI::RPC_MODE_REMOTESYNC:
  56. case MultiplayerAPI::RPC_MODE_PUPPETSYNC: {
  57. // Call it, sync always results in a local call.
  58. return true;
  59. } break;
  60. case MultiplayerAPI::RPC_MODE_MASTER: {
  61. if (is_master) {
  62. r_skip_rpc = true; // I am the master, so skip remote call.
  63. }
  64. return is_master;
  65. } break;
  66. case MultiplayerAPI::RPC_MODE_PUPPET: {
  67. return !is_master;
  68. } break;
  69. }
  70. return false;
  71. }
  72. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  73. switch (mode) {
  74. case MultiplayerAPI::RPC_MODE_DISABLED: {
  75. return false;
  76. } break;
  77. case MultiplayerAPI::RPC_MODE_REMOTE:
  78. case MultiplayerAPI::RPC_MODE_REMOTESYNC: {
  79. return true;
  80. } break;
  81. case MultiplayerAPI::RPC_MODE_MASTERSYNC:
  82. case MultiplayerAPI::RPC_MODE_MASTER: {
  83. return p_node->is_network_master();
  84. } break;
  85. case MultiplayerAPI::RPC_MODE_PUPPETSYNC:
  86. case MultiplayerAPI::RPC_MODE_PUPPET: {
  87. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  88. } break;
  89. }
  90. return false;
  91. }
  92. void MultiplayerAPI::poll() {
  93. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
  94. return;
  95. }
  96. network_peer->poll();
  97. if (!network_peer.is_valid()) { // It's possible that polling might have resulted in a disconnection, so check here.
  98. return;
  99. }
  100. while (network_peer->get_available_packet_count()) {
  101. int sender = network_peer->get_packet_peer();
  102. const uint8_t *packet;
  103. int len;
  104. Error err = network_peer->get_packet(&packet, len);
  105. if (err != OK) {
  106. ERR_PRINT("Error getting packet!");
  107. break; // Something is wrong!
  108. }
  109. rpc_sender_id = sender;
  110. _process_packet(sender, packet, len);
  111. rpc_sender_id = 0;
  112. if (!network_peer.is_valid()) {
  113. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  114. }
  115. }
  116. }
  117. void MultiplayerAPI::clear() {
  118. connected_peers.clear();
  119. path_get_cache.clear();
  120. path_send_cache.clear();
  121. packet_cache.clear();
  122. last_send_cache_id = 1;
  123. }
  124. void MultiplayerAPI::set_root_node(Node *p_node) {
  125. root_node = p_node;
  126. }
  127. void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer) {
  128. if (p_peer == network_peer) {
  129. return; // Nothing to do
  130. }
  131. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED,
  132. "Supplied NetworkedMultiplayerPeer must be connecting or connected.");
  133. if (network_peer.is_valid()) {
  134. network_peer->disconnect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer));
  135. network_peer->disconnect("peer_disconnected", callable_mp(this, &MultiplayerAPI::_del_peer));
  136. network_peer->disconnect("connection_succeeded", callable_mp(this, &MultiplayerAPI::_connected_to_server));
  137. network_peer->disconnect("connection_failed", callable_mp(this, &MultiplayerAPI::_connection_failed));
  138. network_peer->disconnect("server_disconnected", callable_mp(this, &MultiplayerAPI::_server_disconnected));
  139. clear();
  140. }
  141. network_peer = p_peer;
  142. if (network_peer.is_valid()) {
  143. network_peer->connect("peer_connected", callable_mp(this, &MultiplayerAPI::_add_peer));
  144. network_peer->connect("peer_disconnected", callable_mp(this, &MultiplayerAPI::_del_peer));
  145. network_peer->connect("connection_succeeded", callable_mp(this, &MultiplayerAPI::_connected_to_server));
  146. network_peer->connect("connection_failed", callable_mp(this, &MultiplayerAPI::_connection_failed));
  147. network_peer->connect("server_disconnected", callable_mp(this, &MultiplayerAPI::_server_disconnected));
  148. }
  149. }
  150. Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  151. return network_peer;
  152. }
  153. #ifdef DEBUG_ENABLED
  154. void _profile_node_data(const String &p_what, ObjectID p_id) {
  155. if (EngineDebugger::is_profiling("multiplayer")) {
  156. Array values;
  157. values.push_back("node");
  158. values.push_back(p_id);
  159. values.push_back(p_what);
  160. EngineDebugger::profiler_add_frame_data("multiplayer", values);
  161. }
  162. }
  163. void _profile_bandwidth_data(const String &p_inout, int p_size) {
  164. if (EngineDebugger::is_profiling("multiplayer")) {
  165. Array values;
  166. values.push_back("bandwidth");
  167. values.push_back(p_inout);
  168. values.push_back(OS::get_singleton()->get_ticks_msec());
  169. values.push_back(p_size);
  170. EngineDebugger::profiler_add_frame_data("multiplayer", values);
  171. }
  172. }
  173. #endif
  174. // Returns the packet size stripping the node path added when the node is not yet cached.
  175. int get_packet_len(uint32_t p_node_target, int p_packet_len) {
  176. if (p_node_target & 0x80000000) {
  177. int ofs = p_node_target & 0x7FFFFFFF;
  178. return p_packet_len - (p_packet_len - ofs);
  179. } else {
  180. return p_packet_len;
  181. }
  182. }
  183. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  184. ERR_FAIL_COND_MSG(root_node == nullptr, "Multiplayer root node was not initialized. If you are using custom multiplayer, remember to set the root node via MultiplayerAPI.set_root_node before using it.");
  185. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  186. #ifdef DEBUG_ENABLED
  187. _profile_bandwidth_data("in", p_packet_len);
  188. #endif
  189. // Extract the `packet_type` from the LSB three bits:
  190. uint8_t packet_type = p_packet[0] & 7;
  191. switch (packet_type) {
  192. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  193. _process_simplify_path(p_from, p_packet, p_packet_len);
  194. } break;
  195. case NETWORK_COMMAND_CONFIRM_PATH: {
  196. _process_confirm_path(p_from, p_packet, p_packet_len);
  197. } break;
  198. case NETWORK_COMMAND_REMOTE_CALL:
  199. case NETWORK_COMMAND_REMOTE_SET: {
  200. // Extract packet meta
  201. int packet_min_size = 1;
  202. int name_id_offset = 1;
  203. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  204. // Compute the meta size, which depends on the compression level.
  205. int node_id_compression = (p_packet[0] & 24) >> NODE_ID_COMPRESSION_SHIFT;
  206. int name_id_compression = (p_packet[0] & 32) >> NAME_ID_COMPRESSION_SHIFT;
  207. switch (node_id_compression) {
  208. case NETWORK_NODE_ID_COMPRESSION_8:
  209. packet_min_size += 1;
  210. name_id_offset += 1;
  211. break;
  212. case NETWORK_NODE_ID_COMPRESSION_16:
  213. packet_min_size += 2;
  214. name_id_offset += 2;
  215. break;
  216. case NETWORK_NODE_ID_COMPRESSION_32:
  217. packet_min_size += 4;
  218. name_id_offset += 4;
  219. break;
  220. default:
  221. ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");
  222. }
  223. switch (name_id_compression) {
  224. case NETWORK_NAME_ID_COMPRESSION_8:
  225. packet_min_size += 1;
  226. break;
  227. case NETWORK_NAME_ID_COMPRESSION_16:
  228. packet_min_size += 2;
  229. break;
  230. default:
  231. ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");
  232. }
  233. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  234. uint32_t node_target = 0;
  235. switch (node_id_compression) {
  236. case NETWORK_NODE_ID_COMPRESSION_8:
  237. node_target = p_packet[1];
  238. break;
  239. case NETWORK_NODE_ID_COMPRESSION_16:
  240. node_target = decode_uint16(p_packet + 1);
  241. break;
  242. case NETWORK_NODE_ID_COMPRESSION_32:
  243. node_target = decode_uint32(p_packet + 1);
  244. break;
  245. default:
  246. // Unreachable, checked before.
  247. CRASH_NOW();
  248. }
  249. Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);
  250. ERR_FAIL_COND_MSG(node == nullptr, "Invalid packet received. Requested node was not found.");
  251. uint16_t name_id = 0;
  252. switch (name_id_compression) {
  253. case NETWORK_NAME_ID_COMPRESSION_8:
  254. name_id = p_packet[name_id_offset];
  255. break;
  256. case NETWORK_NAME_ID_COMPRESSION_16:
  257. name_id = decode_uint16(p_packet + name_id_offset);
  258. break;
  259. default:
  260. // Unreachable, checked before.
  261. CRASH_NOW();
  262. }
  263. const int packet_len = get_packet_len(node_target, p_packet_len);
  264. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  265. _process_rpc(node, name_id, p_from, p_packet, packet_len, packet_min_size);
  266. } else {
  267. _process_rset(node, name_id, p_from, p_packet, packet_len, packet_min_size);
  268. }
  269. } break;
  270. case NETWORK_COMMAND_RAW: {
  271. _process_raw(p_from, p_packet, p_packet_len);
  272. } break;
  273. }
  274. }
  275. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {
  276. Node *node = nullptr;
  277. if (p_node_target & 0x80000000) {
  278. // Use full path (not cached yet).
  279. int ofs = p_node_target & 0x7FFFFFFF;
  280. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, nullptr, "Invalid packet received. Size smaller than declared.");
  281. String paths;
  282. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  283. NodePath np = paths;
  284. node = root_node->get_node(np);
  285. if (!node) {
  286. ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");
  287. }
  288. } else {
  289. // Use cached path.
  290. int id = p_node_target;
  291. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  292. ERR_FAIL_COND_V_MSG(!E, nullptr, "Invalid packet received. Requests invalid peer cache.");
  293. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  294. ERR_FAIL_COND_V_MSG(!F, nullptr, "Invalid packet received. Unabled to find requested cached node.");
  295. PathGetCache::NodeInfo *ni = &F->get();
  296. // Do proper caching later.
  297. node = root_node->get_node(ni->path);
  298. if (!node) {
  299. ERR_PRINT("Failed to get cached path from RPC: " + String(ni->path) + ".");
  300. }
  301. }
  302. return node;
  303. }
  304. void MultiplayerAPI::_process_rpc(Node *p_node, const uint16_t p_rpc_method_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  305. ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");
  306. // Check that remote can call the RPC on this node.
  307. StringName name = p_node->get_node_rpc_method(p_rpc_method_id);
  308. RPCMode rpc_mode = p_node->get_node_rpc_mode_by_id(p_rpc_method_id);
  309. if (name == StringName() && p_node->get_script_instance()) {
  310. name = p_node->get_script_instance()->get_rpc_method(p_rpc_method_id);
  311. rpc_mode = p_node->get_script_instance()->get_rpc_mode_by_id(p_rpc_method_id);
  312. }
  313. ERR_FAIL_COND(name == StringName());
  314. bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
  315. ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  316. int argc = 0;
  317. bool byte_only = false;
  318. const bool byte_only_or_no_args = ((p_packet[0] & 64) >> BYTE_ONLY_OR_NO_ARGS_SHIFT) == 1;
  319. if (byte_only_or_no_args) {
  320. if (p_offset < p_packet_len) {
  321. // This packet contains only bytes.
  322. argc = 1;
  323. byte_only = true;
  324. } else {
  325. // This rpc calls a method without parameters.
  326. }
  327. } else {
  328. // Normal variant, takes the argument count from the packet.
  329. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  330. argc = p_packet[p_offset];
  331. p_offset += 1;
  332. }
  333. Vector<Variant> args;
  334. Vector<const Variant *> argp;
  335. args.resize(argc);
  336. argp.resize(argc);
  337. #ifdef DEBUG_ENABLED
  338. _profile_node_data("in_rpc", p_node->get_instance_id());
  339. #endif
  340. if (byte_only) {
  341. Vector<uint8_t> pure_data;
  342. const int len = p_packet_len - p_offset;
  343. pure_data.resize(len);
  344. memcpy(pure_data.ptrw(), &p_packet[p_offset], len);
  345. args.write[0] = pure_data;
  346. argp.write[0] = &args[0];
  347. p_offset += len;
  348. } else {
  349. for (int i = 0; i < argc; i++) {
  350. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  351. int vlen;
  352. Error err = _decode_and_decompress_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen);
  353. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
  354. argp.write[i] = &args[i];
  355. p_offset += vlen;
  356. }
  357. }
  358. Callable::CallError ce;
  359. p_node->call(name, (const Variant **)argp.ptr(), argc, ce);
  360. if (ce.error != Callable::CallError::CALL_OK) {
  361. String error = Variant::get_call_error_text(p_node, name, (const Variant **)argp.ptr(), argc, ce);
  362. error = "RPC - " + error;
  363. ERR_PRINT(error);
  364. }
  365. }
  366. void MultiplayerAPI::_process_rset(Node *p_node, const uint16_t p_rpc_property_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  367. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  368. // Check that remote can call the RSET on this node.
  369. StringName name = p_node->get_node_rset_property(p_rpc_property_id);
  370. RPCMode rset_mode = p_node->get_node_rset_mode_by_id(p_rpc_property_id);
  371. if (name == StringName() && p_node->get_script_instance()) {
  372. name = p_node->get_script_instance()->get_rset_property(p_rpc_property_id);
  373. rset_mode = p_node->get_script_instance()->get_rset_mode_by_id(p_rpc_property_id);
  374. }
  375. ERR_FAIL_COND(name == StringName());
  376. bool can_call = _can_call_mode(p_node, rset_mode, p_from);
  377. ERR_FAIL_COND_MSG(!can_call, "RSET '" + String(name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  378. #ifdef DEBUG_ENABLED
  379. _profile_node_data("in_rset", p_node->get_instance_id());
  380. #endif
  381. Variant value;
  382. Error err = _decode_and_decompress_variant(value, &p_packet[p_offset], p_packet_len - p_offset, nullptr);
  383. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RSET value.");
  384. bool valid;
  385. p_node->set(name, value, &valid);
  386. if (!valid) {
  387. String error = "Error setting remote property '" + String(name) + "', not found in object of type " + p_node->get_class() + ".";
  388. ERR_PRINT(error);
  389. }
  390. }
  391. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  392. ERR_FAIL_COND_MSG(p_packet_len < 38, "Invalid packet received. Size too small.");
  393. int ofs = 1;
  394. String methods_md5;
  395. methods_md5.parse_utf8((const char *)(p_packet + ofs), 32);
  396. ofs += 33;
  397. int id = decode_uint32(&p_packet[ofs]);
  398. ofs += 4;
  399. String paths;
  400. paths.parse_utf8((const char *)(p_packet + ofs), p_packet_len - ofs);
  401. NodePath path = paths;
  402. if (!path_get_cache.has(p_from)) {
  403. path_get_cache[p_from] = PathGetCache();
  404. }
  405. Node *node = root_node->get_node(path);
  406. ERR_FAIL_COND(node == nullptr);
  407. const bool valid_rpc_checksum = node->get_rpc_md5() == methods_md5;
  408. if (valid_rpc_checksum == false) {
  409. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  410. }
  411. PathGetCache::NodeInfo ni;
  412. ni.path = path;
  413. path_get_cache[p_from].nodes[id] = ni;
  414. // Encode path to send ack.
  415. CharString pname = String(path).utf8();
  416. int len = encode_cstring(pname.get_data(), nullptr);
  417. Vector<uint8_t> packet;
  418. packet.resize(1 + 1 + len);
  419. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  420. packet.write[1] = valid_rpc_checksum;
  421. encode_cstring(pname.get_data(), &packet.write[2]);
  422. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  423. network_peer->set_target_peer(p_from);
  424. network_peer->put_packet(packet.ptr(), packet.size());
  425. }
  426. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  427. ERR_FAIL_COND_MSG(p_packet_len < 3, "Invalid packet received. Size too small.");
  428. const bool valid_rpc_checksum = p_packet[1];
  429. String paths;
  430. paths.parse_utf8((const char *)&p_packet[2], p_packet_len - 2);
  431. NodePath path = paths;
  432. if (valid_rpc_checksum == false) {
  433. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  434. }
  435. PathSentCache *psc = path_send_cache.getptr(path);
  436. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  437. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  438. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  439. E->get() = true;
  440. }
  441. bool MultiplayerAPI::_send_confirm_path(Node *p_node, NodePath p_path, PathSentCache *psc, int p_target) {
  442. bool has_all_peers = true;
  443. List<int> peers_to_add; // If one is missing, take note to add it.
  444. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  445. if (p_target < 0 && E->get() == -p_target) {
  446. continue; // Continue, excluded.
  447. }
  448. if (p_target > 0 && E->get() != p_target) {
  449. continue; // Continue, not for this peer.
  450. }
  451. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  452. if (!F || !F->get()) {
  453. // Path was not cached, or was cached but is unconfirmed.
  454. if (!F) {
  455. // Not cached at all, take note.
  456. peers_to_add.push_back(E->get());
  457. }
  458. has_all_peers = false;
  459. }
  460. }
  461. if (peers_to_add.size() > 0) {
  462. // Those that need to be added, send a message for this.
  463. // Encode function name.
  464. const CharString path = String(p_path).utf8();
  465. const int path_len = encode_cstring(path.get_data(), nullptr);
  466. // Extract MD5 from rpc methods list.
  467. const String methods_md5 = p_node->get_rpc_md5();
  468. const int methods_md5_len = 33; // 32 + 1 for the `0` that is added by the encoder.
  469. Vector<uint8_t> packet;
  470. packet.resize(1 + 4 + path_len + methods_md5_len);
  471. int ofs = 0;
  472. packet.write[ofs] = NETWORK_COMMAND_SIMPLIFY_PATH;
  473. ofs += 1;
  474. ofs += encode_cstring(methods_md5.utf8().get_data(), &packet.write[ofs]);
  475. ofs += encode_uint32(psc->id, &packet.write[ofs]);
  476. ofs += encode_cstring(path.get_data(), &packet.write[ofs]);
  477. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  478. network_peer->set_target_peer(E->get()); // To all of you.
  479. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  480. network_peer->put_packet(packet.ptr(), packet.size());
  481. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  482. }
  483. }
  484. return has_all_peers;
  485. }
  486. // The variant is compressed and encoded; The first byte contains all the meta
  487. // information and the format is:
  488. // - The first LSB 5 bits are used for the variant type.
  489. // - The next two bits are used to store the encoding mode.
  490. // - The most significant is used to store the boolean value.
  491. #define VARIANT_META_TYPE_MASK 0x1F
  492. #define VARIANT_META_EMODE_MASK 0x60
  493. #define VARIANT_META_BOOL_MASK 0x80
  494. #define ENCODE_8 0 << 5
  495. #define ENCODE_16 1 << 5
  496. #define ENCODE_32 2 << 5
  497. #define ENCODE_64 3 << 5
  498. Error MultiplayerAPI::_encode_and_compress_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) {
  499. // Unreachable because `VARIANT_MAX` == 27 and `ENCODE_VARIANT_MASK` == 31
  500. CRASH_COND(p_variant.get_type() > VARIANT_META_TYPE_MASK);
  501. uint8_t *buf = r_buffer;
  502. r_len = 0;
  503. uint8_t encode_mode = 0;
  504. switch (p_variant.get_type()) {
  505. case Variant::BOOL: {
  506. if (buf) {
  507. // We still have 1 free bit in the meta, so let's use it.
  508. buf[0] = (p_variant.operator bool()) ? (1 << 7) : 0;
  509. buf[0] |= encode_mode | p_variant.get_type();
  510. }
  511. r_len += 1;
  512. } break;
  513. case Variant::INT: {
  514. if (buf) {
  515. // Reserve the first byte for the meta.
  516. buf += 1;
  517. }
  518. r_len += 1;
  519. int64_t val = p_variant;
  520. if (val <= (int64_t)INT8_MAX && val >= (int64_t)INT8_MIN) {
  521. // Use 8 bit
  522. encode_mode = ENCODE_8;
  523. if (buf) {
  524. buf[0] = val;
  525. }
  526. r_len += 1;
  527. } else if (val <= (int64_t)INT16_MAX && val >= (int64_t)INT16_MIN) {
  528. // Use 16 bit
  529. encode_mode = ENCODE_16;
  530. if (buf) {
  531. encode_uint16(val, buf);
  532. }
  533. r_len += 2;
  534. } else if (val <= (int64_t)INT32_MAX && val >= (int64_t)INT32_MIN) {
  535. // Use 32 bit
  536. encode_mode = ENCODE_32;
  537. if (buf) {
  538. encode_uint32(val, buf);
  539. }
  540. r_len += 4;
  541. } else {
  542. // Use 64 bit
  543. encode_mode = ENCODE_64;
  544. if (buf) {
  545. encode_uint64(val, buf);
  546. }
  547. r_len += 8;
  548. }
  549. // Store the meta
  550. if (buf) {
  551. buf -= 1;
  552. buf[0] = encode_mode | p_variant.get_type();
  553. }
  554. } break;
  555. default:
  556. // Any other case is not yet compressed.
  557. Error err = encode_variant(p_variant, r_buffer, r_len, allow_object_decoding);
  558. if (err != OK) {
  559. return err;
  560. }
  561. if (r_buffer) {
  562. // The first byte is not used by the marshaling, so store the type
  563. // so we know how to decompress and decode this variant.
  564. r_buffer[0] = p_variant.get_type();
  565. }
  566. }
  567. return OK;
  568. }
  569. Error MultiplayerAPI::_decode_and_decompress_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) {
  570. const uint8_t *buf = p_buffer;
  571. int len = p_len;
  572. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  573. uint8_t type = buf[0] & VARIANT_META_TYPE_MASK;
  574. uint8_t encode_mode = buf[0] & VARIANT_META_EMODE_MASK;
  575. ERR_FAIL_COND_V(type >= Variant::VARIANT_MAX, ERR_INVALID_DATA);
  576. switch (type) {
  577. case Variant::BOOL: {
  578. bool val = (buf[0] & VARIANT_META_BOOL_MASK) > 0;
  579. r_variant = val;
  580. if (r_len) {
  581. *r_len = 1;
  582. }
  583. } break;
  584. case Variant::INT: {
  585. buf += 1;
  586. len -= 1;
  587. if (r_len) {
  588. *r_len = 1;
  589. }
  590. if (encode_mode == ENCODE_8) {
  591. // 8 bits.
  592. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  593. int8_t val = buf[0];
  594. r_variant = val;
  595. if (r_len) {
  596. (*r_len) += 1;
  597. }
  598. } else if (encode_mode == ENCODE_16) {
  599. // 16 bits.
  600. ERR_FAIL_COND_V(len < 2, ERR_INVALID_DATA);
  601. int16_t val = decode_uint16(buf);
  602. r_variant = val;
  603. if (r_len) {
  604. (*r_len) += 2;
  605. }
  606. } else if (encode_mode == ENCODE_32) {
  607. // 32 bits.
  608. ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
  609. int32_t val = decode_uint32(buf);
  610. r_variant = val;
  611. if (r_len) {
  612. (*r_len) += 4;
  613. }
  614. } else {
  615. // 64 bits.
  616. ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
  617. int64_t val = decode_uint64(buf);
  618. r_variant = val;
  619. if (r_len) {
  620. (*r_len) += 8;
  621. }
  622. }
  623. } break;
  624. default:
  625. Error err = decode_variant(r_variant, p_buffer, p_len, r_len, allow_object_decoding);
  626. if (err != OK) {
  627. return err;
  628. }
  629. }
  630. return OK;
  631. }
  632. void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  633. ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
  634. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING, "Attempt to remote call/set when networking is not connected yet in SceneTree.");
  635. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
  636. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
  637. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  638. ERR_FAIL_COND_MSG(p_to == network_peer->get_unique_id(), "Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()) + ".");
  639. ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
  640. }
  641. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  642. ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  643. // See if the path is cached.
  644. PathSentCache *psc = path_send_cache.getptr(from_path);
  645. if (!psc) {
  646. // Path is not cached, create.
  647. path_send_cache[from_path] = PathSentCache();
  648. psc = path_send_cache.getptr(from_path);
  649. psc->id = last_send_cache_id++;
  650. }
  651. // See if all peers have cached path (if so, call can be fast).
  652. const bool has_all_peers = _send_confirm_path(p_from, from_path, psc, p_to);
  653. // Create base packet, lots of hardcode because it must be tight.
  654. int ofs = 0;
  655. #define MAKE_ROOM(m_amount) \
  656. if (packet_cache.size() < m_amount) \
  657. packet_cache.resize(m_amount);
  658. // Encode meta.
  659. // The meta is composed by a single byte that contains (starting from the least segnificant bit):
  660. // - `NetworkCommands` in the first three bits.
  661. // - `NetworkNodeIdCompression` in the next 2 bits.
  662. // - `NetworkNameIdCompression` in the next 1 bit.
  663. // - `byte_only_or_no_args` in the next 1 bit.
  664. // - So we still have the last bit free!
  665. uint8_t command_type = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  666. uint8_t node_id_compression = UINT8_MAX;
  667. uint8_t name_id_compression = UINT8_MAX;
  668. bool byte_only_or_no_args = false;
  669. MAKE_ROOM(1);
  670. // The meta is composed along the way, so just set 0 for now.
  671. packet_cache.write[0] = 0;
  672. ofs += 1;
  673. // Encode Node ID.
  674. if (has_all_peers) {
  675. // Compress the node ID only if all the target peers already know it.
  676. if (psc->id >= 0 && psc->id <= 255) {
  677. // We can encode the id in 1 byte
  678. node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;
  679. MAKE_ROOM(ofs + 1);
  680. packet_cache.write[ofs] = static_cast<uint8_t>(psc->id);
  681. ofs += 1;
  682. } else if (psc->id >= 0 && psc->id <= 65535) {
  683. // We can encode the id in 2 bytes
  684. node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;
  685. MAKE_ROOM(ofs + 2);
  686. encode_uint16(static_cast<uint16_t>(psc->id), &(packet_cache.write[ofs]));
  687. ofs += 2;
  688. } else {
  689. // Too big, let's use 4 bytes.
  690. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  691. MAKE_ROOM(ofs + 4);
  692. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  693. ofs += 4;
  694. }
  695. } else {
  696. // The targets doesn't know the node yet, so we need to use 32 bits int.
  697. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  698. MAKE_ROOM(ofs + 4);
  699. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  700. ofs += 4;
  701. }
  702. if (p_set) {
  703. // Take the rpc property ID
  704. uint16_t property_id = p_from->get_node_rset_property_id(p_name);
  705. if (property_id == UINT16_MAX && p_from->get_script_instance()) {
  706. property_id = p_from->get_script_instance()->get_rset_property_id(p_name);
  707. }
  708. ERR_FAIL_COND_MSG(property_id == UINT16_MAX, "Unable to take the `property_id` for the property:" + p_name + ". this can happen only if this property is not marked as `remote`.");
  709. if (property_id <= UINT8_MAX) {
  710. // The ID fits in 1 byte
  711. name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
  712. MAKE_ROOM(ofs + 1);
  713. packet_cache.write[ofs] = static_cast<uint8_t>(property_id);
  714. ofs += 1;
  715. } else {
  716. // The ID is larger, let's use 2 bytes
  717. name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
  718. MAKE_ROOM(ofs + 2);
  719. encode_uint16(property_id, &(packet_cache.write[ofs]));
  720. ofs += 2;
  721. }
  722. // Set argument.
  723. int len(0);
  724. Error err = _encode_and_compress_variant(*p_arg[0], nullptr, len);
  725. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  726. MAKE_ROOM(ofs + len);
  727. _encode_and_compress_variant(*p_arg[0], &(packet_cache.write[ofs]), len);
  728. ofs += len;
  729. } else {
  730. // Take the rpc method ID
  731. uint16_t method_id = p_from->get_node_rpc_method_id(p_name);
  732. if (method_id == UINT16_MAX && p_from->get_script_instance()) {
  733. method_id = p_from->get_script_instance()->get_rpc_method_id(p_name);
  734. }
  735. ERR_FAIL_COND_MSG(method_id == UINT16_MAX,
  736. vformat("Unable to take the `method_id` for the function \"%s\" at path: \"%s\". This happens when the method is not marked as `remote`.", p_name, p_from->get_path()));
  737. if (method_id <= UINT8_MAX) {
  738. // The ID fits in 1 byte
  739. name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
  740. MAKE_ROOM(ofs + 1);
  741. packet_cache.write[ofs] = static_cast<uint8_t>(method_id);
  742. ofs += 1;
  743. } else {
  744. // The ID is larger, let's use 2 bytes
  745. name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
  746. MAKE_ROOM(ofs + 2);
  747. encode_uint16(method_id, &(packet_cache.write[ofs]));
  748. ofs += 2;
  749. }
  750. if (p_argcount == 0) {
  751. byte_only_or_no_args = true;
  752. } else if (p_argcount == 1 && p_arg[0]->get_type() == Variant::PACKED_BYTE_ARRAY) {
  753. byte_only_or_no_args = true;
  754. // Special optimization when only the byte vector is sent.
  755. const Vector<uint8_t> data = *p_arg[0];
  756. MAKE_ROOM(ofs + data.size());
  757. copymem(&(packet_cache.write[ofs]), data.ptr(), sizeof(uint8_t) * data.size());
  758. ofs += data.size();
  759. } else {
  760. // Arguments
  761. MAKE_ROOM(ofs + 1);
  762. packet_cache.write[ofs] = p_argcount;
  763. ofs += 1;
  764. for (int i = 0; i < p_argcount; i++) {
  765. int len(0);
  766. Error err = _encode_and_compress_variant(*p_arg[i], nullptr, len);
  767. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  768. MAKE_ROOM(ofs + len);
  769. _encode_and_compress_variant(*p_arg[i], &(packet_cache.write[ofs]), len);
  770. ofs += len;
  771. }
  772. }
  773. }
  774. ERR_FAIL_COND(command_type > 7);
  775. ERR_FAIL_COND(node_id_compression > 3);
  776. ERR_FAIL_COND(name_id_compression > 1);
  777. // We can now set the meta
  778. packet_cache.write[0] = command_type + (node_id_compression << NODE_ID_COMPRESSION_SHIFT) + (name_id_compression << NAME_ID_COMPRESSION_SHIFT) + ((byte_only_or_no_args ? 1 : 0) << BYTE_ONLY_OR_NO_ARGS_SHIFT);
  779. #ifdef DEBUG_ENABLED
  780. _profile_bandwidth_data("out", ofs);
  781. #endif
  782. // Take chance and set transfer mode, since all send methods will use it.
  783. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  784. if (has_all_peers) {
  785. // They all have verified paths, so send fast.
  786. network_peer->set_target_peer(p_to); // To all of you.
  787. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  788. } else {
  789. // Unreachable because the node ID is never compressed if the peers doesn't know it.
  790. CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);
  791. // Not all verified path, so send one by one.
  792. // Append path at the end, since we will need it for some packets.
  793. CharString pname = String(from_path).utf8();
  794. int path_len = encode_cstring(pname.get_data(), nullptr);
  795. MAKE_ROOM(ofs + path_len);
  796. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  797. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  798. if (p_to < 0 && E->get() == -p_to) {
  799. continue; // Continue, excluded.
  800. }
  801. if (p_to > 0 && E->get() != p_to) {
  802. continue; // Continue, not for this peer.
  803. }
  804. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  805. ERR_CONTINUE(!F); // Should never happen.
  806. network_peer->set_target_peer(E->get()); // To this one specifically.
  807. if (F->get()) {
  808. // This one confirmed path, so use id.
  809. encode_uint32(psc->id, &(packet_cache.write[1]));
  810. network_peer->put_packet(packet_cache.ptr(), ofs);
  811. } else {
  812. // This one did not confirm path yet, so use entire path (sorry!).
  813. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  814. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  815. }
  816. }
  817. }
  818. }
  819. void MultiplayerAPI::_add_peer(int p_id) {
  820. connected_peers.insert(p_id);
  821. path_get_cache.insert(p_id, PathGetCache());
  822. emit_signal("network_peer_connected", p_id);
  823. }
  824. void MultiplayerAPI::_del_peer(int p_id) {
  825. connected_peers.erase(p_id);
  826. // Cleanup get cache.
  827. path_get_cache.erase(p_id);
  828. // Cleanup sent cache.
  829. // Some refactoring is needed to make this faster and do paths GC.
  830. List<NodePath> keys;
  831. path_send_cache.get_key_list(&keys);
  832. for (List<NodePath>::Element *E = keys.front(); E; E = E->next()) {
  833. PathSentCache *psc = path_send_cache.getptr(E->get());
  834. psc->confirmed_peers.erase(p_id);
  835. }
  836. emit_signal("network_peer_disconnected", p_id);
  837. }
  838. void MultiplayerAPI::_connected_to_server() {
  839. emit_signal("connected_to_server");
  840. }
  841. void MultiplayerAPI::_connection_failed() {
  842. emit_signal("connection_failed");
  843. }
  844. void MultiplayerAPI::_server_disconnected() {
  845. emit_signal("server_disconnected");
  846. }
  847. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  848. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
  849. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
  850. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to call an RPC via a network peer which is not connected.");
  851. int node_id = network_peer->get_unique_id();
  852. bool skip_rpc = node_id == p_peer_id;
  853. bool call_local_native = false;
  854. bool call_local_script = false;
  855. bool is_master = p_node->is_network_master();
  856. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  857. // Check that send mode can use local call.
  858. RPCMode rpc_mode = p_node->get_node_rpc_mode(p_method);
  859. call_local_native = _should_call_local(rpc_mode, is_master, skip_rpc);
  860. if (call_local_native) {
  861. // Done below.
  862. } else if (p_node->get_script_instance()) {
  863. // Attempt with script.
  864. rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  865. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  866. }
  867. }
  868. if (!skip_rpc) {
  869. #ifdef DEBUG_ENABLED
  870. _profile_node_data("out_rpc", p_node->get_instance_id());
  871. #endif
  872. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  873. }
  874. if (call_local_native) {
  875. int temp_id = rpc_sender_id;
  876. rpc_sender_id = get_network_unique_id();
  877. Callable::CallError ce;
  878. p_node->call(p_method, p_arg, p_argcount, ce);
  879. rpc_sender_id = temp_id;
  880. if (ce.error != Callable::CallError::CALL_OK) {
  881. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  882. error = "rpc() aborted in local call: - " + error + ".";
  883. ERR_PRINT(error);
  884. return;
  885. }
  886. }
  887. if (call_local_script) {
  888. int temp_id = rpc_sender_id;
  889. rpc_sender_id = get_network_unique_id();
  890. Callable::CallError ce;
  891. ce.error = Callable::CallError::CALL_OK;
  892. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  893. rpc_sender_id = temp_id;
  894. if (ce.error != Callable::CallError::CALL_OK) {
  895. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  896. error = "rpc() aborted in script local call: - " + error + ".";
  897. ERR_PRINT(error);
  898. return;
  899. }
  900. }
  901. ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  902. }
  903. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  904. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to RSET while no network peer is active.");
  905. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to RSET on a node which is not inside SceneTree.");
  906. ERR_FAIL_COND_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, "Trying to send an RSET via a network peer which is not connected.");
  907. int node_id = network_peer->get_unique_id();
  908. bool is_master = p_node->is_network_master();
  909. bool skip_rset = node_id == p_peer_id;
  910. bool set_local = false;
  911. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  912. // Check that send mode can use local call.
  913. RPCMode rpc_mode = p_node->get_node_rset_mode(p_property);
  914. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  915. if (set_local) {
  916. bool valid;
  917. int temp_id = rpc_sender_id;
  918. rpc_sender_id = get_network_unique_id();
  919. p_node->set(p_property, p_value, &valid);
  920. rpc_sender_id = temp_id;
  921. if (!valid) {
  922. String error = "rset() aborted in local set, property not found: - " + String(p_property) + ".";
  923. ERR_PRINT(error);
  924. return;
  925. }
  926. } else if (p_node->get_script_instance()) {
  927. // Attempt with script.
  928. rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  929. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  930. if (set_local) {
  931. int temp_id = rpc_sender_id;
  932. rpc_sender_id = get_network_unique_id();
  933. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  934. rpc_sender_id = temp_id;
  935. if (!valid) {
  936. String error = "rset() aborted in local script set, property not found: - " + String(p_property) + ".";
  937. ERR_PRINT(error);
  938. return;
  939. }
  940. }
  941. }
  942. }
  943. if (skip_rset) {
  944. ERR_FAIL_COND_MSG(!set_local, "RSET for '" + p_property + "' on yourself is not allowed by selected mode.");
  945. return;
  946. }
  947. #ifdef DEBUG_ENABLED
  948. _profile_node_data("out_rset", p_node->get_instance_id());
  949. #endif
  950. const Variant *vptr = &p_value;
  951. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  952. }
  953. Error MultiplayerAPI::send_bytes(Vector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  954. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  955. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  956. ERR_FAIL_COND_V_MSG(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a network peer which is not connected.");
  957. MAKE_ROOM(p_data.size() + 1);
  958. const uint8_t *r = p_data.ptr();
  959. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  960. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  961. network_peer->set_target_peer(p_to);
  962. network_peer->set_transfer_mode(p_mode);
  963. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  964. }
  965. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  966. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  967. Vector<uint8_t> out;
  968. int len = p_packet_len - 1;
  969. out.resize(len);
  970. {
  971. uint8_t *w = out.ptrw();
  972. memcpy(&w[0], &p_packet[1], len);
  973. }
  974. emit_signal("network_peer_packet", p_from, out);
  975. }
  976. int MultiplayerAPI::get_network_unique_id() const {
  977. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  978. return network_peer->get_unique_id();
  979. }
  980. bool MultiplayerAPI::is_network_server() const {
  981. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  982. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. I can't be a server.");
  983. return network_peer->is_server();
  984. }
  985. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  986. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  987. network_peer->set_refuse_new_connections(p_refuse);
  988. }
  989. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  990. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  991. return network_peer->is_refusing_new_connections();
  992. }
  993. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  994. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  995. Vector<int> ret;
  996. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  997. ret.push_back(E->get());
  998. }
  999. return ret;
  1000. }
  1001. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  1002. allow_object_decoding = p_enable;
  1003. }
  1004. bool MultiplayerAPI::is_object_decoding_allowed() const {
  1005. return allow_object_decoding;
  1006. }
  1007. void MultiplayerAPI::_bind_methods() {
  1008. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  1009. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  1010. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  1011. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  1012. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  1013. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  1014. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  1015. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  1016. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  1017. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  1018. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  1019. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  1020. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  1021. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  1022. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  1023. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  1024. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  1025. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  1026. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  1027. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  1028. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  1029. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  1030. ADD_SIGNAL(MethodInfo("connected_to_server"));
  1031. ADD_SIGNAL(MethodInfo("connection_failed"));
  1032. ADD_SIGNAL(MethodInfo("server_disconnected"));
  1033. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  1034. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  1035. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  1036. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  1037. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  1038. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  1039. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  1040. }
  1041. MultiplayerAPI::MultiplayerAPI() {
  1042. clear();
  1043. }
  1044. MultiplayerAPI::~MultiplayerAPI() {
  1045. clear();
  1046. }