multiplayer_api.cpp 30 KB

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