webrtc_multiplayer_peer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*************************************************************************/
  2. /* webrtc_multiplayer_peer.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 "webrtc_multiplayer_peer.h"
  31. #include "core/io/marshalls.h"
  32. #include "core/os/os.h"
  33. void WebRTCMultiplayerPeer::_bind_methods() {
  34. ClassDB::bind_method(D_METHOD("initialize", "peer_id", "server_compatibility", "channels_config"), &WebRTCMultiplayerPeer::initialize, DEFVAL(false), DEFVAL(Array()));
  35. ClassDB::bind_method(D_METHOD("add_peer", "peer", "peer_id", "unreliable_lifetime"), &WebRTCMultiplayerPeer::add_peer, DEFVAL(1));
  36. ClassDB::bind_method(D_METHOD("remove_peer", "peer_id"), &WebRTCMultiplayerPeer::remove_peer);
  37. ClassDB::bind_method(D_METHOD("has_peer", "peer_id"), &WebRTCMultiplayerPeer::has_peer);
  38. ClassDB::bind_method(D_METHOD("get_peer", "peer_id"), &WebRTCMultiplayerPeer::get_peer);
  39. ClassDB::bind_method(D_METHOD("get_peers"), &WebRTCMultiplayerPeer::get_peers);
  40. ClassDB::bind_method(D_METHOD("close"), &WebRTCMultiplayerPeer::close);
  41. }
  42. void WebRTCMultiplayerPeer::set_target_peer(int p_peer_id) {
  43. target_peer = p_peer_id;
  44. }
  45. /* Returns the ID of the MultiplayerPeer who sent the most recent packet: */
  46. int WebRTCMultiplayerPeer::get_packet_peer() const {
  47. return next_packet_peer;
  48. }
  49. bool WebRTCMultiplayerPeer::is_server() const {
  50. return unique_id == TARGET_PEER_SERVER;
  51. }
  52. void WebRTCMultiplayerPeer::poll() {
  53. if (peer_map.size() == 0) {
  54. return;
  55. }
  56. List<int> remove;
  57. List<int> add;
  58. for (KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
  59. Ref<ConnectedPeer> peer = E.value;
  60. peer->connection->poll();
  61. // Check peer state
  62. switch (peer->connection->get_connection_state()) {
  63. case WebRTCPeerConnection::STATE_NEW:
  64. case WebRTCPeerConnection::STATE_CONNECTING:
  65. // Go to next peer, not ready yet.
  66. continue;
  67. case WebRTCPeerConnection::STATE_CONNECTED:
  68. // Good to go, go ahead and check channel state.
  69. break;
  70. default:
  71. // Peer is closed or in error state. Got to next peer.
  72. remove.push_back(E.key);
  73. continue;
  74. }
  75. // Check channels state
  76. int ready = 0;
  77. for (List<Ref<WebRTCDataChannel>>::Element *C = peer->channels.front(); C && C->get().is_valid(); C = C->next()) {
  78. Ref<WebRTCDataChannel> ch = C->get();
  79. switch (ch->get_ready_state()) {
  80. case WebRTCDataChannel::STATE_CONNECTING:
  81. continue;
  82. case WebRTCDataChannel::STATE_OPEN:
  83. ready++;
  84. continue;
  85. default:
  86. // Channel was closed or in error state, remove peer id.
  87. remove.push_back(E.key);
  88. }
  89. // We got a closed channel break out, the peer will be removed.
  90. break;
  91. }
  92. // This peer has newly connected, and all channels are now open.
  93. if (ready == peer->channels.size() && !peer->connected) {
  94. peer->connected = true;
  95. add.push_back(E.key);
  96. }
  97. }
  98. // Remove disconnected peers
  99. for (int &E : remove) {
  100. remove_peer(E);
  101. if (next_packet_peer == E) {
  102. next_packet_peer = 0;
  103. }
  104. }
  105. // Signal newly connected peers
  106. for (int &E : add) {
  107. // Already connected to server: simply notify new peer.
  108. // NOTE: Mesh is always connected.
  109. if (connection_status == CONNECTION_CONNECTED) {
  110. emit_signal(SNAME("peer_connected"), E);
  111. }
  112. // Server emulation mode suppresses peer_conencted until server connects.
  113. if (server_compat && E == TARGET_PEER_SERVER) {
  114. // Server connected.
  115. connection_status = CONNECTION_CONNECTED;
  116. emit_signal(SNAME("peer_connected"), TARGET_PEER_SERVER);
  117. emit_signal(SNAME("connection_succeeded"));
  118. // Notify of all previously connected peers
  119. for (const KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) {
  120. if (F.key != 1 && F.value->connected) {
  121. emit_signal(SNAME("peer_connected"), F.key);
  122. }
  123. }
  124. break; // Because we already notified of all newly added peers.
  125. }
  126. }
  127. // Fetch next packet
  128. if (next_packet_peer == 0) {
  129. _find_next_peer();
  130. }
  131. }
  132. void WebRTCMultiplayerPeer::_find_next_peer() {
  133. Map<int, Ref<ConnectedPeer>>::Element *E = peer_map.find(next_packet_peer);
  134. if (E) {
  135. E = E->next();
  136. }
  137. // After last.
  138. while (E) {
  139. for (const Ref<WebRTCDataChannel> &F : E->get()->channels) {
  140. if (F->get_available_packet_count()) {
  141. next_packet_peer = E->key();
  142. return;
  143. }
  144. }
  145. E = E->next();
  146. }
  147. E = peer_map.front();
  148. // Before last
  149. while (E) {
  150. for (const Ref<WebRTCDataChannel> &F : E->get()->channels) {
  151. if (F->get_available_packet_count()) {
  152. next_packet_peer = E->key();
  153. return;
  154. }
  155. }
  156. if (E->key() == (int)next_packet_peer) {
  157. break;
  158. }
  159. E = E->next();
  160. }
  161. // No packet found
  162. next_packet_peer = 0;
  163. }
  164. MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() const {
  165. return connection_status;
  166. }
  167. Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Array p_channels_config) {
  168. ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
  169. channels_config.clear();
  170. for (int i = 0; i < p_channels_config.size(); i++) {
  171. ERR_FAIL_COND_V_MSG(p_channels_config[i].get_type() != Variant::INT, ERR_INVALID_PARAMETER, "The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'");
  172. int mode = p_channels_config[i].operator int();
  173. // Initialize data channel configurations.
  174. Dictionary cfg;
  175. cfg["id"] = CH_RESERVED_MAX + i + 1;
  176. cfg["negotiated"] = true;
  177. cfg["ordered"] = true;
  178. switch (mode) {
  179. case Multiplayer::TRANSFER_MODE_UNRELIABLE_ORDERED:
  180. cfg["maxPacketLifetime"] = 1;
  181. break;
  182. case Multiplayer::TRANSFER_MODE_UNRELIABLE:
  183. cfg["maxPacketLifetime"] = 1;
  184. cfg["ordered"] = false;
  185. break;
  186. case Multiplayer::TRANSFER_MODE_RELIABLE:
  187. break;
  188. default:
  189. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'. Got: %d", mode));
  190. }
  191. channels_config.push_back(cfg);
  192. }
  193. unique_id = p_self_id;
  194. server_compat = p_server_compat;
  195. // Mesh and server are always connected
  196. if (!server_compat || p_self_id == 1) {
  197. connection_status = CONNECTION_CONNECTED;
  198. } else {
  199. connection_status = CONNECTION_CONNECTING;
  200. }
  201. return OK;
  202. }
  203. int WebRTCMultiplayerPeer::get_unique_id() const {
  204. ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
  205. return unique_id;
  206. }
  207. void WebRTCMultiplayerPeer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) {
  208. Array channels;
  209. for (Ref<WebRTCDataChannel> &F : p_connected_peer->channels) {
  210. channels.push_back(F);
  211. }
  212. r_dict["connection"] = p_connected_peer->connection;
  213. r_dict["connected"] = p_connected_peer->connected;
  214. r_dict["channels"] = channels;
  215. }
  216. bool WebRTCMultiplayerPeer::has_peer(int p_peer_id) {
  217. return peer_map.has(p_peer_id);
  218. }
  219. Dictionary WebRTCMultiplayerPeer::get_peer(int p_peer_id) {
  220. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
  221. Dictionary out;
  222. _peer_to_dict(peer_map[p_peer_id], out);
  223. return out;
  224. }
  225. Dictionary WebRTCMultiplayerPeer::get_peers() {
  226. Dictionary out;
  227. for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
  228. Dictionary d;
  229. _peer_to_dict(E.value, d);
  230. out[E.key] = d;
  231. }
  232. return out;
  233. }
  234. Error WebRTCMultiplayerPeer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
  235. ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
  236. ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
  237. ERR_FAIL_COND_V(is_refusing_new_connections(), ERR_UNAUTHORIZED);
  238. // Peer must be valid, and in new state (to create data channels)
  239. ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER);
  240. ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
  241. Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
  242. peer->connection = p_peer;
  243. // Initialize data channels
  244. Dictionary cfg;
  245. cfg["negotiated"] = true;
  246. cfg["ordered"] = true;
  247. cfg["id"] = 1;
  248. peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg);
  249. ERR_FAIL_COND_V(peer->channels[CH_RELIABLE].is_null(), FAILED);
  250. cfg["id"] = 2;
  251. cfg["maxPacketLifetime"] = p_unreliable_lifetime;
  252. peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg);
  253. ERR_FAIL_COND_V(peer->channels[CH_ORDERED].is_null(), FAILED);
  254. cfg["id"] = 3;
  255. cfg["ordered"] = false;
  256. peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg);
  257. ERR_FAIL_COND_V(peer->channels[CH_UNRELIABLE].is_null(), FAILED);
  258. for (const Dictionary &dict : channels_config) {
  259. Ref<WebRTCDataChannel> ch = p_peer->create_data_channel(String::num_int64(dict["id"]), dict);
  260. ERR_FAIL_COND_V(ch.is_null(), FAILED);
  261. peer->channels.push_back(ch);
  262. }
  263. peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
  264. return OK;
  265. }
  266. void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) {
  267. ERR_FAIL_COND(!peer_map.has(p_peer_id));
  268. Ref<ConnectedPeer> peer = peer_map[p_peer_id];
  269. peer_map.erase(p_peer_id);
  270. if (peer->connected) {
  271. peer->connected = false;
  272. emit_signal(SNAME("peer_disconnected"), p_peer_id);
  273. if (server_compat && p_peer_id == TARGET_PEER_SERVER) {
  274. emit_signal(SNAME("server_disconnected"));
  275. connection_status = CONNECTION_DISCONNECTED;
  276. }
  277. }
  278. }
  279. Error WebRTCMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  280. // Peer not available
  281. if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
  282. _find_next_peer();
  283. ERR_FAIL_V(ERR_UNAVAILABLE);
  284. }
  285. for (Ref<WebRTCDataChannel> &E : peer_map[next_packet_peer]->channels) {
  286. if (E->get_available_packet_count()) {
  287. Error err = E->get_packet(r_buffer, r_buffer_size);
  288. _find_next_peer();
  289. return err;
  290. }
  291. }
  292. // Channels for that peer were empty. Bug?
  293. _find_next_peer();
  294. ERR_FAIL_V(ERR_BUG);
  295. }
  296. Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  297. ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
  298. int ch = get_transfer_channel();
  299. if (ch == 0) {
  300. switch (get_transfer_mode()) {
  301. case Multiplayer::TRANSFER_MODE_RELIABLE:
  302. ch = CH_RELIABLE;
  303. break;
  304. case Multiplayer::TRANSFER_MODE_UNRELIABLE_ORDERED:
  305. ch = CH_ORDERED;
  306. break;
  307. case Multiplayer::TRANSFER_MODE_UNRELIABLE:
  308. ch = CH_UNRELIABLE;
  309. break;
  310. }
  311. } else {
  312. ch += CH_RESERVED_MAX - 1;
  313. }
  314. Map<int, Ref<ConnectedPeer>>::Element *E = nullptr;
  315. if (target_peer > 0) {
  316. E = peer_map.find(target_peer);
  317. ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + ".");
  318. ERR_FAIL_COND_V_MSG(E->value()->channels.size() <= ch, ERR_INVALID_PARAMETER, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value()->channels.size()));
  319. ERR_FAIL_COND_V(E->value()->channels[ch].is_null(), ERR_BUG);
  320. return E->value()->channels[ch]->put_packet(p_buffer, p_buffer_size);
  321. } else {
  322. int exclude = -target_peer;
  323. for (KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) {
  324. // Exclude packet. If target_peer == 0 then don't exclude any packets
  325. if (target_peer != 0 && F.key == exclude) {
  326. continue;
  327. }
  328. ERR_CONTINUE_MSG(F.value->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, E->value()->channels.size()));
  329. ERR_CONTINUE(F.value->channels[ch].is_null());
  330. F.value->channels[ch]->put_packet(p_buffer, p_buffer_size);
  331. }
  332. }
  333. return OK;
  334. }
  335. int WebRTCMultiplayerPeer::get_available_packet_count() const {
  336. if (next_packet_peer == 0) {
  337. return 0; // To be sure next call to get_packet works if size > 0 .
  338. }
  339. int size = 0;
  340. for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
  341. for (const Ref<WebRTCDataChannel> &F : E.value->channels) {
  342. size += F->get_available_packet_count();
  343. }
  344. }
  345. return size;
  346. }
  347. int WebRTCMultiplayerPeer::get_max_packet_size() const {
  348. return 1200;
  349. }
  350. void WebRTCMultiplayerPeer::close() {
  351. peer_map.clear();
  352. channels_config.clear();
  353. unique_id = 0;
  354. next_packet_peer = 0;
  355. target_peer = 0;
  356. connection_status = CONNECTION_DISCONNECTED;
  357. }
  358. WebRTCMultiplayerPeer::~WebRTCMultiplayerPeer() {
  359. close();
  360. }