scene_replication_interface.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*************************************************************************/
  2. /* scene_replication_interface.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 "scene_replication_interface.h"
  31. #include "core/io/marshalls.h"
  32. #include "scene/main/node.h"
  33. #include "scene/multiplayer/multiplayer_spawner.h"
  34. #include "scene/multiplayer/multiplayer_synchronizer.h"
  35. #define MAKE_ROOM(m_amount) \
  36. if (packet_cache.size() < m_amount) \
  37. packet_cache.resize(m_amount);
  38. MultiplayerReplicationInterface *SceneReplicationInterface::_create(MultiplayerAPI *p_multiplayer) {
  39. return memnew(SceneReplicationInterface(p_multiplayer));
  40. }
  41. void SceneReplicationInterface::make_default() {
  42. MultiplayerAPI::create_default_replication_interface = _create;
  43. }
  44. void SceneReplicationInterface::_free_remotes(int p_id) {
  45. const HashMap<uint32_t, ObjectID> remotes = rep_state->peer_get_remotes(p_id);
  46. const uint32_t *k = nullptr;
  47. while ((k = remotes.next(k))) {
  48. Node *node = rep_state->get_node(remotes.get(*k));
  49. ERR_CONTINUE(!node);
  50. node->queue_delete();
  51. }
  52. }
  53. void SceneReplicationInterface::on_peer_change(int p_id, bool p_connected) {
  54. if (p_connected) {
  55. rep_state->on_peer_change(p_id, p_connected);
  56. for (const ObjectID &oid : rep_state->get_spawned_nodes()) {
  57. _send_spawn(rep_state->get_node(oid), rep_state->get_spawner(oid), p_id);
  58. }
  59. for (const ObjectID &oid : rep_state->get_path_only_nodes()) {
  60. Node *node = rep_state->get_node(oid);
  61. MultiplayerSynchronizer *sync = rep_state->get_synchronizer(oid);
  62. ERR_CONTINUE(!node || !sync);
  63. if (sync->is_multiplayer_authority()) {
  64. rep_state->peer_add_node(p_id, oid);
  65. }
  66. }
  67. } else {
  68. _free_remotes(p_id);
  69. rep_state->on_peer_change(p_id, p_connected);
  70. }
  71. }
  72. void SceneReplicationInterface::on_reset() {
  73. for (int pid : rep_state->get_peers()) {
  74. _free_remotes(pid);
  75. }
  76. rep_state->reset();
  77. }
  78. void SceneReplicationInterface::on_network_process() {
  79. uint64_t msec = OS::get_singleton()->get_ticks_msec();
  80. for (int peer : rep_state->get_peers()) {
  81. _send_sync(peer, msec);
  82. }
  83. }
  84. Error SceneReplicationInterface::on_spawn(Object *p_obj, Variant p_config) {
  85. Node *node = Object::cast_to<Node>(p_obj);
  86. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  87. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  88. ERR_FAIL_COND_V(!spawner, ERR_INVALID_PARAMETER);
  89. Error err = rep_state->config_add_spawn(node, spawner);
  90. ERR_FAIL_COND_V(err != OK, err);
  91. return _send_spawn(node, spawner, 0);
  92. }
  93. Error SceneReplicationInterface::on_despawn(Object *p_obj, Variant p_config) {
  94. Node *node = Object::cast_to<Node>(p_obj);
  95. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  96. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
  97. ERR_FAIL_COND_V(!p_obj || !spawner, ERR_INVALID_PARAMETER);
  98. Error err = rep_state->config_del_spawn(node, spawner);
  99. ERR_FAIL_COND_V(err != OK, err);
  100. return _send_despawn(node, 0);
  101. }
  102. Error SceneReplicationInterface::on_replication_start(Object *p_obj, Variant p_config) {
  103. Node *node = Object::cast_to<Node>(p_obj);
  104. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  105. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  106. ERR_FAIL_COND_V(!sync, ERR_INVALID_PARAMETER);
  107. rep_state->config_add_sync(node, sync);
  108. // Try to apply initial state if spawning (hack to apply if before ready).
  109. if (pending_spawn == p_obj->get_instance_id()) {
  110. pending_spawn = ObjectID(); // Make sure this only happens once.
  111. const List<NodePath> props = sync->get_replication_config()->get_spawn_properties();
  112. Vector<Variant> vars;
  113. vars.resize(props.size());
  114. int consumed;
  115. Error err = MultiplayerAPI::decode_and_decompress_variants(vars, pending_buffer, pending_buffer_size, consumed);
  116. ERR_FAIL_COND_V(err, err);
  117. err = MultiplayerSynchronizer::set_state(props, node, vars);
  118. ERR_FAIL_COND_V(err, err);
  119. } else if (multiplayer->has_multiplayer_peer() && sync->is_multiplayer_authority()) {
  120. // Either it's a spawn or a static sync, in any case add it to the list of known nodes.
  121. rep_state->peer_add_node(0, p_obj->get_instance_id());
  122. }
  123. return OK;
  124. }
  125. Error SceneReplicationInterface::on_replication_stop(Object *p_obj, Variant p_config) {
  126. Node *node = Object::cast_to<Node>(p_obj);
  127. ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
  128. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
  129. ERR_FAIL_COND_V(!p_obj || !sync, ERR_INVALID_PARAMETER);
  130. return rep_state->config_del_sync(node, sync);
  131. }
  132. Error SceneReplicationInterface::_send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable) {
  133. ERR_FAIL_COND_V(!p_buffer || p_size < 1, ERR_INVALID_PARAMETER);
  134. ERR_FAIL_COND_V(!multiplayer, ERR_UNCONFIGURED);
  135. ERR_FAIL_COND_V(!multiplayer->has_multiplayer_peer(), ERR_UNCONFIGURED);
  136. #ifdef DEBUG_ENABLED
  137. multiplayer->profile_bandwidth("out", p_size);
  138. #endif
  139. Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
  140. peer->set_target_peer(p_peer);
  141. peer->set_transfer_channel(0);
  142. peer->set_transfer_mode(p_reliable ? Multiplayer::TRANSFER_MODE_RELIABLE : Multiplayer::TRANSFER_MODE_UNRELIABLE);
  143. return peer->put_packet(p_buffer, p_size);
  144. }
  145. Error SceneReplicationInterface::_send_spawn(Node *p_node, MultiplayerSpawner *p_spawner, int p_peer) {
  146. ERR_FAIL_COND_V(p_peer < 0, ERR_BUG);
  147. ERR_FAIL_COND_V(!multiplayer, ERR_BUG);
  148. ERR_FAIL_COND_V(!p_spawner || !p_node, ERR_BUG);
  149. const ObjectID oid = p_node->get_instance_id();
  150. uint32_t nid = rep_state->ensure_net_id(oid);
  151. // Prepare custom arg and scene_id
  152. uint8_t scene_id = p_spawner->get_spawn_id(oid);
  153. bool is_custom = scene_id == MultiplayerSpawner::INVALID_ID;
  154. Variant spawn_arg = p_spawner->get_spawn_argument(oid);
  155. int spawn_arg_size = 0;
  156. if (is_custom) {
  157. Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, nullptr, spawn_arg_size, false);
  158. ERR_FAIL_COND_V(err, err);
  159. }
  160. // Prepare spawn state.
  161. int state_size = 0;
  162. Vector<Variant> state_vars;
  163. Vector<const Variant *> state_varp;
  164. MultiplayerSynchronizer *synchronizer = rep_state->get_synchronizer(oid);
  165. if (synchronizer && synchronizer->get_replication_config().is_valid()) {
  166. const List<NodePath> props = synchronizer->get_replication_config()->get_spawn_properties();
  167. Error err = MultiplayerSynchronizer::get_state(props, p_node, state_vars, state_varp);
  168. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to retrieve spawn state.");
  169. err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), nullptr, state_size);
  170. ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to encode spawn state.");
  171. }
  172. // Prepare simplified path.
  173. NodePath rel_path = multiplayer->get_root_path().rel_path_to(p_spawner->get_path());
  174. int path_id = 0;
  175. multiplayer->send_object_cache(p_spawner, rel_path, p_peer, path_id);
  176. // Encode name and parent ID.
  177. CharString cname = p_node->get_name().operator String().utf8();
  178. int nlen = encode_cstring(cname.get_data(), nullptr);
  179. MAKE_ROOM(1 + 1 + 4 + 4 + 4 + nlen + (is_custom ? 4 + spawn_arg_size : 0) + state_size);
  180. uint8_t *ptr = packet_cache.ptrw();
  181. ptr[0] = (uint8_t)MultiplayerAPI::NETWORK_COMMAND_SPAWN;
  182. ptr[1] = scene_id;
  183. int ofs = 2;
  184. ofs += encode_uint32(path_id, &ptr[ofs]);
  185. ofs += encode_uint32(nid, &ptr[ofs]);
  186. ofs += encode_uint32(nlen, &ptr[ofs]);
  187. ofs += encode_cstring(cname.get_data(), &ptr[ofs]);
  188. // Write args
  189. if (is_custom) {
  190. ofs += encode_uint32(spawn_arg_size, &ptr[ofs]);
  191. Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, &ptr[ofs], spawn_arg_size, false);
  192. ERR_FAIL_COND_V(err, err);
  193. ofs += spawn_arg_size;
  194. }
  195. // Write state.
  196. if (state_size) {
  197. Error err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), &ptr[ofs], state_size);
  198. ERR_FAIL_COND_V(err, err);
  199. ofs += state_size;
  200. }
  201. Error err = _send_raw(ptr, ofs, p_peer, true);
  202. ERR_FAIL_COND_V(err, err);
  203. return rep_state->peer_add_node(p_peer, oid);
  204. }
  205. Error SceneReplicationInterface::_send_despawn(Node *p_node, int p_peer) {
  206. const ObjectID oid = p_node->get_instance_id();
  207. MAKE_ROOM(5);
  208. uint8_t *ptr = packet_cache.ptrw();
  209. ptr[0] = (uint8_t)MultiplayerAPI::NETWORK_COMMAND_DESPAWN;
  210. int ofs = 1;
  211. uint32_t nid = rep_state->get_net_id(oid);
  212. ofs += encode_uint32(nid, &ptr[ofs]);
  213. Error err = _send_raw(ptr, ofs, p_peer, true);
  214. ERR_FAIL_COND_V(err, err);
  215. return rep_state->peer_del_node(p_peer, oid);
  216. }
  217. Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  218. ERR_FAIL_COND_V_MSG(p_buffer_len < 14, ERR_INVALID_DATA, "Invalid spawn packet received");
  219. int ofs = 1; // The spawn/despawn command.
  220. uint8_t scene_id = p_buffer[ofs];
  221. ofs += 1;
  222. uint32_t node_target = decode_uint32(&p_buffer[ofs]);
  223. ofs += 4;
  224. MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(multiplayer->get_cached_object(p_from, node_target));
  225. ERR_FAIL_COND_V(!spawner, ERR_DOES_NOT_EXIST);
  226. ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
  227. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  228. ofs += 4;
  229. uint32_t name_len = decode_uint32(&p_buffer[ofs]);
  230. ofs += 4;
  231. ERR_FAIL_COND_V_MSG(name_len > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA, vformat("Invalid spawn packet size: %d, wants: %d", p_buffer_len, ofs + name_len));
  232. ERR_FAIL_COND_V_MSG(name_len < 1, ERR_INVALID_DATA, "Zero spawn name size.");
  233. // We need to make sure no trickery happens here, but we want to allow autogenerated ("@") node names.
  234. const String name = String::utf8((const char *)&p_buffer[ofs], name_len);
  235. ERR_FAIL_COND_V_MSG(name.validate_node_name() != name, ERR_INVALID_DATA, vformat("Invalid node name received: '%s'. Make sure to add nodes via 'add_child(node, true)' remotely.", name));
  236. ofs += name_len;
  237. // Check that we can spawn.
  238. Node *parent = spawner->get_node_or_null(spawner->get_spawn_path());
  239. ERR_FAIL_COND_V(!parent, ERR_UNCONFIGURED);
  240. ERR_FAIL_COND_V(parent->has_node(name), ERR_INVALID_DATA);
  241. Node *node = nullptr;
  242. if (scene_id == MultiplayerSpawner::INVALID_ID) {
  243. // Custom spawn.
  244. ERR_FAIL_COND_V(p_buffer_len - ofs < 4, ERR_INVALID_DATA);
  245. uint32_t arg_size = decode_uint32(&p_buffer[ofs]);
  246. ofs += 4;
  247. ERR_FAIL_COND_V(arg_size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
  248. Variant v;
  249. Error err = MultiplayerAPI::decode_and_decompress_variant(v, &p_buffer[ofs], arg_size, nullptr, false);
  250. ERR_FAIL_COND_V(err != OK, err);
  251. ofs += arg_size;
  252. node = spawner->instantiate_custom(v);
  253. } else {
  254. // Scene based spawn.
  255. node = spawner->instantiate_scene(scene_id);
  256. }
  257. ERR_FAIL_COND_V(!node, ERR_UNAUTHORIZED);
  258. node->set_name(name);
  259. rep_state->peer_add_remote(p_from, net_id, node, spawner);
  260. // The initial state will be applied during the sync config (i.e. before _ready).
  261. int state_len = p_buffer_len - ofs;
  262. if (state_len) {
  263. pending_spawn = node->get_instance_id();
  264. pending_buffer = &p_buffer[ofs];
  265. pending_buffer_size = state_len;
  266. }
  267. parent->add_child(node);
  268. pending_spawn = ObjectID();
  269. pending_buffer = nullptr;
  270. pending_buffer_size = 0;
  271. return OK;
  272. }
  273. Error SceneReplicationInterface::on_despawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  274. ERR_FAIL_COND_V_MSG(p_buffer_len < 5, ERR_INVALID_DATA, "Invalid spawn packet received");
  275. int ofs = 1; // The spawn/despawn command.
  276. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  277. ofs += 4;
  278. Node *node = nullptr;
  279. Error err = rep_state->peer_del_remote(p_from, net_id, &node);
  280. ERR_FAIL_COND_V(err != OK, err);
  281. ERR_FAIL_COND_V(!node, ERR_BUG);
  282. node->queue_delete();
  283. return OK;
  284. }
  285. void SceneReplicationInterface::_send_sync(int p_peer, uint64_t p_msec) {
  286. const Set<ObjectID> &known = rep_state->get_known_nodes(p_peer);
  287. if (known.is_empty()) {
  288. return;
  289. }
  290. MAKE_ROOM(sync_mtu);
  291. uint8_t *ptr = packet_cache.ptrw();
  292. ptr[0] = MultiplayerAPI::NETWORK_COMMAND_SYNC;
  293. int ofs = 1;
  294. ofs += encode_uint16(rep_state->peer_sync_next(p_peer), &ptr[1]);
  295. // Can only send updates for already notified nodes.
  296. // This is a lazy implementation, we could optimize much more here with by grouping by replication config.
  297. for (const ObjectID &oid : known) {
  298. if (!rep_state->update_sync_time(oid, p_msec)) {
  299. continue; // nothing to sync.
  300. }
  301. MultiplayerSynchronizer *sync = rep_state->get_synchronizer(oid);
  302. ERR_CONTINUE(!sync);
  303. Node *node = rep_state->get_node(oid);
  304. ERR_CONTINUE(!node);
  305. int size;
  306. Vector<Variant> vars;
  307. Vector<const Variant *> varp;
  308. const List<NodePath> props = sync->get_replication_config()->get_sync_properties();
  309. Error err = MultiplayerSynchronizer::get_state(props, node, vars, varp);
  310. ERR_CONTINUE_MSG(err != OK, "Unable to retrieve sync state.");
  311. err = MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), nullptr, size);
  312. ERR_CONTINUE_MSG(err != OK, "Unable to encode sync state.");
  313. // TODO Handle single state above MTU.
  314. ERR_CONTINUE_MSG(size > 3 + 4 + 4 + sync_mtu, vformat("Node states bigger then MTU will not be sent (%d > %d): %s", size, sync_mtu, node->get_path()));
  315. if (ofs + 4 + 4 + size > sync_mtu) {
  316. // Send what we got, and reset write.
  317. _send_raw(packet_cache.ptr(), ofs, p_peer, false);
  318. ofs = 3;
  319. }
  320. if (size) {
  321. uint32_t net_id = rep_state->get_net_id(oid);
  322. if (net_id == 0) {
  323. // First time path based ID.
  324. NodePath rel_path = multiplayer->get_root_path().rel_path_to(sync->get_path());
  325. int path_id = 0;
  326. multiplayer->send_object_cache(sync, rel_path, p_peer, path_id);
  327. net_id = path_id;
  328. rep_state->set_net_id(oid, net_id | 0x80000000);
  329. }
  330. ofs += encode_uint32(rep_state->get_net_id(oid), &ptr[ofs]);
  331. ofs += encode_uint32(size, &ptr[ofs]);
  332. MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), &ptr[ofs], size);
  333. ofs += size;
  334. }
  335. }
  336. if (ofs > 3) {
  337. // Got some left over to send.
  338. _send_raw(packet_cache.ptr(), ofs, p_peer, false);
  339. }
  340. }
  341. Error SceneReplicationInterface::on_sync_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
  342. ERR_FAIL_COND_V_MSG(p_buffer_len < 11, ERR_INVALID_DATA, "Invalid sync packet received");
  343. uint16_t time = decode_uint16(&p_buffer[1]);
  344. int ofs = 3;
  345. rep_state->peer_sync_recv(p_from, time);
  346. while (ofs + 8 < p_buffer_len) {
  347. uint32_t net_id = decode_uint32(&p_buffer[ofs]);
  348. ofs += 4;
  349. uint32_t size = decode_uint32(&p_buffer[ofs]);
  350. ofs += 4;
  351. Node *node = nullptr;
  352. if (net_id & 0x80000000) {
  353. MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(multiplayer->get_cached_object(p_from, net_id & 0x7FFFFFFF));
  354. ERR_FAIL_COND_V(!sync || sync->get_multiplayer_authority() != p_from, ERR_UNAUTHORIZED);
  355. node = sync->get_node(sync->get_root_path());
  356. } else {
  357. node = rep_state->peer_get_remote(p_from, net_id);
  358. }
  359. if (!node) {
  360. // Not received yet.
  361. ofs += size;
  362. continue;
  363. }
  364. const ObjectID oid = node->get_instance_id();
  365. if (!rep_state->update_last_node_sync(oid, time)) {
  366. // State is too old.
  367. ofs += size;
  368. continue;
  369. }
  370. MultiplayerSynchronizer *sync = rep_state->get_synchronizer(oid);
  371. ERR_FAIL_COND_V(!sync, ERR_BUG);
  372. ERR_FAIL_COND_V(size > uint32_t(p_buffer_len - ofs), ERR_BUG);
  373. const List<NodePath> props = sync->get_replication_config()->get_sync_properties();
  374. Vector<Variant> vars;
  375. vars.resize(props.size());
  376. int consumed;
  377. Error err = MultiplayerAPI::decode_and_decompress_variants(vars, &p_buffer[ofs], size, consumed);
  378. ERR_FAIL_COND_V(err, err);
  379. err = MultiplayerSynchronizer::set_state(props, node, vars);
  380. ERR_FAIL_COND_V(err, err);
  381. ofs += size;
  382. }
  383. return OK;
  384. }