multiplayer_api.cpp 46 KB

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