multiplayer_api.cpp 35 KB

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