multiplayer_api.cpp 40 KB

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