webrtc_multiplayer_peer.cpp 15 KB

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