2
0

multiplayer_api.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. /*************************************************************************/
  2. /* multiplayer_api.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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. #include <stdint.h>
  34. #ifdef DEBUG_ENABLED
  35. #include "core/os/os.h"
  36. #endif
  37. _FORCE_INLINE_ bool _should_call_local(MultiplayerAPI::RPCMode mode, bool is_master, bool &r_skip_rpc) {
  38. switch (mode) {
  39. case MultiplayerAPI::RPC_MODE_DISABLED: {
  40. // Do nothing.
  41. } break;
  42. case MultiplayerAPI::RPC_MODE_REMOTE: {
  43. // Do nothing also. Remote cannot produce a local call.
  44. } break;
  45. case MultiplayerAPI::RPC_MODE_MASTERSYNC: {
  46. if (is_master)
  47. r_skip_rpc = true; // I am the master, so skip remote call.
  48. [[fallthrough]];
  49. }
  50. case MultiplayerAPI::RPC_MODE_REMOTESYNC:
  51. case MultiplayerAPI::RPC_MODE_PUPPETSYNC: {
  52. // Call it, sync always results in a local call.
  53. return true;
  54. } break;
  55. case MultiplayerAPI::RPC_MODE_MASTER: {
  56. if (is_master)
  57. r_skip_rpc = true; // I am the master, so skip remote call.
  58. return is_master;
  59. } break;
  60. case MultiplayerAPI::RPC_MODE_PUPPET: {
  61. return !is_master;
  62. } break;
  63. }
  64. return false;
  65. }
  66. _FORCE_INLINE_ bool _can_call_mode(Node *p_node, MultiplayerAPI::RPCMode mode, int p_remote_id) {
  67. switch (mode) {
  68. case MultiplayerAPI::RPC_MODE_DISABLED: {
  69. return false;
  70. } break;
  71. case MultiplayerAPI::RPC_MODE_REMOTE:
  72. case MultiplayerAPI::RPC_MODE_REMOTESYNC: {
  73. return true;
  74. } break;
  75. case MultiplayerAPI::RPC_MODE_MASTERSYNC:
  76. case MultiplayerAPI::RPC_MODE_MASTER: {
  77. return p_node->is_network_master();
  78. } break;
  79. case MultiplayerAPI::RPC_MODE_PUPPETSYNC:
  80. case MultiplayerAPI::RPC_MODE_PUPPET: {
  81. return !p_node->is_network_master() && p_remote_id == p_node->get_network_master();
  82. } break;
  83. }
  84. return false;
  85. }
  86. void MultiplayerAPI::poll() {
  87. if (!network_peer.is_valid() || network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED)
  88. return;
  89. network_peer->poll();
  90. if (!network_peer.is_valid()) // It's possible that polling might have resulted in a disconnection, so check here.
  91. return;
  92. while (network_peer->get_available_packet_count()) {
  93. int sender = network_peer->get_packet_peer();
  94. const uint8_t *packet;
  95. int len;
  96. Error err = network_peer->get_packet(&packet, len);
  97. if (err != OK) {
  98. ERR_PRINT("Error getting packet!");
  99. break; // Something is wrong!
  100. }
  101. rpc_sender_id = sender;
  102. _process_packet(sender, packet, len);
  103. rpc_sender_id = 0;
  104. if (!network_peer.is_valid()) {
  105. break; // It's also possible that a packet or RPC caused a disconnection, so also check here.
  106. }
  107. }
  108. }
  109. void MultiplayerAPI::clear() {
  110. connected_peers.clear();
  111. path_get_cache.clear();
  112. path_send_cache.clear();
  113. packet_cache.clear();
  114. last_send_cache_id = 1;
  115. }
  116. void MultiplayerAPI::set_root_node(Node *p_node) {
  117. root_node = p_node;
  118. }
  119. void MultiplayerAPI::set_network_peer(const Ref<NetworkedMultiplayerPeer> &p_peer) {
  120. if (p_peer == network_peer) return; // Nothing to do
  121. ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED,
  122. "Supplied NetworkedMultiplayerPeer must be connecting or connected.");
  123. if (network_peer.is_valid()) {
  124. network_peer->disconnect_compat("peer_connected", this, "_add_peer");
  125. network_peer->disconnect_compat("peer_disconnected", this, "_del_peer");
  126. network_peer->disconnect_compat("connection_succeeded", this, "_connected_to_server");
  127. network_peer->disconnect_compat("connection_failed", this, "_connection_failed");
  128. network_peer->disconnect_compat("server_disconnected", this, "_server_disconnected");
  129. clear();
  130. }
  131. network_peer = p_peer;
  132. if (network_peer.is_valid()) {
  133. network_peer->connect_compat("peer_connected", this, "_add_peer");
  134. network_peer->connect_compat("peer_disconnected", this, "_del_peer");
  135. network_peer->connect_compat("connection_succeeded", this, "_connected_to_server");
  136. network_peer->connect_compat("connection_failed", this, "_connection_failed");
  137. network_peer->connect_compat("server_disconnected", this, "_server_disconnected");
  138. }
  139. }
  140. Ref<NetworkedMultiplayerPeer> MultiplayerAPI::get_network_peer() const {
  141. return network_peer;
  142. }
  143. void MultiplayerAPI::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
  144. 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.");
  145. ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
  146. #ifdef DEBUG_ENABLED
  147. if (profiling) {
  148. bandwidth_incoming_data.write[bandwidth_incoming_pointer].timestamp = OS::get_singleton()->get_ticks_msec();
  149. bandwidth_incoming_data.write[bandwidth_incoming_pointer].packet_size = p_packet_len;
  150. bandwidth_incoming_pointer = (bandwidth_incoming_pointer + 1) % bandwidth_incoming_data.size();
  151. }
  152. #endif
  153. // Extract the `packet_type` from the LSB three bits:
  154. uint8_t packet_type = p_packet[0] & 7;
  155. switch (packet_type) {
  156. case NETWORK_COMMAND_SIMPLIFY_PATH: {
  157. _process_simplify_path(p_from, p_packet, p_packet_len);
  158. } break;
  159. case NETWORK_COMMAND_CONFIRM_PATH: {
  160. _process_confirm_path(p_from, p_packet, p_packet_len);
  161. } break;
  162. case NETWORK_COMMAND_REMOTE_CALL:
  163. case NETWORK_COMMAND_REMOTE_SET: {
  164. // Extract packet meta
  165. int packet_min_size = 1;
  166. int name_id_offset = 1;
  167. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  168. // Compute the meta size, which depends on the compression level.
  169. int node_id_compression = (p_packet[0] & 24) >> 3;
  170. int name_id_compression = (p_packet[0] & 32) >> 5;
  171. switch (node_id_compression) {
  172. case NETWORK_NODE_ID_COMPRESSION_8:
  173. packet_min_size += 1;
  174. name_id_offset += 1;
  175. break;
  176. case NETWORK_NODE_ID_COMPRESSION_16:
  177. packet_min_size += 2;
  178. name_id_offset += 2;
  179. break;
  180. case NETWORK_NODE_ID_COMPRESSION_32:
  181. packet_min_size += 4;
  182. name_id_offset += 4;
  183. break;
  184. default:
  185. ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");
  186. }
  187. switch (name_id_compression) {
  188. case NETWORK_NAME_ID_COMPRESSION_8:
  189. packet_min_size += 1;
  190. break;
  191. case NETWORK_NAME_ID_COMPRESSION_16:
  192. packet_min_size += 2;
  193. break;
  194. default:
  195. ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");
  196. }
  197. ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
  198. uint32_t node_target = 0;
  199. switch (node_id_compression) {
  200. case NETWORK_NODE_ID_COMPRESSION_8:
  201. node_target = p_packet[1];
  202. break;
  203. case NETWORK_NODE_ID_COMPRESSION_16:
  204. node_target = decode_uint16(p_packet + 1);
  205. break;
  206. case NETWORK_NODE_ID_COMPRESSION_32:
  207. node_target = decode_uint32(p_packet + 1);
  208. break;
  209. default:
  210. // Unreachable, checked before.
  211. CRASH_NOW();
  212. }
  213. Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);
  214. ERR_FAIL_COND_MSG(node == NULL, "Invalid packet received. Requested node was not found.");
  215. uint16_t name_id = 0;
  216. switch (name_id_compression) {
  217. case NETWORK_NAME_ID_COMPRESSION_8:
  218. name_id = p_packet[name_id_offset];
  219. break;
  220. case NETWORK_NAME_ID_COMPRESSION_16:
  221. name_id = decode_uint16(p_packet + name_id_offset);
  222. break;
  223. default:
  224. // Unreachable, checked before.
  225. CRASH_NOW();
  226. }
  227. if (packet_type == NETWORK_COMMAND_REMOTE_CALL) {
  228. _process_rpc(node, name_id, p_from, p_packet, p_packet_len, packet_min_size);
  229. } else {
  230. _process_rset(node, name_id, p_from, p_packet, p_packet_len, packet_min_size);
  231. }
  232. } break;
  233. case NETWORK_COMMAND_RAW: {
  234. _process_raw(p_from, p_packet, p_packet_len);
  235. } break;
  236. }
  237. }
  238. Node *MultiplayerAPI::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {
  239. Node *node = NULL;
  240. if (p_node_target & 0x80000000) {
  241. // Use full path (not cached yet).
  242. int ofs = p_node_target & 0x7FFFFFFF;
  243. ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, NULL, "Invalid packet received. Size smaller than declared.");
  244. String paths;
  245. paths.parse_utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
  246. NodePath np = paths;
  247. node = root_node->get_node(np);
  248. if (!node)
  249. ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");
  250. } else {
  251. // Use cached path.
  252. int id = p_node_target;
  253. Map<int, PathGetCache>::Element *E = path_get_cache.find(p_from);
  254. ERR_FAIL_COND_V_MSG(!E, NULL, "Invalid packet received. Requests invalid peer cache.");
  255. Map<int, PathGetCache::NodeInfo>::Element *F = E->get().nodes.find(id);
  256. ERR_FAIL_COND_V_MSG(!F, NULL, "Invalid packet received. Unabled to find requested cached node.");
  257. PathGetCache::NodeInfo *ni = &F->get();
  258. // Do proper caching later.
  259. node = root_node->get_node(ni->path);
  260. if (!node)
  261. ERR_PRINT("Failed to get cached path from RPC: " + String(ni->path) + ".");
  262. }
  263. return node;
  264. }
  265. void MultiplayerAPI::_process_rpc(Node *p_node, const uint16_t p_rpc_method_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  266. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  267. // Check that remote can call the RPC on this node.
  268. StringName name = p_node->get_node_rpc_method(p_rpc_method_id);
  269. RPCMode rpc_mode = p_node->get_node_rpc_mode_by_id(p_rpc_method_id);
  270. if (name == StringName() && p_node->get_script_instance()) {
  271. name = p_node->get_script_instance()->get_rpc_method(p_rpc_method_id);
  272. rpc_mode = p_node->get_script_instance()->get_rpc_mode_by_id(p_rpc_method_id);
  273. }
  274. ERR_FAIL_COND(name == StringName());
  275. bool can_call = _can_call_mode(p_node, rpc_mode, p_from);
  276. ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(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()) + ".");
  277. int argc = p_packet[p_offset];
  278. Vector<Variant> args;
  279. Vector<const Variant *> argp;
  280. args.resize(argc);
  281. argp.resize(argc);
  282. p_offset++;
  283. #ifdef DEBUG_ENABLED
  284. if (profiling) {
  285. ObjectID id = p_node->get_instance_id();
  286. _init_node_profile(id);
  287. profiler_frame_data[id].incoming_rpc += 1;
  288. }
  289. #endif
  290. for (int i = 0; i < argc; i++) {
  291. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  292. int vlen;
  293. Error err = _decode_and_decompress_variant(args.write[i], &p_packet[p_offset], p_packet_len - p_offset, &vlen);
  294. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RPC argument.");
  295. argp.write[i] = &args[i];
  296. p_offset += vlen;
  297. }
  298. Callable::CallError ce;
  299. p_node->call(name, (const Variant **)argp.ptr(), argc, ce);
  300. if (ce.error != Callable::CallError::CALL_OK) {
  301. String error = Variant::get_call_error_text(p_node, name, (const Variant **)argp.ptr(), argc, ce);
  302. error = "RPC - " + error;
  303. ERR_PRINT(error);
  304. }
  305. }
  306. void MultiplayerAPI::_process_rset(Node *p_node, const uint16_t p_rpc_property_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
  307. ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
  308. // Check that remote can call the RSET on this node.
  309. StringName name = p_node->get_node_rset_property(p_rpc_property_id);
  310. RPCMode rset_mode = p_node->get_node_rset_mode_by_id(p_rpc_property_id);
  311. if (name == StringName() && p_node->get_script_instance()) {
  312. name = p_node->get_script_instance()->get_rset_property(p_rpc_property_id);
  313. rset_mode = p_node->get_script_instance()->get_rset_mode_by_id(p_rpc_property_id);
  314. }
  315. ERR_FAIL_COND(name == StringName());
  316. bool can_call = _can_call_mode(p_node, rset_mode, p_from);
  317. ERR_FAIL_COND_MSG(!can_call, "RSET '" + String(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()) + ".");
  318. #ifdef DEBUG_ENABLED
  319. if (profiling) {
  320. ObjectID id = p_node->get_instance_id();
  321. _init_node_profile(id);
  322. profiler_frame_data[id].incoming_rset += 1;
  323. }
  324. #endif
  325. Variant value;
  326. Error err = _decode_and_decompress_variant(value, &p_packet[p_offset], p_packet_len - p_offset, NULL);
  327. ERR_FAIL_COND_MSG(err != OK, "Invalid packet received. Unable to decode RSET value.");
  328. bool valid;
  329. p_node->set(name, value, &valid);
  330. if (!valid) {
  331. String error = "Error setting remote property '" + String(name) + "', not found in object of type " + p_node->get_class() + ".";
  332. ERR_PRINT(error);
  333. }
  334. }
  335. void MultiplayerAPI::_process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  336. ERR_FAIL_COND_MSG(p_packet_len < 38, "Invalid packet received. Size too small.");
  337. int ofs = 1;
  338. String methods_md5;
  339. methods_md5.parse_utf8((const char *)(p_packet + ofs), 32);
  340. ofs += 33;
  341. int id = decode_uint32(&p_packet[ofs]);
  342. ofs += 4;
  343. String paths;
  344. paths.parse_utf8((const char *)(p_packet + ofs), p_packet_len - ofs);
  345. NodePath path = paths;
  346. if (!path_get_cache.has(p_from)) {
  347. path_get_cache[p_from] = PathGetCache();
  348. }
  349. Node *node = root_node->get_node(path);
  350. ERR_FAIL_COND(node == NULL);
  351. const bool valid_rpc_checksum = node->get_rpc_md5() == methods_md5;
  352. if (valid_rpc_checksum == false) {
  353. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  354. }
  355. PathGetCache::NodeInfo ni;
  356. ni.path = path;
  357. path_get_cache[p_from].nodes[id] = ni;
  358. // Encode path to send ack.
  359. CharString pname = String(path).utf8();
  360. int len = encode_cstring(pname.get_data(), NULL);
  361. Vector<uint8_t> packet;
  362. packet.resize(1 + 1 + len);
  363. packet.write[0] = NETWORK_COMMAND_CONFIRM_PATH;
  364. packet.write[1] = valid_rpc_checksum;
  365. encode_cstring(pname.get_data(), &packet.write[2]);
  366. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  367. network_peer->set_target_peer(p_from);
  368. network_peer->put_packet(packet.ptr(), packet.size());
  369. }
  370. void MultiplayerAPI::_process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
  371. ERR_FAIL_COND_MSG(p_packet_len < 3, "Invalid packet received. Size too small.");
  372. const bool valid_rpc_checksum = p_packet[1];
  373. String paths;
  374. paths.parse_utf8((const char *)&p_packet[2], p_packet_len - 2);
  375. NodePath path = paths;
  376. if (valid_rpc_checksum == false) {
  377. ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + path);
  378. }
  379. PathSentCache *psc = path_send_cache.getptr(path);
  380. ERR_FAIL_COND_MSG(!psc, "Invalid packet received. Tries to confirm a path which was not found in cache.");
  381. Map<int, bool>::Element *E = psc->confirmed_peers.find(p_from);
  382. ERR_FAIL_COND_MSG(!E, "Invalid packet received. Source peer was not found in cache for the given path.");
  383. E->get() = true;
  384. }
  385. bool MultiplayerAPI::_send_confirm_path(Node *p_node, NodePath p_path, PathSentCache *psc, int p_target) {
  386. bool has_all_peers = true;
  387. List<int> peers_to_add; // If one is missing, take note to add it.
  388. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  389. if (p_target < 0 && E->get() == -p_target)
  390. continue; // Continue, excluded.
  391. if (p_target > 0 && E->get() != p_target)
  392. continue; // Continue, not for this peer.
  393. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  394. if (!F || !F->get()) {
  395. // Path was not cached, or was cached but is unconfirmed.
  396. if (!F) {
  397. // Not cached at all, take note.
  398. peers_to_add.push_back(E->get());
  399. }
  400. has_all_peers = false;
  401. }
  402. }
  403. if (peers_to_add.size() > 0) {
  404. // Those that need to be added, send a message for this.
  405. // Encode function name.
  406. const CharString path = String(p_path).utf8();
  407. const int path_len = encode_cstring(path.get_data(), NULL);
  408. // Extract MD5 from rpc methods list.
  409. const String methods_md5 = p_node->get_rpc_md5();
  410. const int methods_md5_len = 33; // 32 + 1 for the `0` that is added by the encoder.
  411. Vector<uint8_t> packet;
  412. packet.resize(1 + 4 + path_len + methods_md5_len);
  413. int ofs = 0;
  414. packet.write[ofs] = NETWORK_COMMAND_SIMPLIFY_PATH;
  415. ofs += 1;
  416. ofs += encode_cstring(methods_md5.utf8().get_data(), &packet.write[ofs]);
  417. ofs += encode_uint32(psc->id, &packet.write[ofs]);
  418. ofs += encode_cstring(path.get_data(), &packet.write[ofs]);
  419. for (List<int>::Element *E = peers_to_add.front(); E; E = E->next()) {
  420. network_peer->set_target_peer(E->get()); // To all of you.
  421. network_peer->set_transfer_mode(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  422. network_peer->put_packet(packet.ptr(), packet.size());
  423. psc->confirmed_peers.insert(E->get(), false); // Insert into confirmed, but as false since it was not confirmed.
  424. }
  425. }
  426. return has_all_peers;
  427. }
  428. // The variant is compressed and encoded; The first byte contains all the meta
  429. // information and the format is:
  430. // - The first LSB 5 bits are used for the variant type.
  431. // - The next two bits are used to store the encoding mode.
  432. // - The most significant is used to store the boolean value.
  433. #define VARIANT_META_TYPE_MASK 0x1F
  434. #define VARIANT_META_EMODE_MASK 0x60
  435. #define VARIANT_META_BOOL_MASK 0x80
  436. #define ENCODE_8 0 << 5
  437. #define ENCODE_16 1 << 5
  438. #define ENCODE_32 2 << 5
  439. #define ENCODE_64 3 << 5
  440. Error MultiplayerAPI::_encode_and_compress_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len) {
  441. // Unreachable because `VARIANT_MAX` == 27 and `ENCODE_VARIANT_MASK` == 31
  442. CRASH_COND(p_variant.get_type() > VARIANT_META_TYPE_MASK);
  443. uint8_t *buf = r_buffer;
  444. r_len = 0;
  445. uint8_t encode_mode = 0;
  446. switch (p_variant.get_type()) {
  447. case Variant::BOOL: {
  448. if (buf) {
  449. // We still have 1 free bit in the meta, so let's use it.
  450. buf[0] = (p_variant.operator bool()) ? (1 << 7) : 0;
  451. buf[0] |= encode_mode | p_variant.get_type();
  452. }
  453. r_len += 1;
  454. } break;
  455. case Variant::INT: {
  456. if (buf) {
  457. // Reserve the first byte for the meta.
  458. buf += 1;
  459. }
  460. r_len += 1;
  461. int64_t val = p_variant;
  462. if (val <= (int64_t)INT8_MAX && val >= (int64_t)INT8_MIN) {
  463. // Use 8 bit
  464. encode_mode = ENCODE_8;
  465. if (buf) {
  466. buf[0] = val;
  467. }
  468. r_len += 1;
  469. } else if (val <= (int64_t)INT16_MAX && val >= (int64_t)INT16_MIN) {
  470. // Use 16 bit
  471. encode_mode = ENCODE_16;
  472. if (buf) {
  473. encode_uint16(val, buf);
  474. }
  475. r_len += 2;
  476. } else if (val <= (int64_t)INT32_MAX && val >= (int64_t)INT32_MIN) {
  477. // Use 32 bit
  478. encode_mode = ENCODE_32;
  479. if (buf) {
  480. encode_uint32(val, buf);
  481. }
  482. r_len += 4;
  483. } else {
  484. // Use 64 bit
  485. encode_mode = ENCODE_64;
  486. if (buf) {
  487. encode_uint64(val, buf);
  488. }
  489. r_len += 8;
  490. }
  491. // Store the meta
  492. if (buf) {
  493. buf -= 1;
  494. buf[0] = encode_mode | p_variant.get_type();
  495. }
  496. } break;
  497. default:
  498. // Any other case is not yet compressed.
  499. Error err = encode_variant(p_variant, r_buffer, r_len, allow_object_decoding);
  500. if (err != OK)
  501. return err;
  502. if (r_buffer) {
  503. // The first byte is not used by the marshaling, so store the type
  504. // so we know how to decompress and decode this variant.
  505. r_buffer[0] = p_variant.get_type();
  506. }
  507. }
  508. return OK;
  509. }
  510. Error MultiplayerAPI::_decode_and_decompress_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len) {
  511. const uint8_t *buf = p_buffer;
  512. int len = p_len;
  513. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  514. uint8_t type = buf[0] & VARIANT_META_TYPE_MASK;
  515. uint8_t encode_mode = buf[0] & VARIANT_META_EMODE_MASK;
  516. ERR_FAIL_COND_V(type >= Variant::VARIANT_MAX, ERR_INVALID_DATA);
  517. switch (type) {
  518. case Variant::BOOL: {
  519. bool val = (buf[0] & VARIANT_META_BOOL_MASK) > 0;
  520. r_variant = val;
  521. if (r_len)
  522. *r_len = 1;
  523. } break;
  524. case Variant::INT: {
  525. buf += 1;
  526. len -= 1;
  527. if (r_len)
  528. *r_len = 1;
  529. if (encode_mode == ENCODE_8) {
  530. // 8 bits.
  531. ERR_FAIL_COND_V(len < 1, ERR_INVALID_DATA);
  532. int8_t val = buf[0];
  533. r_variant = val;
  534. if (r_len)
  535. (*r_len) += 1;
  536. } else if (encode_mode == ENCODE_16) {
  537. // 16 bits.
  538. ERR_FAIL_COND_V(len < 2, ERR_INVALID_DATA);
  539. int16_t val = decode_uint16(buf);
  540. r_variant = val;
  541. if (r_len)
  542. (*r_len) += 2;
  543. } else if (encode_mode == ENCODE_32) {
  544. // 32 bits.
  545. ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA);
  546. int32_t val = decode_uint32(buf);
  547. r_variant = val;
  548. if (r_len)
  549. (*r_len) += 4;
  550. } else {
  551. // 64 bits.
  552. ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA);
  553. int64_t val = decode_uint64(buf);
  554. r_variant = val;
  555. if (r_len)
  556. (*r_len) += 8;
  557. }
  558. } break;
  559. default:
  560. Error err = decode_variant(r_variant, p_buffer, p_len, r_len, allow_object_decoding);
  561. if (err != OK)
  562. return err;
  563. }
  564. return OK;
  565. }
  566. 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) {
  567. ERR_FAIL_COND_MSG(network_peer.is_null(), "Attempt to remote call/set when networking is not active in SceneTree.");
  568. 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.");
  569. ERR_FAIL_COND_MSG(network_peer->get_connection_status() == NetworkedMultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to remote call/set when networking is disconnected.");
  570. ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments >255.");
  571. if (p_to != 0 && !connected_peers.has(ABS(p_to))) {
  572. 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()) + ".");
  573. ERR_FAIL_MSG("Attempt to remote call unexisting ID: " + itos(p_to) + ".");
  574. }
  575. NodePath from_path = (root_node->get_path()).rel_path_to(p_from->get_path());
  576. ERR_FAIL_COND_MSG(from_path.is_empty(), "Unable to send RPC. Relative path is empty. THIS IS LIKELY A BUG IN THE ENGINE!");
  577. // See if the path is cached.
  578. PathSentCache *psc = path_send_cache.getptr(from_path);
  579. if (!psc) {
  580. // Path is not cached, create.
  581. path_send_cache[from_path] = PathSentCache();
  582. psc = path_send_cache.getptr(from_path);
  583. psc->id = last_send_cache_id++;
  584. }
  585. // See if all peers have cached path (if so, call can be fast).
  586. const bool has_all_peers = _send_confirm_path(p_from, from_path, psc, p_to);
  587. // Create base packet, lots of hardcode because it must be tight.
  588. int ofs = 0;
  589. #define MAKE_ROOM(m_amount) \
  590. if (packet_cache.size() < m_amount) packet_cache.resize(m_amount);
  591. // Encode meta.
  592. // The meta is composed by a single byte that contains (starting from the least segnificant bit):
  593. // - `NetworkCommands` in the first three bits.
  594. // - `NetworkNodeIdCompression` in the next 2 bits.
  595. // - `NetworkNameIdCompression` in the next 1 bit.
  596. // - So we still have the last two bits free!
  597. uint8_t command_type = p_set ? NETWORK_COMMAND_REMOTE_SET : NETWORK_COMMAND_REMOTE_CALL;
  598. uint8_t node_id_compression = UINT8_MAX;
  599. uint8_t name_id_compression = UINT8_MAX;
  600. MAKE_ROOM(1);
  601. // The meta is composed along the way, so just set 0 for now.
  602. packet_cache.write[0] = 0;
  603. ofs += 1;
  604. // Encode Node ID.
  605. if (has_all_peers) {
  606. // Compress the node ID only if all the target peers already know it.
  607. if (psc->id >= 0 && psc->id <= 255) {
  608. // We can encode the id in 1 byte
  609. node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;
  610. MAKE_ROOM(ofs + 1);
  611. packet_cache.write[ofs] = static_cast<uint8_t>(psc->id);
  612. ofs += 1;
  613. } else if (psc->id >= 0 && psc->id <= 65535) {
  614. // We can encode the id in 2 bytes
  615. node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;
  616. MAKE_ROOM(ofs + 2);
  617. encode_uint16(static_cast<uint16_t>(psc->id), &(packet_cache.write[ofs]));
  618. ofs += 2;
  619. } else {
  620. // Too big, let's use 4 bytes.
  621. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  622. MAKE_ROOM(ofs + 4);
  623. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  624. ofs += 4;
  625. }
  626. } else {
  627. // The targets doesn't know the node yet, so we need to use 32 bits int.
  628. node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
  629. MAKE_ROOM(ofs + 4);
  630. encode_uint32(psc->id, &(packet_cache.write[ofs]));
  631. ofs += 4;
  632. }
  633. if (p_set) {
  634. // Take the rpc property ID
  635. uint16_t property_id = p_from->get_node_rset_property_id(p_name);
  636. if (property_id == UINT16_MAX && p_from->get_script_instance()) {
  637. property_id = p_from->get_script_instance()->get_rset_property_id(p_name);
  638. }
  639. ERR_FAIL_COND_MSG(property_id == UINT16_MAX, "Unable to take the `property_id` for the property:" + p_name + ". this can happen only if this property is not marked as `remote`.");
  640. if (property_id <= UINT8_MAX) {
  641. // The ID fits in 1 byte
  642. name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
  643. MAKE_ROOM(ofs + 1);
  644. packet_cache.write[ofs] = static_cast<uint8_t>(property_id);
  645. ofs += 1;
  646. } else {
  647. // The ID is larger, let's use 2 bytes
  648. name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
  649. MAKE_ROOM(ofs + 2);
  650. encode_uint16(property_id, &(packet_cache.write[ofs]));
  651. ofs += 2;
  652. }
  653. // Set argument.
  654. int len(0);
  655. Error err = _encode_and_compress_variant(*p_arg[0], NULL, len);
  656. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RSET value. THIS IS LIKELY A BUG IN THE ENGINE!");
  657. MAKE_ROOM(ofs + len);
  658. _encode_and_compress_variant(*p_arg[0], &(packet_cache.write[ofs]), len);
  659. ofs += len;
  660. } else {
  661. // Take the rpc method ID
  662. uint16_t method_id = p_from->get_node_rpc_method_id(p_name);
  663. if (method_id == UINT16_MAX && p_from->get_script_instance()) {
  664. method_id = p_from->get_script_instance()->get_rpc_method_id(p_name);
  665. }
  666. ERR_FAIL_COND_MSG(method_id == UINT16_MAX, "Unable to take the `method_id` for the function:" + p_name + ". this can happen only if this method is not marked as `remote`.");
  667. if (method_id <= UINT8_MAX) {
  668. // The ID fits in 1 byte
  669. name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
  670. MAKE_ROOM(ofs + 1);
  671. packet_cache.write[ofs] = static_cast<uint8_t>(method_id);
  672. ofs += 1;
  673. } else {
  674. // The ID is larger, let's use 2 bytes
  675. name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
  676. MAKE_ROOM(ofs + 2);
  677. encode_uint16(method_id, &(packet_cache.write[ofs]));
  678. ofs += 2;
  679. }
  680. // Call arguments.
  681. MAKE_ROOM(ofs + 1);
  682. packet_cache.write[ofs] = p_argcount;
  683. ofs += 1;
  684. for (int i = 0; i < p_argcount; i++) {
  685. int len(0);
  686. Error err = _encode_and_compress_variant(*p_arg[i], NULL, len);
  687. ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC argument. THIS IS LIKELY A BUG IN THE ENGINE!");
  688. MAKE_ROOM(ofs + len);
  689. _encode_and_compress_variant(*p_arg[i], &(packet_cache.write[ofs]), len);
  690. ofs += len;
  691. }
  692. }
  693. ERR_FAIL_COND(command_type > 7);
  694. ERR_FAIL_COND(node_id_compression > 3);
  695. ERR_FAIL_COND(name_id_compression > 1);
  696. // We can now set the meta
  697. packet_cache.write[0] = command_type + (node_id_compression << 3) + (name_id_compression << 5);
  698. #ifdef DEBUG_ENABLED
  699. if (profiling) {
  700. bandwidth_outgoing_data.write[bandwidth_outgoing_pointer].timestamp = OS::get_singleton()->get_ticks_msec();
  701. bandwidth_outgoing_data.write[bandwidth_outgoing_pointer].packet_size = ofs;
  702. bandwidth_outgoing_pointer = (bandwidth_outgoing_pointer + 1) % bandwidth_outgoing_data.size();
  703. }
  704. #endif
  705. // Take chance and set transfer mode, since all send methods will use it.
  706. network_peer->set_transfer_mode(p_unreliable ? NetworkedMultiplayerPeer::TRANSFER_MODE_UNRELIABLE : NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE);
  707. if (has_all_peers) {
  708. // They all have verified paths, so send fast.
  709. network_peer->set_target_peer(p_to); // To all of you.
  710. network_peer->put_packet(packet_cache.ptr(), ofs); // A message with love.
  711. } else {
  712. // Unreachable because the node ID is never compressed if the peers doesn't know it.
  713. CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);
  714. // Not all verified path, so send one by one.
  715. // Append path at the end, since we will need it for some packets.
  716. CharString pname = String(from_path).utf8();
  717. int path_len = encode_cstring(pname.get_data(), NULL);
  718. MAKE_ROOM(ofs + path_len);
  719. encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
  720. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  721. if (p_to < 0 && E->get() == -p_to)
  722. continue; // Continue, excluded.
  723. if (p_to > 0 && E->get() != p_to)
  724. continue; // Continue, not for this peer.
  725. Map<int, bool>::Element *F = psc->confirmed_peers.find(E->get());
  726. ERR_CONTINUE(!F); // Should never happen.
  727. network_peer->set_target_peer(E->get()); // To this one specifically.
  728. if (F->get()) {
  729. // This one confirmed path, so use id.
  730. encode_uint32(psc->id, &(packet_cache.write[1]));
  731. network_peer->put_packet(packet_cache.ptr(), ofs);
  732. } else {
  733. // This one did not confirm path yet, so use entire path (sorry!).
  734. encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
  735. network_peer->put_packet(packet_cache.ptr(), ofs + path_len);
  736. }
  737. }
  738. }
  739. }
  740. void MultiplayerAPI::_add_peer(int p_id) {
  741. connected_peers.insert(p_id);
  742. path_get_cache.insert(p_id, PathGetCache());
  743. emit_signal("network_peer_connected", p_id);
  744. }
  745. void MultiplayerAPI::_del_peer(int p_id) {
  746. connected_peers.erase(p_id);
  747. // Cleanup get cache.
  748. path_get_cache.erase(p_id);
  749. // Cleanup sent cache.
  750. // Some refactoring is needed to make this faster and do paths GC.
  751. List<NodePath> keys;
  752. path_send_cache.get_key_list(&keys);
  753. for (List<NodePath>::Element *E = keys.front(); E; E = E->next()) {
  754. PathSentCache *psc = path_send_cache.getptr(E->get());
  755. psc->confirmed_peers.erase(p_id);
  756. }
  757. emit_signal("network_peer_disconnected", p_id);
  758. }
  759. void MultiplayerAPI::_connected_to_server() {
  760. emit_signal("connected_to_server");
  761. }
  762. void MultiplayerAPI::_connection_failed() {
  763. emit_signal("connection_failed");
  764. }
  765. void MultiplayerAPI::_server_disconnected() {
  766. emit_signal("server_disconnected");
  767. }
  768. void MultiplayerAPI::rpcp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_method, const Variant **p_arg, int p_argcount) {
  769. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to call an RPC while no network peer is active.");
  770. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to call an RPC on a node which is not inside SceneTree.");
  771. 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.");
  772. int node_id = network_peer->get_unique_id();
  773. bool skip_rpc = node_id == p_peer_id;
  774. bool call_local_native = false;
  775. bool call_local_script = false;
  776. bool is_master = p_node->is_network_master();
  777. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  778. // Check that send mode can use local call.
  779. RPCMode rpc_mode = p_node->get_node_rpc_mode(p_method);
  780. call_local_native = _should_call_local(rpc_mode, is_master, skip_rpc);
  781. if (call_local_native) {
  782. // Done below.
  783. } else if (p_node->get_script_instance()) {
  784. // Attempt with script.
  785. rpc_mode = p_node->get_script_instance()->get_rpc_mode(p_method);
  786. call_local_script = _should_call_local(rpc_mode, is_master, skip_rpc);
  787. }
  788. }
  789. if (!skip_rpc) {
  790. #ifdef DEBUG_ENABLED
  791. if (profiling) {
  792. ObjectID id = p_node->get_instance_id();
  793. _init_node_profile(id);
  794. profiler_frame_data[id].outgoing_rpc += 1;
  795. }
  796. #endif
  797. _send_rpc(p_node, p_peer_id, p_unreliable, false, p_method, p_arg, p_argcount);
  798. }
  799. if (call_local_native) {
  800. int temp_id = rpc_sender_id;
  801. rpc_sender_id = get_network_unique_id();
  802. Callable::CallError ce;
  803. p_node->call(p_method, p_arg, p_argcount, ce);
  804. rpc_sender_id = temp_id;
  805. if (ce.error != Callable::CallError::CALL_OK) {
  806. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  807. error = "rpc() aborted in local call: - " + error + ".";
  808. ERR_PRINT(error);
  809. return;
  810. }
  811. }
  812. if (call_local_script) {
  813. int temp_id = rpc_sender_id;
  814. rpc_sender_id = get_network_unique_id();
  815. Callable::CallError ce;
  816. ce.error = Callable::CallError::CALL_OK;
  817. p_node->get_script_instance()->call(p_method, p_arg, p_argcount, ce);
  818. rpc_sender_id = temp_id;
  819. if (ce.error != Callable::CallError::CALL_OK) {
  820. String error = Variant::get_call_error_text(p_node, p_method, p_arg, p_argcount, ce);
  821. error = "rpc() aborted in script local call: - " + error + ".";
  822. ERR_PRINT(error);
  823. return;
  824. }
  825. }
  826. ERR_FAIL_COND_MSG(skip_rpc && !(call_local_native || call_local_script), "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
  827. }
  828. void MultiplayerAPI::rsetp(Node *p_node, int p_peer_id, bool p_unreliable, const StringName &p_property, const Variant &p_value) {
  829. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "Trying to RSET while no network peer is active.");
  830. ERR_FAIL_COND_MSG(!p_node->is_inside_tree(), "Trying to RSET on a node which is not inside SceneTree.");
  831. 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.");
  832. int node_id = network_peer->get_unique_id();
  833. bool is_master = p_node->is_network_master();
  834. bool skip_rset = node_id == p_peer_id;
  835. bool set_local = false;
  836. if (p_peer_id == 0 || p_peer_id == node_id || (p_peer_id < 0 && p_peer_id != -node_id)) {
  837. // Check that send mode can use local call.
  838. RPCMode rpc_mode = p_node->get_node_rset_mode(p_property);
  839. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  840. if (set_local) {
  841. bool valid;
  842. int temp_id = rpc_sender_id;
  843. rpc_sender_id = get_network_unique_id();
  844. p_node->set(p_property, p_value, &valid);
  845. rpc_sender_id = temp_id;
  846. if (!valid) {
  847. String error = "rset() aborted in local set, property not found: - " + String(p_property) + ".";
  848. ERR_PRINT(error);
  849. return;
  850. }
  851. } else if (p_node->get_script_instance()) {
  852. // Attempt with script.
  853. rpc_mode = p_node->get_script_instance()->get_rset_mode(p_property);
  854. set_local = _should_call_local(rpc_mode, is_master, skip_rset);
  855. if (set_local) {
  856. int temp_id = rpc_sender_id;
  857. rpc_sender_id = get_network_unique_id();
  858. bool valid = p_node->get_script_instance()->set(p_property, p_value);
  859. rpc_sender_id = temp_id;
  860. if (!valid) {
  861. String error = "rset() aborted in local script set, property not found: - " + String(p_property) + ".";
  862. ERR_PRINT(error);
  863. return;
  864. }
  865. }
  866. }
  867. }
  868. if (skip_rset) {
  869. ERR_FAIL_COND_MSG(!set_local, "RSET for '" + p_property + "' on yourself is not allowed by selected mode.");
  870. return;
  871. }
  872. #ifdef DEBUG_ENABLED
  873. if (profiling) {
  874. ObjectID id = p_node->get_instance_id();
  875. _init_node_profile(id);
  876. profiler_frame_data[id].outgoing_rset += 1;
  877. }
  878. #endif
  879. const Variant *vptr = &p_value;
  880. _send_rpc(p_node, p_peer_id, p_unreliable, true, p_property, &vptr, 1);
  881. }
  882. Error MultiplayerAPI::send_bytes(Vector<uint8_t> p_data, int p_to, NetworkedMultiplayerPeer::TransferMode p_mode) {
  883. ERR_FAIL_COND_V_MSG(p_data.size() < 1, ERR_INVALID_DATA, "Trying to send an empty raw packet.");
  884. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), ERR_UNCONFIGURED, "Trying to send a raw packet while no network peer is active.");
  885. 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.");
  886. MAKE_ROOM(p_data.size() + 1);
  887. const uint8_t *r = p_data.ptr();
  888. packet_cache.write[0] = NETWORK_COMMAND_RAW;
  889. memcpy(&packet_cache.write[1], &r[0], p_data.size());
  890. network_peer->set_target_peer(p_to);
  891. network_peer->set_transfer_mode(p_mode);
  892. return network_peer->put_packet(packet_cache.ptr(), p_data.size() + 1);
  893. }
  894. void MultiplayerAPI::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
  895. ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
  896. Vector<uint8_t> out;
  897. int len = p_packet_len - 1;
  898. out.resize(len);
  899. {
  900. uint8_t *w = out.ptrw();
  901. memcpy(&w[0], &p_packet[1], len);
  902. }
  903. emit_signal("network_peer_packet", p_from, out);
  904. }
  905. int MultiplayerAPI::get_network_unique_id() const {
  906. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), 0, "No network peer is assigned. Unable to get unique network ID.");
  907. return network_peer->get_unique_id();
  908. }
  909. bool MultiplayerAPI::is_network_server() const {
  910. // XXX Maybe fail silently? Maybe should actually return true to make development of both local and online multiplayer easier?
  911. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. I can't be a server.");
  912. return network_peer->is_server();
  913. }
  914. void MultiplayerAPI::set_refuse_new_network_connections(bool p_refuse) {
  915. ERR_FAIL_COND_MSG(!network_peer.is_valid(), "No network peer is assigned. Unable to set 'refuse_new_connections'.");
  916. network_peer->set_refuse_new_connections(p_refuse);
  917. }
  918. bool MultiplayerAPI::is_refusing_new_network_connections() const {
  919. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), false, "No network peer is assigned. Unable to get 'refuse_new_connections'.");
  920. return network_peer->is_refusing_new_connections();
  921. }
  922. Vector<int> MultiplayerAPI::get_network_connected_peers() const {
  923. ERR_FAIL_COND_V_MSG(!network_peer.is_valid(), Vector<int>(), "No network peer is assigned. Assume no peers are connected.");
  924. Vector<int> ret;
  925. for (Set<int>::Element *E = connected_peers.front(); E; E = E->next()) {
  926. ret.push_back(E->get());
  927. }
  928. return ret;
  929. }
  930. void MultiplayerAPI::set_allow_object_decoding(bool p_enable) {
  931. allow_object_decoding = p_enable;
  932. }
  933. bool MultiplayerAPI::is_object_decoding_allowed() const {
  934. return allow_object_decoding;
  935. }
  936. void MultiplayerAPI::profiling_start() {
  937. #ifdef DEBUG_ENABLED
  938. profiling = true;
  939. profiler_frame_data.clear();
  940. bandwidth_incoming_pointer = 0;
  941. bandwidth_incoming_data.resize(16384); // ~128kB
  942. for (int i = 0; i < bandwidth_incoming_data.size(); ++i) {
  943. bandwidth_incoming_data.write[i].packet_size = -1;
  944. }
  945. bandwidth_outgoing_pointer = 0;
  946. bandwidth_outgoing_data.resize(16384); // ~128kB
  947. for (int i = 0; i < bandwidth_outgoing_data.size(); ++i) {
  948. bandwidth_outgoing_data.write[i].packet_size = -1;
  949. }
  950. #endif
  951. }
  952. void MultiplayerAPI::profiling_end() {
  953. #ifdef DEBUG_ENABLED
  954. profiling = false;
  955. bandwidth_incoming_data.clear();
  956. bandwidth_outgoing_data.clear();
  957. #endif
  958. }
  959. int MultiplayerAPI::get_profiling_frame(ProfilingInfo *r_info) {
  960. int i = 0;
  961. #ifdef DEBUG_ENABLED
  962. for (Map<ObjectID, ProfilingInfo>::Element *E = profiler_frame_data.front(); E; E = E->next()) {
  963. r_info[i] = E->get();
  964. ++i;
  965. }
  966. profiler_frame_data.clear();
  967. #endif
  968. return i;
  969. }
  970. int MultiplayerAPI::get_incoming_bandwidth_usage() {
  971. #ifdef DEBUG_ENABLED
  972. return _get_bandwidth_usage(bandwidth_incoming_data, bandwidth_incoming_pointer);
  973. #else
  974. return 0;
  975. #endif
  976. }
  977. int MultiplayerAPI::get_outgoing_bandwidth_usage() {
  978. #ifdef DEBUG_ENABLED
  979. return _get_bandwidth_usage(bandwidth_outgoing_data, bandwidth_outgoing_pointer);
  980. #else
  981. return 0;
  982. #endif
  983. }
  984. #ifdef DEBUG_ENABLED
  985. int MultiplayerAPI::_get_bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer) {
  986. int total_bandwidth = 0;
  987. uint32_t timestamp = OS::get_singleton()->get_ticks_msec();
  988. uint32_t final_timestamp = timestamp - 1000;
  989. int i = (p_pointer + p_buffer.size() - 1) % p_buffer.size();
  990. while (i != p_pointer && p_buffer[i].packet_size > 0) {
  991. if (p_buffer[i].timestamp < final_timestamp) {
  992. return total_bandwidth;
  993. }
  994. total_bandwidth += p_buffer[i].packet_size;
  995. i = (i + p_buffer.size() - 1) % p_buffer.size();
  996. }
  997. ERR_FAIL_COND_V_MSG(i == p_pointer, total_bandwidth, "Reached the end of the bandwidth profiler buffer, values might be inaccurate.");
  998. return total_bandwidth;
  999. }
  1000. void MultiplayerAPI::_init_node_profile(ObjectID p_node) {
  1001. if (profiler_frame_data.has(p_node))
  1002. return;
  1003. profiler_frame_data.insert(p_node, ProfilingInfo());
  1004. profiler_frame_data[p_node].node = p_node;
  1005. profiler_frame_data[p_node].node_path = Object::cast_to<Node>(ObjectDB::get_instance(p_node))->get_path();
  1006. profiler_frame_data[p_node].incoming_rpc = 0;
  1007. profiler_frame_data[p_node].incoming_rset = 0;
  1008. profiler_frame_data[p_node].outgoing_rpc = 0;
  1009. profiler_frame_data[p_node].outgoing_rset = 0;
  1010. }
  1011. #endif
  1012. void MultiplayerAPI::_bind_methods() {
  1013. ClassDB::bind_method(D_METHOD("set_root_node", "node"), &MultiplayerAPI::set_root_node);
  1014. ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode"), &MultiplayerAPI::send_bytes, DEFVAL(NetworkedMultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(NetworkedMultiplayerPeer::TRANSFER_MODE_RELIABLE));
  1015. ClassDB::bind_method(D_METHOD("has_network_peer"), &MultiplayerAPI::has_network_peer);
  1016. ClassDB::bind_method(D_METHOD("get_network_peer"), &MultiplayerAPI::get_network_peer);
  1017. ClassDB::bind_method(D_METHOD("get_network_unique_id"), &MultiplayerAPI::get_network_unique_id);
  1018. ClassDB::bind_method(D_METHOD("is_network_server"), &MultiplayerAPI::is_network_server);
  1019. ClassDB::bind_method(D_METHOD("get_rpc_sender_id"), &MultiplayerAPI::get_rpc_sender_id);
  1020. ClassDB::bind_method(D_METHOD("_add_peer", "id"), &MultiplayerAPI::_add_peer);
  1021. ClassDB::bind_method(D_METHOD("_del_peer", "id"), &MultiplayerAPI::_del_peer);
  1022. ClassDB::bind_method(D_METHOD("set_network_peer", "peer"), &MultiplayerAPI::set_network_peer);
  1023. ClassDB::bind_method(D_METHOD("poll"), &MultiplayerAPI::poll);
  1024. ClassDB::bind_method(D_METHOD("clear"), &MultiplayerAPI::clear);
  1025. ClassDB::bind_method(D_METHOD("_connected_to_server"), &MultiplayerAPI::_connected_to_server);
  1026. ClassDB::bind_method(D_METHOD("_connection_failed"), &MultiplayerAPI::_connection_failed);
  1027. ClassDB::bind_method(D_METHOD("_server_disconnected"), &MultiplayerAPI::_server_disconnected);
  1028. ClassDB::bind_method(D_METHOD("get_network_connected_peers"), &MultiplayerAPI::get_network_connected_peers);
  1029. ClassDB::bind_method(D_METHOD("set_refuse_new_network_connections", "refuse"), &MultiplayerAPI::set_refuse_new_network_connections);
  1030. ClassDB::bind_method(D_METHOD("is_refusing_new_network_connections"), &MultiplayerAPI::is_refusing_new_network_connections);
  1031. ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &MultiplayerAPI::set_allow_object_decoding);
  1032. ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &MultiplayerAPI::is_object_decoding_allowed);
  1033. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
  1034. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_network_connections"), "set_refuse_new_network_connections", "is_refusing_new_network_connections");
  1035. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "network_peer", PROPERTY_HINT_RESOURCE_TYPE, "NetworkedMultiplayerPeer", 0), "set_network_peer", "get_network_peer");
  1036. ADD_PROPERTY_DEFAULT("refuse_new_network_connections", false);
  1037. ADD_SIGNAL(MethodInfo("network_peer_connected", PropertyInfo(Variant::INT, "id")));
  1038. ADD_SIGNAL(MethodInfo("network_peer_disconnected", PropertyInfo(Variant::INT, "id")));
  1039. ADD_SIGNAL(MethodInfo("network_peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
  1040. ADD_SIGNAL(MethodInfo("connected_to_server"));
  1041. ADD_SIGNAL(MethodInfo("connection_failed"));
  1042. ADD_SIGNAL(MethodInfo("server_disconnected"));
  1043. BIND_ENUM_CONSTANT(RPC_MODE_DISABLED);
  1044. BIND_ENUM_CONSTANT(RPC_MODE_REMOTE);
  1045. BIND_ENUM_CONSTANT(RPC_MODE_MASTER);
  1046. BIND_ENUM_CONSTANT(RPC_MODE_PUPPET);
  1047. BIND_ENUM_CONSTANT(RPC_MODE_REMOTESYNC);
  1048. BIND_ENUM_CONSTANT(RPC_MODE_MASTERSYNC);
  1049. BIND_ENUM_CONSTANT(RPC_MODE_PUPPETSYNC);
  1050. }
  1051. MultiplayerAPI::MultiplayerAPI() :
  1052. allow_object_decoding(false) {
  1053. rpc_sender_id = 0;
  1054. root_node = NULL;
  1055. #ifdef DEBUG_ENABLED
  1056. profiling = false;
  1057. #endif
  1058. clear();
  1059. }
  1060. MultiplayerAPI::~MultiplayerAPI() {
  1061. clear();
  1062. }