multiplayer_synchronizer.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. /**************************************************************************/
  2. /* multiplayer_synchronizer.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 "multiplayer_synchronizer.h"
  31. #include "core/config/engine.h"
  32. #include "scene/main/multiplayer_api.h"
  33. Object *MultiplayerSynchronizer::_get_prop_target(Object *p_obj, const NodePath &p_path) {
  34. if (p_path.get_name_count() == 0) {
  35. return p_obj;
  36. }
  37. Node *node = Object::cast_to<Node>(p_obj);
  38. ERR_FAIL_COND_V_MSG(!node || !node->has_node(p_path), nullptr, vformat("Node '%s' not found.", p_path));
  39. return node->get_node(p_path);
  40. }
  41. void MultiplayerSynchronizer::_stop() {
  42. #ifdef TOOLS_ENABLED
  43. if (Engine::get_singleton()->is_editor_hint()) {
  44. return;
  45. }
  46. #endif
  47. root_node_cache = ObjectID();
  48. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  49. if (node) {
  50. get_multiplayer()->object_configuration_remove(node, this);
  51. }
  52. reset();
  53. }
  54. void MultiplayerSynchronizer::_start() {
  55. #ifdef TOOLS_ENABLED
  56. if (Engine::get_singleton()->is_editor_hint()) {
  57. return;
  58. }
  59. #endif
  60. root_node_cache = ObjectID();
  61. reset();
  62. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  63. if (node) {
  64. root_node_cache = node->get_instance_id();
  65. get_multiplayer()->object_configuration_add(node, this);
  66. _update_process();
  67. }
  68. }
  69. void MultiplayerSynchronizer::_update_process() {
  70. #ifdef TOOLS_ENABLED
  71. if (Engine::get_singleton()->is_editor_hint()) {
  72. return;
  73. }
  74. #endif
  75. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  76. if (!node) {
  77. return;
  78. }
  79. set_process_internal(false);
  80. set_physics_process_internal(false);
  81. if (!visibility_filters.size()) {
  82. return;
  83. }
  84. switch (visibility_update_mode) {
  85. case VISIBILITY_PROCESS_IDLE:
  86. set_process_internal(true);
  87. break;
  88. case VISIBILITY_PROCESS_PHYSICS:
  89. set_physics_process_internal(true);
  90. break;
  91. case VISIBILITY_PROCESS_NONE:
  92. break;
  93. }
  94. }
  95. Node *MultiplayerSynchronizer::get_root_node() {
  96. return root_node_cache.is_valid() ? Object::cast_to<Node>(ObjectDB::get_instance(root_node_cache)) : nullptr;
  97. }
  98. void MultiplayerSynchronizer::reset() {
  99. net_id = 0;
  100. last_sync_usec = 0;
  101. last_inbound_sync = 0;
  102. last_watch_usec = 0;
  103. sync_started = false;
  104. watchers.clear();
  105. }
  106. uint32_t MultiplayerSynchronizer::get_net_id() const {
  107. return net_id;
  108. }
  109. void MultiplayerSynchronizer::set_net_id(uint32_t p_net_id) {
  110. net_id = p_net_id;
  111. }
  112. bool MultiplayerSynchronizer::update_outbound_sync_time(uint64_t p_usec) {
  113. if (last_sync_usec == p_usec) {
  114. // last_sync_usec has been updated in this frame.
  115. return true;
  116. }
  117. if (p_usec < last_sync_usec + sync_interval_usec) {
  118. // Too soon, should skip this synchronization frame.
  119. return false;
  120. }
  121. last_sync_usec = p_usec;
  122. return true;
  123. }
  124. bool MultiplayerSynchronizer::update_inbound_sync_time(uint16_t p_network_time) {
  125. if (!sync_started) {
  126. sync_started = true;
  127. } else if (p_network_time <= last_inbound_sync && last_inbound_sync - p_network_time < 32767) {
  128. return false;
  129. }
  130. last_inbound_sync = p_network_time;
  131. return true;
  132. }
  133. PackedStringArray MultiplayerSynchronizer::get_configuration_warnings() const {
  134. PackedStringArray warnings = Node::get_configuration_warnings();
  135. if (root_path.is_empty() || !has_node(root_path)) {
  136. warnings.push_back(RTR("A valid NodePath must be set in the \"Root Path\" property in order for MultiplayerSynchronizer to be able to synchronize properties."));
  137. }
  138. return warnings;
  139. }
  140. Error MultiplayerSynchronizer::get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs) {
  141. ERR_FAIL_NULL_V(p_obj, ERR_INVALID_PARAMETER);
  142. r_variant.resize(p_properties.size());
  143. r_variant_ptrs.resize(r_variant.size());
  144. int i = 0;
  145. for (const NodePath &prop : p_properties) {
  146. bool valid = false;
  147. const Object *obj = _get_prop_target(p_obj, prop);
  148. ERR_FAIL_NULL_V(obj, FAILED);
  149. r_variant.write[i] = obj->get_indexed(prop.get_subnames(), &valid);
  150. r_variant_ptrs.write[i] = &r_variant[i];
  151. ERR_FAIL_COND_V_MSG(!valid, ERR_INVALID_DATA, vformat("Property '%s' not found.", prop));
  152. i++;
  153. }
  154. return OK;
  155. }
  156. Error MultiplayerSynchronizer::set_state(const List<NodePath> &p_properties, Object *p_obj, const Vector<Variant> &p_state) {
  157. ERR_FAIL_NULL_V(p_obj, ERR_INVALID_PARAMETER);
  158. int i = 0;
  159. for (const NodePath &prop : p_properties) {
  160. Object *obj = _get_prop_target(p_obj, prop);
  161. ERR_FAIL_NULL_V(obj, FAILED);
  162. obj->set_indexed(prop.get_subnames(), p_state[i]);
  163. i += 1;
  164. }
  165. return OK;
  166. }
  167. bool MultiplayerSynchronizer::is_visibility_public() const {
  168. return peer_visibility.has(0);
  169. }
  170. void MultiplayerSynchronizer::set_visibility_public(bool p_visible) {
  171. set_visibility_for(0, p_visible);
  172. }
  173. bool MultiplayerSynchronizer::is_visible_to(int p_peer) {
  174. if (visibility_filters.size()) {
  175. Variant arg = p_peer;
  176. const Variant *argv[1] = { &arg };
  177. for (Callable filter : visibility_filters) {
  178. Variant ret;
  179. Callable::CallError err;
  180. filter.callp(argv, 1, ret, err);
  181. ERR_FAIL_COND_V(err.error != Callable::CallError::CALL_OK || ret.get_type() != Variant::BOOL, false);
  182. if (!ret.operator bool()) {
  183. return false;
  184. }
  185. }
  186. }
  187. return peer_visibility.has(0) || peer_visibility.has(p_peer);
  188. }
  189. void MultiplayerSynchronizer::add_visibility_filter(Callable p_callback) {
  190. visibility_filters.insert(p_callback);
  191. _update_process();
  192. }
  193. void MultiplayerSynchronizer::remove_visibility_filter(Callable p_callback) {
  194. visibility_filters.erase(p_callback);
  195. _update_process();
  196. }
  197. void MultiplayerSynchronizer::set_visibility_for(int p_peer, bool p_visible) {
  198. if (peer_visibility.has(p_peer) == p_visible) {
  199. return;
  200. }
  201. if (p_visible) {
  202. peer_visibility.insert(p_peer);
  203. } else {
  204. peer_visibility.erase(p_peer);
  205. }
  206. update_visibility(p_peer);
  207. }
  208. bool MultiplayerSynchronizer::get_visibility_for(int p_peer) const {
  209. return peer_visibility.has(p_peer);
  210. }
  211. void MultiplayerSynchronizer::set_visibility_update_mode(VisibilityUpdateMode p_mode) {
  212. visibility_update_mode = p_mode;
  213. _update_process();
  214. }
  215. MultiplayerSynchronizer::VisibilityUpdateMode MultiplayerSynchronizer::get_visibility_update_mode() const {
  216. return visibility_update_mode;
  217. }
  218. void MultiplayerSynchronizer::_bind_methods() {
  219. ClassDB::bind_method(D_METHOD("set_root_path", "path"), &MultiplayerSynchronizer::set_root_path);
  220. ClassDB::bind_method(D_METHOD("get_root_path"), &MultiplayerSynchronizer::get_root_path);
  221. ClassDB::bind_method(D_METHOD("set_replication_interval", "milliseconds"), &MultiplayerSynchronizer::set_replication_interval);
  222. ClassDB::bind_method(D_METHOD("get_replication_interval"), &MultiplayerSynchronizer::get_replication_interval);
  223. ClassDB::bind_method(D_METHOD("set_delta_interval", "milliseconds"), &MultiplayerSynchronizer::set_delta_interval);
  224. ClassDB::bind_method(D_METHOD("get_delta_interval"), &MultiplayerSynchronizer::get_delta_interval);
  225. ClassDB::bind_method(D_METHOD("set_replication_config", "config"), &MultiplayerSynchronizer::set_replication_config);
  226. ClassDB::bind_method(D_METHOD("get_replication_config"), &MultiplayerSynchronizer::get_replication_config);
  227. ClassDB::bind_method(D_METHOD("set_visibility_update_mode", "mode"), &MultiplayerSynchronizer::set_visibility_update_mode);
  228. ClassDB::bind_method(D_METHOD("get_visibility_update_mode"), &MultiplayerSynchronizer::get_visibility_update_mode);
  229. ClassDB::bind_method(D_METHOD("update_visibility", "for_peer"), &MultiplayerSynchronizer::update_visibility, DEFVAL(0));
  230. ClassDB::bind_method(D_METHOD("set_visibility_public", "visible"), &MultiplayerSynchronizer::set_visibility_public);
  231. ClassDB::bind_method(D_METHOD("is_visibility_public"), &MultiplayerSynchronizer::is_visibility_public);
  232. ClassDB::bind_method(D_METHOD("add_visibility_filter", "filter"), &MultiplayerSynchronizer::add_visibility_filter);
  233. ClassDB::bind_method(D_METHOD("remove_visibility_filter", "filter"), &MultiplayerSynchronizer::remove_visibility_filter);
  234. ClassDB::bind_method(D_METHOD("set_visibility_for", "peer", "visible"), &MultiplayerSynchronizer::set_visibility_for);
  235. ClassDB::bind_method(D_METHOD("get_visibility_for", "peer"), &MultiplayerSynchronizer::get_visibility_for);
  236. ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
  237. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "replication_interval", PROPERTY_HINT_RANGE, "0,5,0.001,suffix:s"), "set_replication_interval", "get_replication_interval");
  238. ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "delta_interval", PROPERTY_HINT_RANGE, "0,5,0.001,suffix:s"), "set_delta_interval", "get_delta_interval");
  239. ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "replication_config", PROPERTY_HINT_RESOURCE_TYPE, "SceneReplicationConfig", PROPERTY_USAGE_NO_EDITOR), "set_replication_config", "get_replication_config");
  240. ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_update_mode", PROPERTY_HINT_ENUM, "Idle,Physics,None"), "set_visibility_update_mode", "get_visibility_update_mode");
  241. ADD_PROPERTY(PropertyInfo(Variant::BOOL, "public_visibility"), "set_visibility_public", "is_visibility_public");
  242. BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_IDLE);
  243. BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_PHYSICS);
  244. BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_NONE);
  245. ADD_SIGNAL(MethodInfo("synchronized"));
  246. ADD_SIGNAL(MethodInfo("delta_synchronized"));
  247. ADD_SIGNAL(MethodInfo("visibility_changed", PropertyInfo(Variant::INT, "for_peer")));
  248. }
  249. void MultiplayerSynchronizer::_notification(int p_what) {
  250. #ifdef TOOLS_ENABLED
  251. if (Engine::get_singleton()->is_editor_hint()) {
  252. return;
  253. }
  254. #endif
  255. if (root_path.is_empty()) {
  256. return;
  257. }
  258. switch (p_what) {
  259. case NOTIFICATION_ENTER_TREE: {
  260. _start();
  261. } break;
  262. case NOTIFICATION_EXIT_TREE: {
  263. _stop();
  264. } break;
  265. case NOTIFICATION_INTERNAL_PROCESS:
  266. case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
  267. update_visibility(0);
  268. } break;
  269. }
  270. }
  271. void MultiplayerSynchronizer::set_replication_interval(double p_interval) {
  272. ERR_FAIL_COND_MSG(p_interval < 0, "Interval must be greater or equal to 0 (where 0 means default)");
  273. sync_interval_usec = uint64_t(p_interval * 1000 * 1000);
  274. }
  275. double MultiplayerSynchronizer::get_replication_interval() const {
  276. return double(sync_interval_usec) / 1000.0 / 1000.0;
  277. }
  278. void MultiplayerSynchronizer::set_delta_interval(double p_interval) {
  279. ERR_FAIL_COND_MSG(p_interval < 0, "Interval must be greater or equal to 0 (where 0 means default)");
  280. delta_interval_usec = uint64_t(p_interval * 1000 * 1000);
  281. }
  282. double MultiplayerSynchronizer::get_delta_interval() const {
  283. return double(delta_interval_usec) / 1000.0 / 1000.0;
  284. }
  285. void MultiplayerSynchronizer::set_replication_config(Ref<SceneReplicationConfig> p_config) {
  286. replication_config = p_config;
  287. }
  288. Ref<SceneReplicationConfig> MultiplayerSynchronizer::get_replication_config() {
  289. return replication_config;
  290. }
  291. void MultiplayerSynchronizer::update_visibility(int p_for_peer) {
  292. #ifdef TOOLS_ENABLED
  293. if (Engine::get_singleton()->is_editor_hint()) {
  294. return;
  295. }
  296. #endif
  297. Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
  298. if (node && get_multiplayer()->has_multiplayer_peer() && is_multiplayer_authority()) {
  299. emit_signal(SNAME("visibility_changed"), p_for_peer);
  300. }
  301. }
  302. void MultiplayerSynchronizer::set_root_path(const NodePath &p_path) {
  303. if (p_path == root_path) {
  304. return;
  305. }
  306. _stop();
  307. root_path = p_path;
  308. _start();
  309. update_configuration_warnings();
  310. }
  311. NodePath MultiplayerSynchronizer::get_root_path() const {
  312. return root_path;
  313. }
  314. void MultiplayerSynchronizer::set_multiplayer_authority(int p_peer_id, bool p_recursive) {
  315. if (get_multiplayer_authority() == p_peer_id) {
  316. return;
  317. }
  318. _stop();
  319. Node::set_multiplayer_authority(p_peer_id, p_recursive);
  320. _start();
  321. }
  322. Error MultiplayerSynchronizer::_watch_changes(uint64_t p_usec) {
  323. ERR_FAIL_COND_V(replication_config.is_null(), FAILED);
  324. const List<NodePath> props = replication_config->get_watch_properties();
  325. if (props.size() != watchers.size()) {
  326. watchers.resize(props.size());
  327. }
  328. if (props.size() == 0) {
  329. return OK;
  330. }
  331. Node *node = get_root_node();
  332. ERR_FAIL_NULL_V(node, FAILED);
  333. int idx = -1;
  334. Watcher *ptr = watchers.ptrw();
  335. for (const NodePath &prop : props) {
  336. idx++;
  337. bool valid = false;
  338. const Object *obj = _get_prop_target(node, prop);
  339. ERR_CONTINUE_MSG(!obj, vformat("Node not found for property '%s'.", prop));
  340. Variant v = obj->get_indexed(prop.get_subnames(), &valid);
  341. ERR_CONTINUE_MSG(!valid, vformat("Property '%s' not found.", prop));
  342. Watcher &w = ptr[idx];
  343. if (w.prop != prop) {
  344. w.prop = prop;
  345. w.value = v.duplicate(true);
  346. w.last_change_usec = p_usec;
  347. } else if (!w.value.hash_compare(v)) {
  348. w.value = v.duplicate(true);
  349. w.last_change_usec = p_usec;
  350. }
  351. }
  352. return OK;
  353. }
  354. List<Variant> MultiplayerSynchronizer::get_delta_state(uint64_t p_cur_usec, uint64_t p_last_usec, uint64_t &r_indexes) {
  355. r_indexes = 0;
  356. List<Variant> out;
  357. if (last_watch_usec == p_cur_usec) {
  358. // We already watched for changes in this frame.
  359. } else if (p_cur_usec < p_last_usec + delta_interval_usec) {
  360. // Too soon skip delta synchronization.
  361. return out;
  362. } else {
  363. // Watch for changes.
  364. Error err = _watch_changes(p_cur_usec);
  365. ERR_FAIL_COND_V(err != OK, out);
  366. last_watch_usec = p_cur_usec;
  367. }
  368. const Watcher *ptr = watchers.size() ? watchers.ptr() : nullptr;
  369. for (int i = 0; i < watchers.size(); i++) {
  370. const Watcher &w = ptr[i];
  371. if (w.last_change_usec <= p_last_usec) {
  372. continue;
  373. }
  374. out.push_back(w.value);
  375. r_indexes |= 1ULL << i;
  376. }
  377. return out;
  378. }
  379. List<NodePath> MultiplayerSynchronizer::get_delta_properties(uint64_t p_indexes) {
  380. List<NodePath> out;
  381. ERR_FAIL_COND_V(replication_config.is_null(), out);
  382. const List<NodePath> watch_props = replication_config->get_watch_properties();
  383. int idx = 0;
  384. for (const NodePath &prop : watch_props) {
  385. if ((p_indexes & (1ULL << idx++)) == 0) {
  386. continue;
  387. }
  388. out.push_back(prop);
  389. }
  390. return out;
  391. }
  392. SceneReplicationConfig *MultiplayerSynchronizer::get_replication_config_ptr() const {
  393. return replication_config.ptr();
  394. }
  395. MultiplayerSynchronizer::MultiplayerSynchronizer() {
  396. // Publicly visible by default.
  397. peer_visibility.insert(0);
  398. }