multiplayer_api.cpp 26 KB

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