multiplayer_api.cpp 40 KB

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