webrtc_multiplayer_peer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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. HashMap<int, Ref<ConnectedPeer>>::Iterator E = peer_map.find(next_packet_peer);
  134. if (E) {
  135. ++E;
  136. }
  137. // After last.
  138. while (E) {
  139. if (!E->value->connected) {
  140. ++E;
  141. continue;
  142. }
  143. for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
  144. if (F->get_available_packet_count()) {
  145. next_packet_peer = E->key;
  146. return;
  147. }
  148. }
  149. ++E;
  150. }
  151. E = peer_map.begin();
  152. // Before last
  153. while (E) {
  154. if (!E->value->connected) {
  155. ++E;
  156. continue;
  157. }
  158. for (const Ref<WebRTCDataChannel> &F : E->value->channels) {
  159. if (F->get_available_packet_count()) {
  160. next_packet_peer = E->key;
  161. return;
  162. }
  163. }
  164. if (E->key == (int)next_packet_peer) {
  165. break;
  166. }
  167. ++E;
  168. }
  169. // No packet found
  170. next_packet_peer = 0;
  171. }
  172. MultiplayerPeer::ConnectionStatus WebRTCMultiplayerPeer::get_connection_status() const {
  173. return connection_status;
  174. }
  175. Error WebRTCMultiplayerPeer::initialize(int p_self_id, bool p_server_compat, Array p_channels_config) {
  176. ERR_FAIL_COND_V(p_self_id < 1 || p_self_id > ~(1 << 31), ERR_INVALID_PARAMETER);
  177. channels_config.clear();
  178. for (int i = 0; i < p_channels_config.size(); i++) {
  179. 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'");
  180. int mode = p_channels_config[i].operator int();
  181. // Initialize data channel configurations.
  182. Dictionary cfg;
  183. cfg["id"] = CH_RESERVED_MAX + i + 1;
  184. cfg["negotiated"] = true;
  185. cfg["ordered"] = true;
  186. switch (mode) {
  187. case TRANSFER_MODE_UNRELIABLE_ORDERED:
  188. cfg["maxPacketLifetime"] = 1;
  189. break;
  190. case TRANSFER_MODE_UNRELIABLE:
  191. cfg["maxPacketLifetime"] = 1;
  192. cfg["ordered"] = false;
  193. break;
  194. case TRANSFER_MODE_RELIABLE:
  195. break;
  196. default:
  197. ERR_FAIL_V_MSG(ERR_INVALID_PARAMETER, vformat("The 'channels_config' array must contain only enum values from 'MultiplayerPeer.Multiplayer::TransferMode'. Got: %d", mode));
  198. }
  199. channels_config.push_back(cfg);
  200. }
  201. unique_id = p_self_id;
  202. server_compat = p_server_compat;
  203. // Mesh and server are always connected
  204. if (!server_compat || p_self_id == 1) {
  205. connection_status = CONNECTION_CONNECTED;
  206. } else {
  207. connection_status = CONNECTION_CONNECTING;
  208. }
  209. return OK;
  210. }
  211. int WebRTCMultiplayerPeer::get_unique_id() const {
  212. ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, 1);
  213. return unique_id;
  214. }
  215. void WebRTCMultiplayerPeer::_peer_to_dict(Ref<ConnectedPeer> p_connected_peer, Dictionary &r_dict) {
  216. Array channels;
  217. for (Ref<WebRTCDataChannel> &F : p_connected_peer->channels) {
  218. channels.push_back(F);
  219. }
  220. r_dict["connection"] = p_connected_peer->connection;
  221. r_dict["connected"] = p_connected_peer->connected;
  222. r_dict["channels"] = channels;
  223. }
  224. bool WebRTCMultiplayerPeer::has_peer(int p_peer_id) {
  225. return peer_map.has(p_peer_id);
  226. }
  227. Dictionary WebRTCMultiplayerPeer::get_peer(int p_peer_id) {
  228. ERR_FAIL_COND_V(!peer_map.has(p_peer_id), Dictionary());
  229. Dictionary out;
  230. _peer_to_dict(peer_map[p_peer_id], out);
  231. return out;
  232. }
  233. Dictionary WebRTCMultiplayerPeer::get_peers() {
  234. Dictionary out;
  235. for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
  236. Dictionary d;
  237. _peer_to_dict(E.value, d);
  238. out[E.key] = d;
  239. }
  240. return out;
  241. }
  242. Error WebRTCMultiplayerPeer::add_peer(Ref<WebRTCPeerConnection> p_peer, int p_peer_id, int p_unreliable_lifetime) {
  243. ERR_FAIL_COND_V(p_peer_id < 0 || p_peer_id > ~(1 << 31), ERR_INVALID_PARAMETER);
  244. ERR_FAIL_COND_V(p_unreliable_lifetime < 0, ERR_INVALID_PARAMETER);
  245. ERR_FAIL_COND_V(is_refusing_new_connections(), ERR_UNAUTHORIZED);
  246. // Peer must be valid, and in new state (to create data channels)
  247. ERR_FAIL_COND_V(!p_peer.is_valid(), ERR_INVALID_PARAMETER);
  248. ERR_FAIL_COND_V(p_peer->get_connection_state() != WebRTCPeerConnection::STATE_NEW, ERR_INVALID_PARAMETER);
  249. Ref<ConnectedPeer> peer = memnew(ConnectedPeer);
  250. peer->connection = p_peer;
  251. // Initialize data channels
  252. Dictionary cfg;
  253. cfg["negotiated"] = true;
  254. cfg["ordered"] = true;
  255. cfg["id"] = 1;
  256. peer->channels[CH_RELIABLE] = p_peer->create_data_channel("reliable", cfg);
  257. ERR_FAIL_COND_V(peer->channels[CH_RELIABLE].is_null(), FAILED);
  258. cfg["id"] = 2;
  259. cfg["maxPacketLifetime"] = p_unreliable_lifetime;
  260. peer->channels[CH_ORDERED] = p_peer->create_data_channel("ordered", cfg);
  261. ERR_FAIL_COND_V(peer->channels[CH_ORDERED].is_null(), FAILED);
  262. cfg["id"] = 3;
  263. cfg["ordered"] = false;
  264. peer->channels[CH_UNRELIABLE] = p_peer->create_data_channel("unreliable", cfg);
  265. ERR_FAIL_COND_V(peer->channels[CH_UNRELIABLE].is_null(), FAILED);
  266. for (const Dictionary &dict : channels_config) {
  267. Ref<WebRTCDataChannel> ch = p_peer->create_data_channel(String::num_int64(dict["id"]), dict);
  268. ERR_FAIL_COND_V(ch.is_null(), FAILED);
  269. peer->channels.push_back(ch);
  270. }
  271. peer_map[p_peer_id] = peer; // add the new peer connection to the peer_map
  272. return OK;
  273. }
  274. void WebRTCMultiplayerPeer::remove_peer(int p_peer_id) {
  275. ERR_FAIL_COND(!peer_map.has(p_peer_id));
  276. Ref<ConnectedPeer> peer = peer_map[p_peer_id];
  277. peer_map.erase(p_peer_id);
  278. if (peer->connected) {
  279. peer->connected = false;
  280. emit_signal(SNAME("peer_disconnected"), p_peer_id);
  281. if (server_compat && p_peer_id == TARGET_PEER_SERVER) {
  282. emit_signal(SNAME("server_disconnected"));
  283. connection_status = CONNECTION_DISCONNECTED;
  284. }
  285. }
  286. }
  287. Error WebRTCMultiplayerPeer::get_packet(const uint8_t **r_buffer, int &r_buffer_size) {
  288. // Peer not available
  289. if (next_packet_peer == 0 || !peer_map.has(next_packet_peer)) {
  290. _find_next_peer();
  291. ERR_FAIL_V(ERR_UNAVAILABLE);
  292. }
  293. for (Ref<WebRTCDataChannel> &E : peer_map[next_packet_peer]->channels) {
  294. if (E->get_available_packet_count()) {
  295. Error err = E->get_packet(r_buffer, r_buffer_size);
  296. _find_next_peer();
  297. return err;
  298. }
  299. }
  300. // Channels for that peer were empty. Bug?
  301. _find_next_peer();
  302. ERR_FAIL_V(ERR_BUG);
  303. }
  304. Error WebRTCMultiplayerPeer::put_packet(const uint8_t *p_buffer, int p_buffer_size) {
  305. ERR_FAIL_COND_V(connection_status == CONNECTION_DISCONNECTED, ERR_UNCONFIGURED);
  306. int ch = get_transfer_channel();
  307. if (ch == 0) {
  308. switch (get_transfer_mode()) {
  309. case TRANSFER_MODE_RELIABLE:
  310. ch = CH_RELIABLE;
  311. break;
  312. case TRANSFER_MODE_UNRELIABLE_ORDERED:
  313. ch = CH_ORDERED;
  314. break;
  315. case TRANSFER_MODE_UNRELIABLE:
  316. ch = CH_UNRELIABLE;
  317. break;
  318. }
  319. } else {
  320. ch += CH_RESERVED_MAX - 1;
  321. }
  322. if (target_peer > 0) {
  323. HashMap<int, Ref<ConnectedPeer>>::Iterator E = peer_map.find(target_peer);
  324. ERR_FAIL_COND_V_MSG(!E, ERR_INVALID_PARAMETER, "Invalid target peer: " + itos(target_peer) + ".");
  325. 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()));
  326. ERR_FAIL_COND_V(E->value->channels[ch].is_null(), ERR_BUG);
  327. return E->value->channels[ch]->put_packet(p_buffer, p_buffer_size);
  328. } else {
  329. int exclude = -target_peer;
  330. for (KeyValue<int, Ref<ConnectedPeer>> &F : peer_map) {
  331. // Exclude packet. If target_peer == 0 then don't exclude any packets
  332. if (target_peer != 0 && F.key == exclude) {
  333. continue;
  334. }
  335. ERR_CONTINUE_MSG(F.value->channels.size() <= ch, vformat("Unable to send packet on channel %d, max channels: %d", ch, F.value->channels.size()));
  336. ERR_CONTINUE(F.value->channels[ch].is_null());
  337. F.value->channels[ch]->put_packet(p_buffer, p_buffer_size);
  338. }
  339. }
  340. return OK;
  341. }
  342. int WebRTCMultiplayerPeer::get_available_packet_count() const {
  343. if (next_packet_peer == 0) {
  344. return 0; // To be sure next call to get_packet works if size > 0 .
  345. }
  346. int size = 0;
  347. for (const KeyValue<int, Ref<ConnectedPeer>> &E : peer_map) {
  348. if (!E.value->connected) {
  349. continue;
  350. }
  351. for (const Ref<WebRTCDataChannel> &F : E.value->channels) {
  352. size += F->get_available_packet_count();
  353. }
  354. }
  355. return size;
  356. }
  357. int WebRTCMultiplayerPeer::get_max_packet_size() const {
  358. return 1200;
  359. }
  360. void WebRTCMultiplayerPeer::close() {
  361. peer_map.clear();
  362. channels_config.clear();
  363. unique_id = 0;
  364. next_packet_peer = 0;
  365. target_peer = 0;
  366. connection_status = CONNECTION_DISCONNECTED;
  367. }
  368. WebRTCMultiplayerPeer::~WebRTCMultiplayerPeer() {
  369. close();
  370. }