multiplayer_api.cpp 30 KB

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