Path: blob/master/modules/multiplayer/scene_cache_interface.cpp
10277 views
/**************************************************************************/1/* scene_cache_interface.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "scene_cache_interface.h"3132#include "scene_multiplayer.h"3334#include "core/io/marshalls.h"35#include "scene/main/node.h"36#include "scene/main/window.h"3738SceneCacheInterface::NodeCache &SceneCacheInterface::_track(Node *p_node) {39const ObjectID oid = p_node->get_instance_id();40NodeCache *nc = nodes_cache.getptr(oid);41if (!nc) {42nodes_cache[oid] = NodeCache();43p_node->connect(SceneStringName(tree_exited), callable_mp(this, &SceneCacheInterface::_remove_node_cache).bind(oid), Object::CONNECT_ONE_SHOT);44}45return nodes_cache[oid];46}4748void SceneCacheInterface::_remove_node_cache(ObjectID p_oid) {49NodeCache *nc = nodes_cache.getptr(p_oid);50if (!nc) {51return;52}53if (nc->cache_id) {54assigned_ids.erase(nc->cache_id);55}56#if 057// TODO: Find a way to cleanup recv_nodes without breaking visibility and RPCs interactions.58for (KeyValue<int, int> &E : nc->recv_ids) {59PeerInfo *pinfo = peers_info.getptr(E.key);60ERR_CONTINUE(!pinfo);61pinfo->recv_nodes.erase(E.value);62}63#endif64for (KeyValue<int, bool> &E : nc->confirmed_peers) {65PeerInfo *pinfo = peers_info.getptr(E.key);66ERR_CONTINUE(!pinfo);67pinfo->sent_nodes.erase(p_oid);68}69nodes_cache.erase(p_oid);70}7172void SceneCacheInterface::on_peer_change(int p_id, bool p_connected) {73if (p_connected) {74peers_info.insert(p_id, PeerInfo());75} else {76PeerInfo *pinfo = peers_info.getptr(p_id);77ERR_FAIL_NULL(pinfo); // Bug.78for (KeyValue<int, RecvNode> E : pinfo->recv_nodes) {79NodeCache *nc = nodes_cache.getptr(E.value.oid);80if (!nc) {81// Node might have already been deleted locally.82continue;83}84nc->recv_ids.erase(p_id);85}86for (const ObjectID &oid : pinfo->sent_nodes) {87NodeCache *nc = nodes_cache.getptr(oid);88ERR_CONTINUE(!nc);89nc->confirmed_peers.erase(p_id);90}91peers_info.erase(p_id);92}93}9495void SceneCacheInterface::process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {96ERR_FAIL_COND(!peers_info.has(p_from)); // Bug.97ERR_FAIL_COND_MSG(p_packet_len < 38, "Invalid packet received. Size too small.");98Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());99ERR_FAIL_NULL(root_node);100int ofs = 1;101102String methods_md5 = String::utf8((const char *)(p_packet + ofs), 32);103ofs += 33;104105int id = decode_uint32(&p_packet[ofs]);106ofs += 4;107108ERR_FAIL_COND_MSG(peers_info[p_from].recv_nodes.has(id), vformat("Duplicate remote cache ID %d for peer %d", id, p_from));109110String paths = String::utf8((const char *)(p_packet + ofs), p_packet_len - ofs);111112const NodePath path = paths;113114Node *node = root_node->get_node(path);115ERR_FAIL_NULL(node);116const bool valid_rpc_checksum = multiplayer->get_rpc_md5(node) == methods_md5;117if (valid_rpc_checksum == false) {118ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + String(path));119}120121peers_info[p_from].recv_nodes.insert(id, RecvNode(node->get_instance_id(), path));122NodeCache &cache = _track(node);123cache.recv_ids.insert(p_from, id);124125// Send ack.126Vector<uint8_t> packet;127packet.resize(1 + 1 + 4);128packet.write[0] = SceneMultiplayer::NETWORK_COMMAND_CONFIRM_PATH;129packet.write[1] = valid_rpc_checksum;130encode_uint32(id, &packet.write[2]);131132Ref<MultiplayerPeer> multiplayer_peer = multiplayer->get_multiplayer_peer();133ERR_FAIL_COND(multiplayer_peer.is_null());134135multiplayer_peer->set_transfer_channel(0);136multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);137multiplayer->send_command(p_from, packet.ptr(), packet.size());138}139140void SceneCacheInterface::process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {141ERR_FAIL_COND_MSG(p_packet_len != 6, "Invalid packet received. Size too small.");142Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());143ERR_FAIL_NULL(root_node);144145const bool valid_rpc_checksum = p_packet[1];146int id = decode_uint32(&p_packet[2]);147148const ObjectID *oid = assigned_ids.getptr(id);149if (oid == nullptr) {150return; // May be trying to confirm a node that was removed.151}152153if (valid_rpc_checksum == false) {154const Node *node = ObjectDB::get_instance<Node>(*oid);155ERR_FAIL_NULL(node); // Bug.156ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + String(node->get_path()));157}158159NodeCache *cache = nodes_cache.getptr(*oid);160ERR_FAIL_NULL(cache); // Bug.161162bool *confirmed = cache->confirmed_peers.getptr(p_from);163ERR_FAIL_NULL_MSG(confirmed, "Invalid packet received. Tries to confirm a node which was not requested.");164*confirmed = true;165}166167Error SceneCacheInterface::_send_confirm_path(Node *p_node, NodeCache &p_cache, const List<int> &p_peers) {168// Encode function name.169const CharString path = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();170const int path_len = encode_cstring(path.get_data(), nullptr);171172// Extract MD5 from rpc methods list.173const String methods_md5 = multiplayer->get_rpc_md5(p_node);174const int methods_md5_len = 33; // 32 + 1 for the `0` that is added by the encoder.175176Vector<uint8_t> packet;177packet.resize(1 + 4 + path_len + methods_md5_len);178int ofs = 0;179180packet.write[ofs] = SceneMultiplayer::NETWORK_COMMAND_SIMPLIFY_PATH;181ofs += 1;182183ofs += encode_cstring(methods_md5.utf8().get_data(), &packet.write[ofs]);184185ofs += encode_uint32(p_cache.cache_id, &packet.write[ofs]);186187ofs += encode_cstring(path.get_data(), &packet.write[ofs]);188189Ref<MultiplayerPeer> multiplayer_peer = multiplayer->get_multiplayer_peer();190ERR_FAIL_COND_V(multiplayer_peer.is_null(), ERR_BUG);191192Error err = OK;193for (int peer_id : p_peers) {194multiplayer_peer->set_transfer_channel(0);195multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);196err = multiplayer->send_command(peer_id, packet.ptr(), packet.size());197ERR_FAIL_COND_V(err != OK, err);198// Insert into confirmed, but as false since it was not confirmed.199p_cache.confirmed_peers.insert(peer_id, false);200ERR_CONTINUE(!peers_info.has(peer_id));201peers_info[peer_id].sent_nodes.insert(p_node->get_instance_id());202}203return err;204}205206bool SceneCacheInterface::is_cache_confirmed(Node *p_node, int p_peer) {207ERR_FAIL_NULL_V(p_node, false);208const ObjectID oid = p_node->get_instance_id();209NodeCache *cache = nodes_cache.getptr(oid);210bool *confirmed = cache ? cache->confirmed_peers.getptr(p_peer) : nullptr;211return confirmed && *confirmed;212}213214int SceneCacheInterface::make_object_cache(Object *p_obj) {215Node *node = Object::cast_to<Node>(p_obj);216ERR_FAIL_NULL_V(node, -1);217NodeCache &cache = _track(node);218if (cache.cache_id == 0) {219cache.cache_id = last_send_cache_id++;220assigned_ids[cache.cache_id] = p_obj->get_instance_id();221}222return cache.cache_id;223}224225bool SceneCacheInterface::send_object_cache(Object *p_obj, int p_peer_id, int &r_id) {226Node *node = Object::cast_to<Node>(p_obj);227ERR_FAIL_NULL_V(node, false);228// See if the path is cached.229NodeCache &cache = _track(node);230if (cache.cache_id == 0) {231cache.cache_id = last_send_cache_id++;232assigned_ids[cache.cache_id] = p_obj->get_instance_id();233}234r_id = cache.cache_id;235236bool has_all_peers = true;237List<int> peers_to_add; // If one is missing, take note to add it.238239if (p_peer_id > 0) {240// Fast single peer check.241ERR_FAIL_COND_V_MSG(!peers_info.has(p_peer_id), false, "Peer doesn't exist: " + itos(p_peer_id));242243bool *confirmed = cache.confirmed_peers.getptr(p_peer_id);244if (!confirmed) {245peers_to_add.push_back(p_peer_id); // Need to also be notified.246has_all_peers = false;247} else if (!(*confirmed)) {248has_all_peers = false;249}250} else {251// Long and painful.252for (KeyValue<int, PeerInfo> &E : peers_info) {253if (p_peer_id < 0 && E.key == -p_peer_id) {254continue; // Continue, excluded.255}256257bool *confirmed = cache.confirmed_peers.getptr(E.key);258if (!confirmed) {259peers_to_add.push_back(E.key); // Need to also be notified.260has_all_peers = false;261} else if (!(*confirmed)) {262has_all_peers = false;263}264}265}266267if (peers_to_add.size()) {268_send_confirm_path(node, cache, peers_to_add);269}270271return has_all_peers;272}273274Object *SceneCacheInterface::get_cached_object(int p_from, uint32_t p_cache_id) {275PeerInfo *pinfo = peers_info.getptr(p_from);276ERR_FAIL_NULL_V(pinfo, nullptr);277278RecvNode *recv_node = pinfo->recv_nodes.getptr(p_cache_id);279ERR_FAIL_NULL_V_MSG(recv_node, nullptr, vformat("ID %d not found in cache of peer %d.", p_cache_id, p_from));280Node *node = ObjectDB::get_instance<Node>(recv_node->oid);281if (!node) {282// Fallback to path lookup.283Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());284ERR_FAIL_NULL_V(root_node, nullptr);285node = root_node->get_node(recv_node->path);286if (node) {287recv_node->oid = node->get_instance_id();288}289}290ERR_FAIL_NULL_V_MSG(node, nullptr, vformat("Failed to get cached node from peer %d with cache ID %d.", p_from, p_cache_id));291return node;292}293294void SceneCacheInterface::clear() {295for (KeyValue<ObjectID, NodeCache> &E : nodes_cache) {296Object *obj = ObjectDB::get_instance(E.key);297ERR_CONTINUE(!obj);298obj->disconnect(SceneStringName(tree_exited), callable_mp(this, &SceneCacheInterface::_remove_node_cache));299}300peers_info.clear();301nodes_cache.clear();302assigned_ids.clear();303last_send_cache_id = 1;304}305306307