multiplayer_api.cpp 36 KB

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