webrtc_multiplayer_peer.cpp 14 KB

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