multiplayer_api.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "multiplayer_api.h"
  31. #include "core/io/marshalls.h"
  32. #include "scene/main/node.h"
  33. _FORCE_INLINE_ bool _should_call_local(MultiplayerAPI::RPCMode mode, bool is_master, bool &r_skip_rpc) {
  34. switch (mode) {
  35. case MultiplayerAPI::RPC_MODE_DISABLED: {
  36. // Do nothing.
  37. } break;
  38. case MultiplayerAPI::RPC_MODE_REMOTE: {
  39. // Do nothing also. Remote cannot produce a local call.
  40. } break;
  41. case MultiplayerAPI::RPC_MODE_MASTERSYNC: {
  42. if (is_master)
  43. r_skip_rpc = true; // I am the master, so skip remote call.
  44. FALLTHROUGH;
  45. }
  46. case MultiplayerAPI::RPC_MODE_REMOTESYNC:
  47. case MultiplayerAPI::RPC_MODE_PUPPETSYNC: {
  48. // Call it, sync always results in a local call.
  49. return true;
  50. } break;
  51. case MultiplayerAPI::RPC_MODE_MASTER: {
  52. if (is_master)
  53. r_skip_rpc = true; // I am the master, so skip remote call.
  54. return is_master;
  55. } break;
  56. case MultiplayerAPI::RPC_MODE_PUPPET: {
  57. return !is_master;
  58. } break;
  59. }
  60. return false;
  61. }
  62. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  63. switch (mode) {
  64. case MultiplayerAPI::RPC_MODE_DISABLED: {
  65. return false;
  66. } break;
  67. case MultiplayerAPI::RPC_MODE_REMOTE:
  68. case MultiplayerAPI::RPC_MODE_REMOTESYNC: {
  69. return true;
  70. } break;
  71. case MultiplayerAPI::RPC_MODE_MASTERSYNC:
  72. case MultiplayerAPI::RPC_MODE_MASTER: {
  73. return p_node->is_network_master();
  74. } break;
  75. case MultiplayerAPI::RPC_MODE_PUPPETSYNC:
  76. case MultiplayerAPI::RPC_MODE_PUPPET: {
  77. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  78. } break;
  79. }
  80. return false;
  81. }
  82. void MultiplayerAPI::poll() {
  83. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
  84. return;
  85. network_peer->poll();
  86. if (!network_peer.is_valid()) // It's possible that polling might have resulted in a disconnection, so check here.
  87. return;
  88. while (network_peer->get_available_packet_count()) {
  89. int sender = network_peer->get_packet_peer();
  90. const uint8_t *packet;
  91. int len;
  92. Error err = network_peer->get_packet(&packet, len);
  93. if (err != OK) {
  94. ERR_PRINT("Error getting packet!");
  95. }
  96. rpc_sender_id = sender;
  97. _process_packet(sender, packet, len);
  98. rpc_sender_id = 0;
  99. if (!network_peer.is_valid()) {
  100. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  101. }
  102. }
  103. }
  104. void MultiplayerAPI::clear() {
  105. connected_peers.clear();
  106. path_get_cache.clear();
  107. path_send_cache.clear();
  108. packet_cache.clear();
  109. last_send_cache_id = 1;
  110. }
  111. void MultiplayerAPI::set_root_node(Node *p_node) {
  112. root_node = p_node;
  113. }
  114. void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer) {
  115. if (p_peer == network_peer) return; // Nothing to do
  116. if (network_peer.is_valid()) {
  117. network_peer->disconnect("peer_connected", this, "_add_peer");
  118. network_peer->disconnect("peer_disconnected", this, "_del_peer");
  119. network_peer->disconnect("connection_succeeded", this, "_connected_to_server");
  120. network_peer->disconnect("connection_failed", this, "_connection_failed");
  121. network_peer->disconnect("server_disconnected", this, "_server_disconnected");
  122. clear();
  123. }
  124. network_peer = p_peer;
  125. ERR_EXPLAIN("Supplied NetworkedNetworkPeer must be connecting or connected.");
  126. ERR_FAIL_COND(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED);
  127. if (network_peer.is_valid()) {
  128. network_peer->connect("peer_connected", this, "_add_peer");
  129. network_peer->connect("peer_disconnected", this, "_del_peer");
  130. network_peer->connect("connection_succeeded", this, "_connected_to_server");
  131. network_peer->connect("connection_failed", this, "_connection_failed");
  132. network_peer->connect("server_disconnected", this, "_server_disconnected");
  133. }
  134. }
  135. Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  136. return network_peer;
  137. }
  138. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  139. ERR_EXPLAIN("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");
  140. ERR_FAIL_COND(root_node == NULL);
  141. ERR_EXPLAIN("Invalid packet received. Size too small.");
  142. ERR_FAIL_COND(p_packet_len < 1);
  143. uint8_t packet_type = p_packet[0];
  144. switch (packet_type) {
  145. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  146. _process_simplify_path(p_from, p_packet, p_packet_len);
  147. } break;
  148. case NETWORK_COMMAND_CONFIRM_PATH: {
  149. _process_confirm_path(p_from, p_packet, p_packet_len);
  150. } break;
  151. case NETWORK_COMMAND_REMOTE_CALL:
  152. case NETWORK_COMMAND_REMOTE_SET: {
  153. ERR_EXPLAIN("Invalid packet received. Size too small.");
  154. ERR_FAIL_COND(p_packet_len < 6);
  155. Node *node = _process_get_node(p_from, p_packet, p_packet_len);
  156. ERR_EXPLAIN("Invalid packet received. Requested node was not found.");
  157. ERR_FAIL_COND(node == NULL);
  158. // Detect cstring end.
  159. int len_end = 5;
  160. for (; len_end < p_packet_len; len_end++) {
  161. if (p_packet[len_end] == 0) {
  162. break;
  163. }
  164. }
  165. ERR_EXPLAIN("Invalid packet received. Size too small.");
  166. ERR_FAIL_COND(len_end >= p_packet_len);
  167. StringName name = String::utf8((const char *)&p_packet[5]);
  168. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  169. _process_rpc(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  170. } else {
  171. _process_rset(node, name, p_from, p_packet, p_packet_len, len_end + 1);
  172. }
  173. } break;
  174. case NETWORK_COMMAND_RAW: {
  175. _process_raw(p_from, p_packet, p_packet_len);
  176. } break;
  177. }
  178. }
  179. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, int p_packet_len) {
  180. uint32_t target = decode_uint32(&p_packet[1]);
  181. Node *node = NULL;
  182. if (target & 0x80000000) {
  183. // Use full path (not cached yet).
  184. int ofs = target & 0x7FFFFFFF;
  185. ERR_EXPLAIN("Invalid packet received. Size smaller than declared.");
  186. ERR_FAIL_COND_V(ofs >= p_packet_len, NULL);
  187. String paths;
  188. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  189. NodePath np = paths;
  190. node = root_node->get_node(np);
  191. if (!node)
  192. ERR_PRINTS("Failed to get path from RPC: " + String(np));
  193. } else {
  194. // Use cached path.
  195. int id = target;
  196. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  197. ERR_EXPLAIN("Invalid packet received. Requests invalid peer cache.");
  198. ERR_FAIL_COND_V(!E, NULL);
  199. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  200. ERR_EXPLAIN("Invalid packet received. Unabled to find requested cached node.");
  201. ERR_FAIL_COND_V(!F, NULL);
  202. PathGetCache::NodeInfo *ni = &F->get();
  203. // Do proper caching later.
  204. node = root_node->get_node(ni->path);
  205. if (!node)
  206. ERR_PRINTS("Failed to get cached path from RPC: " + String(ni->path));
  207. }
  208. return node;
  209. }
  210. void MultiplayerAPI::_process_rpc(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  211. ERR_EXPLAIN("Invalid packet received. Size too small.");
  212. ERR_FAIL_COND(p_offset >= p_packet_len);
  213. // Check that remote can call the RPC on this node.
  214. RPCMode rpc_mode = RPC_MODE_DISABLED;
  215. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_name);
  216. if (E) {
  217. rpc_mode = E->get();
  218. } else if (p_node->get_script_instance()) {
  219. rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_name);
  220. }
  221. ERR_EXPLAIN("RPC '" + String(p_name) + "' is not allowed from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  222. ERR_FAIL_COND(!_can_call_mode(p_node, rpc_mode, p_from));
  223. int argc = p_packet[p_offset];
  224. Vector<Variant> args;
  225. Vector<const Variant *> argp;
  226. args.resize(argc);
  227. argp.resize(argc);
  228. p_offset++;
  229. for (int i = 0; i < argc; i++) {
  230. ERR_EXPLAIN("Invalid packet received. Size too small.");
  231. ERR_FAIL_COND(p_offset >= p_packet_len);
  232. int vlen;
  233. Error err = decode_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen, allow_object_decoding || network_peer->is_object_decoding_allowed());
  234. ERR_EXPLAIN("Invalid packet received. Unable to decode RPC argument.");
  235. ERR_FAIL_COND(err != OK);
  236. argp.write[i] = &args[i];
  237. p_offset += vlen;
  238. }
  239. Variant::CallError ce;
  240. p_node->call(p_name, (const Variant **)argp.ptr(), argc, ce);
  241. if (ce.error != Variant::CallError::CALL_OK) {
  242. String error = Variant::get_call_error_text(p_node, p_name, (const Variant **)argp.ptr(), argc, ce);
  243. error = "RPC - " + error;
  244. ERR_PRINTS(error);
  245. }
  246. }
  247. void MultiplayerAPI::_process_rset(Node *p_node, const StringName &p_name, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  248. ERR_EXPLAIN("Invalid packet received. Size too small.");
  249. ERR_FAIL_COND(p_offset >= p_packet_len);
  250. // Check that remote can call the RSET on this node.
  251. RPCMode rset_mode = RPC_MODE_DISABLED;
  252. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_name);
  253. if (E) {
  254. rset_mode = E->get();
  255. } else if (p_node->get_script_instance()) {
  256. rset_mode = p_node->get_script_instance()->get_rset_mode(p_name);
  257. }
  258. ERR_EXPLAIN("RSET '" + String(p_name) + "' is not allowed from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  259. ERR_FAIL_COND(!_can_call_mode(p_node, rset_mode, p_from));
  260. Variant value;
  261. Error err = decode_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL, allow_object_decoding || network_peer->is_object_decoding_allowed());
  262. ERR_EXPLAIN("Invalid packet received. Unable to decode RSET value.");
  263. ERR_FAIL_COND(err != OK);
  264. bool valid;
  265. p_node->set(p_name, value, &valid);
  266. if (!valid) {
  267. String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class();
  268. ERR_PRINTS(error);
  269. }
  270. }
  271. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  272. ERR_EXPLAIN("Invalid packet received. Size too small.");
  273. ERR_FAIL_COND(p_packet_len < 5);
  274. int id = decode_uint32(&p_packet[1]);
  275. String paths;
  276. paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
  277. NodePath path = paths;
  278. if (!path_get_cache.has(p_from)) {
  279. path_get_cache[p_from] = PathGetCache();
  280. }
  281. PathGetCache::NodeInfo ni;
  282. ni.path = path;
  283. ni.instance = 0;
  284. path_get_cache[p_from].nodes[id] = ni;
  285. // Encode path to send ack.
  286. CharString pname = String(path).utf8();
  287. int len = encode_cstring(pname.get_data(), NULL);
  288. Vector<uint8_t> packet;
  289. packet.resize(1 + len);
  290. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  291. encode_cstring(pname.get_data(), &packet.write[1]);
  292. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  293. network_peer->set_target_peer(p_from);
  294. network_peer->put_packet(packet.ptr(), packet.size());
  295. }
  296. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  297. ERR_EXPLAIN("Invalid packet received. Size too small.");
  298. ERR_FAIL_COND(p_packet_len < 2);
  299. String paths;
  300. paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
  301. NodePath path = paths;
  302. PathSentCache *psc = path_send_cache.getptr(path);
  303. ERR_EXPLAIN("Invalid packet received. Tries to confirm a path which was not found in cache.");
  304. ERR_FAIL_COND(!psc);
  305. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  306. ERR_EXPLAIN("Invalid packet received. Source peer was not found in cache for the given path.");
  307. ERR_FAIL_COND(!E);
  308. E->get() = true;
  309. }
  310. bool MultiplayerAPI::_send_confirm_path(NodePath p_path, PathSentCache *psc, int p_target) {
  311. bool has_all_peers = true;
  312. List<int> peers_to_add; // If one is missing, take note to add it.
  313. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  314. if (p_target < 0 && E->get() == -p_target)
  315. continue; // Continue, excluded.
  316. if (p_target > 0 && E->get() != p_target)
  317. continue; // Continue, not for this peer.
  318. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  319. if (!F || !F->get()) {
  320. // Path was not cached, or was cached but is unconfirmed.
  321. if (!F) {
  322. // Not cached at all, take note.
  323. peers_to_add.push_back(E->get());
  324. }
  325. has_all_peers = false;
  326. }
  327. }
  328. // Those that need to be added, send a message for this.
  329. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  330. // Encode function name.
  331. CharString pname = String(p_path).utf8();
  332. int len = encode_cstring(pname.get_data(), NULL);
  333. Vector<uint8_t> packet;
  334. packet.resize(1 + 4 + len);
  335. packet.write[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
  336. encode_uint32(psc->id, &packet.write[1]);
  337. encode_cstring(pname.get_data(), &packet.write[5]);
  338. network_peer->set_target_peer(E->get()); // To all of you.
  339. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  340. network_peer->put_packet(packet.ptr(), packet.size());
  341. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  342. }
  343. return has_all_peers;
  344. }
  345. void MultiplayerAPI::_send_rpc(Node *p_from, int p_to, bool p_unreliable, bool p_set, const StringName &p_name, const Variant **p_arg, int p_argcount) {
  346. if (network_peer.is_null()) {
  347. ERR_EXPLAIN("Attempt to remote call/set when networking is not active in SceneTree.");
  348. ERR_FAIL();
  349. }
  350. if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING) {
  351. ERR_EXPLAIN("Attempt to remote call/set when networking is not connected yet in SceneTree.");
  352. ERR_FAIL();
  353. }
  354. if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
  355. ERR_EXPLAIN("Attempt to remote call/set when networking is disconnected.");
  356. ERR_FAIL();
  357. }
  358. if (p_argcount > 255) {
  359. ERR_EXPLAIN("Too many arguments >255.");
  360. ERR_FAIL();
  361. }
  362. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  363. if (p_to == network_peer->get_unique_id()) {
  364. ERR_EXPLAIN("Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()));
  365. } else {
  366. ERR_EXPLAIN("Attempt to remote call unexisting ID: " + itos(p_to));
  367. }
  368. ERR_FAIL();
  369. }
  370. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  371. ERR_EXPLAIN("Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  372. ERR_FAIL_COND(from_path.is_empty());
  373. // See if the path is cached.
  374. PathSentCache *psc = path_send_cache.getptr(from_path);
  375. if (!psc) {
  376. // Path is not cached, create.
  377. path_send_cache[from_path] = PathSentCache();
  378. psc = path_send_cache.getptr(from_path);
  379. psc->id = last_send_cache_id++;
  380. }
  381. // Create base packet, lots of hardcode because it must be tight.
  382. int ofs = 0;
  383. #define MAKE_ROOM(m_amount) \
  384. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  385. // Encode type.
  386. MAKE_ROOM(1);
  387. packet_cache.write[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  388. ofs += 1;
  389. // Encode ID.
  390. MAKE_ROOM(ofs + 4);
  391. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  392. ofs += 4;
  393. // Encode function name.
  394. CharString name = String(p_name).utf8();
  395. int len = encode_cstring(name.get_data(), NULL);
  396. MAKE_ROOM(ofs + len);
  397. encode_cstring(name.get_data(), &(packet_cache.write[ofs]));
  398. ofs += len;
  399. if (p_set) {
  400. // Set argument.
  401. Error err = encode_variant(*p_arg[0], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  402. ERR_EXPLAIN("Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  403. ERR_FAIL_COND(err != OK);
  404. MAKE_ROOM(ofs + len);
  405. encode_variant(*p_arg[0], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  406. ofs += len;
  407. } else {
  408. // Call arguments.
  409. MAKE_ROOM(ofs + 1);
  410. packet_cache.write[ofs] = p_argcount;
  411. ofs += 1;
  412. for (int i = 0; i < p_argcount; i++) {
  413. Error err = encode_variant(*p_arg[i], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  414. ERR_EXPLAIN("Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  415. ERR_FAIL_COND(err != OK);
  416. MAKE_ROOM(ofs + len);
  417. encode_variant(*p_arg[i], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  418. ofs += len;
  419. }
  420. }
  421. // See if all peers have cached path (is so, call can be fast).
  422. bool has_all_peers = _send_confirm_path(from_path, psc, p_to);
  423. // Take chance and set transfer mode, since all send methods will use it.
  424. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  425. if (has_all_peers) {
  426. // They all have verified paths, so send fast.
  427. network_peer->set_target_peer(p_to); // To all of you.
  428. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  429. } else {
  430. // Not all verified path, so send one by one.
  431. // Append path at the end, since we will need it for some packets.
  432. CharString pname = String(from_path).utf8();
  433. int path_len = encode_cstring(pname.get_data(), NULL);
  434. MAKE_ROOM(ofs + path_len);
  435. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  436. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  437. if (p_to < 0 && E->get() == -p_to)
  438. continue; // Continue, excluded.
  439. if (p_to > 0 && E->get() != p_to)
  440. continue; // Continue, not for this peer.
  441. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  442. ERR_CONTINUE(!F); // Should never happen.
  443. network_peer->set_target_peer(E->get()); // To this one specifically.
  444. if (F->get()) {
  445. // This one confirmed path, so use id.
  446. encode_uint32(psc->id, &(packet_cache.write[1]));
  447. network_peer->put_packet(packet_cache.ptr(), ofs);
  448. } else {
  449. // This one did not confirm path yet, so use entire path (sorry!).
  450. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  451. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  452. }
  453. }
  454. }
  455. }
  456. void MultiplayerAPI::_add_peer(int p_id) {
  457. connected_peers.insert(p_id);
  458. path_get_cache.insert(p_id, PathGetCache());
  459. emit_signal("network_peer_connected", p_id);
  460. }
  461. void MultiplayerAPI::_del_peer(int p_id) {
  462. connected_peers.erase(p_id);
  463. path_get_cache.erase(p_id); // I no longer need your cache, sorry.
  464. emit_signal("network_peer_disconnected", p_id);
  465. }
  466. void MultiplayerAPI::_connected_to_server() {
  467. emit_signal("connected_to_server");
  468. }
  469. void MultiplayerAPI::_connection_failed() {
  470. emit_signal("connection_failed");
  471. }
  472. void MultiplayerAPI::_server_disconnected() {
  473. emit_signal("server_disconnected");
  474. }
  475. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  476. ERR_EXPLAIN("Trying to call an RPC while no network peer is active.");
  477. ERR_FAIL_COND(!network_peer.is_valid());
  478. ERR_EXPLAIN("Trying to call an RPC on a node which is not inside SceneTree.");
  479. ERR_FAIL_COND(!p_node->is_inside_tree());
  480. ERR_EXPLAIN("Trying to call an RPC via a network peer which is not connected.");
  481. ERR_FAIL_COND(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED);
  482. int node_id = network_peer->get_unique_id();
  483. bool skip_rpc = false;
  484. bool call_local_native = false;
  485. bool call_local_script = false;
  486. bool is_master = p_node->is_network_master();
  487. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  488. // Check that send mode can use local call.
  489. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_method);
  490. if (E) {
  491. call_local_native = _should_call_local(E->get(), is_master, skip_rpc);
  492. }
  493. if (call_local_native) {
  494. // Done below.
  495. } else if (p_node->get_script_instance()) {
  496. // Attempt with script.
  497. RPCMode rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  498. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  499. }
  500. }
  501. if (!skip_rpc) {
  502. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  503. }
  504. if (call_local_native) {
  505. Variant::CallError ce;
  506. p_node->call(p_method, p_arg, p_argcount, ce);
  507. if (ce.error != Variant::CallError::CALL_OK) {
  508. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  509. error = "rpc() aborted in local call: - " + error;
  510. ERR_PRINTS(error);
  511. return;
  512. }
  513. }
  514. if (call_local_script) {
  515. Variant::CallError ce;
  516. ce.error = Variant::CallError::CALL_OK;
  517. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  518. if (ce.error != Variant::CallError::CALL_OK) {
  519. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  520. error = "rpc() aborted in script local call: - " + error;
  521. ERR_PRINTS(error);
  522. return;
  523. }
  524. }
  525. }
  526. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  527. ERR_EXPLAIN("Trying to RSET while no network peer is active.");
  528. ERR_FAIL_COND(!network_peer.is_valid());
  529. ERR_EXPLAIN("Trying to RSET on a node which is not inside SceneTree.");
  530. ERR_FAIL_COND(!p_node->is_inside_tree());
  531. ERR_EXPLAIN("Trying to send an RSET via a network peer which is not connected.");
  532. ERR_FAIL_COND(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED);
  533. int node_id = network_peer->get_unique_id();
  534. bool is_master = p_node->is_network_master();
  535. bool skip_rset = false;
  536. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  537. // Check that send mode can use local call.
  538. bool set_local = false;
  539. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_property);
  540. if (E) {
  541. set_local = _should_call_local(E->get(), is_master, skip_rset);
  542. }
  543. if (set_local) {
  544. bool valid;
  545. p_node->set(p_property, p_value, &valid);
  546. if (!valid) {
  547. String error = "rset() aborted in local set, property not found: - " + String(p_property);
  548. ERR_PRINTS(error);
  549. return;
  550. }
  551. } else if (p_node->get_script_instance()) {
  552. // Attempt with script.
  553. RPCMode rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  554. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  555. if (set_local) {
  556. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  557. if (!valid) {
  558. String error = "rset() aborted in local script set, property not found: - " + String(p_property);
  559. ERR_PRINTS(error);
  560. return;
  561. }
  562. }
  563. }
  564. }
  565. if (skip_rset)
  566. return;
  567. const Variant *vptr = &p_value;
  568. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  569. }
  570. Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  571. ERR_EXPLAIN("Trying to send an empty raw packet.");
  572. ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_DATA);
  573. ERR_EXPLAIN("Trying to send a raw packet while no network peer is active.");
  574. ERR_FAIL_COND_V(!network_peer.is_valid(), ERR_UNCONFIGURED);
  575. ERR_EXPLAIN("Trying to send a raw packet via a network peer which is not connected.");
  576. ERR_FAIL_COND_V(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  577. MAKE_ROOM(p_data.size() + 1);
  578. PoolVector<uint8_t>::Read r = p_data.read();
  579. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  580. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  581. network_peer->set_target_peer(p_to);
  582. network_peer->set_transfer_mode(p_mode);
  583. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  584. }
  585. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  586. ERR_EXPLAIN("Invalid packet received. Size too small.");
  587. ERR_FAIL_COND(p_packet_len < 2);
  588. PoolVector<uint8_t> out;
  589. int len = p_packet_len - 1;
  590. out.resize(len);
  591. {
  592. PoolVector<uint8_t>::Write w = out.write();
  593. memcpy(&w[0], &p_packet[1], len);
  594. }
  595. emit_signal("network_peer_packet", p_from, out);
  596. }
  597. int MultiplayerAPI::get_network_unique_id() const {
  598. ERR_EXPLAIN("No network peer is assigned. Unable to get unique network ID.");
  599. ERR_FAIL_COND_V(!network_peer.is_valid(), 0);
  600. return network_peer->get_unique_id();
  601. }
  602. bool MultiplayerAPI::is_network_server() const {
  603. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  604. ERR_EXPLAIN("No network peer is assigned. I can't be a server.");
  605. ERR_FAIL_COND_V(!network_peer.is_valid(), false);
  606. return network_peer->is_server();
  607. }
  608. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  609. ERR_EXPLAIN("No network peer is assigned. Unable to set 'refuse_new_connections'.");
  610. ERR_FAIL_COND(!network_peer.is_valid());
  611. network_peer->set_refuse_new_connections(p_refuse);
  612. }
  613. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  614. ERR_EXPLAIN("No network peer is assigned. Unable to get 'refuse_new_connections'.");
  615. ERR_FAIL_COND_V(!network_peer.is_valid(), false);
  616. return network_peer->is_refusing_new_connections();
  617. }
  618. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  619. ERR_EXPLAIN("No network peer is assigned. Assume no peers are connected.");
  620. ERR_FAIL_COND_V(!network_peer.is_valid(), Vector<int>());
  621. Vector<int> ret;
  622. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  623. ret.push_back(E->get());
  624. }
  625. return ret;
  626. }
  627. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  628. allow_object_decoding = p_enable;
  629. }
  630. bool MultiplayerAPI::is_object_decoding_allowed() const {
  631. return allow_object_decoding;
  632. }
  633. void MultiplayerAPI::_bind_methods() {
  634. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  635. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  636. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  637. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  638. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  639. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  640. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  641. ClassDB::bind_method(D_METHOD("_add_peer", "id"), &MultiplayerAPI::_add_peer);
  642. ClassDB::bind_method(D_METHOD("_del_peer", "id"), &MultiplayerAPI::_del_peer);
  643. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  644. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  645. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  646. ClassDB::bind_method(D_METHOD("_connected_to_server"), &MultiplayerAPI::_connected_to_server);
  647. ClassDB::bind_method(D_METHOD("_connection_failed"), &MultiplayerAPI::_connection_failed);
  648. ClassDB::bind_method(D_METHOD("_server_disconnected"), &MultiplayerAPI::_server_disconnected);
  649. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  650. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  651. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  652. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  653. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  654. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  655. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  656. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  657. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  658. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  659. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "packet")));
  660. ADD_SIGNAL(MethodInfo("connected_to_server"));
  661. ADD_SIGNAL(MethodInfo("connection_failed"));
  662. ADD_SIGNAL(MethodInfo("server_disconnected"));
  663. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  664. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  665. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  666. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  667. BIND_ENUM_CONSTANT(RPC_MODE_SLAVE); // Deprecated.
  668. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  669. BIND_ENUM_CONSTANT(RPC_MODE_SYNC); // Deprecated.
  670. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  671. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  672. }
  673. MultiplayerAPI::MultiplayerAPI() :
  674. allow_object_decoding(false) {
  675. rpc_sender_id = 0;
  676. root_node = NULL;
  677. clear();
  678. }
  679. MultiplayerAPI::~MultiplayerAPI() {
  680. clear();
  681. }