multiplayer_api.cpp 44 KB

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