webrtc_multiplayer.cpp 13 KB

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