multiplayer_api.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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. bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
  222. ERR_EXPLAIN("RPC '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rpc_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  223. ERR_FAIL_COND(!can_call);
  224. int argc = p_packet[p_offset];
  225. Vector<Variant> args;
  226. Vector<const Variant *> argp;
  227. args.resize(argc);
  228. argp.resize(argc);
  229. p_offset++;
  230. for (int i = 0; i < argc; i++) {
  231. ERR_EXPLAIN("Invalid packet received. Size too small.");
  232. ERR_FAIL_COND(p_offset >= p_packet_len);
  233. int vlen;
  234. 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());
  235. ERR_EXPLAIN("Invalid packet received. Unable to decode RPC argument.");
  236. ERR_FAIL_COND(err != OK);
  237. argp.write[i] = &args[i];
  238. p_offset += vlen;
  239. }
  240. Variant::CallError ce;
  241. p_node->call(p_name, (const Variant **)argp.ptr(), argc, ce);
  242. if (ce.error != Variant::CallError::CALL_OK) {
  243. String error = Variant::get_call_error_text(p_node, p_name, (const Variant **)argp.ptr(), argc, ce);
  244. error = "RPC - " + error;
  245. ERR_PRINTS(error);
  246. }
  247. }
  248. 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) {
  249. ERR_EXPLAIN("Invalid packet received. Size too small.");
  250. ERR_FAIL_COND(p_offset >= p_packet_len);
  251. // Check that remote can call the RSET on this node.
  252. RPCMode rset_mode = RPC_MODE_DISABLED;
  253. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_name);
  254. if (E) {
  255. rset_mode = E->get();
  256. } else if (p_node->get_script_instance()) {
  257. rset_mode = p_node->get_script_instance()->get_rset_mode(p_name);
  258. }
  259. bool can_call = _can_call_mode(p_node, rset_mode, p_from);
  260. ERR_EXPLAIN("RSET '" + String(p_name) + "' is not allowed on node " + p_node->get_path() + " from: " + itos(p_from) + ". Mode is " + itos((int)rset_mode) + ", master is " + itos(p_node->get_network_master()) + ".");
  261. ERR_FAIL_COND(!can_call);
  262. Variant value;
  263. Error err = decode_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL, allow_object_decoding || network_peer->is_object_decoding_allowed());
  264. ERR_EXPLAIN("Invalid packet received. Unable to decode RSET value.");
  265. ERR_FAIL_COND(err != OK);
  266. bool valid;
  267. p_node->set(p_name, value, &valid);
  268. if (!valid) {
  269. String error = "Error setting remote property '" + String(p_name) + "', not found in object of type " + p_node->get_class();
  270. ERR_PRINTS(error);
  271. }
  272. }
  273. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  274. ERR_EXPLAIN("Invalid packet received. Size too small.");
  275. ERR_FAIL_COND(p_packet_len < 5);
  276. int id = decode_uint32(&p_packet[1]);
  277. String paths;
  278. paths.parse_utf8((const char *)&p_packet[5], p_packet_len - 5);
  279. NodePath path = paths;
  280. if (!path_get_cache.has(p_from)) {
  281. path_get_cache[p_from] = PathGetCache();
  282. }
  283. PathGetCache::NodeInfo ni;
  284. ni.path = path;
  285. ni.instance = 0;
  286. path_get_cache[p_from].nodes[id] = ni;
  287. // Encode path to send ack.
  288. CharString pname = String(path).utf8();
  289. int len = encode_cstring(pname.get_data(), NULL);
  290. Vector<uint8_t> packet;
  291. packet.resize(1 + len);
  292. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  293. encode_cstring(pname.get_data(), &packet.write[1]);
  294. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  295. network_peer->set_target_peer(p_from);
  296. network_peer->put_packet(packet.ptr(), packet.size());
  297. }
  298. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  299. ERR_EXPLAIN("Invalid packet received. Size too small.");
  300. ERR_FAIL_COND(p_packet_len < 2);
  301. String paths;
  302. paths.parse_utf8((const char *)&p_packet[1], p_packet_len - 1);
  303. NodePath path = paths;
  304. PathSentCache *psc = path_send_cache.getptr(path);
  305. ERR_EXPLAIN("Invalid packet received. Tries to confirm a path which was not found in cache.");
  306. ERR_FAIL_COND(!psc);
  307. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  308. ERR_EXPLAIN("Invalid packet received. Source peer was not found in cache for the given path.");
  309. ERR_FAIL_COND(!E);
  310. E->get() = true;
  311. }
  312. bool MultiplayerAPI::_send_confirm_path(NodePath p_path, PathSentCache *psc, int p_target) {
  313. bool has_all_peers = true;
  314. List<int> peers_to_add; // If one is missing, take note to add it.
  315. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  316. if (p_target < 0 && E->get() == -p_target)
  317. continue; // Continue, excluded.
  318. if (p_target > 0 && E->get() != p_target)
  319. continue; // Continue, not for this peer.
  320. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  321. if (!F || !F->get()) {
  322. // Path was not cached, or was cached but is unconfirmed.
  323. if (!F) {
  324. // Not cached at all, take note.
  325. peers_to_add.push_back(E->get());
  326. }
  327. has_all_peers = false;
  328. }
  329. }
  330. // Those that need to be added, send a message for this.
  331. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  332. // Encode function name.
  333. CharString pname = String(p_path).utf8();
  334. int len = encode_cstring(pname.get_data(), NULL);
  335. Vector<uint8_t> packet;
  336. packet.resize(1 + 4 + len);
  337. packet.write[0] = NETWORK_COMMAND_SIMPLIFY_PATH;
  338. encode_uint32(psc->id, &packet.write[1]);
  339. encode_cstring(pname.get_data(), &packet.write[5]);
  340. network_peer->set_target_peer(E->get()); // To all of you.
  341. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  342. network_peer->put_packet(packet.ptr(), packet.size());
  343. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  344. }
  345. return has_all_peers;
  346. }
  347. 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) {
  348. if (network_peer.is_null()) {
  349. ERR_EXPLAIN("Attempt to remote call/set when networking is not active in SceneTree.");
  350. ERR_FAIL();
  351. }
  352. if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_CONNECTING) {
  353. ERR_EXPLAIN("Attempt to remote call/set when networking is not connected yet in SceneTree.");
  354. ERR_FAIL();
  355. }
  356. if (network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED) {
  357. ERR_EXPLAIN("Attempt to remote call/set when networking is disconnected.");
  358. ERR_FAIL();
  359. }
  360. if (p_argcount > 255) {
  361. ERR_EXPLAIN("Too many arguments >255.");
  362. ERR_FAIL();
  363. }
  364. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  365. if (p_to == network_peer->get_unique_id()) {
  366. ERR_EXPLAIN("Attempt to remote call/set yourself! unique ID: " + itos(network_peer->get_unique_id()));
  367. } else {
  368. ERR_EXPLAIN("Attempt to remote call unexisting ID: " + itos(p_to));
  369. }
  370. ERR_FAIL();
  371. }
  372. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  373. ERR_EXPLAIN("Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  374. ERR_FAIL_COND(from_path.is_empty());
  375. // See if the path is cached.
  376. PathSentCache *psc = path_send_cache.getptr(from_path);
  377. if (!psc) {
  378. // Path is not cached, create.
  379. path_send_cache[from_path] = PathSentCache();
  380. psc = path_send_cache.getptr(from_path);
  381. psc->id = last_send_cache_id++;
  382. }
  383. // Create base packet, lots of hardcode because it must be tight.
  384. int ofs = 0;
  385. #define MAKE_ROOM(m_amount) \
  386. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  387. // Encode type.
  388. MAKE_ROOM(1);
  389. packet_cache.write[0] = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  390. ofs += 1;
  391. // Encode ID.
  392. MAKE_ROOM(ofs + 4);
  393. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  394. ofs += 4;
  395. // Encode function name.
  396. CharString name = String(p_name).utf8();
  397. int len = encode_cstring(name.get_data(), NULL);
  398. MAKE_ROOM(ofs + len);
  399. encode_cstring(name.get_data(), &(packet_cache.write[ofs]));
  400. ofs += len;
  401. if (p_set) {
  402. // Set argument.
  403. Error err = encode_variant(*p_arg[0], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  404. ERR_EXPLAIN("Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  405. ERR_FAIL_COND(err != OK);
  406. MAKE_ROOM(ofs + len);
  407. encode_variant(*p_arg[0], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  408. ofs += len;
  409. } else {
  410. // Call arguments.
  411. MAKE_ROOM(ofs + 1);
  412. packet_cache.write[ofs] = p_argcount;
  413. ofs += 1;
  414. for (int i = 0; i < p_argcount; i++) {
  415. Error err = encode_variant(*p_arg[i], NULL, len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  416. ERR_EXPLAIN("Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  417. ERR_FAIL_COND(err != OK);
  418. MAKE_ROOM(ofs + len);
  419. encode_variant(*p_arg[i], &(packet_cache.write[ofs]), len, allow_object_decoding || network_peer->is_object_decoding_allowed());
  420. ofs += len;
  421. }
  422. }
  423. // See if all peers have cached path (is so, call can be fast).
  424. bool has_all_peers = _send_confirm_path(from_path, psc, p_to);
  425. // Take chance and set transfer mode, since all send methods will use it.
  426. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  427. if (has_all_peers) {
  428. // They all have verified paths, so send fast.
  429. network_peer->set_target_peer(p_to); // To all of you.
  430. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  431. } else {
  432. // Not all verified path, so send one by one.
  433. // Append path at the end, since we will need it for some packets.
  434. CharString pname = String(from_path).utf8();
  435. int path_len = encode_cstring(pname.get_data(), NULL);
  436. MAKE_ROOM(ofs + path_len);
  437. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  438. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  439. if (p_to < 0 && E->get() == -p_to)
  440. continue; // Continue, excluded.
  441. if (p_to > 0 && E->get() != p_to)
  442. continue; // Continue, not for this peer.
  443. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  444. ERR_CONTINUE(!F); // Should never happen.
  445. network_peer->set_target_peer(E->get()); // To this one specifically.
  446. if (F->get()) {
  447. // This one confirmed path, so use id.
  448. encode_uint32(psc->id, &(packet_cache.write[1]));
  449. network_peer->put_packet(packet_cache.ptr(), ofs);
  450. } else {
  451. // This one did not confirm path yet, so use entire path (sorry!).
  452. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  453. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  454. }
  455. }
  456. }
  457. }
  458. void MultiplayerAPI::_add_peer(int p_id) {
  459. connected_peers.insert(p_id);
  460. path_get_cache.insert(p_id, PathGetCache());
  461. emit_signal("network_peer_connected", p_id);
  462. }
  463. void MultiplayerAPI::_del_peer(int p_id) {
  464. connected_peers.erase(p_id);
  465. path_get_cache.erase(p_id); // I no longer need your cache, sorry.
  466. emit_signal("network_peer_disconnected", p_id);
  467. }
  468. void MultiplayerAPI::_connected_to_server() {
  469. emit_signal("connected_to_server");
  470. }
  471. void MultiplayerAPI::_connection_failed() {
  472. emit_signal("connection_failed");
  473. }
  474. void MultiplayerAPI::_server_disconnected() {
  475. emit_signal("server_disconnected");
  476. }
  477. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  478. ERR_EXPLAIN("Trying to call an RPC while no network peer is active.");
  479. ERR_FAIL_COND(!network_peer.is_valid());
  480. ERR_EXPLAIN("Trying to call an RPC on a node which is not inside SceneTree.");
  481. ERR_FAIL_COND(!p_node->is_inside_tree());
  482. ERR_EXPLAIN("Trying to call an RPC via a network peer which is not connected.");
  483. ERR_FAIL_COND(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED);
  484. int node_id = network_peer->get_unique_id();
  485. bool skip_rpc = node_id == p_peer_id;
  486. bool call_local_native = false;
  487. bool call_local_script = false;
  488. bool is_master = p_node->is_network_master();
  489. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  490. // Check that send mode can use local call.
  491. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rpc_mode(p_method);
  492. if (E) {
  493. call_local_native = _should_call_local(E->get(), is_master, skip_rpc);
  494. }
  495. if (call_local_native) {
  496. // Done below.
  497. } else if (p_node->get_script_instance()) {
  498. // Attempt with script.
  499. RPCMode rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  500. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  501. }
  502. }
  503. if (!skip_rpc) {
  504. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  505. }
  506. if (call_local_native) {
  507. int temp_id = rpc_sender_id;
  508. rpc_sender_id = get_network_unique_id();
  509. Variant::CallError ce;
  510. p_node->call(p_method, p_arg, p_argcount, ce);
  511. rpc_sender_id = temp_id;
  512. if (ce.error != Variant::CallError::CALL_OK) {
  513. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  514. error = "rpc() aborted in local call: - " + error;
  515. ERR_PRINTS(error);
  516. return;
  517. }
  518. }
  519. if (call_local_script) {
  520. int temp_id = rpc_sender_id;
  521. rpc_sender_id = get_network_unique_id();
  522. Variant::CallError ce;
  523. ce.error = Variant::CallError::CALL_OK;
  524. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  525. rpc_sender_id = temp_id;
  526. if (ce.error != Variant::CallError::CALL_OK) {
  527. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  528. error = "rpc() aborted in script local call: - " + error;
  529. ERR_PRINTS(error);
  530. return;
  531. }
  532. }
  533. ERR_EXPLAIN("RPC '" + p_method + "' on yourself is not allowed by selected mode");
  534. ERR_FAIL_COND(skip_rpc && !(call_local_native || call_local_script));
  535. }
  536. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  537. ERR_EXPLAIN("Trying to RSET while no network peer is active.");
  538. ERR_FAIL_COND(!network_peer.is_valid());
  539. ERR_EXPLAIN("Trying to RSET on a node which is not inside SceneTree.");
  540. ERR_FAIL_COND(!p_node->is_inside_tree());
  541. ERR_EXPLAIN("Trying to send an RSET via a network peer which is not connected.");
  542. ERR_FAIL_COND(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED);
  543. int node_id = network_peer->get_unique_id();
  544. bool is_master = p_node->is_network_master();
  545. bool skip_rset = node_id == p_peer_id;
  546. bool set_local = false;
  547. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  548. // Check that send mode can use local call.
  549. const Map<StringName, RPCMode>::Element *E = p_node->get_node_rset_mode(p_property);
  550. if (E) {
  551. set_local = _should_call_local(E->get(), is_master, skip_rset);
  552. }
  553. if (set_local) {
  554. bool valid;
  555. int temp_id = rpc_sender_id;
  556. rpc_sender_id = get_network_unique_id();
  557. p_node->set(p_property, p_value, &valid);
  558. rpc_sender_id = temp_id;
  559. if (!valid) {
  560. String error = "rset() aborted in local set, property not found: - " + String(p_property);
  561. ERR_PRINTS(error);
  562. return;
  563. }
  564. } else if (p_node->get_script_instance()) {
  565. // Attempt with script.
  566. RPCMode rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  567. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  568. if (set_local) {
  569. int temp_id = rpc_sender_id;
  570. rpc_sender_id = get_network_unique_id();
  571. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  572. rpc_sender_id = temp_id;
  573. if (!valid) {
  574. String error = "rset() aborted in local script set, property not found: - " + String(p_property);
  575. ERR_PRINTS(error);
  576. return;
  577. }
  578. }
  579. }
  580. }
  581. if (skip_rset) {
  582. ERR_EXPLAIN("RSET for '" + p_property + "' on yourself is not allowed by selected mode");
  583. ERR_FAIL_COND(!set_local);
  584. return;
  585. }
  586. const Variant *vptr = &p_value;
  587. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  588. }
  589. Error MultiplayerAPI::send_bytes(PoolVector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  590. ERR_EXPLAIN("Trying to send an empty raw packet.");
  591. ERR_FAIL_COND_V(p_data.size() < 1, ERR_INVALID_DATA);
  592. ERR_EXPLAIN("Trying to send a raw packet while no network peer is active.");
  593. ERR_FAIL_COND_V(!network_peer.is_valid(), ERR_UNCONFIGURED);
  594. ERR_EXPLAIN("Trying to send a raw packet via a network peer which is not connected.");
  595. ERR_FAIL_COND_V(network_peer->get_connection_status() != NetworkedMultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
  596. MAKE_ROOM(p_data.size() + 1);
  597. PoolVector<uint8_t>::Read r = p_data.read();
  598. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  599. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  600. network_peer->set_target_peer(p_to);
  601. network_peer->set_transfer_mode(p_mode);
  602. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  603. }
  604. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  605. ERR_EXPLAIN("Invalid packet received. Size too small.");
  606. ERR_FAIL_COND(p_packet_len < 2);
  607. PoolVector<uint8_t> out;
  608. int len = p_packet_len - 1;
  609. out.resize(len);
  610. {
  611. PoolVector<uint8_t>::Write w = out.write();
  612. memcpy(&w[0], &p_packet[1], len);
  613. }
  614. emit_signal("network_peer_packet", p_from, out);
  615. }
  616. int MultiplayerAPI::get_network_unique_id() const {
  617. ERR_EXPLAIN("No network peer is assigned. Unable to get unique network ID.");
  618. ERR_FAIL_COND_V(!network_peer.is_valid(), 0);
  619. return network_peer->get_unique_id();
  620. }
  621. bool MultiplayerAPI::is_network_server() const {
  622. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  623. ERR_EXPLAIN("No network peer is assigned. I can't be a server.");
  624. ERR_FAIL_COND_V(!network_peer.is_valid(), false);
  625. return network_peer->is_server();
  626. }
  627. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  628. ERR_EXPLAIN("No network peer is assigned. Unable to set 'refuse_new_connections'.");
  629. ERR_FAIL_COND(!network_peer.is_valid());
  630. network_peer->set_refuse_new_connections(p_refuse);
  631. }
  632. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  633. ERR_EXPLAIN("No network peer is assigned. Unable to get 'refuse_new_connections'.");
  634. ERR_FAIL_COND_V(!network_peer.is_valid(), false);
  635. return network_peer->is_refusing_new_connections();
  636. }
  637. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  638. ERR_EXPLAIN("No network peer is assigned. Assume no peers are connected.");
  639. ERR_FAIL_COND_V(!network_peer.is_valid(), Vector<int>());
  640. Vector<int> ret;
  641. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  642. ret.push_back(E->get());
  643. }
  644. return ret;
  645. }
  646. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  647. allow_object_decoding = p_enable;
  648. }
  649. bool MultiplayerAPI::is_object_decoding_allowed() const {
  650. return allow_object_decoding;
  651. }
  652. void MultiplayerAPI::_bind_methods() {
  653. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  654. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  655. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  656. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  657. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  658. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  659. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  660. ClassDB::bind_method(D_METHOD("_add_peer", "id"), &MultiplayerAPI::_add_peer);
  661. ClassDB::bind_method(D_METHOD("_del_peer", "id"), &MultiplayerAPI::_del_peer);
  662. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  663. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  664. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  665. ClassDB::bind_method(D_METHOD("_connected_to_server"), &MultiplayerAPI::_connected_to_server);
  666. ClassDB::bind_method(D_METHOD("_connection_failed"), &MultiplayerAPI::_connection_failed);
  667. ClassDB::bind_method(D_METHOD("_server_disconnected"), &MultiplayerAPI::_server_disconnected);
  668. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  669. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  670. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  671. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  672. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  673. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  674. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  675. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  676. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  677. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  678. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::POOL_BYTE_ARRAY, "packet")));
  679. ADD_SIGNAL(MethodInfo("connected_to_server"));
  680. ADD_SIGNAL(MethodInfo("connection_failed"));
  681. ADD_SIGNAL(MethodInfo("server_disconnected"));
  682. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  683. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  684. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  685. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  686. BIND_ENUM_CONSTANT(RPC_MODE_SLAVE); // Deprecated.
  687. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  688. BIND_ENUM_CONSTANT(RPC_MODE_SYNC); // Deprecated.
  689. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  690. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  691. }
  692. MultiplayerAPI::MultiplayerAPI() :
  693. allow_object_decoding(false) {
  694. rpc_sender_id = 0;
  695. root_node = NULL;
  696. clear();
  697. }
  698. MultiplayerAPI::~MultiplayerAPI() {
  699. clear();
  700. }