initial commit, 4.5 stable
Some checks failed
🔗 GHA / 📊 Static checks (push) Has been cancelled
🔗 GHA / 🤖 Android (push) Has been cancelled
🔗 GHA / 🍏 iOS (push) Has been cancelled
🔗 GHA / 🐧 Linux (push) Has been cancelled
🔗 GHA / 🍎 macOS (push) Has been cancelled
🔗 GHA / 🏁 Windows (push) Has been cancelled
🔗 GHA / 🌐 Web (push) Has been cancelled
Some checks failed
🔗 GHA / 📊 Static checks (push) Has been cancelled
🔗 GHA / 🤖 Android (push) Has been cancelled
🔗 GHA / 🍏 iOS (push) Has been cancelled
🔗 GHA / 🐧 Linux (push) Has been cancelled
🔗 GHA / 🍎 macOS (push) Has been cancelled
🔗 GHA / 🏁 Windows (push) Has been cancelled
🔗 GHA / 🌐 Web (push) Has been cancelled
This commit is contained in:
22
modules/multiplayer/SCsub
Normal file
22
modules/multiplayer/SCsub
Normal file
@@ -0,0 +1,22 @@
|
||||
#!/usr/bin/env python
|
||||
from misc.utility.scons_hints import *
|
||||
|
||||
Import("env")
|
||||
Import("env_modules")
|
||||
|
||||
env_mp = env_modules.Clone()
|
||||
|
||||
module_obj = []
|
||||
env_mp.add_source_files(module_obj, "*.cpp")
|
||||
|
||||
if env.editor_build:
|
||||
env_mp.add_source_files(module_obj, "editor/*.cpp")
|
||||
|
||||
env.modules_sources += module_obj
|
||||
|
||||
if env["tests"]:
|
||||
env_mp.Append(CPPDEFINES=["TESTS_ENABLED"])
|
||||
env_mp.add_source_files(env.modules_sources, "./tests/*.cpp")
|
||||
|
||||
if env["disable_exceptions"]:
|
||||
env_mp.Append(CPPDEFINES=["DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS"])
|
20
modules/multiplayer/config.py
Normal file
20
modules/multiplayer/config.py
Normal file
@@ -0,0 +1,20 @@
|
||||
def can_build(env, platform):
|
||||
return True
|
||||
|
||||
|
||||
def configure(env):
|
||||
pass
|
||||
|
||||
|
||||
def get_doc_classes():
|
||||
return [
|
||||
"SceneReplicationConfig",
|
||||
"SceneMultiplayer",
|
||||
"MultiplayerSpawner",
|
||||
"MultiplayerSynchronizer",
|
||||
"OfflineMultiplayerPeer",
|
||||
]
|
||||
|
||||
|
||||
def get_doc_path():
|
||||
return "doc_classes"
|
76
modules/multiplayer/doc_classes/MultiplayerSpawner.xml
Normal file
76
modules/multiplayer/doc_classes/MultiplayerSpawner.xml
Normal file
@@ -0,0 +1,76 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="MultiplayerSpawner" inherits="Node" keywords="network" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
|
||||
<brief_description>
|
||||
Automatically replicates spawnable nodes from the authority to other multiplayer peers.
|
||||
</brief_description>
|
||||
<description>
|
||||
Spawnable scenes can be configured in the editor or through code (see [method add_spawnable_scene]).
|
||||
Also supports custom node spawns through [method spawn], calling [member spawn_function] on all peers.
|
||||
Internally, [MultiplayerSpawner] uses [method MultiplayerAPI.object_configuration_add] to notify spawns passing the spawned node as the [code]object[/code] and itself as the [code]configuration[/code], and [method MultiplayerAPI.object_configuration_remove] to notify despawns in a similar way.
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
<methods>
|
||||
<method name="add_spawnable_scene">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="String" />
|
||||
<description>
|
||||
Adds a scene path to spawnable scenes, making it automatically replicated from the multiplayer authority to other peers when added as children of the node pointed by [member spawn_path].
|
||||
</description>
|
||||
</method>
|
||||
<method name="clear_spawnable_scenes">
|
||||
<return type="void" />
|
||||
<description>
|
||||
Clears all spawnable scenes. Does not despawn existing instances on remote peers.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_spawnable_scene" qualifiers="const">
|
||||
<return type="String" />
|
||||
<param index="0" name="index" type="int" />
|
||||
<description>
|
||||
Returns the spawnable scene path by index.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_spawnable_scene_count" qualifiers="const">
|
||||
<return type="int" />
|
||||
<description>
|
||||
Returns the count of spawnable scene paths.
|
||||
</description>
|
||||
</method>
|
||||
<method name="spawn">
|
||||
<return type="Node" />
|
||||
<param index="0" name="data" type="Variant" default="null" />
|
||||
<description>
|
||||
Requests a custom spawn, with [param data] passed to [member spawn_function] on all peers. Returns the locally spawned node instance already inside the scene tree, and added as a child of the node pointed by [member spawn_path].
|
||||
[b]Note:[/b] Spawnable scenes are spawned automatically. [method spawn] is only needed for custom spawns.
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
<members>
|
||||
<member name="spawn_function" type="Callable" setter="set_spawn_function" getter="get_spawn_function">
|
||||
Method called on all peers when a custom [method spawn] is requested by the authority. Will receive the [code]data[/code] parameter, and should return a [Node] that is not in the scene tree.
|
||||
[b]Note:[/b] The returned node should [b]not[/b] be added to the scene with [method Node.add_child]. This is done automatically.
|
||||
</member>
|
||||
<member name="spawn_limit" type="int" setter="set_spawn_limit" getter="get_spawn_limit" default="0">
|
||||
Maximum number of nodes allowed to be spawned by this spawner. Includes both spawnable scenes and custom spawns.
|
||||
When set to [code]0[/code] (the default), there is no limit.
|
||||
</member>
|
||||
<member name="spawn_path" type="NodePath" setter="set_spawn_path" getter="get_spawn_path" default="NodePath("")">
|
||||
Path to the spawn root. Spawnable scenes that are added as direct children are replicated to other peers.
|
||||
</member>
|
||||
</members>
|
||||
<signals>
|
||||
<signal name="despawned">
|
||||
<param index="0" name="node" type="Node" />
|
||||
<description>
|
||||
Emitted when a spawnable scene or custom spawn was despawned by the multiplayer authority. Only called on remote peers.
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="spawned">
|
||||
<param index="0" name="node" type="Node" />
|
||||
<description>
|
||||
Emitted when a spawnable scene or custom spawn was spawned by the multiplayer authority. Only called on remote peers.
|
||||
</description>
|
||||
</signal>
|
||||
</signals>
|
||||
</class>
|
104
modules/multiplayer/doc_classes/MultiplayerSynchronizer.xml
Normal file
104
modules/multiplayer/doc_classes/MultiplayerSynchronizer.xml
Normal file
@@ -0,0 +1,104 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="MultiplayerSynchronizer" inherits="Node" keywords="network" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
|
||||
<brief_description>
|
||||
Synchronizes properties from the multiplayer authority to the remote peers.
|
||||
</brief_description>
|
||||
<description>
|
||||
By default, [MultiplayerSynchronizer] synchronizes configured properties to all peers.
|
||||
Visibility can be handled directly with [method set_visibility_for] or as-needed with [method add_visibility_filter] and [method update_visibility].
|
||||
[MultiplayerSpawner]s will handle nodes according to visibility of synchronizers as long as the node at [member root_path] was spawned by one.
|
||||
Internally, [MultiplayerSynchronizer] uses [method MultiplayerAPI.object_configuration_add] to notify synchronization start passing the [Node] at [member root_path] as the [code]object[/code] and itself as the [code]configuration[/code], and uses [method MultiplayerAPI.object_configuration_remove] to notify synchronization end in a similar way.
|
||||
[b]Note:[/b] Synchronization is not supported for [Object] type properties, like [Resource]. Properties that are unique to each peer, like the instance IDs of [Object]s (see [method Object.get_instance_id]) or [RID]s, will also not work in synchronization.
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
<methods>
|
||||
<method name="add_visibility_filter">
|
||||
<return type="void" />
|
||||
<param index="0" name="filter" type="Callable" />
|
||||
<description>
|
||||
Adds a peer visibility filter for this synchronizer.
|
||||
[param filter] should take a peer ID [int] and return a [bool].
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_visibility_for" qualifiers="const">
|
||||
<return type="bool" />
|
||||
<param index="0" name="peer" type="int" />
|
||||
<description>
|
||||
Queries the current visibility for peer [param peer].
|
||||
</description>
|
||||
</method>
|
||||
<method name="remove_visibility_filter">
|
||||
<return type="void" />
|
||||
<param index="0" name="filter" type="Callable" />
|
||||
<description>
|
||||
Removes a peer visibility filter from this synchronizer.
|
||||
</description>
|
||||
</method>
|
||||
<method name="set_visibility_for">
|
||||
<return type="void" />
|
||||
<param index="0" name="peer" type="int" />
|
||||
<param index="1" name="visible" type="bool" />
|
||||
<description>
|
||||
Sets the visibility of [param peer] to [param visible]. If [param peer] is [code]0[/code], the value of [member public_visibility] will be updated instead.
|
||||
</description>
|
||||
</method>
|
||||
<method name="update_visibility">
|
||||
<return type="void" />
|
||||
<param index="0" name="for_peer" type="int" default="0" />
|
||||
<description>
|
||||
Updates the visibility of [param for_peer] according to visibility filters. If [param for_peer] is [code]0[/code] (the default), all peers' visibilties are updated.
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
<members>
|
||||
<member name="delta_interval" type="float" setter="set_delta_interval" getter="get_delta_interval" default="0.0">
|
||||
Time interval between delta synchronizations. Used when the replication is set to [constant SceneReplicationConfig.REPLICATION_MODE_ON_CHANGE]. If set to [code]0.0[/code] (the default), delta synchronizations happen every network process frame.
|
||||
</member>
|
||||
<member name="public_visibility" type="bool" setter="set_visibility_public" getter="is_visibility_public" default="true">
|
||||
Whether synchronization should be visible to all peers by default. See [method set_visibility_for] and [method add_visibility_filter] for ways of configuring fine-grained visibility options.
|
||||
</member>
|
||||
<member name="replication_config" type="SceneReplicationConfig" setter="set_replication_config" getter="get_replication_config">
|
||||
Resource containing which properties to synchronize.
|
||||
</member>
|
||||
<member name="replication_interval" type="float" setter="set_replication_interval" getter="get_replication_interval" default="0.0">
|
||||
Time interval between synchronizations. Used when the replication is set to [constant SceneReplicationConfig.REPLICATION_MODE_ALWAYS]. If set to [code]0.0[/code] (the default), synchronizations happen every network process frame.
|
||||
</member>
|
||||
<member name="root_path" type="NodePath" setter="set_root_path" getter="get_root_path" default="NodePath("..")">
|
||||
Node path that replicated properties are relative to.
|
||||
If [member root_path] was spawned by a [MultiplayerSpawner], the node will be also be spawned and despawned based on this synchronizer visibility options.
|
||||
</member>
|
||||
<member name="visibility_update_mode" type="int" setter="set_visibility_update_mode" getter="get_visibility_update_mode" enum="MultiplayerSynchronizer.VisibilityUpdateMode" default="0">
|
||||
Specifies when visibility filters are updated.
|
||||
</member>
|
||||
</members>
|
||||
<signals>
|
||||
<signal name="delta_synchronized">
|
||||
<description>
|
||||
Emitted when a new delta synchronization state is received by this synchronizer after the properties have been updated.
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="synchronized">
|
||||
<description>
|
||||
Emitted when a new synchronization state is received by this synchronizer after the properties have been updated.
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="visibility_changed">
|
||||
<param index="0" name="for_peer" type="int" />
|
||||
<description>
|
||||
Emitted when visibility of [param for_peer] is updated. See [method update_visibility].
|
||||
</description>
|
||||
</signal>
|
||||
</signals>
|
||||
<constants>
|
||||
<constant name="VISIBILITY_PROCESS_IDLE" value="0" enum="VisibilityUpdateMode">
|
||||
Visibility filters are updated during process frames (see [constant Node.NOTIFICATION_INTERNAL_PROCESS]).
|
||||
</constant>
|
||||
<constant name="VISIBILITY_PROCESS_PHYSICS" value="1" enum="VisibilityUpdateMode">
|
||||
Visibility filters are updated during physics frames (see [constant Node.NOTIFICATION_INTERNAL_PHYSICS_PROCESS]).
|
||||
</constant>
|
||||
<constant name="VISIBILITY_PROCESS_NONE" value="2" enum="VisibilityUpdateMode">
|
||||
Visibility filters are not updated automatically, and must be updated manually by calling [method update_visibility].
|
||||
</constant>
|
||||
</constants>
|
||||
</class>
|
12
modules/multiplayer/doc_classes/OfflineMultiplayerPeer.xml
Normal file
12
modules/multiplayer/doc_classes/OfflineMultiplayerPeer.xml
Normal file
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="OfflineMultiplayerPeer" inherits="MultiplayerPeer" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
|
||||
<brief_description>
|
||||
A [MultiplayerPeer] which is always connected and acts as a server.
|
||||
</brief_description>
|
||||
<description>
|
||||
This is the default [member MultiplayerAPI.multiplayer_peer] for the [member Node.multiplayer]. It mimics the behavior of a server with no peers connected.
|
||||
This means that the [SceneTree] will act as the multiplayer authority by default. Calls to [method MultiplayerAPI.is_server] will return [code]true[/code], and calls to [method MultiplayerAPI.get_unique_id] will return [constant MultiplayerPeer.TARGET_PEER_SERVER].
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
</class>
|
113
modules/multiplayer/doc_classes/SceneMultiplayer.xml
Normal file
113
modules/multiplayer/doc_classes/SceneMultiplayer.xml
Normal file
@@ -0,0 +1,113 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="SceneMultiplayer" inherits="MultiplayerAPI" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
|
||||
<brief_description>
|
||||
High-level multiplayer API implementation.
|
||||
</brief_description>
|
||||
<description>
|
||||
This class is the default implementation of [MultiplayerAPI], used to provide multiplayer functionalities in Godot Engine.
|
||||
This implementation supports RPCs via [method Node.rpc] and [method Node.rpc_id] and requires [method MultiplayerAPI.rpc] to be passed a [Node] (it will fail for other object types).
|
||||
This implementation additionally provide [SceneTree] replication via the [MultiplayerSpawner] and [MultiplayerSynchronizer] nodes, and the [SceneReplicationConfig] resource.
|
||||
[b]Note:[/b] The high-level multiplayer API protocol is an implementation detail and isn't meant to be used by non-Godot servers. It may change without notice.
|
||||
[b]Note:[/b] When exporting to Android, make sure to enable the [code]INTERNET[/code] permission in the Android export preset before exporting the project or using one-click deploy. Otherwise, network communication of any kind will be blocked by Android.
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
<methods>
|
||||
<method name="clear">
|
||||
<return type="void" />
|
||||
<description>
|
||||
Clears the current SceneMultiplayer network state (you shouldn't call this unless you know what you are doing).
|
||||
</description>
|
||||
</method>
|
||||
<method name="complete_auth">
|
||||
<return type="int" enum="Error" />
|
||||
<param index="0" name="id" type="int" />
|
||||
<description>
|
||||
Mark the authentication step as completed for the remote peer identified by [param id]. The [signal MultiplayerAPI.peer_connected] signal will be emitted for this peer once the remote side also completes the authentication. No further authentication messages are expected to be received from this peer.
|
||||
If a peer disconnects before completing authentication, either due to a network issue, the [member auth_timeout] expiring, or manually calling [method disconnect_peer], the [signal peer_authentication_failed] signal will be emitted instead of [signal MultiplayerAPI.peer_disconnected].
|
||||
</description>
|
||||
</method>
|
||||
<method name="disconnect_peer">
|
||||
<return type="void" />
|
||||
<param index="0" name="id" type="int" />
|
||||
<description>
|
||||
Disconnects the peer identified by [param id], removing it from the list of connected peers, and closing the underlying connection with it.
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_authenticating_peers">
|
||||
<return type="PackedInt32Array" />
|
||||
<description>
|
||||
Returns the IDs of the peers currently trying to authenticate with this [MultiplayerAPI].
|
||||
</description>
|
||||
</method>
|
||||
<method name="send_auth">
|
||||
<return type="int" enum="Error" />
|
||||
<param index="0" name="id" type="int" />
|
||||
<param index="1" name="data" type="PackedByteArray" />
|
||||
<description>
|
||||
Sends the specified [param data] to the remote peer identified by [param id] as part of an authentication message. This can be used to authenticate peers, and control when [signal MultiplayerAPI.peer_connected] is emitted (and the remote peer accepted as one of the connected peers).
|
||||
</description>
|
||||
</method>
|
||||
<method name="send_bytes">
|
||||
<return type="int" enum="Error" />
|
||||
<param index="0" name="bytes" type="PackedByteArray" />
|
||||
<param index="1" name="id" type="int" default="0" />
|
||||
<param index="2" name="mode" type="int" enum="MultiplayerPeer.TransferMode" default="2" />
|
||||
<param index="3" name="channel" type="int" default="0" />
|
||||
<description>
|
||||
Sends the given raw [param bytes] to a specific peer identified by [param id] (see [method MultiplayerPeer.set_target_peer]). Default ID is [code]0[/code], i.e. broadcast to all peers.
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
<members>
|
||||
<member name="allow_object_decoding" type="bool" setter="set_allow_object_decoding" getter="is_object_decoding_allowed" default="false">
|
||||
If [code]true[/code], the MultiplayerAPI will allow encoding and decoding of object during RPCs.
|
||||
[b]Warning:[/b] Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threat such as remote code execution.
|
||||
</member>
|
||||
<member name="auth_callback" type="Callable" setter="set_auth_callback" getter="get_auth_callback" default="Callable()">
|
||||
The callback to execute when receiving authentication data sent via [method send_auth]. If the [Callable] is empty (default), peers will be automatically accepted as soon as they connect.
|
||||
</member>
|
||||
<member name="auth_timeout" type="float" setter="set_auth_timeout" getter="get_auth_timeout" default="3.0">
|
||||
If set to a value greater than [code]0.0[/code], the maximum duration in seconds peers can stay in the authenticating state, after which the authentication will automatically fail. See the [signal peer_authenticating] and [signal peer_authentication_failed] signals.
|
||||
</member>
|
||||
<member name="max_delta_packet_size" type="int" setter="set_max_delta_packet_size" getter="get_max_delta_packet_size" default="65535">
|
||||
Maximum size of each delta packet. Higher values increase the chance of receiving full updates in a single frame, but also the chance of causing networking congestion (higher latency, disconnections). See [MultiplayerSynchronizer].
|
||||
</member>
|
||||
<member name="max_sync_packet_size" type="int" setter="set_max_sync_packet_size" getter="get_max_sync_packet_size" default="1350">
|
||||
Maximum size of each synchronization packet. Higher values increase the chance of receiving full updates in a single frame, but also the chance of packet loss. See [MultiplayerSynchronizer].
|
||||
</member>
|
||||
<member name="refuse_new_connections" type="bool" setter="set_refuse_new_connections" getter="is_refusing_new_connections" default="false">
|
||||
If [code]true[/code], the MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] refuses new incoming connections.
|
||||
</member>
|
||||
<member name="root_path" type="NodePath" setter="set_root_path" getter="get_root_path" default="NodePath("")">
|
||||
The root path to use for RPCs and replication. Instead of an absolute path, a relative path will be used to find the node upon which the RPC should be executed.
|
||||
This effectively allows to have different branches of the scene tree to be managed by different MultiplayerAPI, allowing for example to run both client and server in the same scene.
|
||||
</member>
|
||||
<member name="server_relay" type="bool" setter="set_server_relay_enabled" getter="is_server_relay_enabled" default="true">
|
||||
Enable or disable the server feature that notifies clients of other peers' connection/disconnection, and relays messages between them. When this option is [code]false[/code], clients won't be automatically notified of other peers and won't be able to send them packets through the server.
|
||||
[b]Note:[/b] Changing this option while other peers are connected may lead to unexpected behaviors.
|
||||
[b]Note:[/b] Support for this feature may depend on the current [MultiplayerPeer] configuration. See [method MultiplayerPeer.is_server_relay_supported].
|
||||
</member>
|
||||
</members>
|
||||
<signals>
|
||||
<signal name="peer_authenticating">
|
||||
<param index="0" name="id" type="int" />
|
||||
<description>
|
||||
Emitted when this MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] connects to a new peer and a valid [member auth_callback] is set. In this case, the [signal MultiplayerAPI.peer_connected] will not be emitted until [method complete_auth] is called with given peer [param id]. While in this state, the peer will not be included in the list returned by [method MultiplayerAPI.get_peers] (but in the one returned by [method get_authenticating_peers]), and only authentication data will be sent or received. See [method send_auth] for sending authentication data.
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="peer_authentication_failed">
|
||||
<param index="0" name="id" type="int" />
|
||||
<description>
|
||||
Emitted when this MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] disconnects from a peer for which authentication had not yet completed. See [signal peer_authenticating].
|
||||
</description>
|
||||
</signal>
|
||||
<signal name="peer_packet">
|
||||
<param index="0" name="id" type="int" />
|
||||
<param index="1" name="packet" type="PackedByteArray" />
|
||||
<description>
|
||||
Emitted when this MultiplayerAPI's [member MultiplayerAPI.multiplayer_peer] receives a [param packet] with custom data (see [method send_bytes]). ID is the peer ID of the peer that sent the packet.
|
||||
</description>
|
||||
</signal>
|
||||
</signals>
|
||||
</class>
|
119
modules/multiplayer/doc_classes/SceneReplicationConfig.xml
Normal file
119
modules/multiplayer/doc_classes/SceneReplicationConfig.xml
Normal file
@@ -0,0 +1,119 @@
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<class name="SceneReplicationConfig" inherits="Resource" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
|
||||
<brief_description>
|
||||
Configuration for properties to synchronize with a [MultiplayerSynchronizer].
|
||||
</brief_description>
|
||||
<description>
|
||||
</description>
|
||||
<tutorials>
|
||||
</tutorials>
|
||||
<methods>
|
||||
<method name="add_property">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<param index="1" name="index" type="int" default="-1" />
|
||||
<description>
|
||||
Adds the property identified by the given [param path] to the list of the properties being synchronized, optionally passing an [param index].
|
||||
[b]Note:[/b] For details on restrictions and limitations on property synchronization, see [MultiplayerSynchronizer].
|
||||
</description>
|
||||
</method>
|
||||
<method name="get_properties" qualifiers="const">
|
||||
<return type="NodePath[]" />
|
||||
<description>
|
||||
Returns a list of synchronized property [NodePath]s.
|
||||
</description>
|
||||
</method>
|
||||
<method name="has_property" qualifiers="const">
|
||||
<return type="bool" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Returns [code]true[/code] if the given [param path] is configured for synchronization.
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_get_index" qualifiers="const">
|
||||
<return type="int" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Finds the index of the given [param path].
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_get_replication_mode">
|
||||
<return type="int" enum="SceneReplicationConfig.ReplicationMode" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Returns the replication mode for the property identified by the given [param path].
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_get_spawn">
|
||||
<return type="bool" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Returns [code]true[/code] if the property identified by the given [param path] is configured to be synchronized on spawn.
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_get_sync" deprecated="Use [method property_get_replication_mode] instead.">
|
||||
<return type="bool" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Returns [code]true[/code] if the property identified by the given [param path] is configured to be synchronized on process.
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_get_watch" deprecated="Use [method property_get_replication_mode] instead.">
|
||||
<return type="bool" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Returns [code]true[/code] if the property identified by the given [param path] is configured to be reliably synchronized when changes are detected on process.
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_set_replication_mode">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<param index="1" name="mode" type="int" enum="SceneReplicationConfig.ReplicationMode" />
|
||||
<description>
|
||||
Sets the synchronization mode for the property identified by the given [param path].
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_set_spawn">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<param index="1" name="enabled" type="bool" />
|
||||
<description>
|
||||
Sets whether the property identified by the given [param path] is configured to be synchronized on spawn.
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_set_sync" deprecated="Use [method property_set_replication_mode] with [constant REPLICATION_MODE_ALWAYS] instead.">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<param index="1" name="enabled" type="bool" />
|
||||
<description>
|
||||
Sets whether the property identified by the given [param path] is configured to be synchronized on process.
|
||||
</description>
|
||||
</method>
|
||||
<method name="property_set_watch" deprecated="Use [method property_set_replication_mode] with [constant REPLICATION_MODE_ON_CHANGE] instead.">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<param index="1" name="enabled" type="bool" />
|
||||
<description>
|
||||
Sets whether the property identified by the given [param path] is configured to be reliably synchronized when changes are detected on process.
|
||||
</description>
|
||||
</method>
|
||||
<method name="remove_property">
|
||||
<return type="void" />
|
||||
<param index="0" name="path" type="NodePath" />
|
||||
<description>
|
||||
Removes the property identified by the given [param path] from the configuration.
|
||||
</description>
|
||||
</method>
|
||||
</methods>
|
||||
<constants>
|
||||
<constant name="REPLICATION_MODE_NEVER" value="0" enum="ReplicationMode">
|
||||
Do not keep the given property synchronized.
|
||||
</constant>
|
||||
<constant name="REPLICATION_MODE_ALWAYS" value="1" enum="ReplicationMode">
|
||||
Replicate the given property on process by constantly sending updates using unreliable transfer mode.
|
||||
</constant>
|
||||
<constant name="REPLICATION_MODE_ON_CHANGE" value="2" enum="ReplicationMode">
|
||||
Replicate the given property on process by sending updates using reliable transfer mode when its value changes.
|
||||
</constant>
|
||||
</constants>
|
||||
</class>
|
432
modules/multiplayer/editor/editor_network_profiler.cpp
Normal file
432
modules/multiplayer/editor/editor_network_profiler.cpp
Normal file
@@ -0,0 +1,432 @@
|
||||
/**************************************************************************/
|
||||
/* editor_network_profiler.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "editor_network_profiler.h"
|
||||
|
||||
#include "editor/editor_string_names.h"
|
||||
#include "editor/run/editor_run_bar.h"
|
||||
#include "editor/settings/editor_settings.h"
|
||||
#include "editor/themes/editor_scale.h"
|
||||
#include "scene/gui/check_box.h"
|
||||
#include "scene/gui/flow_container.h"
|
||||
#include "scene/gui/line_edit.h"
|
||||
|
||||
void EditorNetworkProfiler::_bind_methods() {
|
||||
ADD_SIGNAL(MethodInfo("enable_profiling", PropertyInfo(Variant::BOOL, "enable")));
|
||||
ADD_SIGNAL(MethodInfo("open_request", PropertyInfo(Variant::STRING, "path")));
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_notification(int p_what) {
|
||||
switch (p_what) {
|
||||
case NOTIFICATION_THEME_CHANGED: {
|
||||
if (activate->is_pressed()) {
|
||||
activate->set_button_icon(theme_cache.stop_icon);
|
||||
} else {
|
||||
activate->set_button_icon(theme_cache.play_icon);
|
||||
}
|
||||
clear_button->set_button_icon(theme_cache.clear_icon);
|
||||
|
||||
incoming_bandwidth_text->set_right_icon(theme_cache.incoming_bandwidth_icon);
|
||||
outgoing_bandwidth_text->set_right_icon(theme_cache.outgoing_bandwidth_icon);
|
||||
|
||||
// This needs to be done here to set the faded color when the profiler is first opened
|
||||
incoming_bandwidth_text->add_theme_color_override("font_uneditable_color", theme_cache.incoming_bandwidth_color * Color(1, 1, 1, 0.5));
|
||||
outgoing_bandwidth_text->add_theme_color_override("font_uneditable_color", theme_cache.outgoing_bandwidth_color * Color(1, 1, 1, 0.5));
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_update_theme_item_cache() {
|
||||
VBoxContainer::_update_theme_item_cache();
|
||||
|
||||
theme_cache.node_icon = get_theme_icon(SNAME("Node"), EditorStringName(EditorIcons));
|
||||
theme_cache.stop_icon = get_theme_icon(SNAME("Stop"), EditorStringName(EditorIcons));
|
||||
theme_cache.play_icon = get_theme_icon(SNAME("Play"), EditorStringName(EditorIcons));
|
||||
theme_cache.clear_icon = get_theme_icon(SNAME("Clear"), EditorStringName(EditorIcons));
|
||||
|
||||
theme_cache.multiplayer_synchronizer_icon = get_theme_icon("MultiplayerSynchronizer", EditorStringName(EditorIcons));
|
||||
theme_cache.instance_options_icon = get_theme_icon(SNAME("InstanceOptions"), EditorStringName(EditorIcons));
|
||||
|
||||
theme_cache.incoming_bandwidth_icon = get_theme_icon(SNAME("ArrowDown"), EditorStringName(EditorIcons));
|
||||
theme_cache.outgoing_bandwidth_icon = get_theme_icon(SNAME("ArrowUp"), EditorStringName(EditorIcons));
|
||||
|
||||
theme_cache.incoming_bandwidth_color = get_theme_color(SceneStringName(font_color), EditorStringName(Editor));
|
||||
theme_cache.outgoing_bandwidth_color = get_theme_color(SceneStringName(font_color), EditorStringName(Editor));
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_refresh() {
|
||||
if (!dirty) {
|
||||
return;
|
||||
}
|
||||
dirty = false;
|
||||
refresh_rpc_data();
|
||||
refresh_replication_data();
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::refresh_rpc_data() {
|
||||
counters_display->clear();
|
||||
|
||||
TreeItem *root = counters_display->create_item();
|
||||
int cols = counters_display->get_columns();
|
||||
|
||||
for (const KeyValue<ObjectID, RPCNodeInfo> &E : rpc_data) {
|
||||
TreeItem *node = counters_display->create_item(root);
|
||||
|
||||
for (int j = 0; j < cols; ++j) {
|
||||
node->set_text_alignment(j, j > 0 ? HORIZONTAL_ALIGNMENT_RIGHT : HORIZONTAL_ALIGNMENT_LEFT);
|
||||
}
|
||||
|
||||
node->set_text(0, E.value.node_path);
|
||||
node->set_text(1, E.value.incoming_rpc == 0 ? "-" : vformat(TTR("%d (%s)"), E.value.incoming_rpc, String::humanize_size(E.value.incoming_size)));
|
||||
node->set_text(2, E.value.outgoing_rpc == 0 ? "-" : vformat(TTR("%d (%s)"), E.value.outgoing_rpc, String::humanize_size(E.value.outgoing_size)));
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::refresh_replication_data() {
|
||||
replication_display->clear();
|
||||
|
||||
TreeItem *root = replication_display->create_item();
|
||||
|
||||
for (const KeyValue<ObjectID, SyncInfo> &E : sync_data) {
|
||||
// Ensure the nodes have at least a temporary cache.
|
||||
ObjectID ids[3] = { E.value.synchronizer, E.value.config, E.value.root_node };
|
||||
for (uint32_t i = 0; i < 3; i++) {
|
||||
const ObjectID &id = ids[i];
|
||||
if (!node_data.has(id)) {
|
||||
missing_node_data.insert(id);
|
||||
node_data[id] = NodeInfo(id);
|
||||
}
|
||||
}
|
||||
|
||||
TreeItem *node = replication_display->create_item(root);
|
||||
|
||||
const NodeInfo &root_info = node_data[E.value.root_node];
|
||||
const NodeInfo &sync_info = node_data[E.value.synchronizer];
|
||||
const NodeInfo &cfg_info = node_data[E.value.config];
|
||||
|
||||
node->set_text(0, root_info.path.get_file());
|
||||
node->set_icon(0, has_theme_icon(root_info.type, EditorStringName(EditorIcons)) ? get_theme_icon(root_info.type, EditorStringName(EditorIcons)) : theme_cache.node_icon);
|
||||
node->set_tooltip_text(0, root_info.path);
|
||||
|
||||
node->set_text(1, sync_info.path.get_file());
|
||||
node->set_icon(1, theme_cache.multiplayer_synchronizer_icon);
|
||||
node->set_tooltip_text(1, sync_info.path);
|
||||
|
||||
int cfg_idx = cfg_info.path.find("::");
|
||||
if (cfg_info.path.begins_with("res://") && ResourceLoader::exists(cfg_info.path) && cfg_idx > 0) {
|
||||
String res_idstr = cfg_info.path.substr(cfg_idx + 2).replace("SceneReplicationConfig_", "");
|
||||
String scene_path = cfg_info.path.substr(0, cfg_idx);
|
||||
node->set_text(2, vformat("%s (%s)", res_idstr, scene_path.get_file()));
|
||||
node->add_button(2, theme_cache.instance_options_icon);
|
||||
node->set_tooltip_text(2, cfg_info.path);
|
||||
node->set_metadata(2, scene_path);
|
||||
} else {
|
||||
node->set_text(2, cfg_info.path);
|
||||
node->set_metadata(2, "");
|
||||
}
|
||||
|
||||
node->set_text(3, vformat("%d - %d", E.value.incoming_syncs, E.value.outgoing_syncs));
|
||||
node->set_text(4, vformat("%d - %d", E.value.incoming_size, E.value.outgoing_size));
|
||||
}
|
||||
}
|
||||
|
||||
Array EditorNetworkProfiler::pop_missing_node_data() {
|
||||
Array out;
|
||||
for (const ObjectID &id : missing_node_data) {
|
||||
out.push_back(id);
|
||||
}
|
||||
missing_node_data.clear();
|
||||
return out;
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::add_node_data(const NodeInfo &p_info) {
|
||||
ERR_FAIL_COND(!node_data.has(p_info.id));
|
||||
node_data[p_info.id] = p_info;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_activate_pressed() {
|
||||
_update_button_text();
|
||||
|
||||
if (activate->is_pressed()) {
|
||||
refresh_timer->start();
|
||||
} else {
|
||||
refresh_timer->stop();
|
||||
}
|
||||
|
||||
emit_signal(SNAME("enable_profiling"), activate->is_pressed());
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_update_button_text() {
|
||||
if (activate->is_pressed()) {
|
||||
activate->set_button_icon(theme_cache.stop_icon);
|
||||
activate->set_text(TTR("Stop"));
|
||||
} else {
|
||||
activate->set_button_icon(theme_cache.play_icon);
|
||||
activate->set_text(TTR("Start"));
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::started() {
|
||||
_clear_pressed();
|
||||
activate->set_disabled(false);
|
||||
|
||||
if (EditorSettings::get_singleton()->get_project_metadata("debug_options", "autostart_network_profiler", false)) {
|
||||
set_profiling(true);
|
||||
refresh_timer->start();
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::stopped() {
|
||||
activate->set_disabled(true);
|
||||
set_profiling(false);
|
||||
refresh_timer->stop();
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::set_profiling(bool p_pressed) {
|
||||
activate->set_pressed(p_pressed);
|
||||
_update_button_text();
|
||||
emit_signal(SNAME("enable_profiling"), activate->is_pressed());
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_clear_pressed() {
|
||||
rpc_data.clear();
|
||||
sync_data.clear();
|
||||
node_data.clear();
|
||||
missing_node_data.clear();
|
||||
set_bandwidth(0, 0);
|
||||
refresh_rpc_data();
|
||||
refresh_replication_data();
|
||||
clear_button->set_disabled(true);
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_autostart_toggled(bool p_toggled_on) {
|
||||
EditorSettings::get_singleton()->set_project_metadata("debug_options", "autostart_network_profiler", p_toggled_on);
|
||||
EditorRunBar::get_singleton()->update_profiler_autostart_indicator();
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::_replication_button_clicked(TreeItem *p_item, int p_column, int p_idx, MouseButton p_button) {
|
||||
if (!p_item) {
|
||||
return;
|
||||
}
|
||||
String meta = p_item->get_metadata(p_column);
|
||||
if (meta.size() && ResourceLoader::exists(meta)) {
|
||||
emit_signal("open_request", meta);
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::add_rpc_frame_data(const RPCNodeInfo &p_frame) {
|
||||
if (clear_button->is_disabled()) {
|
||||
clear_button->set_disabled(false);
|
||||
}
|
||||
dirty = true;
|
||||
if (!rpc_data.has(p_frame.node)) {
|
||||
rpc_data.insert(p_frame.node, p_frame);
|
||||
} else {
|
||||
rpc_data[p_frame.node].incoming_rpc += p_frame.incoming_rpc;
|
||||
rpc_data[p_frame.node].outgoing_rpc += p_frame.outgoing_rpc;
|
||||
}
|
||||
if (p_frame.incoming_rpc) {
|
||||
rpc_data[p_frame.node].incoming_size = p_frame.incoming_size / p_frame.incoming_rpc;
|
||||
}
|
||||
if (p_frame.outgoing_rpc) {
|
||||
rpc_data[p_frame.node].outgoing_size = p_frame.outgoing_size / p_frame.outgoing_rpc;
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::add_sync_frame_data(const SyncInfo &p_frame) {
|
||||
if (clear_button->is_disabled()) {
|
||||
clear_button->set_disabled(false);
|
||||
}
|
||||
dirty = true;
|
||||
if (!sync_data.has(p_frame.synchronizer)) {
|
||||
sync_data[p_frame.synchronizer] = p_frame;
|
||||
} else {
|
||||
sync_data[p_frame.synchronizer].incoming_syncs += p_frame.incoming_syncs;
|
||||
sync_data[p_frame.synchronizer].outgoing_syncs += p_frame.outgoing_syncs;
|
||||
}
|
||||
SyncInfo &info = sync_data[p_frame.synchronizer];
|
||||
if (p_frame.incoming_syncs) {
|
||||
info.incoming_size = p_frame.incoming_size / p_frame.incoming_syncs;
|
||||
}
|
||||
if (p_frame.outgoing_syncs) {
|
||||
info.outgoing_size = p_frame.outgoing_size / p_frame.outgoing_syncs;
|
||||
}
|
||||
}
|
||||
|
||||
void EditorNetworkProfiler::set_bandwidth(int p_incoming, int p_outgoing) {
|
||||
incoming_bandwidth_text->set_text(vformat(TTR("%s/s"), String::humanize_size(p_incoming)));
|
||||
outgoing_bandwidth_text->set_text(vformat(TTR("%s/s"), String::humanize_size(p_outgoing)));
|
||||
|
||||
// Make labels more prominent when the bandwidth is greater than 0 to attract user attention
|
||||
incoming_bandwidth_text->add_theme_color_override(
|
||||
"font_uneditable_color",
|
||||
theme_cache.incoming_bandwidth_color * Color(1, 1, 1, p_incoming > 0 ? 1 : 0.5));
|
||||
outgoing_bandwidth_text->add_theme_color_override(
|
||||
"font_uneditable_color",
|
||||
theme_cache.outgoing_bandwidth_color * Color(1, 1, 1, p_outgoing > 0 ? 1 : 0.5));
|
||||
}
|
||||
|
||||
bool EditorNetworkProfiler::is_profiling() {
|
||||
return activate->is_pressed();
|
||||
}
|
||||
|
||||
EditorNetworkProfiler::EditorNetworkProfiler() {
|
||||
FlowContainer *container = memnew(FlowContainer);
|
||||
container->add_theme_constant_override(SNAME("h_separation"), 8 * EDSCALE);
|
||||
container->add_theme_constant_override(SNAME("v_separation"), 2 * EDSCALE);
|
||||
add_child(container);
|
||||
|
||||
activate = memnew(Button);
|
||||
activate->set_toggle_mode(true);
|
||||
activate->set_text(TTR("Start"));
|
||||
activate->set_disabled(true);
|
||||
activate->connect(SceneStringName(pressed), callable_mp(this, &EditorNetworkProfiler::_activate_pressed));
|
||||
container->add_child(activate);
|
||||
|
||||
clear_button = memnew(Button);
|
||||
clear_button->set_text(TTR("Clear"));
|
||||
clear_button->set_disabled(true);
|
||||
clear_button->connect(SceneStringName(pressed), callable_mp(this, &EditorNetworkProfiler::_clear_pressed));
|
||||
container->add_child(clear_button);
|
||||
|
||||
CheckBox *autostart_checkbox = memnew(CheckBox);
|
||||
autostart_checkbox->set_text(TTR("Autostart"));
|
||||
autostart_checkbox->set_pressed(EditorSettings::get_singleton()->get_project_metadata("debug_options", "autostart_network_profiler", false));
|
||||
autostart_checkbox->connect(SceneStringName(toggled), callable_mp(this, &EditorNetworkProfiler::_autostart_toggled));
|
||||
container->add_child(autostart_checkbox);
|
||||
|
||||
Control *c = memnew(Control);
|
||||
c->set_h_size_flags(SIZE_EXPAND_FILL);
|
||||
container->add_child(c);
|
||||
|
||||
HBoxContainer *hb = memnew(HBoxContainer);
|
||||
hb->add_theme_constant_override(SNAME("separation"), 8 * EDSCALE);
|
||||
container->add_child(hb);
|
||||
|
||||
Label *lb = memnew(Label);
|
||||
// TRANSLATORS: This is the label for the network profiler's incoming bandwidth.
|
||||
lb->set_focus_mode(FOCUS_ACCESSIBILITY);
|
||||
lb->set_text(TTR("Down", "Network"));
|
||||
hb->add_child(lb);
|
||||
|
||||
incoming_bandwidth_text = memnew(LineEdit);
|
||||
incoming_bandwidth_text->set_editable(false);
|
||||
incoming_bandwidth_text->set_custom_minimum_size(Size2(120, 0) * EDSCALE);
|
||||
incoming_bandwidth_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
|
||||
incoming_bandwidth_text->set_accessibility_name(TTRC("Incoming Bandwidth"));
|
||||
hb->add_child(incoming_bandwidth_text);
|
||||
|
||||
Control *down_up_spacer = memnew(Control);
|
||||
down_up_spacer->set_custom_minimum_size(Size2(30, 0) * EDSCALE);
|
||||
hb->add_child(down_up_spacer);
|
||||
|
||||
lb = memnew(Label);
|
||||
// TRANSLATORS: This is the label for the network profiler's outgoing bandwidth.
|
||||
lb->set_focus_mode(FOCUS_ACCESSIBILITY);
|
||||
lb->set_text(TTR("Up", "Network"));
|
||||
hb->add_child(lb);
|
||||
|
||||
outgoing_bandwidth_text = memnew(LineEdit);
|
||||
outgoing_bandwidth_text->set_editable(false);
|
||||
outgoing_bandwidth_text->set_custom_minimum_size(Size2(120, 0) * EDSCALE);
|
||||
outgoing_bandwidth_text->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_RIGHT);
|
||||
outgoing_bandwidth_text->set_accessibility_name(TTRC("Outgoing Bandwidth"));
|
||||
hb->add_child(outgoing_bandwidth_text);
|
||||
|
||||
// Set initial texts in the incoming/outgoing bandwidth labels
|
||||
set_bandwidth(0, 0);
|
||||
|
||||
HSplitContainer *sc = memnew(HSplitContainer);
|
||||
add_child(sc);
|
||||
sc->set_v_size_flags(SIZE_EXPAND_FILL);
|
||||
sc->set_h_size_flags(SIZE_EXPAND_FILL);
|
||||
sc->set_split_offset(100 * EDSCALE);
|
||||
|
||||
// RPC
|
||||
counters_display = memnew(Tree);
|
||||
counters_display->set_custom_minimum_size(Size2(280, 0) * EDSCALE);
|
||||
counters_display->set_v_size_flags(SIZE_EXPAND_FILL);
|
||||
counters_display->set_h_size_flags(SIZE_EXPAND_FILL);
|
||||
counters_display->set_hide_folding(true);
|
||||
counters_display->set_hide_root(true);
|
||||
counters_display->set_columns(3);
|
||||
counters_display->set_column_titles_visible(true);
|
||||
counters_display->set_column_title(0, TTR("Node"));
|
||||
counters_display->set_column_expand(0, true);
|
||||
counters_display->set_column_clip_content(0, true);
|
||||
counters_display->set_column_custom_minimum_width(0, 60 * EDSCALE);
|
||||
counters_display->set_column_title(1, TTR("Incoming RPC"));
|
||||
counters_display->set_column_expand(1, false);
|
||||
counters_display->set_column_clip_content(1, true);
|
||||
counters_display->set_column_custom_minimum_width(1, 120 * EDSCALE);
|
||||
counters_display->set_column_title(2, TTR("Outgoing RPC"));
|
||||
counters_display->set_column_expand(2, false);
|
||||
counters_display->set_column_clip_content(2, true);
|
||||
counters_display->set_column_custom_minimum_width(2, 120 * EDSCALE);
|
||||
sc->add_child(counters_display);
|
||||
|
||||
// Replication
|
||||
replication_display = memnew(Tree);
|
||||
replication_display->set_custom_minimum_size(Size2(280, 0) * EDSCALE);
|
||||
replication_display->set_v_size_flags(SIZE_EXPAND_FILL);
|
||||
replication_display->set_h_size_flags(SIZE_EXPAND_FILL);
|
||||
replication_display->set_hide_folding(true);
|
||||
replication_display->set_hide_root(true);
|
||||
replication_display->set_columns(5);
|
||||
replication_display->set_column_titles_visible(true);
|
||||
replication_display->set_column_title(0, TTR("Root"));
|
||||
replication_display->set_column_expand(0, true);
|
||||
replication_display->set_column_clip_content(0, true);
|
||||
replication_display->set_column_custom_minimum_width(0, 80 * EDSCALE);
|
||||
replication_display->set_column_title(1, TTR("Synchronizer"));
|
||||
replication_display->set_column_expand(1, true);
|
||||
replication_display->set_column_clip_content(1, true);
|
||||
replication_display->set_column_custom_minimum_width(1, 80 * EDSCALE);
|
||||
replication_display->set_column_title(2, TTR("Config"));
|
||||
replication_display->set_column_expand(2, true);
|
||||
replication_display->set_column_clip_content(2, true);
|
||||
replication_display->set_column_custom_minimum_width(2, 80 * EDSCALE);
|
||||
replication_display->set_column_title(3, TTR("Count"));
|
||||
replication_display->set_column_expand(3, false);
|
||||
replication_display->set_column_clip_content(3, true);
|
||||
replication_display->set_column_custom_minimum_width(3, 80 * EDSCALE);
|
||||
replication_display->set_column_title(4, TTR("Size"));
|
||||
replication_display->set_column_expand(4, false);
|
||||
replication_display->set_column_clip_content(4, true);
|
||||
replication_display->set_column_custom_minimum_width(4, 80 * EDSCALE);
|
||||
replication_display->connect("button_clicked", callable_mp(this, &EditorNetworkProfiler::_replication_button_clicked));
|
||||
sc->add_child(replication_display);
|
||||
|
||||
refresh_timer = memnew(Timer);
|
||||
refresh_timer->set_wait_time(0.5);
|
||||
refresh_timer->connect("timeout", callable_mp(this, &EditorNetworkProfiler::_refresh));
|
||||
add_child(refresh_timer);
|
||||
}
|
121
modules/multiplayer/editor/editor_network_profiler.h
Normal file
121
modules/multiplayer/editor/editor_network_profiler.h
Normal file
@@ -0,0 +1,121 @@
|
||||
/**************************************************************************/
|
||||
/* editor_network_profiler.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "../multiplayer_debugger.h"
|
||||
|
||||
#include "scene/debugger/scene_debugger.h"
|
||||
#include "scene/gui/box_container.h"
|
||||
#include "scene/gui/button.h"
|
||||
#include "scene/gui/label.h"
|
||||
#include "scene/gui/split_container.h"
|
||||
#include "scene/gui/tree.h"
|
||||
|
||||
class EditorNetworkProfiler : public VBoxContainer {
|
||||
GDCLASS(EditorNetworkProfiler, VBoxContainer)
|
||||
|
||||
public:
|
||||
struct NodeInfo {
|
||||
ObjectID id;
|
||||
String type;
|
||||
String path;
|
||||
|
||||
NodeInfo() {}
|
||||
NodeInfo(const ObjectID &p_id) {
|
||||
id = p_id;
|
||||
path = String::num_int64(p_id);
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
using RPCNodeInfo = MultiplayerDebugger::RPCNodeInfo;
|
||||
using SyncInfo = MultiplayerDebugger::SyncInfo;
|
||||
|
||||
bool dirty = false;
|
||||
Timer *refresh_timer = nullptr;
|
||||
Button *activate = nullptr;
|
||||
Button *clear_button = nullptr;
|
||||
Tree *counters_display = nullptr;
|
||||
LineEdit *incoming_bandwidth_text = nullptr;
|
||||
LineEdit *outgoing_bandwidth_text = nullptr;
|
||||
Tree *replication_display = nullptr;
|
||||
|
||||
HashMap<ObjectID, RPCNodeInfo> rpc_data;
|
||||
HashMap<ObjectID, SyncInfo> sync_data;
|
||||
HashMap<ObjectID, NodeInfo> node_data;
|
||||
HashSet<ObjectID> missing_node_data;
|
||||
|
||||
struct ThemeCache {
|
||||
Ref<Texture2D> node_icon;
|
||||
Ref<Texture2D> stop_icon;
|
||||
Ref<Texture2D> play_icon;
|
||||
Ref<Texture2D> clear_icon;
|
||||
|
||||
Ref<Texture2D> multiplayer_synchronizer_icon;
|
||||
Ref<Texture2D> instance_options_icon;
|
||||
|
||||
Ref<Texture2D> incoming_bandwidth_icon;
|
||||
Ref<Texture2D> outgoing_bandwidth_icon;
|
||||
|
||||
Color incoming_bandwidth_color;
|
||||
Color outgoing_bandwidth_color;
|
||||
} theme_cache;
|
||||
|
||||
void _activate_pressed();
|
||||
void _clear_pressed();
|
||||
void _autostart_toggled(bool p_toggled_on);
|
||||
void _refresh();
|
||||
void _update_button_text();
|
||||
void _replication_button_clicked(TreeItem *p_item, int p_column, int p_idx, MouseButton p_button);
|
||||
|
||||
protected:
|
||||
virtual void _update_theme_item_cache() override;
|
||||
|
||||
void _notification(int p_what);
|
||||
static void _bind_methods();
|
||||
|
||||
public:
|
||||
void refresh_rpc_data();
|
||||
void refresh_replication_data();
|
||||
|
||||
Array pop_missing_node_data();
|
||||
void add_node_data(const NodeInfo &p_info);
|
||||
void add_rpc_frame_data(const RPCNodeInfo &p_frame);
|
||||
void add_sync_frame_data(const SyncInfo &p_frame);
|
||||
void set_bandwidth(int p_incoming, int p_outgoing);
|
||||
bool is_profiling();
|
||||
|
||||
void set_profiling(bool p_pressed);
|
||||
void started();
|
||||
void stopped();
|
||||
|
||||
EditorNetworkProfiler();
|
||||
};
|
180
modules/multiplayer/editor/multiplayer_editor_plugin.cpp
Normal file
180
modules/multiplayer/editor/multiplayer_editor_plugin.cpp
Normal file
@@ -0,0 +1,180 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_editor_plugin.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "multiplayer_editor_plugin.h"
|
||||
|
||||
#include "../multiplayer_synchronizer.h"
|
||||
#include "editor_network_profiler.h"
|
||||
#include "replication_editor.h"
|
||||
|
||||
#include "editor/editor_interface.h"
|
||||
#include "editor/editor_node.h"
|
||||
#include "editor/gui/editor_bottom_panel.h"
|
||||
#include "editor/settings/editor_command_palette.h"
|
||||
|
||||
void MultiplayerEditorDebugger::_bind_methods() {
|
||||
ADD_SIGNAL(MethodInfo("open_request", PropertyInfo(Variant::STRING, "path")));
|
||||
}
|
||||
|
||||
bool MultiplayerEditorDebugger::has_capture(const String &p_capture) const {
|
||||
return p_capture == "multiplayer";
|
||||
}
|
||||
|
||||
void MultiplayerEditorDebugger::_open_request(const String &p_path) {
|
||||
emit_signal("open_request", p_path);
|
||||
}
|
||||
|
||||
bool MultiplayerEditorDebugger::capture(const String &p_message, const Array &p_data, int p_session) {
|
||||
ERR_FAIL_COND_V(!profilers.has(p_session), false);
|
||||
EditorNetworkProfiler *profiler = profilers[p_session];
|
||||
if (p_message == "multiplayer:rpc") {
|
||||
MultiplayerDebugger::RPCFrame frame;
|
||||
frame.deserialize(p_data);
|
||||
for (int i = 0; i < frame.infos.size(); i++) {
|
||||
profiler->add_rpc_frame_data(frame.infos[i]);
|
||||
}
|
||||
return true;
|
||||
} else if (p_message == "multiplayer:syncs") {
|
||||
MultiplayerDebugger::ReplicationFrame frame;
|
||||
frame.deserialize(p_data);
|
||||
for (const KeyValue<ObjectID, MultiplayerDebugger::SyncInfo> &E : frame.infos) {
|
||||
profiler->add_sync_frame_data(E.value);
|
||||
}
|
||||
Array missing = profiler->pop_missing_node_data();
|
||||
if (missing.size()) {
|
||||
// Asks for the object information.
|
||||
get_session(p_session)->send_message("multiplayer:cache", missing);
|
||||
}
|
||||
return true;
|
||||
} else if (p_message == "multiplayer:cache") {
|
||||
ERR_FAIL_COND_V(p_data.size() % 3, false);
|
||||
for (int i = 0; i < p_data.size(); i += 3) {
|
||||
EditorNetworkProfiler::NodeInfo info;
|
||||
info.id = p_data[i].operator ObjectID();
|
||||
info.type = p_data[i + 1].operator String();
|
||||
info.path = p_data[i + 2].operator String();
|
||||
profiler->add_node_data(info);
|
||||
}
|
||||
return true;
|
||||
} else if (p_message == "multiplayer:bandwidth") {
|
||||
ERR_FAIL_COND_V(p_data.size() < 2, false);
|
||||
profiler->set_bandwidth(p_data[0], p_data[1]);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void MultiplayerEditorDebugger::_profiler_activate(bool p_enable, int p_session_id) {
|
||||
Ref<EditorDebuggerSession> session = get_session(p_session_id);
|
||||
ERR_FAIL_COND(session.is_null());
|
||||
session->toggle_profiler("multiplayer:bandwidth", p_enable);
|
||||
session->toggle_profiler("multiplayer:rpc", p_enable);
|
||||
session->toggle_profiler("multiplayer:replication", p_enable);
|
||||
}
|
||||
|
||||
void MultiplayerEditorDebugger::setup_session(int p_session_id) {
|
||||
Ref<EditorDebuggerSession> session = get_session(p_session_id);
|
||||
ERR_FAIL_COND(session.is_null());
|
||||
EditorNetworkProfiler *profiler = memnew(EditorNetworkProfiler);
|
||||
profiler->connect("enable_profiling", callable_mp(this, &MultiplayerEditorDebugger::_profiler_activate).bind(p_session_id));
|
||||
profiler->connect("open_request", callable_mp(this, &MultiplayerEditorDebugger::_open_request));
|
||||
profiler->set_name(TTR("Network Profiler"));
|
||||
session->connect("started", callable_mp(profiler, &EditorNetworkProfiler::started));
|
||||
session->connect("stopped", callable_mp(profiler, &EditorNetworkProfiler::stopped));
|
||||
session->add_session_tab(profiler);
|
||||
profilers[p_session_id] = profiler;
|
||||
}
|
||||
|
||||
/// MultiplayerEditorPlugin
|
||||
|
||||
MultiplayerEditorPlugin::MultiplayerEditorPlugin() {
|
||||
repl_editor = memnew(ReplicationEditor);
|
||||
button = EditorNode::get_bottom_panel()->add_item(TTRC("Replication"), repl_editor, ED_SHORTCUT_AND_COMMAND("bottom_panels/toggle_replication_bottom_panel", TTRC("Toggle Replication Bottom Panel")));
|
||||
button->hide();
|
||||
repl_editor->get_pin()->connect(SceneStringName(pressed), callable_mp(this, &MultiplayerEditorPlugin::_pinned));
|
||||
debugger.instantiate();
|
||||
debugger->connect("open_request", callable_mp(this, &MultiplayerEditorPlugin::_open_request));
|
||||
}
|
||||
|
||||
void MultiplayerEditorPlugin::_open_request(const String &p_path) {
|
||||
EditorInterface::get_singleton()->open_scene_from_path(p_path);
|
||||
}
|
||||
|
||||
void MultiplayerEditorPlugin::_notification(int p_what) {
|
||||
switch (p_what) {
|
||||
case NOTIFICATION_ENTER_TREE: {
|
||||
get_tree()->connect("node_removed", callable_mp(this, &MultiplayerEditorPlugin::_node_removed));
|
||||
add_debugger_plugin(debugger);
|
||||
} break;
|
||||
case NOTIFICATION_EXIT_TREE: {
|
||||
remove_debugger_plugin(debugger);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerEditorPlugin::_node_removed(Node *p_node) {
|
||||
if (p_node && p_node == repl_editor->get_current()) {
|
||||
repl_editor->edit(nullptr);
|
||||
if (repl_editor->is_visible_in_tree()) {
|
||||
EditorNode::get_bottom_panel()->hide_bottom_panel();
|
||||
}
|
||||
button->hide();
|
||||
repl_editor->get_pin()->set_pressed(false);
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerEditorPlugin::_pinned() {
|
||||
if (!repl_editor->get_pin()->is_pressed() && repl_editor->get_current() == nullptr) {
|
||||
if (repl_editor->is_visible_in_tree()) {
|
||||
EditorNode::get_bottom_panel()->hide_bottom_panel();
|
||||
}
|
||||
button->hide();
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerEditorPlugin::edit(Object *p_object) {
|
||||
repl_editor->edit(Object::cast_to<MultiplayerSynchronizer>(p_object));
|
||||
}
|
||||
|
||||
bool MultiplayerEditorPlugin::handles(Object *p_object) const {
|
||||
return p_object->is_class("MultiplayerSynchronizer");
|
||||
}
|
||||
|
||||
void MultiplayerEditorPlugin::make_visible(bool p_visible) {
|
||||
if (p_visible) {
|
||||
button->show();
|
||||
EditorNode::get_bottom_panel()->make_item_visible(repl_editor);
|
||||
} else if (!repl_editor->get_pin()->is_pressed()) {
|
||||
if (repl_editor->is_visible_in_tree()) {
|
||||
EditorNode::get_bottom_panel()->hide_bottom_panel();
|
||||
}
|
||||
button->hide();
|
||||
}
|
||||
}
|
79
modules/multiplayer/editor/multiplayer_editor_plugin.h
Normal file
79
modules/multiplayer/editor/multiplayer_editor_plugin.h
Normal file
@@ -0,0 +1,79 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_editor_plugin.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "editor/debugger/editor_debugger_plugin.h"
|
||||
#include "editor/plugins/editor_plugin.h"
|
||||
|
||||
class EditorNetworkProfiler;
|
||||
class MultiplayerEditorDebugger : public EditorDebuggerPlugin {
|
||||
GDCLASS(MultiplayerEditorDebugger, EditorDebuggerPlugin);
|
||||
|
||||
private:
|
||||
HashMap<int, EditorNetworkProfiler *> profilers;
|
||||
|
||||
void _open_request(const String &p_path);
|
||||
void _profiler_activate(bool p_enable, int p_session_id);
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
public:
|
||||
virtual bool has_capture(const String &p_capture) const override;
|
||||
virtual bool capture(const String &p_message, const Array &p_data, int p_index) override;
|
||||
virtual void setup_session(int p_session_id) override;
|
||||
};
|
||||
|
||||
class ReplicationEditor;
|
||||
|
||||
class MultiplayerEditorPlugin : public EditorPlugin {
|
||||
GDCLASS(MultiplayerEditorPlugin, EditorPlugin);
|
||||
|
||||
private:
|
||||
Button *button = nullptr;
|
||||
ReplicationEditor *repl_editor = nullptr;
|
||||
Ref<MultiplayerEditorDebugger> debugger;
|
||||
|
||||
void _open_request(const String &p_path);
|
||||
void _node_removed(Node *p_node);
|
||||
|
||||
void _pinned();
|
||||
|
||||
protected:
|
||||
void _notification(int p_what);
|
||||
|
||||
public:
|
||||
virtual void edit(Object *p_object) override;
|
||||
virtual bool handles(Object *p_object) const override;
|
||||
virtual void make_visible(bool p_visible) override;
|
||||
|
||||
MultiplayerEditorPlugin();
|
||||
};
|
589
modules/multiplayer/editor/replication_editor.cpp
Normal file
589
modules/multiplayer/editor/replication_editor.cpp
Normal file
@@ -0,0 +1,589 @@
|
||||
/**************************************************************************/
|
||||
/* replication_editor.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "replication_editor.h"
|
||||
|
||||
#include "../multiplayer_synchronizer.h"
|
||||
|
||||
#include "editor/editor_node.h"
|
||||
#include "editor/editor_string_names.h"
|
||||
#include "editor/editor_undo_redo_manager.h"
|
||||
#include "editor/inspector/property_selector.h"
|
||||
#include "editor/scene/scene_tree_editor.h"
|
||||
#include "editor/settings/editor_settings.h"
|
||||
#include "editor/themes/editor_scale.h"
|
||||
#include "editor/themes/editor_theme_manager.h"
|
||||
#include "scene/gui/dialogs.h"
|
||||
#include "scene/gui/line_edit.h"
|
||||
#include "scene/gui/separator.h"
|
||||
#include "scene/gui/tree.h"
|
||||
|
||||
void ReplicationEditor::_pick_node_filter_text_changed(const String &p_newtext) {
|
||||
TreeItem *root_item = pick_node->get_scene_tree()->get_scene_tree()->get_root();
|
||||
|
||||
Vector<Node *> select_candidates;
|
||||
Node *to_select = nullptr;
|
||||
|
||||
String filter = pick_node->get_filter_line_edit()->get_text();
|
||||
|
||||
_pick_node_select_recursive(root_item, filter, select_candidates);
|
||||
|
||||
if (!select_candidates.is_empty()) {
|
||||
for (int i = 0; i < select_candidates.size(); ++i) {
|
||||
Node *candidate = select_candidates[i];
|
||||
|
||||
if (((String)candidate->get_name()).to_lower().begins_with(filter.to_lower())) {
|
||||
to_select = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!to_select) {
|
||||
to_select = select_candidates[0];
|
||||
}
|
||||
}
|
||||
|
||||
pick_node->get_scene_tree()->set_selected(to_select);
|
||||
}
|
||||
|
||||
void ReplicationEditor::_pick_node_select_recursive(TreeItem *p_item, const String &p_filter, Vector<Node *> &p_select_candidates) {
|
||||
if (!p_item) {
|
||||
return;
|
||||
}
|
||||
|
||||
NodePath np = p_item->get_metadata(0);
|
||||
Node *node = get_node(np);
|
||||
|
||||
if (!p_filter.is_empty() && ((String)node->get_name()).containsn(p_filter)) {
|
||||
p_select_candidates.push_back(node);
|
||||
}
|
||||
|
||||
TreeItem *c = p_item->get_first_child();
|
||||
|
||||
while (c) {
|
||||
_pick_node_select_recursive(c, p_filter, p_select_candidates);
|
||||
c = c->get_next();
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicationEditor::_pick_node_selected(NodePath p_path) {
|
||||
Node *root = current->get_node(current->get_root_path());
|
||||
ERR_FAIL_NULL(root);
|
||||
Node *node = get_node(p_path);
|
||||
ERR_FAIL_NULL(node);
|
||||
NodePath path_to = root->get_path_to(node);
|
||||
adding_node_path = path_to;
|
||||
prop_selector->select_property_from_instance(node);
|
||||
}
|
||||
|
||||
void ReplicationEditor::_pick_new_property() {
|
||||
if (current == nullptr) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Select a replicator node in order to pick a property to add to it."));
|
||||
return;
|
||||
}
|
||||
Node *root = current->get_node(current->get_root_path());
|
||||
if (!root) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Not possible to add a new property to synchronize without a root."));
|
||||
return;
|
||||
}
|
||||
pick_node->popup_scenetree_dialog(nullptr, current);
|
||||
pick_node->get_filter_line_edit()->clear();
|
||||
pick_node->get_filter_line_edit()->grab_focus();
|
||||
}
|
||||
|
||||
void ReplicationEditor::_add_sync_property(String p_path) {
|
||||
config = current->get_replication_config();
|
||||
|
||||
if (config.is_valid() && config->has_property(p_path)) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Property is already being synchronized."));
|
||||
return;
|
||||
}
|
||||
|
||||
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
|
||||
undo_redo->create_action(TTR("Add property to synchronizer"));
|
||||
|
||||
if (config.is_null()) {
|
||||
config.instantiate();
|
||||
current->set_replication_config(config);
|
||||
undo_redo->add_do_method(current, "set_replication_config", config);
|
||||
undo_redo->add_undo_method(current, "set_replication_config", Ref<SceneReplicationConfig>());
|
||||
_update_config();
|
||||
}
|
||||
|
||||
undo_redo->add_do_method(config.ptr(), "add_property", p_path);
|
||||
undo_redo->add_undo_method(config.ptr(), "remove_property", p_path);
|
||||
undo_redo->add_do_method(this, "_update_config");
|
||||
undo_redo->add_undo_method(this, "_update_config");
|
||||
undo_redo->commit_action();
|
||||
}
|
||||
|
||||
void ReplicationEditor::_pick_node_property_selected(String p_name) {
|
||||
String adding_prop_path = String(adding_node_path) + ":" + p_name;
|
||||
|
||||
_add_sync_property(adding_prop_path);
|
||||
}
|
||||
|
||||
/// ReplicationEditor
|
||||
ReplicationEditor::ReplicationEditor() {
|
||||
set_v_size_flags(SIZE_EXPAND_FILL);
|
||||
set_custom_minimum_size(Size2(0, 200) * EDSCALE);
|
||||
|
||||
delete_dialog = memnew(ConfirmationDialog);
|
||||
delete_dialog->connect("canceled", callable_mp(this, &ReplicationEditor::_dialog_closed).bind(false));
|
||||
delete_dialog->connect(SceneStringName(confirmed), callable_mp(this, &ReplicationEditor::_dialog_closed).bind(true));
|
||||
add_child(delete_dialog);
|
||||
|
||||
VBoxContainer *vb = memnew(VBoxContainer);
|
||||
vb->set_v_size_flags(SIZE_EXPAND_FILL);
|
||||
add_child(vb);
|
||||
|
||||
pick_node = memnew(SceneTreeDialog);
|
||||
add_child(pick_node);
|
||||
pick_node->set_title(TTR("Pick a node to synchronize:"));
|
||||
pick_node->connect("selected", callable_mp(this, &ReplicationEditor::_pick_node_selected));
|
||||
pick_node->get_filter_line_edit()->connect(SceneStringName(text_changed), callable_mp(this, &ReplicationEditor::_pick_node_filter_text_changed));
|
||||
|
||||
prop_selector = memnew(PropertySelector);
|
||||
add_child(prop_selector);
|
||||
// Filter out properties that cannot be synchronized.
|
||||
// * RIDs do not match across network.
|
||||
// * Objects are too large for replication.
|
||||
Vector<Variant::Type> types = {
|
||||
Variant::BOOL,
|
||||
Variant::INT,
|
||||
Variant::FLOAT,
|
||||
Variant::STRING,
|
||||
|
||||
Variant::VECTOR2,
|
||||
Variant::VECTOR2I,
|
||||
Variant::RECT2,
|
||||
Variant::RECT2I,
|
||||
Variant::VECTOR3,
|
||||
Variant::VECTOR3I,
|
||||
Variant::TRANSFORM2D,
|
||||
Variant::VECTOR4,
|
||||
Variant::VECTOR4I,
|
||||
Variant::PLANE,
|
||||
Variant::QUATERNION,
|
||||
Variant::AABB,
|
||||
Variant::BASIS,
|
||||
Variant::TRANSFORM3D,
|
||||
Variant::PROJECTION,
|
||||
|
||||
Variant::COLOR,
|
||||
Variant::STRING_NAME,
|
||||
Variant::NODE_PATH,
|
||||
// Variant::RID,
|
||||
// Variant::OBJECT,
|
||||
Variant::SIGNAL,
|
||||
Variant::DICTIONARY,
|
||||
Variant::ARRAY,
|
||||
|
||||
Variant::PACKED_BYTE_ARRAY,
|
||||
Variant::PACKED_INT32_ARRAY,
|
||||
Variant::PACKED_INT64_ARRAY,
|
||||
Variant::PACKED_FLOAT32_ARRAY,
|
||||
Variant::PACKED_FLOAT64_ARRAY,
|
||||
Variant::PACKED_STRING_ARRAY,
|
||||
Variant::PACKED_VECTOR2_ARRAY,
|
||||
Variant::PACKED_VECTOR3_ARRAY,
|
||||
Variant::PACKED_COLOR_ARRAY,
|
||||
Variant::PACKED_VECTOR4_ARRAY,
|
||||
};
|
||||
prop_selector->set_type_filter(types);
|
||||
prop_selector->connect("selected", callable_mp(this, &ReplicationEditor::_pick_node_property_selected));
|
||||
|
||||
HBoxContainer *hb = memnew(HBoxContainer);
|
||||
vb->add_child(hb);
|
||||
|
||||
add_pick_button = memnew(Button);
|
||||
add_pick_button->connect(SceneStringName(pressed), callable_mp(this, &ReplicationEditor::_pick_new_property));
|
||||
add_pick_button->set_text(TTR("Add property to sync..."));
|
||||
hb->add_child(add_pick_button);
|
||||
|
||||
VSeparator *vs = memnew(VSeparator);
|
||||
vs->set_custom_minimum_size(Size2(30 * EDSCALE, 0));
|
||||
hb->add_child(vs);
|
||||
hb->add_child(memnew(Label(TTR("Path:"))));
|
||||
|
||||
np_line_edit = memnew(LineEdit);
|
||||
np_line_edit->set_placeholder(":property");
|
||||
np_line_edit->set_accessibility_name(TTRC("Path:"));
|
||||
np_line_edit->set_h_size_flags(SIZE_EXPAND_FILL);
|
||||
np_line_edit->connect(SceneStringName(text_submitted), callable_mp(this, &ReplicationEditor::_np_text_submitted));
|
||||
hb->add_child(np_line_edit);
|
||||
|
||||
add_from_path_button = memnew(Button);
|
||||
add_from_path_button->connect(SceneStringName(pressed), callable_mp(this, &ReplicationEditor::_add_pressed));
|
||||
add_from_path_button->set_text(TTR("Add from path"));
|
||||
hb->add_child(add_from_path_button);
|
||||
|
||||
vs = memnew(VSeparator);
|
||||
vs->set_custom_minimum_size(Size2(30 * EDSCALE, 0));
|
||||
hb->add_child(vs);
|
||||
|
||||
pin = memnew(Button);
|
||||
pin->set_theme_type_variation(SceneStringName(FlatButton));
|
||||
pin->set_toggle_mode(true);
|
||||
pin->set_tooltip_text(TTR("Pin replication editor"));
|
||||
hb->add_child(pin);
|
||||
|
||||
tree = memnew(Tree);
|
||||
tree->set_hide_root(true);
|
||||
tree->set_columns(4);
|
||||
tree->set_column_titles_visible(true);
|
||||
tree->set_column_title(0, TTR("Properties"));
|
||||
tree->set_column_expand(0, true);
|
||||
tree->set_column_title(1, TTR("Spawn"));
|
||||
tree->set_column_expand(1, false);
|
||||
tree->set_column_custom_minimum_width(1, 100);
|
||||
tree->set_column_title(2, TTR("Replicate"));
|
||||
tree->set_column_custom_minimum_width(2, 100);
|
||||
tree->set_column_expand(2, false);
|
||||
tree->set_column_expand(3, false);
|
||||
tree->create_item();
|
||||
tree->connect("button_clicked", callable_mp(this, &ReplicationEditor::_tree_button_pressed));
|
||||
tree->connect("item_edited", callable_mp(this, &ReplicationEditor::_tree_item_edited));
|
||||
tree->set_v_size_flags(SIZE_EXPAND_FILL);
|
||||
vb->add_child(tree);
|
||||
|
||||
drop_label = memnew(Label);
|
||||
drop_label->set_focus_mode(FOCUS_ACCESSIBILITY);
|
||||
drop_label->set_text(TTR("Add properties using the options above, or\ndrag them from the inspector and drop them here."));
|
||||
drop_label->set_horizontal_alignment(HORIZONTAL_ALIGNMENT_CENTER);
|
||||
drop_label->set_vertical_alignment(VERTICAL_ALIGNMENT_CENTER);
|
||||
tree->add_child(drop_label);
|
||||
drop_label->set_anchors_and_offsets_preset(Control::PRESET_FULL_RECT);
|
||||
|
||||
SET_DRAG_FORWARDING_CDU(tree, ReplicationEditor);
|
||||
}
|
||||
|
||||
void ReplicationEditor::_bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("_update_config"), &ReplicationEditor::_update_config);
|
||||
ClassDB::bind_method(D_METHOD("_update_value", "property", "column", "value"), &ReplicationEditor::_update_value);
|
||||
}
|
||||
|
||||
bool ReplicationEditor::_can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const {
|
||||
Dictionary d = p_data;
|
||||
if (!d.has("type")) {
|
||||
return false;
|
||||
}
|
||||
String t = d["type"];
|
||||
if (t != "obj_property") {
|
||||
return false;
|
||||
}
|
||||
Object *obj = d["object"];
|
||||
if (!obj) {
|
||||
return false;
|
||||
}
|
||||
Node *node = Object::cast_to<Node>(obj);
|
||||
if (!node) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void ReplicationEditor::_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) {
|
||||
if (current == nullptr) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Select a replicator node in order to pick a property to add to it."));
|
||||
return;
|
||||
}
|
||||
Node *root = current->get_node(current->get_root_path());
|
||||
if (!root) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Not possible to add a new property to synchronize without a root."));
|
||||
return;
|
||||
}
|
||||
|
||||
Dictionary d = p_data;
|
||||
if (!d.has("type")) {
|
||||
return;
|
||||
}
|
||||
String t = d["type"];
|
||||
if (t != "obj_property") {
|
||||
return;
|
||||
}
|
||||
Object *obj = d["object"];
|
||||
if (!obj) {
|
||||
return;
|
||||
}
|
||||
Node *node = Object::cast_to<Node>(obj);
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
|
||||
String path = String(root->get_path_to(node));
|
||||
path += ":" + String(d["property"]);
|
||||
|
||||
_add_sync_property(path);
|
||||
}
|
||||
|
||||
void ReplicationEditor::_notification(int p_what) {
|
||||
switch (p_what) {
|
||||
case EditorSettings::NOTIFICATION_EDITOR_SETTINGS_CHANGED: {
|
||||
if (!EditorThemeManager::is_generated_theme_outdated()) {
|
||||
break;
|
||||
}
|
||||
[[fallthrough]];
|
||||
}
|
||||
case NOTIFICATION_ENTER_TREE: {
|
||||
add_theme_style_override(SceneStringName(panel), EditorNode::get_singleton()->get_editor_theme()->get_stylebox(SceneStringName(panel), SNAME("Panel")));
|
||||
add_pick_button->set_button_icon(get_theme_icon(SNAME("Add"), EditorStringName(EditorIcons)));
|
||||
pin->set_button_icon(get_theme_icon(SNAME("Pin"), EditorStringName(EditorIcons)));
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicationEditor::_add_pressed() {
|
||||
if (!current) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Please select a MultiplayerSynchronizer first."));
|
||||
return;
|
||||
}
|
||||
if (current->get_root_path().is_empty()) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("The MultiplayerSynchronizer needs a root path."));
|
||||
return;
|
||||
}
|
||||
String np_text = np_line_edit->get_text();
|
||||
|
||||
if (np_text.is_empty()) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Property/path must not be empty."));
|
||||
return;
|
||||
}
|
||||
|
||||
int idx = np_text.find_char(':');
|
||||
if (idx == -1) {
|
||||
np_text = ".:" + np_text;
|
||||
} else if (idx == 0) {
|
||||
np_text = "." + np_text;
|
||||
}
|
||||
NodePath path = NodePath(np_text);
|
||||
if (path.is_empty()) {
|
||||
EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid property path: '%s'"), np_text));
|
||||
return;
|
||||
}
|
||||
|
||||
_add_sync_property(String(path));
|
||||
}
|
||||
|
||||
void ReplicationEditor::_np_text_submitted(const String &p_newtext) {
|
||||
_add_pressed();
|
||||
}
|
||||
|
||||
void ReplicationEditor::_tree_item_edited() {
|
||||
TreeItem *ti = tree->get_edited();
|
||||
if (!ti || config.is_null()) {
|
||||
return;
|
||||
}
|
||||
int column = tree->get_edited_column();
|
||||
ERR_FAIL_COND(column < 1 || column > 2);
|
||||
const NodePath prop = ti->get_metadata(0);
|
||||
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
|
||||
|
||||
if (column == 1) {
|
||||
undo_redo->create_action(TTR("Set spawn property"));
|
||||
bool value = ti->is_checked(column);
|
||||
undo_redo->add_do_method(config.ptr(), "property_set_spawn", prop, value);
|
||||
undo_redo->add_undo_method(config.ptr(), "property_set_spawn", prop, !value);
|
||||
undo_redo->add_do_method(this, "_update_value", prop, column, value ? 1 : 0);
|
||||
undo_redo->add_undo_method(this, "_update_value", prop, column, value ? 0 : 1);
|
||||
undo_redo->commit_action();
|
||||
} else if (column == 2) {
|
||||
undo_redo->create_action(TTR("Set sync property"));
|
||||
int value = ti->get_range(column);
|
||||
int old_value = config->property_get_replication_mode(prop);
|
||||
// We have a hard limit of 64 watchable properties per synchronizer.
|
||||
if (value == SceneReplicationConfig::REPLICATION_MODE_ON_CHANGE && config->get_watch_properties().size() >= 64) {
|
||||
EditorNode::get_singleton()->show_warning(TTR("Each MultiplayerSynchronizer can have no more than 64 watched properties."));
|
||||
ti->set_range(column, old_value);
|
||||
return;
|
||||
}
|
||||
undo_redo->add_do_method(config.ptr(), "property_set_replication_mode", prop, value);
|
||||
undo_redo->add_undo_method(config.ptr(), "property_set_replication_mode", prop, old_value);
|
||||
undo_redo->add_do_method(this, "_update_value", prop, column, value);
|
||||
undo_redo->add_undo_method(this, "_update_value", prop, column, old_value);
|
||||
undo_redo->commit_action();
|
||||
} else {
|
||||
ERR_FAIL();
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicationEditor::_tree_button_pressed(Object *p_item, int p_column, int p_id, MouseButton p_button) {
|
||||
if (p_button != MouseButton::LEFT) {
|
||||
return;
|
||||
}
|
||||
|
||||
TreeItem *ti = Object::cast_to<TreeItem>(p_item);
|
||||
if (!ti) {
|
||||
return;
|
||||
}
|
||||
deleting = ti->get_metadata(0);
|
||||
delete_dialog->set_text(TTR("Delete Property?") + "\n\"" + ti->get_text(0) + "\"");
|
||||
delete_dialog->popup_centered();
|
||||
}
|
||||
|
||||
void ReplicationEditor::_dialog_closed(bool p_confirmed) {
|
||||
if (deleting.is_empty() || config.is_null()) {
|
||||
return;
|
||||
}
|
||||
if (p_confirmed) {
|
||||
const NodePath prop = deleting;
|
||||
int idx = config->property_get_index(prop);
|
||||
bool spawn = config->property_get_spawn(prop);
|
||||
SceneReplicationConfig::ReplicationMode mode = config->property_get_replication_mode(prop);
|
||||
EditorUndoRedoManager *undo_redo = EditorUndoRedoManager::get_singleton();
|
||||
undo_redo->create_action(TTR("Remove Property"));
|
||||
undo_redo->add_do_method(config.ptr(), "remove_property", prop);
|
||||
undo_redo->add_undo_method(config.ptr(), "add_property", prop, idx);
|
||||
undo_redo->add_undo_method(config.ptr(), "property_set_spawn", prop, spawn);
|
||||
undo_redo->add_undo_method(config.ptr(), "property_set_replication_mode", prop, mode);
|
||||
undo_redo->add_do_method(this, "_update_config");
|
||||
undo_redo->add_undo_method(this, "_update_config");
|
||||
undo_redo->commit_action();
|
||||
}
|
||||
deleting = NodePath();
|
||||
}
|
||||
|
||||
void ReplicationEditor::_update_value(const NodePath &p_prop, int p_column, int p_value) {
|
||||
if (!tree->get_root()) {
|
||||
return;
|
||||
}
|
||||
TreeItem *ti = tree->get_root()->get_first_child();
|
||||
while (ti) {
|
||||
if (ti->get_metadata(0).operator NodePath() == p_prop) {
|
||||
if (p_column == 1) {
|
||||
ti->set_checked(p_column, p_value != 0);
|
||||
} else if (p_column == 2) {
|
||||
ti->set_range(p_column, p_value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
ti = ti->get_next();
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicationEditor::_update_config() {
|
||||
deleting = NodePath();
|
||||
tree->clear();
|
||||
tree->create_item();
|
||||
drop_label->set_visible(true);
|
||||
if (config.is_null()) {
|
||||
return;
|
||||
}
|
||||
TypedArray<NodePath> props = config->get_properties();
|
||||
if (props.size()) {
|
||||
drop_label->set_visible(false);
|
||||
}
|
||||
for (int i = 0; i < props.size(); i++) {
|
||||
const NodePath path = props[i];
|
||||
_add_property(path, config->property_get_spawn(path), config->property_get_replication_mode(path));
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicationEditor::edit(MultiplayerSynchronizer *p_sync) {
|
||||
if (current == p_sync) {
|
||||
return;
|
||||
}
|
||||
current = p_sync;
|
||||
if (current) {
|
||||
config = current->get_replication_config();
|
||||
} else {
|
||||
config.unref();
|
||||
}
|
||||
_update_config();
|
||||
}
|
||||
|
||||
Ref<Texture2D> ReplicationEditor::_get_class_icon(const Node *p_node) {
|
||||
if (!p_node || !has_theme_icon(p_node->get_class(), EditorStringName(EditorIcons))) {
|
||||
return get_theme_icon(SNAME("ImportFail"), EditorStringName(EditorIcons));
|
||||
}
|
||||
return get_theme_icon(p_node->get_class(), EditorStringName(EditorIcons));
|
||||
}
|
||||
|
||||
static bool can_sync(const Variant &p_var) {
|
||||
switch (p_var.get_type()) {
|
||||
case Variant::RID:
|
||||
case Variant::OBJECT:
|
||||
return false;
|
||||
case Variant::ARRAY: {
|
||||
const Array &arr = p_var;
|
||||
if (arr.is_typed()) {
|
||||
const uint32_t type = arr.get_typed_builtin();
|
||||
return (type != Variant::RID) && (type != Variant::OBJECT);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
void ReplicationEditor::_add_property(const NodePath &p_property, bool p_spawn, SceneReplicationConfig::ReplicationMode p_mode) {
|
||||
String prop = String(p_property);
|
||||
TreeItem *item = tree->create_item();
|
||||
item->set_selectable(0, false);
|
||||
item->set_selectable(1, false);
|
||||
item->set_selectable(2, false);
|
||||
item->set_selectable(3, false);
|
||||
item->set_text(0, prop);
|
||||
item->set_metadata(0, prop);
|
||||
Node *root_node = current && !current->get_root_path().is_empty() ? current->get_node(current->get_root_path()) : nullptr;
|
||||
Ref<Texture2D> icon = _get_class_icon(root_node);
|
||||
if (root_node) {
|
||||
String path = prop.substr(0, prop.find_char(':'));
|
||||
String subpath = prop.substr(path.size());
|
||||
Node *node = root_node->get_node_or_null(path);
|
||||
if (!node) {
|
||||
node = root_node;
|
||||
}
|
||||
item->set_text(0, String(node->get_name()) + ":" + subpath);
|
||||
icon = _get_class_icon(node);
|
||||
bool valid = false;
|
||||
Variant value = node->get(subpath, &valid);
|
||||
if (valid && !can_sync(value)) {
|
||||
item->set_icon(0, get_theme_icon(SNAME("StatusWarning"), EditorStringName(EditorIcons)));
|
||||
item->set_tooltip_text(0, TTR("Property of this type not supported."));
|
||||
} else {
|
||||
item->set_icon(0, icon);
|
||||
}
|
||||
} else {
|
||||
item->set_icon(0, icon);
|
||||
}
|
||||
item->add_button(3, get_theme_icon(SNAME("Remove"), EditorStringName(EditorIcons)));
|
||||
item->set_text_alignment(1, HORIZONTAL_ALIGNMENT_CENTER);
|
||||
item->set_cell_mode(1, TreeItem::CELL_MODE_CHECK);
|
||||
item->set_checked(1, p_spawn);
|
||||
item->set_editable(1, true);
|
||||
item->set_text_alignment(2, HORIZONTAL_ALIGNMENT_CENTER);
|
||||
item->set_cell_mode(2, TreeItem::CELL_MODE_RANGE);
|
||||
item->set_range_config(2, 0, 2, 1);
|
||||
item->set_text(2, TTR("Never", "Replication Mode") + "," + TTR("Always", "Replication Mode") + "," + TTR("On Change", "Replication Mode"));
|
||||
item->set_range(2, (int)p_mode);
|
||||
item->set_editable(2, true);
|
||||
}
|
104
modules/multiplayer/editor/replication_editor.h
Normal file
104
modules/multiplayer/editor/replication_editor.h
Normal file
@@ -0,0 +1,104 @@
|
||||
/**************************************************************************/
|
||||
/* replication_editor.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "../scene_replication_config.h"
|
||||
|
||||
#include "editor/plugins/editor_plugin.h"
|
||||
#include "scene/gui/box_container.h"
|
||||
|
||||
class ConfirmationDialog;
|
||||
class MultiplayerSynchronizer;
|
||||
class AcceptDialog;
|
||||
class LineEdit;
|
||||
class Tree;
|
||||
class TreeItem;
|
||||
class PropertySelector;
|
||||
class SceneTreeDialog;
|
||||
|
||||
class ReplicationEditor : public VBoxContainer {
|
||||
GDCLASS(ReplicationEditor, VBoxContainer);
|
||||
|
||||
private:
|
||||
MultiplayerSynchronizer *current = nullptr;
|
||||
|
||||
ConfirmationDialog *delete_dialog = nullptr;
|
||||
Button *add_pick_button = nullptr;
|
||||
Button *add_from_path_button = nullptr;
|
||||
LineEdit *np_line_edit = nullptr;
|
||||
|
||||
Label *drop_label = nullptr;
|
||||
|
||||
Ref<SceneReplicationConfig> config;
|
||||
NodePath deleting;
|
||||
Tree *tree = nullptr;
|
||||
|
||||
PropertySelector *prop_selector = nullptr;
|
||||
SceneTreeDialog *pick_node = nullptr;
|
||||
NodePath adding_node_path;
|
||||
|
||||
Button *pin = nullptr;
|
||||
|
||||
Ref<Texture2D> _get_class_icon(const Node *p_node);
|
||||
|
||||
void _add_pressed();
|
||||
void _np_text_submitted(const String &p_newtext);
|
||||
void _tree_item_edited();
|
||||
void _tree_button_pressed(Object *p_item, int p_column, int p_id, MouseButton p_button);
|
||||
void _update_value(const NodePath &p_prop, int p_column, int p_checked);
|
||||
void _update_config();
|
||||
void _dialog_closed(bool p_confirmed);
|
||||
void _add_property(const NodePath &p_property, bool p_spawn, SceneReplicationConfig::ReplicationMode p_mode);
|
||||
|
||||
void _pick_node_filter_text_changed(const String &p_newtext);
|
||||
void _pick_node_select_recursive(TreeItem *p_item, const String &p_filter, Vector<Node *> &p_select_candidates);
|
||||
void _pick_node_selected(NodePath p_path);
|
||||
|
||||
void _pick_new_property();
|
||||
void _pick_node_property_selected(String p_name);
|
||||
|
||||
bool _can_drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from) const;
|
||||
void _drop_data_fw(const Point2 &p_point, const Variant &p_data, Control *p_from);
|
||||
|
||||
void _add_sync_property(String p_path);
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
void _notification(int p_what);
|
||||
|
||||
public:
|
||||
void edit(MultiplayerSynchronizer *p_object);
|
||||
MultiplayerSynchronizer *get_current() const { return current; }
|
||||
|
||||
Button *get_pin() { return pin; }
|
||||
ReplicationEditor();
|
||||
};
|
329
modules/multiplayer/multiplayer_debugger.cpp
Normal file
329
modules/multiplayer/multiplayer_debugger.cpp
Normal file
@@ -0,0 +1,329 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_debugger.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "multiplayer_debugger.h"
|
||||
|
||||
#include "multiplayer_synchronizer.h"
|
||||
#include "scene_replication_config.h"
|
||||
|
||||
#include "core/debugger/engine_debugger.h"
|
||||
#include "scene/main/node.h"
|
||||
|
||||
List<Ref<EngineProfiler>> multiplayer_profilers;
|
||||
|
||||
void MultiplayerDebugger::initialize() {
|
||||
Ref<BandwidthProfiler> bandwidth;
|
||||
bandwidth.instantiate();
|
||||
bandwidth->bind("multiplayer:bandwidth");
|
||||
multiplayer_profilers.push_back(bandwidth);
|
||||
|
||||
Ref<RPCProfiler> rpc_profiler;
|
||||
rpc_profiler.instantiate();
|
||||
rpc_profiler->bind("multiplayer:rpc");
|
||||
multiplayer_profilers.push_back(rpc_profiler);
|
||||
|
||||
Ref<ReplicationProfiler> replication_profiler;
|
||||
replication_profiler.instantiate();
|
||||
replication_profiler->bind("multiplayer:replication");
|
||||
multiplayer_profilers.push_back(replication_profiler);
|
||||
|
||||
EngineDebugger::register_message_capture("multiplayer", EngineDebugger::Capture(nullptr, &_capture));
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::deinitialize() {
|
||||
multiplayer_profilers.clear();
|
||||
}
|
||||
|
||||
Error MultiplayerDebugger::_capture(void *p_user, const String &p_msg, const Array &p_args, bool &r_captured) {
|
||||
if (p_msg == "cache") {
|
||||
Array out;
|
||||
for (int i = 0; i < p_args.size(); i++) {
|
||||
ObjectID id = p_args[i].operator ObjectID();
|
||||
Object *obj = ObjectDB::get_instance(id);
|
||||
ERR_CONTINUE(!obj);
|
||||
if (Object::cast_to<SceneReplicationConfig>(obj)) {
|
||||
out.push_back(id);
|
||||
out.push_back(obj->get_class());
|
||||
out.push_back(((SceneReplicationConfig *)obj)->get_path());
|
||||
} else if (Object::cast_to<Node>(obj)) {
|
||||
out.push_back(id);
|
||||
out.push_back(obj->get_class());
|
||||
out.push_back(String(((Node *)obj)->get_path()));
|
||||
} else {
|
||||
ERR_FAIL_V(FAILED);
|
||||
}
|
||||
}
|
||||
EngineDebugger::get_singleton()->send_message("multiplayer:cache", out);
|
||||
return OK;
|
||||
}
|
||||
ERR_FAIL_V(FAILED);
|
||||
}
|
||||
|
||||
// BandwidthProfiler
|
||||
|
||||
int MultiplayerDebugger::BandwidthProfiler::bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer) {
|
||||
ERR_FAIL_COND_V(p_buffer.is_empty(), 0);
|
||||
int total_bandwidth = 0;
|
||||
|
||||
uint64_t timestamp = OS::get_singleton()->get_ticks_msec();
|
||||
uint64_t final_timestamp = timestamp - 1000;
|
||||
|
||||
int i = (p_pointer + p_buffer.size() - 1) % p_buffer.size();
|
||||
|
||||
while (i != p_pointer && p_buffer[i].packet_size > 0) {
|
||||
if (p_buffer[i].timestamp < final_timestamp) {
|
||||
return total_bandwidth;
|
||||
}
|
||||
total_bandwidth += p_buffer[i].packet_size;
|
||||
i = (i + p_buffer.size() - 1) % p_buffer.size();
|
||||
}
|
||||
|
||||
ERR_FAIL_COND_V_MSG(i == p_pointer, total_bandwidth, "Reached the end of the bandwidth profiler buffer, values might be inaccurate.");
|
||||
return total_bandwidth;
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::BandwidthProfiler::toggle(bool p_enable, const Array &p_opts) {
|
||||
if (!p_enable) {
|
||||
bandwidth_in.clear();
|
||||
bandwidth_out.clear();
|
||||
} else {
|
||||
bandwidth_in_ptr = 0;
|
||||
bandwidth_in.resize(16384); // ~128kB
|
||||
for (int i = 0; i < bandwidth_in.size(); ++i) {
|
||||
bandwidth_in.write[i].packet_size = -1;
|
||||
}
|
||||
bandwidth_out_ptr = 0;
|
||||
bandwidth_out.resize(16384); // ~128kB
|
||||
for (int i = 0; i < bandwidth_out.size(); ++i) {
|
||||
bandwidth_out.write[i].packet_size = -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::BandwidthProfiler::add(const Array &p_data) {
|
||||
ERR_FAIL_COND(p_data.size() < 3);
|
||||
const String inout = p_data[0];
|
||||
int time = p_data[1];
|
||||
int size = p_data[2];
|
||||
if (inout == "in") {
|
||||
bandwidth_in.write[bandwidth_in_ptr].timestamp = time;
|
||||
bandwidth_in.write[bandwidth_in_ptr].packet_size = size;
|
||||
bandwidth_in_ptr = (bandwidth_in_ptr + 1) % bandwidth_in.size();
|
||||
} else if (inout == "out") {
|
||||
bandwidth_out.write[bandwidth_out_ptr].timestamp = time;
|
||||
bandwidth_out.write[bandwidth_out_ptr].packet_size = size;
|
||||
bandwidth_out_ptr = (bandwidth_out_ptr + 1) % bandwidth_out.size();
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::BandwidthProfiler::tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) {
|
||||
uint64_t pt = OS::get_singleton()->get_ticks_msec();
|
||||
if (pt - last_bandwidth_time > 200) {
|
||||
last_bandwidth_time = pt;
|
||||
int incoming_bandwidth = bandwidth_usage(bandwidth_in, bandwidth_in_ptr);
|
||||
int outgoing_bandwidth = bandwidth_usage(bandwidth_out, bandwidth_out_ptr);
|
||||
|
||||
Array arr = { incoming_bandwidth, outgoing_bandwidth };
|
||||
EngineDebugger::get_singleton()->send_message("multiplayer:bandwidth", arr);
|
||||
}
|
||||
}
|
||||
|
||||
// RPCProfiler
|
||||
|
||||
Array MultiplayerDebugger::RPCFrame::serialize() {
|
||||
Array arr = { infos.size() * 6 };
|
||||
for (int i = 0; i < infos.size(); ++i) {
|
||||
arr.push_back(uint64_t(infos[i].node));
|
||||
arr.push_back(infos[i].node_path);
|
||||
arr.push_back(infos[i].incoming_rpc);
|
||||
arr.push_back(infos[i].incoming_size);
|
||||
arr.push_back(infos[i].outgoing_rpc);
|
||||
arr.push_back(infos[i].outgoing_size);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
bool MultiplayerDebugger::RPCFrame::deserialize(const Array &p_arr) {
|
||||
ERR_FAIL_COND_V(p_arr.is_empty(), false);
|
||||
uint32_t size = p_arr[0];
|
||||
ERR_FAIL_COND_V(size % 6, false);
|
||||
ERR_FAIL_COND_V((uint32_t)p_arr.size() != size + 1, false);
|
||||
infos.resize(size / 6);
|
||||
int idx = 1;
|
||||
for (uint32_t i = 0; i < size / 6; i++) {
|
||||
infos.write[i].node = uint64_t(p_arr[idx]);
|
||||
infos.write[i].node_path = p_arr[idx + 1];
|
||||
infos.write[i].incoming_rpc = p_arr[idx + 2];
|
||||
infos.write[i].incoming_size = p_arr[idx + 3];
|
||||
infos.write[i].outgoing_rpc = p_arr[idx + 4];
|
||||
infos.write[i].outgoing_size = p_arr[idx + 5];
|
||||
idx += 6;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::RPCProfiler::init_node(const ObjectID p_node) {
|
||||
if (rpc_node_data.has(p_node)) {
|
||||
return;
|
||||
}
|
||||
rpc_node_data.insert(p_node, RPCNodeInfo());
|
||||
rpc_node_data[p_node].node = p_node;
|
||||
rpc_node_data[p_node].node_path = String(ObjectDB::get_instance<Node>(p_node)->get_path());
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::RPCProfiler::toggle(bool p_enable, const Array &p_opts) {
|
||||
rpc_node_data.clear();
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::RPCProfiler::add(const Array &p_data) {
|
||||
ERR_FAIL_COND(p_data.size() != 3);
|
||||
const String what = p_data[0];
|
||||
const ObjectID id = p_data[1];
|
||||
const int size = p_data[2];
|
||||
init_node(id);
|
||||
RPCNodeInfo &info = rpc_node_data[id];
|
||||
if (what == "rpc_in") {
|
||||
info.incoming_rpc++;
|
||||
info.incoming_size += size;
|
||||
} else if (what == "rpc_out") {
|
||||
info.outgoing_rpc++;
|
||||
info.outgoing_size += size;
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::RPCProfiler::tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) {
|
||||
uint64_t pt = OS::get_singleton()->get_ticks_msec();
|
||||
if (pt - last_profile_time > 100) {
|
||||
last_profile_time = pt;
|
||||
RPCFrame frame;
|
||||
for (const KeyValue<ObjectID, RPCNodeInfo> &E : rpc_node_data) {
|
||||
frame.infos.push_back(E.value);
|
||||
}
|
||||
rpc_node_data.clear();
|
||||
EngineDebugger::get_singleton()->send_message("multiplayer:rpc", frame.serialize());
|
||||
}
|
||||
}
|
||||
|
||||
// ReplicationProfiler
|
||||
|
||||
MultiplayerDebugger::SyncInfo::SyncInfo(MultiplayerSynchronizer *p_sync) {
|
||||
ERR_FAIL_NULL(p_sync);
|
||||
synchronizer = p_sync->get_instance_id();
|
||||
if (p_sync->get_replication_config_ptr()) {
|
||||
config = p_sync->get_replication_config_ptr()->get_instance_id();
|
||||
}
|
||||
if (p_sync->get_root_node()) {
|
||||
root_node = p_sync->get_root_node()->get_instance_id();
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::SyncInfo::write_to_array(Array &r_arr) const {
|
||||
r_arr.push_back(synchronizer);
|
||||
r_arr.push_back(config);
|
||||
r_arr.push_back(root_node);
|
||||
r_arr.push_back(incoming_syncs);
|
||||
r_arr.push_back(incoming_size);
|
||||
r_arr.push_back(outgoing_syncs);
|
||||
r_arr.push_back(outgoing_size);
|
||||
}
|
||||
|
||||
bool MultiplayerDebugger::SyncInfo::read_from_array(const Array &p_arr, int p_offset) {
|
||||
ERR_FAIL_COND_V(p_arr.size() - p_offset < 7, false);
|
||||
synchronizer = int64_t(p_arr[p_offset]);
|
||||
config = int64_t(p_arr[p_offset + 1]);
|
||||
root_node = int64_t(p_arr[p_offset + 2]);
|
||||
incoming_syncs = p_arr[p_offset + 3];
|
||||
incoming_size = p_arr[p_offset + 4];
|
||||
outgoing_syncs = p_arr[p_offset + 5];
|
||||
outgoing_size = p_arr[p_offset + 6];
|
||||
return true;
|
||||
}
|
||||
|
||||
Array MultiplayerDebugger::ReplicationFrame::serialize() {
|
||||
Array arr = { infos.size() * 7 };
|
||||
for (const KeyValue<ObjectID, SyncInfo> &E : infos) {
|
||||
E.value.write_to_array(arr);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
bool MultiplayerDebugger::ReplicationFrame::deserialize(const Array &p_arr) {
|
||||
ERR_FAIL_COND_V(p_arr.is_empty(), false);
|
||||
uint32_t size = p_arr[0];
|
||||
ERR_FAIL_COND_V(size % 7, false);
|
||||
ERR_FAIL_COND_V((uint32_t)p_arr.size() != size + 1, false);
|
||||
int idx = 1;
|
||||
for (uint32_t i = 0; i < size / 7; i++) {
|
||||
SyncInfo info;
|
||||
if (!info.read_from_array(p_arr, idx)) {
|
||||
return false;
|
||||
}
|
||||
infos[info.synchronizer] = info;
|
||||
idx += 7;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::ReplicationProfiler::toggle(bool p_enable, const Array &p_opts) {
|
||||
sync_data.clear();
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::ReplicationProfiler::add(const Array &p_data) {
|
||||
ERR_FAIL_COND(p_data.size() != 3);
|
||||
const String what = p_data[0];
|
||||
const ObjectID id = p_data[1];
|
||||
const uint64_t size = p_data[2];
|
||||
MultiplayerSynchronizer *sync = ObjectDB::get_instance<MultiplayerSynchronizer>(id);
|
||||
ERR_FAIL_NULL(sync);
|
||||
if (!sync_data.has(id)) {
|
||||
sync_data[id] = SyncInfo(sync);
|
||||
}
|
||||
SyncInfo &info = sync_data[id];
|
||||
if (what == "sync_in") {
|
||||
info.incoming_syncs++;
|
||||
info.incoming_size += size;
|
||||
} else if (what == "sync_out") {
|
||||
info.outgoing_syncs++;
|
||||
info.outgoing_size += size;
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerDebugger::ReplicationProfiler::tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time) {
|
||||
uint64_t pt = OS::get_singleton()->get_ticks_msec();
|
||||
if (pt - last_profile_time > 100) {
|
||||
last_profile_time = pt;
|
||||
ReplicationFrame frame;
|
||||
for (const KeyValue<ObjectID, SyncInfo> &E : sync_data) {
|
||||
frame.infos[E.key] = E.value;
|
||||
}
|
||||
sync_data.clear();
|
||||
EngineDebugger::get_singleton()->send_message("multiplayer:syncs", frame.serialize());
|
||||
}
|
||||
}
|
129
modules/multiplayer/multiplayer_debugger.h
Normal file
129
modules/multiplayer/multiplayer_debugger.h
Normal file
@@ -0,0 +1,129 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_debugger.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/debugger/engine_profiler.h"
|
||||
|
||||
class MultiplayerSynchronizer;
|
||||
|
||||
class MultiplayerDebugger {
|
||||
public:
|
||||
struct RPCNodeInfo {
|
||||
ObjectID node;
|
||||
String node_path;
|
||||
int incoming_rpc = 0;
|
||||
int incoming_size = 0;
|
||||
int outgoing_rpc = 0;
|
||||
int outgoing_size = 0;
|
||||
};
|
||||
|
||||
struct RPCFrame {
|
||||
Vector<RPCNodeInfo> infos;
|
||||
|
||||
Array serialize();
|
||||
bool deserialize(const Array &p_arr);
|
||||
};
|
||||
|
||||
struct SyncInfo {
|
||||
ObjectID synchronizer;
|
||||
ObjectID config;
|
||||
ObjectID root_node;
|
||||
int incoming_syncs = 0;
|
||||
int incoming_size = 0;
|
||||
int outgoing_syncs = 0;
|
||||
int outgoing_size = 0;
|
||||
|
||||
void write_to_array(Array &r_arr) const;
|
||||
bool read_from_array(const Array &p_arr, int p_offset);
|
||||
|
||||
SyncInfo() {}
|
||||
SyncInfo(MultiplayerSynchronizer *p_sync);
|
||||
};
|
||||
|
||||
struct ReplicationFrame {
|
||||
HashMap<ObjectID, SyncInfo> infos;
|
||||
|
||||
Array serialize();
|
||||
bool deserialize(const Array &p_arr);
|
||||
};
|
||||
|
||||
private:
|
||||
class BandwidthProfiler : public EngineProfiler {
|
||||
protected:
|
||||
struct BandwidthFrame {
|
||||
uint32_t timestamp;
|
||||
int packet_size;
|
||||
};
|
||||
|
||||
int bandwidth_in_ptr = 0;
|
||||
Vector<BandwidthFrame> bandwidth_in;
|
||||
int bandwidth_out_ptr = 0;
|
||||
Vector<BandwidthFrame> bandwidth_out;
|
||||
uint64_t last_bandwidth_time = 0;
|
||||
|
||||
int bandwidth_usage(const Vector<BandwidthFrame> &p_buffer, int p_pointer);
|
||||
|
||||
public:
|
||||
void toggle(bool p_enable, const Array &p_opts);
|
||||
void add(const Array &p_data);
|
||||
void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time);
|
||||
};
|
||||
|
||||
class RPCProfiler : public EngineProfiler {
|
||||
private:
|
||||
HashMap<ObjectID, RPCNodeInfo> rpc_node_data;
|
||||
uint64_t last_profile_time = 0;
|
||||
|
||||
void init_node(const ObjectID p_node);
|
||||
|
||||
public:
|
||||
void toggle(bool p_enable, const Array &p_opts);
|
||||
void add(const Array &p_data);
|
||||
void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time);
|
||||
};
|
||||
|
||||
class ReplicationProfiler : public EngineProfiler {
|
||||
private:
|
||||
HashMap<ObjectID, SyncInfo> sync_data;
|
||||
uint64_t last_profile_time = 0;
|
||||
|
||||
public:
|
||||
void toggle(bool p_enable, const Array &p_opts);
|
||||
void add(const Array &p_data);
|
||||
void tick(double p_frame_time, double p_process_time, double p_physics_time, double p_physics_frame_time);
|
||||
};
|
||||
|
||||
static Error _capture(void *p_user, const String &p_msg, const Array &p_args, bool &r_captured);
|
||||
|
||||
public:
|
||||
static void initialize();
|
||||
static void deinitialize();
|
||||
};
|
332
modules/multiplayer/multiplayer_spawner.cpp
Normal file
332
modules/multiplayer/multiplayer_spawner.cpp
Normal file
@@ -0,0 +1,332 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_spawner.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "multiplayer_spawner.h"
|
||||
|
||||
#include "scene/main/multiplayer_api.h"
|
||||
|
||||
#ifdef TOOLS_ENABLED
|
||||
/* This is editor only */
|
||||
bool MultiplayerSpawner::_set(const StringName &p_name, const Variant &p_value) {
|
||||
if (p_name == "_spawnable_scene_count") {
|
||||
spawnable_scenes.resize(p_value);
|
||||
notify_property_list_changed();
|
||||
return true;
|
||||
} else {
|
||||
String ns = p_name;
|
||||
if (ns.begins_with("scenes/")) {
|
||||
uint32_t index = ns.get_slicec('/', 1).to_int();
|
||||
ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
|
||||
spawnable_scenes[index].path = ResourceUID::ensure_path(p_value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool MultiplayerSpawner::_get(const StringName &p_name, Variant &r_ret) const {
|
||||
if (p_name == "_spawnable_scene_count") {
|
||||
r_ret = spawnable_scenes.size();
|
||||
return true;
|
||||
} else {
|
||||
String ns = p_name;
|
||||
if (ns.begins_with("scenes/")) {
|
||||
uint32_t index = ns.get_slicec('/', 1).to_int();
|
||||
ERR_FAIL_UNSIGNED_INDEX_V(index, spawnable_scenes.size(), false);
|
||||
r_ret = ResourceUID::path_to_uid(spawnable_scenes[index].path);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_get_property_list(List<PropertyInfo> *p_list) const {
|
||||
p_list->push_back(PropertyInfo(Variant::INT, "_spawnable_scene_count", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_EDITOR | PROPERTY_USAGE_ARRAY, "Auto Spawn List,scenes/"));
|
||||
List<String> exts;
|
||||
ResourceLoader::get_recognized_extensions_for_type("PackedScene", &exts);
|
||||
String ext_hint;
|
||||
for (const String &E : exts) {
|
||||
if (!ext_hint.is_empty()) {
|
||||
ext_hint += ",";
|
||||
}
|
||||
ext_hint += "*." + E;
|
||||
}
|
||||
for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
|
||||
p_list->push_back(PropertyInfo(Variant::STRING, "scenes/" + itos(i), PROPERTY_HINT_FILE, ext_hint, PROPERTY_USAGE_EDITOR));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
PackedStringArray MultiplayerSpawner::get_configuration_warnings() const {
|
||||
PackedStringArray warnings = Node::get_configuration_warnings();
|
||||
|
||||
if (spawn_path.is_empty() || !has_node(spawn_path)) {
|
||||
warnings.push_back(RTR("A valid NodePath must be set in the \"Spawn Path\" property in order for MultiplayerSpawner to be able to spawn Nodes."));
|
||||
}
|
||||
return warnings;
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::add_spawnable_scene(const String &p_path) {
|
||||
SpawnableScene sc;
|
||||
sc.path = ResourceUID::ensure_path(p_path);
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
ERR_FAIL_COND(!ResourceLoader::exists(sc.path));
|
||||
}
|
||||
spawnable_scenes.push_back(sc);
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
Node *node = get_spawn_node();
|
||||
if (spawnable_scenes.size() == 1 && node && !node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
|
||||
node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
|
||||
}
|
||||
}
|
||||
|
||||
int MultiplayerSpawner::get_spawnable_scene_count() const {
|
||||
return spawnable_scenes.size();
|
||||
}
|
||||
|
||||
String MultiplayerSpawner::get_spawnable_scene(int p_idx) const {
|
||||
ERR_FAIL_INDEX_V(p_idx, (int)spawnable_scenes.size(), "");
|
||||
return spawnable_scenes[p_idx].path;
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::clear_spawnable_scenes() {
|
||||
spawnable_scenes.clear();
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
Node *node = get_spawn_node();
|
||||
if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
|
||||
node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
|
||||
}
|
||||
}
|
||||
|
||||
Vector<String> MultiplayerSpawner::_get_spawnable_scenes() const {
|
||||
Vector<String> ss;
|
||||
ss.resize(spawnable_scenes.size());
|
||||
for (int i = 0; i < ss.size(); i++) {
|
||||
ss.write[i] = ResourceUID::path_to_uid(spawnable_scenes[i].path);
|
||||
}
|
||||
return ss;
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_set_spawnable_scenes(const Vector<String> &p_scenes) {
|
||||
clear_spawnable_scenes();
|
||||
for (int i = 0; i < p_scenes.size(); i++) {
|
||||
add_spawnable_scene(p_scenes[i]);
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("add_spawnable_scene", "path"), &MultiplayerSpawner::add_spawnable_scene);
|
||||
ClassDB::bind_method(D_METHOD("get_spawnable_scene_count"), &MultiplayerSpawner::get_spawnable_scene_count);
|
||||
ClassDB::bind_method(D_METHOD("get_spawnable_scene", "index"), &MultiplayerSpawner::get_spawnable_scene);
|
||||
ClassDB::bind_method(D_METHOD("clear_spawnable_scenes"), &MultiplayerSpawner::clear_spawnable_scenes);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("_get_spawnable_scenes"), &MultiplayerSpawner::_get_spawnable_scenes);
|
||||
ClassDB::bind_method(D_METHOD("_set_spawnable_scenes", "scenes"), &MultiplayerSpawner::_set_spawnable_scenes);
|
||||
|
||||
ADD_PROPERTY(PropertyInfo(Variant::PACKED_STRING_ARRAY, "_spawnable_scenes", PROPERTY_HINT_NONE, "", (PROPERTY_USAGE_STORAGE | PROPERTY_USAGE_INTERNAL)), "_set_spawnable_scenes", "_get_spawnable_scenes");
|
||||
|
||||
ClassDB::bind_method(D_METHOD("spawn", "data"), &MultiplayerSpawner::spawn, DEFVAL(Variant()));
|
||||
|
||||
ClassDB::bind_method(D_METHOD("get_spawn_path"), &MultiplayerSpawner::get_spawn_path);
|
||||
ClassDB::bind_method(D_METHOD("set_spawn_path", "path"), &MultiplayerSpawner::set_spawn_path);
|
||||
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "spawn_path", PROPERTY_HINT_NONE, ""), "set_spawn_path", "get_spawn_path");
|
||||
|
||||
ClassDB::bind_method(D_METHOD("get_spawn_limit"), &MultiplayerSpawner::get_spawn_limit);
|
||||
ClassDB::bind_method(D_METHOD("set_spawn_limit", "limit"), &MultiplayerSpawner::set_spawn_limit);
|
||||
ADD_PROPERTY(PropertyInfo(Variant::INT, "spawn_limit", PROPERTY_HINT_RANGE, "0,1024,1,or_greater"), "set_spawn_limit", "get_spawn_limit");
|
||||
|
||||
ClassDB::bind_method(D_METHOD("get_spawn_function"), &MultiplayerSpawner::get_spawn_function);
|
||||
ClassDB::bind_method(D_METHOD("set_spawn_function", "spawn_function"), &MultiplayerSpawner::set_spawn_function);
|
||||
ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "spawn_function", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NONE), "set_spawn_function", "get_spawn_function");
|
||||
|
||||
ADD_SIGNAL(MethodInfo("despawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
|
||||
ADD_SIGNAL(MethodInfo("spawned", PropertyInfo(Variant::OBJECT, "node", PROPERTY_HINT_RESOURCE_TYPE, "Node")));
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_update_spawn_node() {
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (spawn_node.is_valid()) {
|
||||
Node *node = ObjectDB::get_instance<Node>(spawn_node);
|
||||
if (node && node->is_connected("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added))) {
|
||||
node->disconnect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
|
||||
}
|
||||
}
|
||||
Node *node = spawn_path.is_empty() && is_inside_tree() ? nullptr : get_node_or_null(spawn_path);
|
||||
if (node) {
|
||||
spawn_node = node->get_instance_id();
|
||||
if (get_spawnable_scene_count()) {
|
||||
node->connect("child_entered_tree", callable_mp(this, &MultiplayerSpawner::_node_added));
|
||||
}
|
||||
} else {
|
||||
spawn_node = ObjectID();
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_notification(int p_what) {
|
||||
switch (p_what) {
|
||||
case NOTIFICATION_POST_ENTER_TREE: {
|
||||
_update_spawn_node();
|
||||
} break;
|
||||
|
||||
case NOTIFICATION_EXIT_TREE: {
|
||||
_update_spawn_node();
|
||||
|
||||
for (const KeyValue<ObjectID, SpawnInfo> &E : tracked_nodes) {
|
||||
Node *node = ObjectDB::get_instance<Node>(E.key);
|
||||
ERR_CONTINUE(!node);
|
||||
node->disconnect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit));
|
||||
get_multiplayer()->object_configuration_remove(node, this);
|
||||
}
|
||||
tracked_nodes.clear();
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_node_added(Node *p_node) {
|
||||
if (!get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority()) {
|
||||
return;
|
||||
}
|
||||
if (tracked_nodes.has(p_node->get_instance_id())) {
|
||||
return;
|
||||
}
|
||||
const Node *parent = get_spawn_node();
|
||||
if (!parent || p_node->get_parent() != parent) {
|
||||
return;
|
||||
}
|
||||
int id = find_spawnable_scene_index_from_path(p_node->get_scene_file_path());
|
||||
if (id == INVALID_ID) {
|
||||
return;
|
||||
}
|
||||
const String name = p_node->get_name();
|
||||
ERR_FAIL_COND_MSG(name.validate_node_name() != name, vformat("Unable to auto-spawn node with reserved name: %s. Make sure to add your replicated scenes via 'add_child(node, true)' to produce valid names.", name));
|
||||
_track(p_node, Variant(), id);
|
||||
}
|
||||
|
||||
NodePath MultiplayerSpawner::get_spawn_path() const {
|
||||
return spawn_path;
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::set_spawn_path(const NodePath &p_path) {
|
||||
spawn_path = p_path;
|
||||
_update_spawn_node();
|
||||
update_configuration_warnings();
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_track(Node *p_node, const Variant &p_argument, int p_scene_id) {
|
||||
ObjectID oid = p_node->get_instance_id();
|
||||
if (!tracked_nodes.has(oid)) {
|
||||
tracked_nodes[oid] = SpawnInfo(p_argument.duplicate(true), p_scene_id);
|
||||
p_node->connect(SceneStringName(tree_exiting), callable_mp(this, &MultiplayerSpawner::_node_exit).bind(p_node->get_instance_id()), CONNECT_ONE_SHOT);
|
||||
_spawn_notify(p_node->get_instance_id());
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_spawn_notify(ObjectID p_id) {
|
||||
get_multiplayer()->object_configuration_add(ObjectDB::get_instance(p_id), this);
|
||||
}
|
||||
|
||||
void MultiplayerSpawner::_node_exit(ObjectID p_id) {
|
||||
Node *node = ObjectDB::get_instance<Node>(p_id);
|
||||
ERR_FAIL_NULL(node);
|
||||
if (tracked_nodes.has(p_id)) {
|
||||
tracked_nodes.erase(p_id);
|
||||
get_multiplayer()->object_configuration_remove(node, this);
|
||||
}
|
||||
}
|
||||
|
||||
int MultiplayerSpawner::find_spawnable_scene_index_from_path(const String &p_scene) const {
|
||||
for (uint32_t i = 0; i < spawnable_scenes.size(); i++) {
|
||||
if (spawnable_scenes[i].path == p_scene) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return INVALID_ID;
|
||||
}
|
||||
|
||||
int MultiplayerSpawner::find_spawnable_scene_index_from_object(const ObjectID &p_id) const {
|
||||
const SpawnInfo *info = tracked_nodes.getptr(p_id);
|
||||
return info ? info->id : INVALID_ID;
|
||||
}
|
||||
|
||||
const Variant MultiplayerSpawner::get_spawn_argument(const ObjectID &p_id) const {
|
||||
const SpawnInfo *info = tracked_nodes.getptr(p_id);
|
||||
return info ? info->args : Variant();
|
||||
}
|
||||
|
||||
Node *MultiplayerSpawner::instantiate_scene(int p_id) {
|
||||
ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
|
||||
ERR_FAIL_UNSIGNED_INDEX_V((uint32_t)p_id, spawnable_scenes.size(), nullptr);
|
||||
SpawnableScene &sc = spawnable_scenes[p_id];
|
||||
if (sc.cache.is_null()) {
|
||||
sc.cache = ResourceLoader::load(sc.path);
|
||||
}
|
||||
ERR_FAIL_COND_V_MSG(sc.cache.is_null(), nullptr, "Invalid spawnable scene: " + sc.path);
|
||||
return sc.cache->instantiate();
|
||||
}
|
||||
|
||||
Node *MultiplayerSpawner::instantiate_custom(const Variant &p_data) {
|
||||
ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
|
||||
ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires a valid 'spawn_function'.");
|
||||
const Variant *argv[1] = { &p_data };
|
||||
Variant ret;
|
||||
Callable::CallError ce;
|
||||
spawn_function.callp(argv, 1, ret, ce);
|
||||
ERR_FAIL_COND_V_MSG(ce.error != Callable::CallError::CALL_OK, nullptr, "Failed to call spawn function.");
|
||||
ERR_FAIL_COND_V_MSG(ret.get_type() != Variant::OBJECT, nullptr, "The spawn function must return a Node.");
|
||||
return Object::cast_to<Node>(ret.operator Object *());
|
||||
}
|
||||
|
||||
Node *MultiplayerSpawner::spawn(const Variant &p_data) {
|
||||
ERR_FAIL_COND_V(!is_inside_tree() || !get_multiplayer()->has_multiplayer_peer() || !is_multiplayer_authority(), nullptr);
|
||||
ERR_FAIL_COND_V_MSG(spawn_limit && spawn_limit <= tracked_nodes.size(), nullptr, "Spawn limit reached!");
|
||||
ERR_FAIL_COND_V_MSG(!spawn_function.is_valid(), nullptr, "Custom spawn requires the 'spawn_function' property to be a valid callable.");
|
||||
|
||||
Node *parent = get_spawn_node();
|
||||
ERR_FAIL_NULL_V_MSG(parent, nullptr, "Cannot find spawn node.");
|
||||
|
||||
Node *node = instantiate_custom(p_data);
|
||||
ERR_FAIL_NULL_V_MSG(node, nullptr, "The 'spawn_function' callable must return a valid node.");
|
||||
|
||||
_track(node, p_data);
|
||||
parent->add_child(node, true);
|
||||
return node;
|
||||
}
|
116
modules/multiplayer/multiplayer_spawner.h
Normal file
116
modules/multiplayer/multiplayer_spawner.h
Normal file
@@ -0,0 +1,116 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_spawner.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/templates/local_vector.h"
|
||||
#include "scene/main/node.h"
|
||||
#include "scene/resources/packed_scene.h"
|
||||
|
||||
class MultiplayerSpawner : public Node {
|
||||
GDCLASS(MultiplayerSpawner, Node);
|
||||
|
||||
public:
|
||||
enum {
|
||||
INVALID_ID = 0xFF,
|
||||
};
|
||||
|
||||
private:
|
||||
struct SpawnableScene {
|
||||
String path;
|
||||
Ref<PackedScene> cache;
|
||||
};
|
||||
|
||||
LocalVector<SpawnableScene> spawnable_scenes;
|
||||
|
||||
HashSet<ResourceUID::ID> spawnable_ids;
|
||||
NodePath spawn_path;
|
||||
|
||||
struct SpawnInfo {
|
||||
Variant args;
|
||||
int id = INVALID_ID;
|
||||
SpawnInfo(Variant p_args, int p_id) {
|
||||
id = p_id;
|
||||
args = p_args;
|
||||
}
|
||||
SpawnInfo() {}
|
||||
};
|
||||
|
||||
ObjectID spawn_node;
|
||||
HashMap<ObjectID, SpawnInfo> tracked_nodes;
|
||||
uint32_t spawn_limit = 0;
|
||||
Callable spawn_function;
|
||||
|
||||
void _update_spawn_node();
|
||||
void _track(Node *p_node, const Variant &p_argument, int p_scene_id = INVALID_ID);
|
||||
void _node_added(Node *p_node);
|
||||
void _node_exit(ObjectID p_id);
|
||||
void _spawn_notify(ObjectID p_id);
|
||||
|
||||
Vector<String> _get_spawnable_scenes() const;
|
||||
void _set_spawnable_scenes(const Vector<String> &p_scenes);
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
void _notification(int p_what);
|
||||
|
||||
#ifdef TOOLS_ENABLED
|
||||
bool _set(const StringName &p_name, const Variant &p_value);
|
||||
bool _get(const StringName &p_name, Variant &r_ret) const;
|
||||
void _get_property_list(List<PropertyInfo> *p_list) const;
|
||||
#endif
|
||||
public:
|
||||
PackedStringArray get_configuration_warnings() const override;
|
||||
|
||||
Node *get_spawn_node() const {
|
||||
return spawn_node.is_valid() ? ObjectDB::get_instance<Node>(spawn_node) : nullptr;
|
||||
}
|
||||
|
||||
void add_spawnable_scene(const String &p_path);
|
||||
int get_spawnable_scene_count() const;
|
||||
String get_spawnable_scene(int p_idx) const;
|
||||
void clear_spawnable_scenes();
|
||||
|
||||
NodePath get_spawn_path() const;
|
||||
void set_spawn_path(const NodePath &p_path);
|
||||
uint32_t get_spawn_limit() const { return spawn_limit; }
|
||||
void set_spawn_limit(uint32_t p_limit) { spawn_limit = p_limit; }
|
||||
void set_spawn_function(Callable p_spawn_function) { spawn_function = p_spawn_function; }
|
||||
Callable get_spawn_function() const { return spawn_function; }
|
||||
|
||||
const Variant get_spawn_argument(const ObjectID &p_id) const;
|
||||
int find_spawnable_scene_index_from_object(const ObjectID &p_id) const;
|
||||
int find_spawnable_scene_index_from_path(const String &p_path) const;
|
||||
Node *spawn(const Variant &p_data = Variant());
|
||||
Node *instantiate_custom(const Variant &p_data);
|
||||
Node *instantiate_scene(int p_idx);
|
||||
|
||||
MultiplayerSpawner() {}
|
||||
};
|
457
modules/multiplayer/multiplayer_synchronizer.cpp
Normal file
457
modules/multiplayer/multiplayer_synchronizer.cpp
Normal file
@@ -0,0 +1,457 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_synchronizer.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "multiplayer_synchronizer.h"
|
||||
|
||||
#include "core/config/engine.h"
|
||||
#include "scene/main/multiplayer_api.h"
|
||||
|
||||
Object *MultiplayerSynchronizer::_get_prop_target(Object *p_obj, const NodePath &p_path) {
|
||||
if (p_path.get_name_count() == 0) {
|
||||
return p_obj;
|
||||
}
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_COND_V_MSG(!node || !node->has_node(p_path), nullptr, vformat("Node '%s' not found.", p_path));
|
||||
return node->get_node(p_path);
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::_stop() {
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
root_node_cache = ObjectID();
|
||||
Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
|
||||
if (node) {
|
||||
get_multiplayer()->object_configuration_remove(node, this);
|
||||
}
|
||||
reset();
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::_start() {
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
root_node_cache = ObjectID();
|
||||
reset();
|
||||
Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
|
||||
if (node) {
|
||||
root_node_cache = node->get_instance_id();
|
||||
get_multiplayer()->object_configuration_add(node, this);
|
||||
_update_process();
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::_update_process() {
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
set_process_internal(false);
|
||||
set_physics_process_internal(false);
|
||||
if (!visibility_filters.size()) {
|
||||
return;
|
||||
}
|
||||
switch (visibility_update_mode) {
|
||||
case VISIBILITY_PROCESS_IDLE:
|
||||
set_process_internal(true);
|
||||
break;
|
||||
case VISIBILITY_PROCESS_PHYSICS:
|
||||
set_physics_process_internal(true);
|
||||
break;
|
||||
case VISIBILITY_PROCESS_NONE:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Node *MultiplayerSynchronizer::get_root_node() {
|
||||
return root_node_cache.is_valid() ? ObjectDB::get_instance<Node>(root_node_cache) : nullptr;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::reset() {
|
||||
net_id = 0;
|
||||
last_sync_usec = 0;
|
||||
last_inbound_sync = 0;
|
||||
last_watch_usec = 0;
|
||||
sync_started = false;
|
||||
watchers.clear();
|
||||
}
|
||||
|
||||
uint32_t MultiplayerSynchronizer::get_net_id() const {
|
||||
return net_id;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_net_id(uint32_t p_net_id) {
|
||||
net_id = p_net_id;
|
||||
}
|
||||
|
||||
bool MultiplayerSynchronizer::update_outbound_sync_time(uint64_t p_usec) {
|
||||
if (last_sync_usec == p_usec) {
|
||||
// last_sync_usec has been updated in this frame.
|
||||
return true;
|
||||
}
|
||||
if (p_usec < last_sync_usec + sync_interval_usec) {
|
||||
// Too soon, should skip this synchronization frame.
|
||||
return false;
|
||||
}
|
||||
last_sync_usec = p_usec;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool MultiplayerSynchronizer::update_inbound_sync_time(uint16_t p_network_time) {
|
||||
if (!sync_started) {
|
||||
sync_started = true;
|
||||
} else if (p_network_time <= last_inbound_sync && last_inbound_sync - p_network_time < 32767) {
|
||||
return false;
|
||||
}
|
||||
last_inbound_sync = p_network_time;
|
||||
return true;
|
||||
}
|
||||
|
||||
PackedStringArray MultiplayerSynchronizer::get_configuration_warnings() const {
|
||||
PackedStringArray warnings = Node::get_configuration_warnings();
|
||||
|
||||
if (root_path.is_empty() || !has_node(root_path)) {
|
||||
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."));
|
||||
}
|
||||
|
||||
return warnings;
|
||||
}
|
||||
|
||||
Error MultiplayerSynchronizer::get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs) {
|
||||
ERR_FAIL_NULL_V(p_obj, ERR_INVALID_PARAMETER);
|
||||
r_variant.resize(p_properties.size());
|
||||
r_variant_ptrs.resize(r_variant.size());
|
||||
int i = 0;
|
||||
for (const NodePath &prop : p_properties) {
|
||||
bool valid = false;
|
||||
const Object *obj = _get_prop_target(p_obj, prop);
|
||||
ERR_FAIL_NULL_V(obj, FAILED);
|
||||
r_variant.write[i] = obj->get_indexed(prop.get_subnames(), &valid);
|
||||
r_variant_ptrs.write[i] = &r_variant[i];
|
||||
ERR_FAIL_COND_V_MSG(!valid, ERR_INVALID_DATA, vformat("Property '%s' not found.", prop));
|
||||
i++;
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error MultiplayerSynchronizer::set_state(const List<NodePath> &p_properties, Object *p_obj, const Vector<Variant> &p_state) {
|
||||
ERR_FAIL_NULL_V(p_obj, ERR_INVALID_PARAMETER);
|
||||
int i = 0;
|
||||
for (const NodePath &prop : p_properties) {
|
||||
Object *obj = _get_prop_target(p_obj, prop);
|
||||
ERR_FAIL_NULL_V(obj, FAILED);
|
||||
obj->set_indexed(prop.get_subnames(), p_state[i]);
|
||||
i += 1;
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
bool MultiplayerSynchronizer::is_visibility_public() const {
|
||||
return peer_visibility.has(0);
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_visibility_public(bool p_visible) {
|
||||
set_visibility_for(0, p_visible);
|
||||
}
|
||||
|
||||
bool MultiplayerSynchronizer::is_visible_to(int p_peer) {
|
||||
if (visibility_filters.size()) {
|
||||
Variant arg = p_peer;
|
||||
const Variant *argv[1] = { &arg };
|
||||
for (Callable filter : visibility_filters) {
|
||||
Variant ret;
|
||||
Callable::CallError err;
|
||||
filter.callp(argv, 1, ret, err);
|
||||
ERR_FAIL_COND_V(err.error != Callable::CallError::CALL_OK || ret.get_type() != Variant::BOOL, false);
|
||||
if (!ret.operator bool()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return peer_visibility.has(0) || peer_visibility.has(p_peer);
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::add_visibility_filter(Callable p_callback) {
|
||||
visibility_filters.insert(p_callback);
|
||||
_update_process();
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::remove_visibility_filter(Callable p_callback) {
|
||||
visibility_filters.erase(p_callback);
|
||||
_update_process();
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_visibility_for(int p_peer, bool p_visible) {
|
||||
if (peer_visibility.has(p_peer) == p_visible) {
|
||||
return;
|
||||
}
|
||||
if (p_visible) {
|
||||
peer_visibility.insert(p_peer);
|
||||
} else {
|
||||
peer_visibility.erase(p_peer);
|
||||
}
|
||||
update_visibility(p_peer);
|
||||
}
|
||||
|
||||
bool MultiplayerSynchronizer::get_visibility_for(int p_peer) const {
|
||||
return peer_visibility.has(p_peer);
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_visibility_update_mode(VisibilityUpdateMode p_mode) {
|
||||
visibility_update_mode = p_mode;
|
||||
_update_process();
|
||||
}
|
||||
|
||||
MultiplayerSynchronizer::VisibilityUpdateMode MultiplayerSynchronizer::get_visibility_update_mode() const {
|
||||
return visibility_update_mode;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::_bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("set_root_path", "path"), &MultiplayerSynchronizer::set_root_path);
|
||||
ClassDB::bind_method(D_METHOD("get_root_path"), &MultiplayerSynchronizer::get_root_path);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_replication_interval", "milliseconds"), &MultiplayerSynchronizer::set_replication_interval);
|
||||
ClassDB::bind_method(D_METHOD("get_replication_interval"), &MultiplayerSynchronizer::get_replication_interval);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_delta_interval", "milliseconds"), &MultiplayerSynchronizer::set_delta_interval);
|
||||
ClassDB::bind_method(D_METHOD("get_delta_interval"), &MultiplayerSynchronizer::get_delta_interval);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_replication_config", "config"), &MultiplayerSynchronizer::set_replication_config);
|
||||
ClassDB::bind_method(D_METHOD("get_replication_config"), &MultiplayerSynchronizer::get_replication_config);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_visibility_update_mode", "mode"), &MultiplayerSynchronizer::set_visibility_update_mode);
|
||||
ClassDB::bind_method(D_METHOD("get_visibility_update_mode"), &MultiplayerSynchronizer::get_visibility_update_mode);
|
||||
ClassDB::bind_method(D_METHOD("update_visibility", "for_peer"), &MultiplayerSynchronizer::update_visibility, DEFVAL(0));
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_visibility_public", "visible"), &MultiplayerSynchronizer::set_visibility_public);
|
||||
ClassDB::bind_method(D_METHOD("is_visibility_public"), &MultiplayerSynchronizer::is_visibility_public);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("add_visibility_filter", "filter"), &MultiplayerSynchronizer::add_visibility_filter);
|
||||
ClassDB::bind_method(D_METHOD("remove_visibility_filter", "filter"), &MultiplayerSynchronizer::remove_visibility_filter);
|
||||
ClassDB::bind_method(D_METHOD("set_visibility_for", "peer", "visible"), &MultiplayerSynchronizer::set_visibility_for);
|
||||
ClassDB::bind_method(D_METHOD("get_visibility_for", "peer"), &MultiplayerSynchronizer::get_visibility_for);
|
||||
|
||||
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "replication_interval", PROPERTY_HINT_RANGE, "0,5,0.001,suffix:s"), "set_replication_interval", "get_replication_interval");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "delta_interval", PROPERTY_HINT_RANGE, "0,5,0.001,suffix:s"), "set_delta_interval", "get_delta_interval");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "replication_config", PROPERTY_HINT_RESOURCE_TYPE, "SceneReplicationConfig", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_EDITOR_INSTANTIATE_OBJECT), "set_replication_config", "get_replication_config");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::INT, "visibility_update_mode", PROPERTY_HINT_ENUM, "Idle,Physics,None"), "set_visibility_update_mode", "get_visibility_update_mode");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "public_visibility"), "set_visibility_public", "is_visibility_public");
|
||||
|
||||
BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_IDLE);
|
||||
BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_PHYSICS);
|
||||
BIND_ENUM_CONSTANT(VISIBILITY_PROCESS_NONE);
|
||||
|
||||
ADD_SIGNAL(MethodInfo("synchronized"));
|
||||
ADD_SIGNAL(MethodInfo("delta_synchronized"));
|
||||
ADD_SIGNAL(MethodInfo("visibility_changed", PropertyInfo(Variant::INT, "for_peer")));
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::_notification(int p_what) {
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
if (root_path.is_empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (p_what) {
|
||||
case NOTIFICATION_ENTER_TREE: {
|
||||
_start();
|
||||
} break;
|
||||
|
||||
case NOTIFICATION_EXIT_TREE: {
|
||||
_stop();
|
||||
} break;
|
||||
|
||||
case NOTIFICATION_INTERNAL_PROCESS:
|
||||
case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: {
|
||||
update_visibility(0);
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_replication_interval(double p_interval) {
|
||||
ERR_FAIL_COND_MSG(p_interval < 0, "Interval must be greater or equal to 0 (where 0 means default)");
|
||||
sync_interval_usec = uint64_t(p_interval * 1000 * 1000);
|
||||
}
|
||||
|
||||
double MultiplayerSynchronizer::get_replication_interval() const {
|
||||
return double(sync_interval_usec) / 1000.0 / 1000.0;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_delta_interval(double p_interval) {
|
||||
ERR_FAIL_COND_MSG(p_interval < 0, "Interval must be greater or equal to 0 (where 0 means default)");
|
||||
delta_interval_usec = uint64_t(p_interval * 1000 * 1000);
|
||||
}
|
||||
|
||||
double MultiplayerSynchronizer::get_delta_interval() const {
|
||||
return double(delta_interval_usec) / 1000.0 / 1000.0;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_replication_config(Ref<SceneReplicationConfig> p_config) {
|
||||
replication_config = p_config;
|
||||
}
|
||||
|
||||
Ref<SceneReplicationConfig> MultiplayerSynchronizer::get_replication_config() {
|
||||
return replication_config;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::update_visibility(int p_for_peer) {
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (Engine::get_singleton()->is_editor_hint()) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
Node *node = is_inside_tree() ? get_node_or_null(root_path) : nullptr;
|
||||
if (node && get_multiplayer()->has_multiplayer_peer() && is_multiplayer_authority()) {
|
||||
emit_signal(SceneStringName(visibility_changed), p_for_peer);
|
||||
}
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_root_path(const NodePath &p_path) {
|
||||
if (p_path == root_path) {
|
||||
return;
|
||||
}
|
||||
_stop();
|
||||
root_path = p_path;
|
||||
_start();
|
||||
update_configuration_warnings();
|
||||
}
|
||||
|
||||
NodePath MultiplayerSynchronizer::get_root_path() const {
|
||||
return root_path;
|
||||
}
|
||||
|
||||
void MultiplayerSynchronizer::set_multiplayer_authority(int p_peer_id, bool p_recursive) {
|
||||
if (get_multiplayer_authority() == p_peer_id) {
|
||||
return;
|
||||
}
|
||||
_stop();
|
||||
Node::set_multiplayer_authority(p_peer_id, p_recursive);
|
||||
_start();
|
||||
}
|
||||
|
||||
Error MultiplayerSynchronizer::_watch_changes(uint64_t p_usec) {
|
||||
ERR_FAIL_COND_V(replication_config.is_null(), FAILED);
|
||||
const List<NodePath> props = replication_config->get_watch_properties();
|
||||
if (props.size() != watchers.size()) {
|
||||
watchers.resize(props.size());
|
||||
}
|
||||
if (props.is_empty()) {
|
||||
return OK;
|
||||
}
|
||||
Node *node = get_root_node();
|
||||
ERR_FAIL_NULL_V(node, FAILED);
|
||||
int idx = -1;
|
||||
Watcher *ptr = watchers.ptrw();
|
||||
for (const NodePath &prop : props) {
|
||||
idx++;
|
||||
bool valid = false;
|
||||
const Object *obj = _get_prop_target(node, prop);
|
||||
ERR_CONTINUE_MSG(!obj, vformat("Node not found for property '%s'.", prop));
|
||||
Variant v = obj->get_indexed(prop.get_subnames(), &valid);
|
||||
ERR_CONTINUE_MSG(!valid, vformat("Property '%s' not found.", prop));
|
||||
Watcher &w = ptr[idx];
|
||||
if (w.prop != prop) {
|
||||
w.prop = prop;
|
||||
w.value = v.duplicate(true);
|
||||
w.last_change_usec = p_usec;
|
||||
} else if (!w.value.hash_compare(v)) {
|
||||
w.value = v.duplicate(true);
|
||||
w.last_change_usec = p_usec;
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
List<Variant> MultiplayerSynchronizer::get_delta_state(uint64_t p_cur_usec, uint64_t p_last_usec, uint64_t &r_indexes) {
|
||||
r_indexes = 0;
|
||||
List<Variant> out;
|
||||
|
||||
if (last_watch_usec == p_cur_usec) {
|
||||
// We already watched for changes in this frame.
|
||||
|
||||
} else if (p_cur_usec < p_last_usec + delta_interval_usec) {
|
||||
// Too soon skip delta synchronization.
|
||||
return out;
|
||||
|
||||
} else {
|
||||
// Watch for changes.
|
||||
Error err = _watch_changes(p_cur_usec);
|
||||
ERR_FAIL_COND_V(err != OK, out);
|
||||
last_watch_usec = p_cur_usec;
|
||||
}
|
||||
|
||||
const Watcher *ptr = watchers.size() ? watchers.ptr() : nullptr;
|
||||
for (int i = 0; i < watchers.size(); i++) {
|
||||
const Watcher &w = ptr[i];
|
||||
if (w.last_change_usec <= p_last_usec) {
|
||||
continue;
|
||||
}
|
||||
out.push_back(w.value);
|
||||
r_indexes |= 1ULL << i;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
List<NodePath> MultiplayerSynchronizer::get_delta_properties(uint64_t p_indexes) {
|
||||
List<NodePath> out;
|
||||
ERR_FAIL_COND_V(replication_config.is_null(), out);
|
||||
const List<NodePath> watch_props = replication_config->get_watch_properties();
|
||||
int idx = 0;
|
||||
for (const NodePath &prop : watch_props) {
|
||||
if ((p_indexes & (1ULL << idx++)) == 0) {
|
||||
continue;
|
||||
}
|
||||
out.push_back(prop);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
SceneReplicationConfig *MultiplayerSynchronizer::get_replication_config_ptr() const {
|
||||
return replication_config.ptr();
|
||||
}
|
||||
|
||||
MultiplayerSynchronizer::MultiplayerSynchronizer() {
|
||||
// Publicly visible by default.
|
||||
peer_visibility.insert(0);
|
||||
}
|
126
modules/multiplayer/multiplayer_synchronizer.h
Normal file
126
modules/multiplayer/multiplayer_synchronizer.h
Normal file
@@ -0,0 +1,126 @@
|
||||
/**************************************************************************/
|
||||
/* multiplayer_synchronizer.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "scene_replication_config.h"
|
||||
|
||||
#include "scene/main/node.h"
|
||||
|
||||
class MultiplayerSynchronizer : public Node {
|
||||
GDCLASS(MultiplayerSynchronizer, Node);
|
||||
|
||||
public:
|
||||
enum VisibilityUpdateMode {
|
||||
VISIBILITY_PROCESS_IDLE,
|
||||
VISIBILITY_PROCESS_PHYSICS,
|
||||
VISIBILITY_PROCESS_NONE,
|
||||
};
|
||||
|
||||
private:
|
||||
struct Watcher {
|
||||
NodePath prop;
|
||||
uint64_t last_change_usec = 0;
|
||||
Variant value;
|
||||
};
|
||||
|
||||
Ref<SceneReplicationConfig> replication_config;
|
||||
NodePath root_path = NodePath(".."); // Start with parent, like with AnimationPlayer.
|
||||
uint64_t sync_interval_usec = 0;
|
||||
uint64_t delta_interval_usec = 0;
|
||||
VisibilityUpdateMode visibility_update_mode = VISIBILITY_PROCESS_IDLE;
|
||||
HashSet<Callable> visibility_filters;
|
||||
HashSet<int> peer_visibility;
|
||||
Vector<Watcher> watchers;
|
||||
uint64_t last_watch_usec = 0;
|
||||
|
||||
ObjectID root_node_cache;
|
||||
uint64_t last_sync_usec = 0;
|
||||
uint16_t last_inbound_sync = 0;
|
||||
uint32_t net_id = 0;
|
||||
bool sync_started = false;
|
||||
|
||||
static Object *_get_prop_target(Object *p_obj, const NodePath &p_prop);
|
||||
void _start();
|
||||
void _stop();
|
||||
void _update_process();
|
||||
Error _watch_changes(uint64_t p_usec);
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
void _notification(int p_what);
|
||||
|
||||
public:
|
||||
static Error get_state(const List<NodePath> &p_properties, Object *p_obj, Vector<Variant> &r_variant, Vector<const Variant *> &r_variant_ptrs);
|
||||
static Error set_state(const List<NodePath> &p_properties, Object *p_obj, const Vector<Variant> &p_state);
|
||||
|
||||
void reset();
|
||||
Node *get_root_node();
|
||||
|
||||
uint32_t get_net_id() const;
|
||||
void set_net_id(uint32_t p_net_id);
|
||||
|
||||
bool update_outbound_sync_time(uint64_t p_usec);
|
||||
bool update_inbound_sync_time(uint16_t p_network_time);
|
||||
|
||||
PackedStringArray get_configuration_warnings() const override;
|
||||
|
||||
void set_replication_interval(double p_interval);
|
||||
double get_replication_interval() const;
|
||||
|
||||
void set_delta_interval(double p_interval);
|
||||
double get_delta_interval() const;
|
||||
|
||||
void set_replication_config(Ref<SceneReplicationConfig> p_config);
|
||||
Ref<SceneReplicationConfig> get_replication_config();
|
||||
|
||||
void set_root_path(const NodePath &p_path);
|
||||
NodePath get_root_path() const;
|
||||
virtual void set_multiplayer_authority(int p_peer_id, bool p_recursive = true) override;
|
||||
|
||||
bool is_visibility_public() const;
|
||||
void set_visibility_public(bool p_public);
|
||||
bool is_visible_to(int p_peer);
|
||||
void set_visibility_for(int p_peer, bool p_visible);
|
||||
bool get_visibility_for(int p_peer) const;
|
||||
void update_visibility(int p_for_peer);
|
||||
void set_visibility_update_mode(VisibilityUpdateMode p_mode);
|
||||
void add_visibility_filter(Callable p_callback);
|
||||
void remove_visibility_filter(Callable p_callback);
|
||||
VisibilityUpdateMode get_visibility_update_mode() const;
|
||||
|
||||
List<Variant> get_delta_state(uint64_t p_cur_usec, uint64_t p_last_usec, uint64_t &r_indexes);
|
||||
List<NodePath> get_delta_properties(uint64_t p_indexes);
|
||||
SceneReplicationConfig *get_replication_config_ptr() const;
|
||||
|
||||
MultiplayerSynchronizer();
|
||||
};
|
||||
|
||||
VARIANT_ENUM_CAST(MultiplayerSynchronizer::VisibilityUpdateMode);
|
67
modules/multiplayer/register_types.cpp
Normal file
67
modules/multiplayer/register_types.cpp
Normal file
@@ -0,0 +1,67 @@
|
||||
/**************************************************************************/
|
||||
/* register_types.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "register_types.h"
|
||||
|
||||
#include "multiplayer_debugger.h"
|
||||
#include "multiplayer_spawner.h"
|
||||
#include "multiplayer_synchronizer.h"
|
||||
#include "scene_multiplayer.h"
|
||||
#include "scene_replication_interface.h"
|
||||
#include "scene_rpc_interface.h"
|
||||
|
||||
#ifdef TOOLS_ENABLED
|
||||
#include "editor/multiplayer_editor_plugin.h"
|
||||
#endif
|
||||
|
||||
void initialize_multiplayer_module(ModuleInitializationLevel p_level) {
|
||||
if (p_level == MODULE_INITIALIZATION_LEVEL_SCENE) {
|
||||
GDREGISTER_CLASS(SceneReplicationConfig);
|
||||
GDREGISTER_CLASS(MultiplayerSpawner);
|
||||
GDREGISTER_CLASS(MultiplayerSynchronizer);
|
||||
GDREGISTER_CLASS(OfflineMultiplayerPeer);
|
||||
GDREGISTER_CLASS(SceneMultiplayer);
|
||||
if (GD_IS_CLASS_ENABLED(MultiplayerAPI)) {
|
||||
MultiplayerAPI::set_default_interface("SceneMultiplayer");
|
||||
MultiplayerDebugger::initialize();
|
||||
}
|
||||
}
|
||||
#ifdef TOOLS_ENABLED
|
||||
if (p_level == MODULE_INITIALIZATION_LEVEL_EDITOR) {
|
||||
EditorPlugins::add_by_type<MultiplayerEditorPlugin>();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void uninitialize_multiplayer_module(ModuleInitializationLevel p_level) {
|
||||
if (GD_IS_CLASS_ENABLED(MultiplayerAPI)) {
|
||||
MultiplayerDebugger::deinitialize();
|
||||
}
|
||||
}
|
36
modules/multiplayer/register_types.h
Normal file
36
modules/multiplayer/register_types.h
Normal file
@@ -0,0 +1,36 @@
|
||||
/**************************************************************************/
|
||||
/* register_types.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "modules/register_module_types.h"
|
||||
|
||||
void initialize_multiplayer_module(ModuleInitializationLevel p_level);
|
||||
void uninitialize_multiplayer_module(ModuleInitializationLevel p_level);
|
305
modules/multiplayer/scene_cache_interface.cpp
Normal file
305
modules/multiplayer/scene_cache_interface.cpp
Normal file
@@ -0,0 +1,305 @@
|
||||
/**************************************************************************/
|
||||
/* scene_cache_interface.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "scene_cache_interface.h"
|
||||
|
||||
#include "scene_multiplayer.h"
|
||||
|
||||
#include "core/io/marshalls.h"
|
||||
#include "scene/main/node.h"
|
||||
#include "scene/main/window.h"
|
||||
|
||||
SceneCacheInterface::NodeCache &SceneCacheInterface::_track(Node *p_node) {
|
||||
const ObjectID oid = p_node->get_instance_id();
|
||||
NodeCache *nc = nodes_cache.getptr(oid);
|
||||
if (!nc) {
|
||||
nodes_cache[oid] = NodeCache();
|
||||
p_node->connect(SceneStringName(tree_exited), callable_mp(this, &SceneCacheInterface::_remove_node_cache).bind(oid), Object::CONNECT_ONE_SHOT);
|
||||
}
|
||||
return nodes_cache[oid];
|
||||
}
|
||||
|
||||
void SceneCacheInterface::_remove_node_cache(ObjectID p_oid) {
|
||||
NodeCache *nc = nodes_cache.getptr(p_oid);
|
||||
if (!nc) {
|
||||
return;
|
||||
}
|
||||
if (nc->cache_id) {
|
||||
assigned_ids.erase(nc->cache_id);
|
||||
}
|
||||
#if 0
|
||||
// TODO: Find a way to cleanup recv_nodes without breaking visibility and RPCs interactions.
|
||||
for (KeyValue<int, int> &E : nc->recv_ids) {
|
||||
PeerInfo *pinfo = peers_info.getptr(E.key);
|
||||
ERR_CONTINUE(!pinfo);
|
||||
pinfo->recv_nodes.erase(E.value);
|
||||
}
|
||||
#endif
|
||||
for (KeyValue<int, bool> &E : nc->confirmed_peers) {
|
||||
PeerInfo *pinfo = peers_info.getptr(E.key);
|
||||
ERR_CONTINUE(!pinfo);
|
||||
pinfo->sent_nodes.erase(p_oid);
|
||||
}
|
||||
nodes_cache.erase(p_oid);
|
||||
}
|
||||
|
||||
void SceneCacheInterface::on_peer_change(int p_id, bool p_connected) {
|
||||
if (p_connected) {
|
||||
peers_info.insert(p_id, PeerInfo());
|
||||
} else {
|
||||
PeerInfo *pinfo = peers_info.getptr(p_id);
|
||||
ERR_FAIL_NULL(pinfo); // Bug.
|
||||
for (KeyValue<int, RecvNode> E : pinfo->recv_nodes) {
|
||||
NodeCache *nc = nodes_cache.getptr(E.value.oid);
|
||||
if (!nc) {
|
||||
// Node might have already been deleted locally.
|
||||
continue;
|
||||
}
|
||||
nc->recv_ids.erase(p_id);
|
||||
}
|
||||
for (const ObjectID &oid : pinfo->sent_nodes) {
|
||||
NodeCache *nc = nodes_cache.getptr(oid);
|
||||
ERR_CONTINUE(!nc);
|
||||
nc->confirmed_peers.erase(p_id);
|
||||
}
|
||||
peers_info.erase(p_id);
|
||||
}
|
||||
}
|
||||
|
||||
void SceneCacheInterface::process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
|
||||
ERR_FAIL_COND(!peers_info.has(p_from)); // Bug.
|
||||
ERR_FAIL_COND_MSG(p_packet_len < 38, "Invalid packet received. Size too small.");
|
||||
Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());
|
||||
ERR_FAIL_NULL(root_node);
|
||||
int ofs = 1;
|
||||
|
||||
String methods_md5 = String::utf8((const char *)(p_packet + ofs), 32);
|
||||
ofs += 33;
|
||||
|
||||
int id = decode_uint32(&p_packet[ofs]);
|
||||
ofs += 4;
|
||||
|
||||
ERR_FAIL_COND_MSG(peers_info[p_from].recv_nodes.has(id), vformat("Duplicate remote cache ID %d for peer %d", id, p_from));
|
||||
|
||||
String paths = String::utf8((const char *)(p_packet + ofs), p_packet_len - ofs);
|
||||
|
||||
const NodePath path = paths;
|
||||
|
||||
Node *node = root_node->get_node(path);
|
||||
ERR_FAIL_NULL(node);
|
||||
const bool valid_rpc_checksum = multiplayer->get_rpc_md5(node) == methods_md5;
|
||||
if (valid_rpc_checksum == false) {
|
||||
ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + String(path));
|
||||
}
|
||||
|
||||
peers_info[p_from].recv_nodes.insert(id, RecvNode(node->get_instance_id(), path));
|
||||
NodeCache &cache = _track(node);
|
||||
cache.recv_ids.insert(p_from, id);
|
||||
|
||||
// Send ack.
|
||||
Vector<uint8_t> packet;
|
||||
packet.resize(1 + 1 + 4);
|
||||
packet.write[0] = SceneMultiplayer::NETWORK_COMMAND_CONFIRM_PATH;
|
||||
packet.write[1] = valid_rpc_checksum;
|
||||
encode_uint32(id, &packet.write[2]);
|
||||
|
||||
Ref<MultiplayerPeer> multiplayer_peer = multiplayer->get_multiplayer_peer();
|
||||
ERR_FAIL_COND(multiplayer_peer.is_null());
|
||||
|
||||
multiplayer_peer->set_transfer_channel(0);
|
||||
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
|
||||
multiplayer->send_command(p_from, packet.ptr(), packet.size());
|
||||
}
|
||||
|
||||
void SceneCacheInterface::process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len) {
|
||||
ERR_FAIL_COND_MSG(p_packet_len != 6, "Invalid packet received. Size too small.");
|
||||
Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());
|
||||
ERR_FAIL_NULL(root_node);
|
||||
|
||||
const bool valid_rpc_checksum = p_packet[1];
|
||||
int id = decode_uint32(&p_packet[2]);
|
||||
|
||||
const ObjectID *oid = assigned_ids.getptr(id);
|
||||
if (oid == nullptr) {
|
||||
return; // May be trying to confirm a node that was removed.
|
||||
}
|
||||
|
||||
if (valid_rpc_checksum == false) {
|
||||
const Node *node = ObjectDB::get_instance<Node>(*oid);
|
||||
ERR_FAIL_NULL(node); // Bug.
|
||||
ERR_PRINT("The rpc node checksum failed. Make sure to have the same methods on both nodes. Node path: " + String(node->get_path()));
|
||||
}
|
||||
|
||||
NodeCache *cache = nodes_cache.getptr(*oid);
|
||||
ERR_FAIL_NULL(cache); // Bug.
|
||||
|
||||
bool *confirmed = cache->confirmed_peers.getptr(p_from);
|
||||
ERR_FAIL_NULL_MSG(confirmed, "Invalid packet received. Tries to confirm a node which was not requested.");
|
||||
*confirmed = true;
|
||||
}
|
||||
|
||||
Error SceneCacheInterface::_send_confirm_path(Node *p_node, NodeCache &p_cache, const List<int> &p_peers) {
|
||||
// Encode function name.
|
||||
const CharString path = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();
|
||||
const int path_len = encode_cstring(path.get_data(), nullptr);
|
||||
|
||||
// Extract MD5 from rpc methods list.
|
||||
const String methods_md5 = multiplayer->get_rpc_md5(p_node);
|
||||
const int methods_md5_len = 33; // 32 + 1 for the `0` that is added by the encoder.
|
||||
|
||||
Vector<uint8_t> packet;
|
||||
packet.resize(1 + 4 + path_len + methods_md5_len);
|
||||
int ofs = 0;
|
||||
|
||||
packet.write[ofs] = SceneMultiplayer::NETWORK_COMMAND_SIMPLIFY_PATH;
|
||||
ofs += 1;
|
||||
|
||||
ofs += encode_cstring(methods_md5.utf8().get_data(), &packet.write[ofs]);
|
||||
|
||||
ofs += encode_uint32(p_cache.cache_id, &packet.write[ofs]);
|
||||
|
||||
ofs += encode_cstring(path.get_data(), &packet.write[ofs]);
|
||||
|
||||
Ref<MultiplayerPeer> multiplayer_peer = multiplayer->get_multiplayer_peer();
|
||||
ERR_FAIL_COND_V(multiplayer_peer.is_null(), ERR_BUG);
|
||||
|
||||
Error err = OK;
|
||||
for (int peer_id : p_peers) {
|
||||
multiplayer_peer->set_transfer_channel(0);
|
||||
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
|
||||
err = multiplayer->send_command(peer_id, packet.ptr(), packet.size());
|
||||
ERR_FAIL_COND_V(err != OK, err);
|
||||
// Insert into confirmed, but as false since it was not confirmed.
|
||||
p_cache.confirmed_peers.insert(peer_id, false);
|
||||
ERR_CONTINUE(!peers_info.has(peer_id));
|
||||
peers_info[peer_id].sent_nodes.insert(p_node->get_instance_id());
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
bool SceneCacheInterface::is_cache_confirmed(Node *p_node, int p_peer) {
|
||||
ERR_FAIL_NULL_V(p_node, false);
|
||||
const ObjectID oid = p_node->get_instance_id();
|
||||
NodeCache *cache = nodes_cache.getptr(oid);
|
||||
bool *confirmed = cache ? cache->confirmed_peers.getptr(p_peer) : nullptr;
|
||||
return confirmed && *confirmed;
|
||||
}
|
||||
|
||||
int SceneCacheInterface::make_object_cache(Object *p_obj) {
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_NULL_V(node, -1);
|
||||
NodeCache &cache = _track(node);
|
||||
if (cache.cache_id == 0) {
|
||||
cache.cache_id = last_send_cache_id++;
|
||||
assigned_ids[cache.cache_id] = p_obj->get_instance_id();
|
||||
}
|
||||
return cache.cache_id;
|
||||
}
|
||||
|
||||
bool SceneCacheInterface::send_object_cache(Object *p_obj, int p_peer_id, int &r_id) {
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_NULL_V(node, false);
|
||||
// See if the path is cached.
|
||||
NodeCache &cache = _track(node);
|
||||
if (cache.cache_id == 0) {
|
||||
cache.cache_id = last_send_cache_id++;
|
||||
assigned_ids[cache.cache_id] = p_obj->get_instance_id();
|
||||
}
|
||||
r_id = cache.cache_id;
|
||||
|
||||
bool has_all_peers = true;
|
||||
List<int> peers_to_add; // If one is missing, take note to add it.
|
||||
|
||||
if (p_peer_id > 0) {
|
||||
// Fast single peer check.
|
||||
ERR_FAIL_COND_V_MSG(!peers_info.has(p_peer_id), false, "Peer doesn't exist: " + itos(p_peer_id));
|
||||
|
||||
bool *confirmed = cache.confirmed_peers.getptr(p_peer_id);
|
||||
if (!confirmed) {
|
||||
peers_to_add.push_back(p_peer_id); // Need to also be notified.
|
||||
has_all_peers = false;
|
||||
} else if (!(*confirmed)) {
|
||||
has_all_peers = false;
|
||||
}
|
||||
} else {
|
||||
// Long and painful.
|
||||
for (KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
if (p_peer_id < 0 && E.key == -p_peer_id) {
|
||||
continue; // Continue, excluded.
|
||||
}
|
||||
|
||||
bool *confirmed = cache.confirmed_peers.getptr(E.key);
|
||||
if (!confirmed) {
|
||||
peers_to_add.push_back(E.key); // Need to also be notified.
|
||||
has_all_peers = false;
|
||||
} else if (!(*confirmed)) {
|
||||
has_all_peers = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (peers_to_add.size()) {
|
||||
_send_confirm_path(node, cache, peers_to_add);
|
||||
}
|
||||
|
||||
return has_all_peers;
|
||||
}
|
||||
|
||||
Object *SceneCacheInterface::get_cached_object(int p_from, uint32_t p_cache_id) {
|
||||
PeerInfo *pinfo = peers_info.getptr(p_from);
|
||||
ERR_FAIL_NULL_V(pinfo, nullptr);
|
||||
|
||||
RecvNode *recv_node = pinfo->recv_nodes.getptr(p_cache_id);
|
||||
ERR_FAIL_NULL_V_MSG(recv_node, nullptr, vformat("ID %d not found in cache of peer %d.", p_cache_id, p_from));
|
||||
Node *node = ObjectDB::get_instance<Node>(recv_node->oid);
|
||||
if (!node) {
|
||||
// Fallback to path lookup.
|
||||
Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());
|
||||
ERR_FAIL_NULL_V(root_node, nullptr);
|
||||
node = root_node->get_node(recv_node->path);
|
||||
if (node) {
|
||||
recv_node->oid = node->get_instance_id();
|
||||
}
|
||||
}
|
||||
ERR_FAIL_NULL_V_MSG(node, nullptr, vformat("Failed to get cached node from peer %d with cache ID %d.", p_from, p_cache_id));
|
||||
return node;
|
||||
}
|
||||
|
||||
void SceneCacheInterface::clear() {
|
||||
for (KeyValue<ObjectID, NodeCache> &E : nodes_cache) {
|
||||
Object *obj = ObjectDB::get_instance(E.key);
|
||||
ERR_CONTINUE(!obj);
|
||||
obj->disconnect(SceneStringName(tree_exited), callable_mp(this, &SceneCacheInterface::_remove_node_cache));
|
||||
}
|
||||
peers_info.clear();
|
||||
nodes_cache.clear();
|
||||
assigned_ids.clear();
|
||||
last_send_cache_id = 1;
|
||||
}
|
90
modules/multiplayer/scene_cache_interface.h
Normal file
90
modules/multiplayer/scene_cache_interface.h
Normal file
@@ -0,0 +1,90 @@
|
||||
/**************************************************************************/
|
||||
/* scene_cache_interface.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/object/ref_counted.h"
|
||||
|
||||
class Node;
|
||||
class SceneMultiplayer;
|
||||
|
||||
class SceneCacheInterface : public RefCounted {
|
||||
GDCLASS(SceneCacheInterface, RefCounted);
|
||||
|
||||
private:
|
||||
SceneMultiplayer *multiplayer = nullptr;
|
||||
|
||||
//path sent caches
|
||||
struct NodeCache {
|
||||
int cache_id = 0;
|
||||
HashMap<int, int> recv_ids; // peer id, remote cache id
|
||||
HashMap<int, bool> confirmed_peers; // peer id, confirmed
|
||||
};
|
||||
|
||||
struct RecvNode {
|
||||
ObjectID oid;
|
||||
NodePath path;
|
||||
|
||||
RecvNode(const ObjectID &p_oid, const NodePath &p_path) {
|
||||
oid = p_oid;
|
||||
path = p_path;
|
||||
}
|
||||
};
|
||||
|
||||
struct PeerInfo {
|
||||
HashMap<int, RecvNode> recv_nodes; // remote cache id, (ObjectID, NodePath)
|
||||
HashSet<ObjectID> sent_nodes;
|
||||
};
|
||||
|
||||
HashMap<ObjectID, NodeCache> nodes_cache;
|
||||
HashMap<int, ObjectID> assigned_ids;
|
||||
HashMap<int, PeerInfo> peers_info;
|
||||
int last_send_cache_id = 1;
|
||||
|
||||
void _remove_node_cache(ObjectID p_oid);
|
||||
NodeCache &_track(Node *p_node);
|
||||
|
||||
protected:
|
||||
Error _send_confirm_path(Node *p_node, NodeCache &p_cache, const List<int> &p_peers);
|
||||
|
||||
public:
|
||||
void clear();
|
||||
void on_peer_change(int p_id, bool p_connected);
|
||||
void process_simplify_path(int p_from, const uint8_t *p_packet, int p_packet_len);
|
||||
void process_confirm_path(int p_from, const uint8_t *p_packet, int p_packet_len);
|
||||
|
||||
// Returns true if all peers have cached path.
|
||||
bool send_object_cache(Object *p_obj, int p_target, int &p_id);
|
||||
int make_object_cache(Object *p_obj);
|
||||
Object *get_cached_object(int p_from, uint32_t p_cache_id);
|
||||
bool is_cache_confirmed(Node *p_path, int p_peer);
|
||||
|
||||
SceneCacheInterface(SceneMultiplayer *p_multiplayer) { multiplayer = p_multiplayer; }
|
||||
};
|
698
modules/multiplayer/scene_multiplayer.cpp
Normal file
698
modules/multiplayer/scene_multiplayer.cpp
Normal file
@@ -0,0 +1,698 @@
|
||||
/**************************************************************************/
|
||||
/* scene_multiplayer.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "scene_multiplayer.h"
|
||||
|
||||
#include "core/debugger/engine_debugger.h"
|
||||
#include "core/io/marshalls.h"
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
#include "core/os/os.h"
|
||||
#endif
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ void SceneMultiplayer::_profile_bandwidth(const String &p_what, int p_value) {
|
||||
if (EngineDebugger::is_profiling("multiplayer:bandwidth")) {
|
||||
Array values = {
|
||||
p_what,
|
||||
OS::get_singleton()->get_ticks_msec(),
|
||||
p_value
|
||||
};
|
||||
EngineDebugger::profiler_add_frame_data("multiplayer:bandwidth", values);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
void SceneMultiplayer::_update_status() {
|
||||
MultiplayerPeer::ConnectionStatus status = multiplayer_peer.is_valid() ? multiplayer_peer->get_connection_status() : MultiplayerPeer::CONNECTION_DISCONNECTED;
|
||||
if (last_connection_status != status) {
|
||||
if (status == MultiplayerPeer::CONNECTION_DISCONNECTED) {
|
||||
if (last_connection_status == MultiplayerPeer::CONNECTION_CONNECTING) {
|
||||
emit_signal(SNAME("connection_failed"));
|
||||
} else {
|
||||
emit_signal(SNAME("server_disconnected"));
|
||||
}
|
||||
clear();
|
||||
}
|
||||
last_connection_status = status;
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::poll() {
|
||||
_update_status();
|
||||
if (last_connection_status == MultiplayerPeer::CONNECTION_DISCONNECTED) {
|
||||
return OK;
|
||||
}
|
||||
|
||||
multiplayer_peer->poll();
|
||||
|
||||
_update_status();
|
||||
if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) {
|
||||
// We might be still connecting, or polling might have resulted in a disconnection.
|
||||
return OK;
|
||||
}
|
||||
|
||||
while (multiplayer_peer->get_available_packet_count()) {
|
||||
int sender = multiplayer_peer->get_packet_peer();
|
||||
const uint8_t *packet;
|
||||
int len;
|
||||
|
||||
int channel = multiplayer_peer->get_packet_channel();
|
||||
MultiplayerPeer::TransferMode mode = multiplayer_peer->get_packet_mode();
|
||||
|
||||
Error err = multiplayer_peer->get_packet(&packet, len);
|
||||
ERR_FAIL_COND_V_MSG(err != OK, err, vformat("Error getting packet! %d", err));
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_bandwidth("in", len);
|
||||
#endif
|
||||
|
||||
if (pending_peers.has(sender)) {
|
||||
ERR_CONTINUE(len < 2 || (packet[0] & CMD_MASK) != NETWORK_COMMAND_SYS || packet[1] != SYS_COMMAND_AUTH);
|
||||
// Auth message.
|
||||
PackedByteArray pba;
|
||||
pba.resize(len - 2);
|
||||
if (pba.size()) {
|
||||
memcpy(pba.ptrw(), &packet[2], len - 2);
|
||||
// User callback
|
||||
const Variant sv = sender;
|
||||
const Variant pbav = pba;
|
||||
const Variant *argv[2] = { &sv, &pbav };
|
||||
Variant ret;
|
||||
Callable::CallError ce;
|
||||
auth_callback.callp(argv, 2, ret, ce);
|
||||
ERR_CONTINUE_MSG(ce.error != Callable::CallError::CALL_OK, "Failed to call authentication callback");
|
||||
} else {
|
||||
// Remote complete notification.
|
||||
pending_peers[sender].remote = true;
|
||||
if (pending_peers[sender].local) {
|
||||
pending_peers.erase(sender);
|
||||
_admit_peer(sender);
|
||||
}
|
||||
}
|
||||
continue; // Auth in progress.
|
||||
}
|
||||
|
||||
ERR_CONTINUE(!connected_peers.has(sender));
|
||||
|
||||
if (len && (packet[0] & CMD_MASK) == NETWORK_COMMAND_SYS) {
|
||||
// Sys messages are processed separately since they might call _process_packet themselves.
|
||||
if (len > 1 && packet[1] == SYS_COMMAND_AUTH) {
|
||||
ERR_CONTINUE(len != 2);
|
||||
// If we are here, we already admitted the peer locally, and this is just a confirmation packet.
|
||||
continue;
|
||||
}
|
||||
|
||||
_process_sys(sender, packet, len, mode, channel);
|
||||
} else {
|
||||
remote_sender_id = sender;
|
||||
_process_packet(sender, packet, len);
|
||||
remote_sender_id = 0;
|
||||
}
|
||||
|
||||
_update_status();
|
||||
if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // It's possible that processing a packet might have resulted in a disconnection, so check here.
|
||||
return OK;
|
||||
}
|
||||
}
|
||||
if (pending_peers.size() && auth_timeout) {
|
||||
HashSet<int> to_drop;
|
||||
uint64_t time = OS::get_singleton()->get_ticks_msec();
|
||||
for (const KeyValue<int, PendingPeer> &pending : pending_peers) {
|
||||
if (pending.value.time + auth_timeout <= time) {
|
||||
multiplayer_peer->disconnect_peer(pending.key);
|
||||
to_drop.insert(pending.key);
|
||||
}
|
||||
}
|
||||
for (const int &P : to_drop) {
|
||||
// Each signal might trigger a disconnection.
|
||||
pending_peers.erase(P);
|
||||
emit_signal(SNAME("peer_authentication_failed"), P);
|
||||
}
|
||||
}
|
||||
|
||||
_update_status();
|
||||
if (last_connection_status != MultiplayerPeer::CONNECTION_CONNECTED) { // Signals might have triggered disconnection.
|
||||
return OK;
|
||||
}
|
||||
|
||||
replicator->on_network_process();
|
||||
return OK;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::clear() {
|
||||
last_connection_status = MultiplayerPeer::CONNECTION_DISCONNECTED;
|
||||
pending_peers.clear();
|
||||
connected_peers.clear();
|
||||
packet_cache.clear();
|
||||
replicator->on_reset();
|
||||
cache->clear();
|
||||
relay_buffer->clear();
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_root_path(const NodePath &p_path) {
|
||||
ERR_FAIL_COND_MSG(!p_path.is_absolute() && !p_path.is_empty(), "SceneMultiplayer root path must be absolute.");
|
||||
root_path = p_path;
|
||||
}
|
||||
|
||||
NodePath SceneMultiplayer::get_root_path() const {
|
||||
return root_path;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) {
|
||||
if (p_peer == multiplayer_peer) {
|
||||
return; // Nothing to do
|
||||
}
|
||||
|
||||
ERR_FAIL_COND_MSG(p_peer.is_valid() && p_peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED,
|
||||
"Supplied MultiplayerPeer must be connecting or connected.");
|
||||
|
||||
if (multiplayer_peer.is_valid()) {
|
||||
multiplayer_peer->disconnect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
|
||||
multiplayer_peer->disconnect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
|
||||
clear();
|
||||
}
|
||||
|
||||
multiplayer_peer = p_peer;
|
||||
|
||||
if (multiplayer_peer.is_valid()) {
|
||||
multiplayer_peer->connect("peer_connected", callable_mp(this, &SceneMultiplayer::_add_peer));
|
||||
multiplayer_peer->connect("peer_disconnected", callable_mp(this, &SceneMultiplayer::_del_peer));
|
||||
}
|
||||
_update_status();
|
||||
}
|
||||
|
||||
Ref<MultiplayerPeer> SceneMultiplayer::get_multiplayer_peer() {
|
||||
return multiplayer_peer;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_process_packet(int p_from, const uint8_t *p_packet, int p_packet_len) {
|
||||
ERR_FAIL_COND_MSG(root_path.is_empty(), "Multiplayer root was not initialized. If you are using custom multiplayer, remember to set the root path via SceneMultiplayer.set_root_path before using it.");
|
||||
ERR_FAIL_COND_MSG(p_packet_len < 1, "Invalid packet received. Size too small.");
|
||||
|
||||
// Extract the `packet_type` from the LSB three bits:
|
||||
uint8_t packet_type = p_packet[0] & CMD_MASK;
|
||||
|
||||
switch (packet_type) {
|
||||
case NETWORK_COMMAND_SIMPLIFY_PATH: {
|
||||
cache->process_simplify_path(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
|
||||
case NETWORK_COMMAND_CONFIRM_PATH: {
|
||||
cache->process_confirm_path(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
|
||||
case NETWORK_COMMAND_REMOTE_CALL: {
|
||||
rpc->process_rpc(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
|
||||
case NETWORK_COMMAND_RAW: {
|
||||
_process_raw(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
case NETWORK_COMMAND_SPAWN: {
|
||||
replicator->on_spawn_receive(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
case NETWORK_COMMAND_DESPAWN: {
|
||||
replicator->on_despawn_receive(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
case NETWORK_COMMAND_SYNC: {
|
||||
replicator->on_sync_receive(p_from, p_packet, p_packet_len);
|
||||
} break;
|
||||
default: {
|
||||
ERR_FAIL_MSG("Invalid network command from " + itos(p_from));
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ Error SceneMultiplayer::_send(const uint8_t *p_packet, int p_packet_len) {
|
||||
_profile_bandwidth("out", p_packet_len);
|
||||
return multiplayer_peer->put_packet(p_packet, p_packet_len);
|
||||
}
|
||||
#endif
|
||||
|
||||
Error SceneMultiplayer::send_command(int p_to, const uint8_t *p_packet, int p_packet_len) {
|
||||
if (server_relay && get_unique_id() != 1 && p_to != 1 && multiplayer_peer->is_server_relay_supported()) {
|
||||
// Send relay packet.
|
||||
relay_buffer->seek(0);
|
||||
relay_buffer->put_u8(NETWORK_COMMAND_SYS);
|
||||
relay_buffer->put_u8(SYS_COMMAND_RELAY);
|
||||
relay_buffer->put_32(p_to); // Set the destination.
|
||||
relay_buffer->put_data(p_packet, p_packet_len);
|
||||
multiplayer_peer->set_target_peer(1);
|
||||
const Vector<uint8_t> data = relay_buffer->get_data_array();
|
||||
return _send(data.ptr(), relay_buffer->get_position());
|
||||
}
|
||||
if (p_to > 0) {
|
||||
ERR_FAIL_COND_V(!connected_peers.has(p_to), ERR_BUG);
|
||||
multiplayer_peer->set_target_peer(p_to);
|
||||
return _send(p_packet, p_packet_len);
|
||||
} else {
|
||||
for (const int &pid : connected_peers) {
|
||||
if (p_to && pid == -p_to) {
|
||||
continue;
|
||||
}
|
||||
multiplayer_peer->set_target_peer(pid);
|
||||
_send(p_packet, p_packet_len);
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel) {
|
||||
ERR_FAIL_COND_MSG(p_packet_len < SYS_CMD_SIZE, "Invalid packet received. Size too small.");
|
||||
uint8_t sys_cmd_type = p_packet[1];
|
||||
int32_t peer = int32_t(decode_uint32(&p_packet[2]));
|
||||
switch (sys_cmd_type) {
|
||||
case SYS_COMMAND_ADD_PEER: {
|
||||
ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
|
||||
_admit_peer(peer); // Relayed peers are automatically accepted.
|
||||
} break;
|
||||
case SYS_COMMAND_DEL_PEER: {
|
||||
ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported() || get_unique_id() == 1 || p_from != 1);
|
||||
_del_peer(peer);
|
||||
} break;
|
||||
case SYS_COMMAND_RELAY: {
|
||||
ERR_FAIL_COND(!server_relay || !multiplayer_peer->is_server_relay_supported());
|
||||
ERR_FAIL_COND(p_packet_len < SYS_CMD_SIZE + 1);
|
||||
const uint8_t *packet = p_packet + SYS_CMD_SIZE;
|
||||
int len = p_packet_len - SYS_CMD_SIZE;
|
||||
bool should_process = false;
|
||||
if (get_unique_id() == 1) { // I am the server.
|
||||
// The requested target might have disconnected while the packet was in transit.
|
||||
if (unlikely(peer > 0 && !connected_peers.has(peer))) {
|
||||
return;
|
||||
}
|
||||
// Send relay packet.
|
||||
relay_buffer->seek(0);
|
||||
relay_buffer->put_u8(NETWORK_COMMAND_SYS);
|
||||
relay_buffer->put_u8(SYS_COMMAND_RELAY);
|
||||
relay_buffer->put_32(p_from); // Set the source.
|
||||
relay_buffer->put_data(packet, len);
|
||||
const Vector<uint8_t> data = relay_buffer->get_data_array();
|
||||
multiplayer_peer->set_transfer_mode(p_mode);
|
||||
multiplayer_peer->set_transfer_channel(p_channel);
|
||||
if (peer > 0) {
|
||||
// Single destination.
|
||||
multiplayer_peer->set_target_peer(peer);
|
||||
_send(data.ptr(), relay_buffer->get_position());
|
||||
} else {
|
||||
// Multiple destinations.
|
||||
for (const int &P : connected_peers) {
|
||||
// Not to sender, nor excluded.
|
||||
if (P == p_from || P == -peer) {
|
||||
continue;
|
||||
}
|
||||
multiplayer_peer->set_target_peer(P);
|
||||
_send(data.ptr(), relay_buffer->get_position());
|
||||
}
|
||||
if (peer != -1) {
|
||||
// The server is one of the targets, process the packet with sender as source.
|
||||
should_process = true;
|
||||
peer = p_from;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ERR_FAIL_COND(p_from != 1); // Bug.
|
||||
should_process = true;
|
||||
}
|
||||
if (should_process) {
|
||||
remote_sender_id = peer;
|
||||
_process_packet(peer, packet, len);
|
||||
remote_sender_id = 0;
|
||||
}
|
||||
} break;
|
||||
default: {
|
||||
ERR_FAIL();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_add_peer(int p_id) {
|
||||
if (auth_callback.is_valid()) {
|
||||
pending_peers[p_id] = PendingPeer();
|
||||
pending_peers[p_id].time = OS::get_singleton()->get_ticks_msec();
|
||||
emit_signal(SNAME("peer_authenticating"), p_id);
|
||||
return;
|
||||
} else {
|
||||
_admit_peer(p_id);
|
||||
}
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_admit_peer(int p_id) {
|
||||
if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
|
||||
// Notify others of connection, and send connected peers to newly connected one.
|
||||
uint8_t buf[SYS_CMD_SIZE];
|
||||
buf[0] = NETWORK_COMMAND_SYS;
|
||||
buf[1] = SYS_COMMAND_ADD_PEER;
|
||||
multiplayer_peer->set_transfer_channel(0);
|
||||
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
|
||||
for (const int &P : connected_peers) {
|
||||
// Send new peer to already connected.
|
||||
encode_uint32(p_id, &buf[2]);
|
||||
multiplayer_peer->set_target_peer(P);
|
||||
_send(buf, sizeof(buf));
|
||||
// Send already connected to new peer.
|
||||
encode_uint32(P, &buf[2]);
|
||||
multiplayer_peer->set_target_peer(p_id);
|
||||
_send(buf, sizeof(buf));
|
||||
}
|
||||
}
|
||||
|
||||
connected_peers.insert(p_id);
|
||||
cache->on_peer_change(p_id, true);
|
||||
replicator->on_peer_change(p_id, true);
|
||||
if (p_id == 1) {
|
||||
emit_signal(SNAME("connected_to_server"));
|
||||
}
|
||||
emit_signal(SNAME("peer_connected"), p_id);
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_del_peer(int p_id) {
|
||||
if (pending_peers.has(p_id)) {
|
||||
pending_peers.erase(p_id);
|
||||
emit_signal(SNAME("peer_authentication_failed"), p_id);
|
||||
return;
|
||||
} else if (!connected_peers.has(p_id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (server_relay && get_unique_id() == 1 && multiplayer_peer->is_server_relay_supported()) {
|
||||
// Notify others of disconnection.
|
||||
uint8_t buf[SYS_CMD_SIZE];
|
||||
buf[0] = NETWORK_COMMAND_SYS;
|
||||
buf[1] = SYS_COMMAND_DEL_PEER;
|
||||
multiplayer_peer->set_transfer_channel(0);
|
||||
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
|
||||
encode_uint32(p_id, &buf[2]);
|
||||
for (const int &P : connected_peers) {
|
||||
if (P == p_id) {
|
||||
continue;
|
||||
}
|
||||
multiplayer_peer->set_target_peer(P);
|
||||
_send(buf, sizeof(buf));
|
||||
}
|
||||
}
|
||||
|
||||
replicator->on_peer_change(p_id, false);
|
||||
cache->on_peer_change(p_id, false);
|
||||
connected_peers.erase(p_id);
|
||||
emit_signal(SNAME("peer_disconnected"), p_id);
|
||||
}
|
||||
|
||||
void SceneMultiplayer::disconnect_peer(int p_id) {
|
||||
ERR_FAIL_COND(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED);
|
||||
// Block signals to avoid emitting peer_disconnected.
|
||||
bool blocking = is_blocking_signals();
|
||||
set_block_signals(true);
|
||||
_del_peer(p_id);
|
||||
set_block_signals(blocking);
|
||||
multiplayer_peer->disconnect_peer(p_id);
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::send_bytes(Vector<uint8_t> p_data, int p_to, MultiplayerPeer::TransferMode p_mode, int p_channel) {
|
||||
ERR_FAIL_COND_V_MSG(p_data.is_empty(), ERR_INVALID_DATA, "Trying to send an empty raw packet.");
|
||||
ERR_FAIL_COND_V_MSG(multiplayer_peer.is_null(), ERR_UNCONFIGURED, "Trying to send a raw packet while no multiplayer peer is active.");
|
||||
ERR_FAIL_COND_V_MSG(multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED, "Trying to send a raw packet via a multiplayer peer which is not connected.");
|
||||
|
||||
if (packet_cache.size() < p_data.size() + 1) {
|
||||
packet_cache.resize(p_data.size() + 1);
|
||||
}
|
||||
|
||||
const uint8_t *r = p_data.ptr();
|
||||
packet_cache.write[0] = NETWORK_COMMAND_RAW;
|
||||
memcpy(&packet_cache.write[1], &r[0], p_data.size());
|
||||
|
||||
multiplayer_peer->set_transfer_channel(p_channel);
|
||||
multiplayer_peer->set_transfer_mode(p_mode);
|
||||
return send_command(p_to, packet_cache.ptr(), p_data.size() + 1);
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::send_auth(int p_to, Vector<uint8_t> p_data) {
|
||||
ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
|
||||
ERR_FAIL_COND_V(!pending_peers.has(p_to), ERR_INVALID_PARAMETER);
|
||||
ERR_FAIL_COND_V(p_data.is_empty(), ERR_INVALID_PARAMETER);
|
||||
ERR_FAIL_COND_V_MSG(pending_peers[p_to].local, ERR_FILE_CANT_WRITE, "The authentication session was previously marked as completed, no more authentication data can be sent.");
|
||||
ERR_FAIL_COND_V_MSG(pending_peers[p_to].remote, ERR_FILE_CANT_WRITE, "The remote peer notified that the authentication session was completed, no more authentication data can be sent.");
|
||||
|
||||
if (packet_cache.size() < p_data.size() + 2) {
|
||||
packet_cache.resize(p_data.size() + 2);
|
||||
}
|
||||
|
||||
packet_cache.write[0] = NETWORK_COMMAND_SYS;
|
||||
packet_cache.write[1] = SYS_COMMAND_AUTH;
|
||||
memcpy(&packet_cache.write[2], p_data.ptr(), p_data.size());
|
||||
|
||||
multiplayer_peer->set_target_peer(p_to);
|
||||
multiplayer_peer->set_transfer_channel(0);
|
||||
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
|
||||
return _send(packet_cache.ptr(), p_data.size() + 2);
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::complete_auth(int p_peer) {
|
||||
ERR_FAIL_COND_V(multiplayer_peer.is_null() || multiplayer_peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_UNCONFIGURED);
|
||||
ERR_FAIL_COND_V(!pending_peers.has(p_peer), ERR_INVALID_PARAMETER);
|
||||
ERR_FAIL_COND_V_MSG(pending_peers[p_peer].local, ERR_FILE_CANT_WRITE, "The authentication session was already marked as completed.");
|
||||
pending_peers[p_peer].local = true;
|
||||
|
||||
// Notify the remote peer that the authentication has completed.
|
||||
uint8_t buf[2] = { NETWORK_COMMAND_SYS, SYS_COMMAND_AUTH };
|
||||
multiplayer_peer->set_target_peer(p_peer);
|
||||
multiplayer_peer->set_transfer_channel(0);
|
||||
multiplayer_peer->set_transfer_mode(MultiplayerPeer::TRANSFER_MODE_RELIABLE);
|
||||
Error err = _send(buf, 2);
|
||||
|
||||
// The remote peer already reported the authentication as completed, so admit the peer.
|
||||
// May generate new packets, so it must happen after sending confirmation.
|
||||
if (pending_peers[p_peer].remote) {
|
||||
pending_peers.erase(p_peer);
|
||||
_admit_peer(p_peer);
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_auth_callback(Callable p_callback) {
|
||||
auth_callback = p_callback;
|
||||
}
|
||||
|
||||
Callable SceneMultiplayer::get_auth_callback() const {
|
||||
return auth_callback;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_auth_timeout(double p_timeout) {
|
||||
ERR_FAIL_COND_MSG(p_timeout < 0, "Timeout must be greater or equal to 0 (where 0 means no timeout)");
|
||||
auth_timeout = uint64_t(p_timeout * 1000);
|
||||
}
|
||||
|
||||
double SceneMultiplayer::get_auth_timeout() const {
|
||||
return double(auth_timeout) / 1000.0;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_process_raw(int p_from, const uint8_t *p_packet, int p_packet_len) {
|
||||
ERR_FAIL_COND_MSG(p_packet_len < 2, "Invalid packet received. Size too small.");
|
||||
|
||||
Vector<uint8_t> out;
|
||||
int len = p_packet_len - 1;
|
||||
out.resize(len);
|
||||
{
|
||||
uint8_t *w = out.ptrw();
|
||||
memcpy(&w[0], &p_packet[1], len);
|
||||
}
|
||||
emit_signal(SNAME("peer_packet"), p_from, out);
|
||||
}
|
||||
|
||||
int SceneMultiplayer::get_unique_id() {
|
||||
ERR_FAIL_COND_V_MSG(multiplayer_peer.is_null(), 0, "No multiplayer peer is assigned. Unable to get unique ID.");
|
||||
return multiplayer_peer->get_unique_id();
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_refuse_new_connections(bool p_refuse) {
|
||||
ERR_FAIL_COND_MSG(multiplayer_peer.is_null(), "No multiplayer peer is assigned. Unable to set 'refuse_new_connections'.");
|
||||
multiplayer_peer->set_refuse_new_connections(p_refuse);
|
||||
}
|
||||
|
||||
bool SceneMultiplayer::is_refusing_new_connections() const {
|
||||
ERR_FAIL_COND_V_MSG(multiplayer_peer.is_null(), false, "No multiplayer peer is assigned. Unable to get 'refuse_new_connections'.");
|
||||
return multiplayer_peer->is_refusing_new_connections();
|
||||
}
|
||||
|
||||
Vector<int> SceneMultiplayer::get_peer_ids() {
|
||||
ERR_FAIL_COND_V_MSG(multiplayer_peer.is_null(), Vector<int>(), "No multiplayer peer is assigned. Assume no peers are connected.");
|
||||
|
||||
Vector<int> ret;
|
||||
for (const int &E : connected_peers) {
|
||||
ret.push_back(E);
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
Vector<int> SceneMultiplayer::get_authenticating_peer_ids() {
|
||||
Vector<int> out;
|
||||
out.resize(pending_peers.size());
|
||||
int idx = 0;
|
||||
for (const KeyValue<int, PendingPeer> &E : pending_peers) {
|
||||
out.write[idx++] = E.key;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_allow_object_decoding(bool p_enable) {
|
||||
allow_object_decoding = p_enable;
|
||||
}
|
||||
|
||||
bool SceneMultiplayer::is_object_decoding_allowed() const {
|
||||
return allow_object_decoding;
|
||||
}
|
||||
|
||||
String SceneMultiplayer::get_rpc_md5(const Object *p_obj) {
|
||||
return rpc->get_rpc_md5(p_obj);
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
|
||||
return rpc->rpcp(p_obj, p_peer_id, p_method, p_arg, p_argcount);
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::object_configuration_add(Object *p_obj, Variant p_config) {
|
||||
if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
|
||||
set_root_path(p_config);
|
||||
return OK;
|
||||
}
|
||||
MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
|
||||
MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
|
||||
if (spawner) {
|
||||
return replicator->on_spawn(p_obj, p_config);
|
||||
} else if (sync) {
|
||||
return replicator->on_replication_start(p_obj, p_config);
|
||||
}
|
||||
return ERR_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
Error SceneMultiplayer::object_configuration_remove(Object *p_obj, Variant p_config) {
|
||||
if (p_obj == nullptr && p_config.get_type() == Variant::NODE_PATH) {
|
||||
ERR_FAIL_COND_V(root_path != p_config.operator NodePath(), ERR_INVALID_PARAMETER);
|
||||
set_root_path(NodePath());
|
||||
return OK;
|
||||
}
|
||||
MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
|
||||
MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
|
||||
if (spawner) {
|
||||
return replicator->on_despawn(p_obj, p_config);
|
||||
}
|
||||
if (sync) {
|
||||
return replicator->on_replication_stop(p_obj, p_config);
|
||||
}
|
||||
return ERR_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_server_relay_enabled(bool p_enabled) {
|
||||
server_relay = p_enabled;
|
||||
}
|
||||
|
||||
bool SceneMultiplayer::is_server_relay_enabled() const {
|
||||
return server_relay;
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_max_sync_packet_size(int p_size) {
|
||||
replicator->set_max_sync_packet_size(p_size);
|
||||
}
|
||||
|
||||
int SceneMultiplayer::get_max_sync_packet_size() const {
|
||||
return replicator->get_max_sync_packet_size();
|
||||
}
|
||||
|
||||
void SceneMultiplayer::set_max_delta_packet_size(int p_size) {
|
||||
replicator->set_max_delta_packet_size(p_size);
|
||||
}
|
||||
|
||||
int SceneMultiplayer::get_max_delta_packet_size() const {
|
||||
return replicator->get_max_delta_packet_size();
|
||||
}
|
||||
|
||||
void SceneMultiplayer::_bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("set_root_path", "path"), &SceneMultiplayer::set_root_path);
|
||||
ClassDB::bind_method(D_METHOD("get_root_path"), &SceneMultiplayer::get_root_path);
|
||||
ClassDB::bind_method(D_METHOD("clear"), &SceneMultiplayer::clear);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("disconnect_peer", "id"), &SceneMultiplayer::disconnect_peer);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("get_authenticating_peers"), &SceneMultiplayer::get_authenticating_peer_ids);
|
||||
ClassDB::bind_method(D_METHOD("send_auth", "id", "data"), &SceneMultiplayer::send_auth);
|
||||
ClassDB::bind_method(D_METHOD("complete_auth", "id"), &SceneMultiplayer::complete_auth);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_auth_callback", "callback"), &SceneMultiplayer::set_auth_callback);
|
||||
ClassDB::bind_method(D_METHOD("get_auth_callback"), &SceneMultiplayer::get_auth_callback);
|
||||
ClassDB::bind_method(D_METHOD("set_auth_timeout", "timeout"), &SceneMultiplayer::set_auth_timeout);
|
||||
ClassDB::bind_method(D_METHOD("get_auth_timeout"), &SceneMultiplayer::get_auth_timeout);
|
||||
|
||||
ClassDB::bind_method(D_METHOD("set_refuse_new_connections", "refuse"), &SceneMultiplayer::set_refuse_new_connections);
|
||||
ClassDB::bind_method(D_METHOD("is_refusing_new_connections"), &SceneMultiplayer::is_refusing_new_connections);
|
||||
ClassDB::bind_method(D_METHOD("set_allow_object_decoding", "enable"), &SceneMultiplayer::set_allow_object_decoding);
|
||||
ClassDB::bind_method(D_METHOD("is_object_decoding_allowed"), &SceneMultiplayer::is_object_decoding_allowed);
|
||||
ClassDB::bind_method(D_METHOD("set_server_relay_enabled", "enabled"), &SceneMultiplayer::set_server_relay_enabled);
|
||||
ClassDB::bind_method(D_METHOD("is_server_relay_enabled"), &SceneMultiplayer::is_server_relay_enabled);
|
||||
ClassDB::bind_method(D_METHOD("send_bytes", "bytes", "id", "mode", "channel"), &SceneMultiplayer::send_bytes, DEFVAL(MultiplayerPeer::TARGET_PEER_BROADCAST), DEFVAL(MultiplayerPeer::TRANSFER_MODE_RELIABLE), DEFVAL(0));
|
||||
|
||||
ClassDB::bind_method(D_METHOD("get_max_sync_packet_size"), &SceneMultiplayer::get_max_sync_packet_size);
|
||||
ClassDB::bind_method(D_METHOD("set_max_sync_packet_size", "size"), &SceneMultiplayer::set_max_sync_packet_size);
|
||||
ClassDB::bind_method(D_METHOD("get_max_delta_packet_size"), &SceneMultiplayer::get_max_delta_packet_size);
|
||||
ClassDB::bind_method(D_METHOD("set_max_delta_packet_size", "size"), &SceneMultiplayer::set_max_delta_packet_size);
|
||||
|
||||
ADD_PROPERTY(PropertyInfo(Variant::NODE_PATH, "root_path"), "set_root_path", "get_root_path");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::CALLABLE, "auth_callback"), "set_auth_callback", "get_auth_callback");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::FLOAT, "auth_timeout", PROPERTY_HINT_RANGE, "0,30,0.1,or_greater,suffix:s"), "set_auth_timeout", "get_auth_timeout");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "allow_object_decoding"), "set_allow_object_decoding", "is_object_decoding_allowed");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "refuse_new_connections"), "set_refuse_new_connections", "is_refusing_new_connections");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::BOOL, "server_relay"), "set_server_relay_enabled", "is_server_relay_enabled");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_sync_packet_size"), "set_max_sync_packet_size", "get_max_sync_packet_size");
|
||||
ADD_PROPERTY(PropertyInfo(Variant::INT, "max_delta_packet_size"), "set_max_delta_packet_size", "get_max_delta_packet_size");
|
||||
|
||||
ADD_PROPERTY_DEFAULT("refuse_new_connections", false);
|
||||
|
||||
ADD_SIGNAL(MethodInfo("peer_authenticating", PropertyInfo(Variant::INT, "id")));
|
||||
ADD_SIGNAL(MethodInfo("peer_authentication_failed", PropertyInfo(Variant::INT, "id")));
|
||||
ADD_SIGNAL(MethodInfo("peer_packet", PropertyInfo(Variant::INT, "id"), PropertyInfo(Variant::PACKED_BYTE_ARRAY, "packet")));
|
||||
}
|
||||
|
||||
SceneMultiplayer::SceneMultiplayer() {
|
||||
relay_buffer.instantiate();
|
||||
cache.instantiate(this);
|
||||
replicator.instantiate(this, cache.ptr());
|
||||
rpc.instantiate(this, cache.ptr(), replicator.ptr());
|
||||
set_multiplayer_peer(Ref<OfflineMultiplayerPeer>(memnew(OfflineMultiplayerPeer)));
|
||||
}
|
||||
|
||||
SceneMultiplayer::~SceneMultiplayer() {
|
||||
clear();
|
||||
// Ensure unref in reverse order for safety (we shouldn't use those pointers in the deconstructors anyway).
|
||||
rpc.unref();
|
||||
replicator.unref();
|
||||
cache.unref();
|
||||
}
|
205
modules/multiplayer/scene_multiplayer.h
Normal file
205
modules/multiplayer/scene_multiplayer.h
Normal file
@@ -0,0 +1,205 @@
|
||||
/**************************************************************************/
|
||||
/* scene_multiplayer.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "scene_cache_interface.h"
|
||||
#include "scene_replication_interface.h"
|
||||
#include "scene_rpc_interface.h"
|
||||
|
||||
#include "scene/main/multiplayer_api.h"
|
||||
|
||||
class OfflineMultiplayerPeer : public MultiplayerPeer {
|
||||
GDCLASS(OfflineMultiplayerPeer, MultiplayerPeer);
|
||||
|
||||
public:
|
||||
virtual int get_available_packet_count() const override { return 0; }
|
||||
virtual Error get_packet(const uint8_t **r_buffer, int &r_buffer_size) override {
|
||||
*r_buffer = nullptr;
|
||||
r_buffer_size = 0;
|
||||
return OK;
|
||||
}
|
||||
virtual Error put_packet(const uint8_t *p_buffer, int p_buffer_size) override { return OK; }
|
||||
virtual int get_max_packet_size() const override { return 0; }
|
||||
|
||||
virtual void set_target_peer(int p_peer_id) override {}
|
||||
virtual int get_packet_peer() const override { return 0; }
|
||||
virtual TransferMode get_packet_mode() const override { return TRANSFER_MODE_RELIABLE; }
|
||||
virtual int get_packet_channel() const override { return 0; }
|
||||
virtual void disconnect_peer(int p_peer, bool p_force = false) override {}
|
||||
virtual bool is_server() const override { return true; }
|
||||
virtual void poll() override {}
|
||||
virtual void close() override {}
|
||||
virtual int get_unique_id() const override { return TARGET_PEER_SERVER; }
|
||||
virtual ConnectionStatus get_connection_status() const override { return CONNECTION_CONNECTED; }
|
||||
};
|
||||
|
||||
class SceneMultiplayer : public MultiplayerAPI {
|
||||
GDCLASS(SceneMultiplayer, MultiplayerAPI);
|
||||
|
||||
public:
|
||||
enum NetworkCommands {
|
||||
NETWORK_COMMAND_REMOTE_CALL = 0,
|
||||
NETWORK_COMMAND_SIMPLIFY_PATH,
|
||||
NETWORK_COMMAND_CONFIRM_PATH,
|
||||
NETWORK_COMMAND_RAW,
|
||||
NETWORK_COMMAND_SPAWN,
|
||||
NETWORK_COMMAND_DESPAWN,
|
||||
NETWORK_COMMAND_SYNC,
|
||||
NETWORK_COMMAND_SYS,
|
||||
};
|
||||
|
||||
enum SysCommands {
|
||||
SYS_COMMAND_AUTH,
|
||||
SYS_COMMAND_ADD_PEER,
|
||||
SYS_COMMAND_DEL_PEER,
|
||||
SYS_COMMAND_RELAY,
|
||||
};
|
||||
|
||||
enum {
|
||||
SYS_CMD_SIZE = 6, // Command + sys command + peer_id (+ optional payload).
|
||||
};
|
||||
|
||||
// For each command, the 4 MSB can contain custom flags, as defined by subsystems.
|
||||
enum {
|
||||
CMD_FLAG_0_SHIFT = 4,
|
||||
CMD_FLAG_1_SHIFT = 5,
|
||||
CMD_FLAG_2_SHIFT = 6,
|
||||
CMD_FLAG_3_SHIFT = 7,
|
||||
};
|
||||
|
||||
// This is the mask that will be used to extract the command.
|
||||
enum {
|
||||
CMD_MASK = 7, // 0x7 -> 0b00000111
|
||||
};
|
||||
|
||||
private:
|
||||
struct PendingPeer {
|
||||
bool local = false;
|
||||
bool remote = false;
|
||||
uint64_t time = 0;
|
||||
};
|
||||
|
||||
Ref<MultiplayerPeer> multiplayer_peer;
|
||||
MultiplayerPeer::ConnectionStatus last_connection_status = MultiplayerPeer::CONNECTION_DISCONNECTED;
|
||||
HashMap<int, PendingPeer> pending_peers; // true if locally finalized.
|
||||
Callable auth_callback;
|
||||
uint64_t auth_timeout = 3000;
|
||||
HashSet<int> connected_peers;
|
||||
int remote_sender_id = 0;
|
||||
int remote_sender_override = 0;
|
||||
|
||||
Vector<uint8_t> packet_cache;
|
||||
|
||||
NodePath root_path;
|
||||
bool allow_object_decoding = false;
|
||||
bool server_relay = true;
|
||||
Ref<StreamPeerBuffer> relay_buffer;
|
||||
|
||||
Ref<SceneCacheInterface> cache;
|
||||
Ref<SceneReplicationInterface> replicator;
|
||||
Ref<SceneRPCInterface> rpc;
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ void _profile_bandwidth(const String &p_what, int p_value);
|
||||
_FORCE_INLINE_ Error _send(const uint8_t *p_packet, int p_packet_len); // Also profiles.
|
||||
#else
|
||||
_FORCE_INLINE_ Error _send(const uint8_t *p_packet, int p_packet_len) {
|
||||
return multiplayer_peer->put_packet(p_packet, p_packet_len);
|
||||
}
|
||||
#endif
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
void _process_packet(int p_from, const uint8_t *p_packet, int p_packet_len);
|
||||
void _process_raw(int p_from, const uint8_t *p_packet, int p_packet_len);
|
||||
void _process_sys(int p_from, const uint8_t *p_packet, int p_packet_len, MultiplayerPeer::TransferMode p_mode, int p_channel);
|
||||
|
||||
void _add_peer(int p_id);
|
||||
void _admit_peer(int p_id);
|
||||
void _del_peer(int p_id);
|
||||
void _update_status();
|
||||
|
||||
public:
|
||||
virtual void set_multiplayer_peer(const Ref<MultiplayerPeer> &p_peer) override;
|
||||
virtual Ref<MultiplayerPeer> get_multiplayer_peer() override;
|
||||
|
||||
virtual Error poll() override;
|
||||
virtual int get_unique_id() override;
|
||||
virtual Vector<int> get_peer_ids() override;
|
||||
virtual int get_remote_sender_id() override { return remote_sender_override ? remote_sender_override : remote_sender_id; }
|
||||
|
||||
virtual Error rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) override;
|
||||
|
||||
virtual Error object_configuration_add(Object *p_obj, Variant p_config) override;
|
||||
virtual Error object_configuration_remove(Object *p_obj, Variant p_config) override;
|
||||
|
||||
void clear();
|
||||
|
||||
// Usually from object_configuration_add/remove
|
||||
void set_root_path(const NodePath &p_path);
|
||||
NodePath get_root_path() const;
|
||||
|
||||
void disconnect_peer(int p_id);
|
||||
|
||||
Error send_auth(int p_to, Vector<uint8_t> p_bytes);
|
||||
Error complete_auth(int p_peer);
|
||||
void set_auth_callback(Callable p_callback);
|
||||
Callable get_auth_callback() const;
|
||||
void set_auth_timeout(double p_timeout);
|
||||
double get_auth_timeout() const;
|
||||
Vector<int> get_authenticating_peer_ids();
|
||||
|
||||
Error send_command(int p_to, const uint8_t *p_packet, int p_packet_len); // Used internally to relay packets when needed.
|
||||
Error send_bytes(Vector<uint8_t> p_data, int p_to = MultiplayerPeer::TARGET_PEER_BROADCAST, MultiplayerPeer::TransferMode p_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE, int p_channel = 0);
|
||||
String get_rpc_md5(const Object *p_obj);
|
||||
|
||||
const HashSet<int> get_connected_peers() const { return connected_peers; }
|
||||
|
||||
void set_remote_sender_override(int p_id) { remote_sender_override = p_id; }
|
||||
void set_refuse_new_connections(bool p_refuse);
|
||||
bool is_refusing_new_connections() const;
|
||||
|
||||
void set_allow_object_decoding(bool p_enable);
|
||||
bool is_object_decoding_allowed() const;
|
||||
|
||||
void set_server_relay_enabled(bool p_enabled);
|
||||
bool is_server_relay_enabled() const;
|
||||
|
||||
void set_max_sync_packet_size(int p_size);
|
||||
int get_max_sync_packet_size() const;
|
||||
|
||||
void set_max_delta_packet_size(int p_size);
|
||||
int get_max_delta_packet_size() const;
|
||||
|
||||
SceneMultiplayer();
|
||||
~SceneMultiplayer();
|
||||
};
|
291
modules/multiplayer/scene_replication_config.cpp
Normal file
291
modules/multiplayer/scene_replication_config.cpp
Normal file
@@ -0,0 +1,291 @@
|
||||
/**************************************************************************/
|
||||
/* scene_replication_config.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "scene_replication_config.h"
|
||||
|
||||
bool SceneReplicationConfig::_set(const StringName &p_name, const Variant &p_value) {
|
||||
String prop_name = p_name;
|
||||
|
||||
if (prop_name.begins_with("properties/")) {
|
||||
int idx = prop_name.get_slicec('/', 1).to_int();
|
||||
String what = prop_name.get_slicec('/', 2);
|
||||
|
||||
if (properties.size() == idx && what == "path") {
|
||||
ERR_FAIL_COND_V(p_value.get_type() != Variant::NODE_PATH, false);
|
||||
NodePath path = p_value;
|
||||
ERR_FAIL_COND_V(path.is_empty() || path.get_subname_count() == 0, false);
|
||||
add_property(path);
|
||||
return true;
|
||||
}
|
||||
ERR_FAIL_INDEX_V(idx, properties.size(), false);
|
||||
const ReplicationProperty &prop = properties.get(idx);
|
||||
if (what == "replication_mode") {
|
||||
ERR_FAIL_COND_V(p_value.get_type() != Variant::INT, false);
|
||||
ReplicationMode mode = (ReplicationMode)p_value.operator int();
|
||||
ERR_FAIL_COND_V(mode < REPLICATION_MODE_NEVER || mode > REPLICATION_MODE_ON_CHANGE, false);
|
||||
property_set_replication_mode(prop.name, mode);
|
||||
return true;
|
||||
}
|
||||
ERR_FAIL_COND_V(p_value.get_type() != Variant::BOOL, false);
|
||||
if (what == "spawn") {
|
||||
property_set_spawn(prop.name, p_value);
|
||||
return true;
|
||||
} else if (what == "sync") {
|
||||
// Deprecated.
|
||||
property_set_sync(prop.name, p_value);
|
||||
return true;
|
||||
} else if (what == "watch") {
|
||||
// Deprecated.
|
||||
property_set_watch(prop.name, p_value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool SceneReplicationConfig::_get(const StringName &p_name, Variant &r_ret) const {
|
||||
String prop_name = p_name;
|
||||
|
||||
if (prop_name.begins_with("properties/")) {
|
||||
int idx = prop_name.get_slicec('/', 1).to_int();
|
||||
String what = prop_name.get_slicec('/', 2);
|
||||
ERR_FAIL_INDEX_V(idx, properties.size(), false);
|
||||
const ReplicationProperty &prop = properties.get(idx);
|
||||
if (what == "path") {
|
||||
r_ret = prop.name;
|
||||
return true;
|
||||
} else if (what == "spawn") {
|
||||
r_ret = prop.spawn;
|
||||
return true;
|
||||
} else if (what == "replication_mode") {
|
||||
r_ret = prop.mode;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::_get_property_list(List<PropertyInfo> *p_list) const {
|
||||
for (int i = 0; i < properties.size(); i++) {
|
||||
p_list->push_back(PropertyInfo(Variant::STRING, "properties/" + itos(i) + "/path", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
|
||||
p_list->push_back(PropertyInfo(Variant::STRING, "properties/" + itos(i) + "/spawn", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
|
||||
p_list->push_back(PropertyInfo(Variant::INT, "properties/" + itos(i) + "/replication_mode", PROPERTY_HINT_ENUM, "Never,Always,On Change", PROPERTY_USAGE_NO_EDITOR | PROPERTY_USAGE_INTERNAL));
|
||||
}
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::reset_state() {
|
||||
dirty = false;
|
||||
properties.clear();
|
||||
sync_props.clear();
|
||||
spawn_props.clear();
|
||||
watch_props.clear();
|
||||
}
|
||||
|
||||
TypedArray<NodePath> SceneReplicationConfig::get_properties() const {
|
||||
TypedArray<NodePath> paths;
|
||||
for (const ReplicationProperty &prop : properties) {
|
||||
paths.push_back(prop.name);
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::add_property(const NodePath &p_path, int p_index) {
|
||||
ERR_FAIL_COND(properties.find(p_path));
|
||||
ERR_FAIL_COND(p_path == NodePath());
|
||||
|
||||
if (p_index < 0 || p_index == properties.size()) {
|
||||
properties.push_back(ReplicationProperty(p_path));
|
||||
dirty = true;
|
||||
return;
|
||||
}
|
||||
|
||||
ERR_FAIL_INDEX(p_index, properties.size());
|
||||
|
||||
List<ReplicationProperty>::Element *I = properties.front();
|
||||
int c = 0;
|
||||
while (c < p_index) {
|
||||
I = I->next();
|
||||
c++;
|
||||
}
|
||||
properties.insert_before(I, ReplicationProperty(p_path));
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::remove_property(const NodePath &p_path) {
|
||||
properties.erase(p_path);
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
bool SceneReplicationConfig::has_property(const NodePath &p_path) const {
|
||||
for (const ReplicationProperty &property : properties) {
|
||||
if (property.name == p_path) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int SceneReplicationConfig::property_get_index(const NodePath &p_path) const {
|
||||
int i = 0;
|
||||
for (List<ReplicationProperty>::ConstIterator itr = properties.begin(); itr != properties.end(); ++itr, ++i) {
|
||||
if (itr->name == p_path) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
ERR_FAIL_V(-1);
|
||||
}
|
||||
|
||||
bool SceneReplicationConfig::property_get_spawn(const NodePath &p_path) {
|
||||
List<ReplicationProperty>::Element *E = properties.find(p_path);
|
||||
ERR_FAIL_COND_V(!E, false);
|
||||
return E->get().spawn;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::property_set_spawn(const NodePath &p_path, bool p_enabled) {
|
||||
List<ReplicationProperty>::Element *E = properties.find(p_path);
|
||||
ERR_FAIL_COND(!E);
|
||||
if (E->get().spawn == p_enabled) {
|
||||
return;
|
||||
}
|
||||
E->get().spawn = p_enabled;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
bool SceneReplicationConfig::property_get_sync(const NodePath &p_path) {
|
||||
List<ReplicationProperty>::Element *E = properties.find(p_path);
|
||||
ERR_FAIL_COND_V(!E, false);
|
||||
return E->get().mode == REPLICATION_MODE_ALWAYS;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::property_set_sync(const NodePath &p_path, bool p_enabled) {
|
||||
if (p_enabled) {
|
||||
property_set_replication_mode(p_path, REPLICATION_MODE_ALWAYS);
|
||||
} else if (property_get_replication_mode(p_path) == REPLICATION_MODE_ALWAYS) {
|
||||
property_set_replication_mode(p_path, REPLICATION_MODE_NEVER);
|
||||
}
|
||||
}
|
||||
|
||||
bool SceneReplicationConfig::property_get_watch(const NodePath &p_path) {
|
||||
List<ReplicationProperty>::Element *E = properties.find(p_path);
|
||||
ERR_FAIL_COND_V(!E, false);
|
||||
return E->get().mode == REPLICATION_MODE_ON_CHANGE;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::property_set_watch(const NodePath &p_path, bool p_enabled) {
|
||||
if (p_enabled) {
|
||||
property_set_replication_mode(p_path, REPLICATION_MODE_ON_CHANGE);
|
||||
} else if (property_get_replication_mode(p_path) == REPLICATION_MODE_ON_CHANGE) {
|
||||
property_set_replication_mode(p_path, REPLICATION_MODE_NEVER);
|
||||
}
|
||||
}
|
||||
|
||||
SceneReplicationConfig::ReplicationMode SceneReplicationConfig::property_get_replication_mode(const NodePath &p_path) {
|
||||
List<ReplicationProperty>::Element *E = properties.find(p_path);
|
||||
ERR_FAIL_COND_V(!E, REPLICATION_MODE_NEVER);
|
||||
return E->get().mode;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::property_set_replication_mode(const NodePath &p_path, ReplicationMode p_mode) {
|
||||
List<ReplicationProperty>::Element *E = properties.find(p_path);
|
||||
ERR_FAIL_COND(!E);
|
||||
if (E->get().mode == p_mode) {
|
||||
return;
|
||||
}
|
||||
E->get().mode = p_mode;
|
||||
dirty = true;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::_update() {
|
||||
if (!dirty) {
|
||||
return;
|
||||
}
|
||||
dirty = false;
|
||||
sync_props.clear();
|
||||
spawn_props.clear();
|
||||
watch_props.clear();
|
||||
for (const ReplicationProperty &prop : properties) {
|
||||
if (prop.spawn) {
|
||||
spawn_props.push_back(prop.name);
|
||||
}
|
||||
switch (prop.mode) {
|
||||
case REPLICATION_MODE_ALWAYS:
|
||||
sync_props.push_back(prop.name);
|
||||
break;
|
||||
case REPLICATION_MODE_ON_CHANGE:
|
||||
watch_props.push_back(prop.name);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const List<NodePath> &SceneReplicationConfig::get_spawn_properties() {
|
||||
if (dirty) {
|
||||
_update();
|
||||
}
|
||||
return spawn_props;
|
||||
}
|
||||
|
||||
const List<NodePath> &SceneReplicationConfig::get_sync_properties() {
|
||||
if (dirty) {
|
||||
_update();
|
||||
}
|
||||
return sync_props;
|
||||
}
|
||||
|
||||
const List<NodePath> &SceneReplicationConfig::get_watch_properties() {
|
||||
if (dirty) {
|
||||
_update();
|
||||
}
|
||||
return watch_props;
|
||||
}
|
||||
|
||||
void SceneReplicationConfig::_bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("get_properties"), &SceneReplicationConfig::get_properties);
|
||||
ClassDB::bind_method(D_METHOD("add_property", "path", "index"), &SceneReplicationConfig::add_property, DEFVAL(-1));
|
||||
ClassDB::bind_method(D_METHOD("has_property", "path"), &SceneReplicationConfig::has_property);
|
||||
ClassDB::bind_method(D_METHOD("remove_property", "path"), &SceneReplicationConfig::remove_property);
|
||||
ClassDB::bind_method(D_METHOD("property_get_index", "path"), &SceneReplicationConfig::property_get_index);
|
||||
ClassDB::bind_method(D_METHOD("property_get_spawn", "path"), &SceneReplicationConfig::property_get_spawn);
|
||||
ClassDB::bind_method(D_METHOD("property_set_spawn", "path", "enabled"), &SceneReplicationConfig::property_set_spawn);
|
||||
ClassDB::bind_method(D_METHOD("property_get_replication_mode", "path"), &SceneReplicationConfig::property_get_replication_mode);
|
||||
ClassDB::bind_method(D_METHOD("property_set_replication_mode", "path", "mode"), &SceneReplicationConfig::property_set_replication_mode);
|
||||
|
||||
BIND_ENUM_CONSTANT(REPLICATION_MODE_NEVER);
|
||||
BIND_ENUM_CONSTANT(REPLICATION_MODE_ALWAYS);
|
||||
BIND_ENUM_CONSTANT(REPLICATION_MODE_ON_CHANGE);
|
||||
|
||||
// Deprecated.
|
||||
ClassDB::bind_method(D_METHOD("property_get_sync", "path"), &SceneReplicationConfig::property_get_sync);
|
||||
ClassDB::bind_method(D_METHOD("property_set_sync", "path", "enabled"), &SceneReplicationConfig::property_set_sync);
|
||||
ClassDB::bind_method(D_METHOD("property_get_watch", "path"), &SceneReplicationConfig::property_get_watch);
|
||||
ClassDB::bind_method(D_METHOD("property_set_watch", "path", "enabled"), &SceneReplicationConfig::property_set_watch);
|
||||
}
|
109
modules/multiplayer/scene_replication_config.h
Normal file
109
modules/multiplayer/scene_replication_config.h
Normal file
@@ -0,0 +1,109 @@
|
||||
/**************************************************************************/
|
||||
/* scene_replication_config.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/io/resource.h"
|
||||
#include "core/variant/typed_array.h"
|
||||
|
||||
class SceneReplicationConfig : public Resource {
|
||||
GDCLASS(SceneReplicationConfig, Resource);
|
||||
OBJ_SAVE_TYPE(SceneReplicationConfig);
|
||||
RES_BASE_EXTENSION("repl");
|
||||
|
||||
public:
|
||||
enum ReplicationMode {
|
||||
REPLICATION_MODE_NEVER,
|
||||
REPLICATION_MODE_ALWAYS,
|
||||
REPLICATION_MODE_ON_CHANGE,
|
||||
};
|
||||
|
||||
private:
|
||||
struct ReplicationProperty {
|
||||
NodePath name;
|
||||
bool spawn = true;
|
||||
ReplicationMode mode = REPLICATION_MODE_ALWAYS;
|
||||
|
||||
bool operator==(const ReplicationProperty &p_to) {
|
||||
return name == p_to.name;
|
||||
}
|
||||
|
||||
ReplicationProperty() {}
|
||||
|
||||
ReplicationProperty(const NodePath &p_name) {
|
||||
name = p_name;
|
||||
}
|
||||
};
|
||||
|
||||
List<ReplicationProperty> properties;
|
||||
List<NodePath> spawn_props;
|
||||
List<NodePath> sync_props;
|
||||
List<NodePath> watch_props;
|
||||
bool dirty = false;
|
||||
|
||||
void _update();
|
||||
|
||||
protected:
|
||||
static void _bind_methods();
|
||||
|
||||
bool _set(const StringName &p_name, const Variant &p_value);
|
||||
bool _get(const StringName &p_name, Variant &r_ret) const;
|
||||
void _get_property_list(List<PropertyInfo> *p_list) const;
|
||||
|
||||
public:
|
||||
virtual void reset_state() override; // Required since we use variable amount of properties.
|
||||
|
||||
TypedArray<NodePath> get_properties() const;
|
||||
|
||||
void add_property(const NodePath &p_path, int p_index = -1);
|
||||
void remove_property(const NodePath &p_path);
|
||||
bool has_property(const NodePath &p_path) const;
|
||||
|
||||
int property_get_index(const NodePath &p_path) const;
|
||||
bool property_get_spawn(const NodePath &p_path);
|
||||
void property_set_spawn(const NodePath &p_path, bool p_enabled);
|
||||
|
||||
bool property_get_sync(const NodePath &p_path);
|
||||
void property_set_sync(const NodePath &p_path, bool p_enabled);
|
||||
|
||||
bool property_get_watch(const NodePath &p_path);
|
||||
void property_set_watch(const NodePath &p_path, bool p_enabled);
|
||||
|
||||
ReplicationMode property_get_replication_mode(const NodePath &p_path);
|
||||
void property_set_replication_mode(const NodePath &p_path, ReplicationMode p_mode);
|
||||
|
||||
const List<NodePath> &get_spawn_properties();
|
||||
const List<NodePath> &get_sync_properties();
|
||||
const List<NodePath> &get_watch_properties();
|
||||
|
||||
SceneReplicationConfig() {}
|
||||
};
|
||||
|
||||
VARIANT_ENUM_CAST(SceneReplicationConfig::ReplicationMode);
|
917
modules/multiplayer/scene_replication_interface.cpp
Normal file
917
modules/multiplayer/scene_replication_interface.cpp
Normal file
@@ -0,0 +1,917 @@
|
||||
/**************************************************************************/
|
||||
/* scene_replication_interface.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "scene_replication_interface.h"
|
||||
|
||||
#include "scene_multiplayer.h"
|
||||
|
||||
#include "core/debugger/engine_debugger.h"
|
||||
#include "core/io/marshalls.h"
|
||||
#include "scene/main/node.h"
|
||||
|
||||
#define MAKE_ROOM(m_amount) \
|
||||
if (packet_cache.size() < m_amount) \
|
||||
packet_cache.resize(m_amount);
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ void SceneReplicationInterface::_profile_node_data(const String &p_what, ObjectID p_id, int p_size) {
|
||||
if (EngineDebugger::is_profiling("multiplayer:replication")) {
|
||||
Array values = { p_what, p_id, p_size };
|
||||
EngineDebugger::profiler_add_frame_data("multiplayer:replication", values);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
SceneReplicationInterface::TrackedNode &SceneReplicationInterface::_track(const ObjectID &p_id) {
|
||||
if (!tracked_nodes.has(p_id)) {
|
||||
tracked_nodes[p_id] = TrackedNode(p_id);
|
||||
Node *node = get_id_as<Node>(p_id);
|
||||
node->connect(SceneStringName(tree_exited), callable_mp(this, &SceneReplicationInterface::_untrack).bind(p_id), Node::CONNECT_ONE_SHOT);
|
||||
}
|
||||
return tracked_nodes[p_id];
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::_untrack(const ObjectID &p_id) {
|
||||
if (!tracked_nodes.has(p_id)) {
|
||||
return;
|
||||
}
|
||||
uint32_t net_id = tracked_nodes[p_id].net_id;
|
||||
uint32_t peer = tracked_nodes[p_id].remote_peer;
|
||||
tracked_nodes.erase(p_id);
|
||||
// If it was spawned by a remote, remove it from the received nodes.
|
||||
if (peer && peers_info.has(peer)) {
|
||||
peers_info[peer].recv_nodes.erase(net_id);
|
||||
}
|
||||
// If we spawned or synced it, we need to remove it from any peer it was sent to.
|
||||
if (net_id || peer == 0) {
|
||||
for (KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
E.value.spawn_nodes.erase(p_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::_free_remotes(const PeerInfo &p_info) {
|
||||
for (const KeyValue<uint32_t, ObjectID> &E : p_info.recv_nodes) {
|
||||
Node *node = tracked_nodes.has(E.value) ? get_id_as<Node>(E.value) : nullptr;
|
||||
ERR_CONTINUE(!node);
|
||||
node->queue_free();
|
||||
}
|
||||
}
|
||||
|
||||
bool SceneReplicationInterface::_has_authority(const Node *p_node) {
|
||||
return multiplayer->has_multiplayer_peer() && p_node->get_multiplayer_authority() == multiplayer->get_unique_id();
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::on_peer_change(int p_id, bool p_connected) {
|
||||
if (p_connected) {
|
||||
peers_info[p_id] = PeerInfo();
|
||||
for (const ObjectID &oid : spawned_nodes) {
|
||||
_update_spawn_visibility(p_id, oid);
|
||||
}
|
||||
for (const ObjectID &oid : sync_nodes) {
|
||||
_update_sync_visibility(p_id, get_id_as<MultiplayerSynchronizer>(oid));
|
||||
}
|
||||
} else {
|
||||
ERR_FAIL_COND(!peers_info.has(p_id));
|
||||
_free_remotes(peers_info[p_id]);
|
||||
peers_info.erase(p_id);
|
||||
}
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::on_reset() {
|
||||
for (const KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
_free_remotes(E.value);
|
||||
}
|
||||
peers_info.clear();
|
||||
// Tracked nodes are cleared on deletion, here we only reset the ids so they can be later re-assigned.
|
||||
for (KeyValue<ObjectID, TrackedNode> &E : tracked_nodes) {
|
||||
TrackedNode &tobj = E.value;
|
||||
tobj.net_id = 0;
|
||||
tobj.remote_peer = 0;
|
||||
}
|
||||
for (const ObjectID &oid : sync_nodes) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
|
||||
ERR_CONTINUE(!sync);
|
||||
sync->reset();
|
||||
}
|
||||
last_net_id = 0;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::on_network_process() {
|
||||
// Prevent endless stalling in case of unforeseen spawn errors.
|
||||
if (spawn_queue.size()) {
|
||||
ERR_PRINT("An error happened during last spawn, this usually means the 'ready' signal was not emitted by the spawned node.");
|
||||
for (const ObjectID &oid : spawn_queue) {
|
||||
Node *node = get_id_as<Node>(oid);
|
||||
ERR_CONTINUE(!node);
|
||||
if (node->is_connected(SceneStringName(ready), callable_mp(this, &SceneReplicationInterface::_node_ready))) {
|
||||
node->disconnect(SceneStringName(ready), callable_mp(this, &SceneReplicationInterface::_node_ready));
|
||||
}
|
||||
}
|
||||
spawn_queue.clear();
|
||||
}
|
||||
|
||||
// Process syncs.
|
||||
uint64_t usec = OS::get_singleton()->get_ticks_usec();
|
||||
for (KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
const HashSet<ObjectID> to_sync = E.value.sync_nodes;
|
||||
if (to_sync.is_empty()) {
|
||||
continue; // Nothing to sync
|
||||
}
|
||||
uint16_t sync_net_time = ++E.value.last_sent_sync;
|
||||
_send_sync(E.key, to_sync, sync_net_time, usec);
|
||||
_send_delta(E.key, to_sync, usec, E.value.last_watch_usecs);
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_spawn(Object *p_obj, Variant p_config) {
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
|
||||
MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
|
||||
ERR_FAIL_NULL_V(spawner, ERR_INVALID_PARAMETER);
|
||||
// Track node.
|
||||
const ObjectID oid = node->get_instance_id();
|
||||
TrackedNode &tobj = _track(oid);
|
||||
|
||||
// Spawn state needs to be callected after "ready", but the spawn order follows "enter_tree".
|
||||
ERR_FAIL_COND_V(tobj.spawner != ObjectID(), ERR_ALREADY_IN_USE);
|
||||
tobj.spawner = spawner->get_instance_id();
|
||||
spawn_queue.insert(oid);
|
||||
node->connect(SceneStringName(ready), callable_mp(this, &SceneReplicationInterface::_node_ready).bind(oid), Node::CONNECT_ONE_SHOT);
|
||||
return OK;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::_node_ready(const ObjectID &p_oid) {
|
||||
ERR_FAIL_COND(!spawn_queue.has(p_oid)); // Bug.
|
||||
|
||||
// If we are a nested spawn, we need to wait until the parent is ready.
|
||||
if (p_oid != *(spawn_queue.begin())) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const ObjectID &oid : spawn_queue) {
|
||||
ERR_CONTINUE(!tracked_nodes.has(oid));
|
||||
|
||||
TrackedNode &tobj = tracked_nodes[oid];
|
||||
MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tobj.spawner);
|
||||
ERR_CONTINUE(!spawner);
|
||||
|
||||
spawned_nodes.insert(oid);
|
||||
if (_has_authority(spawner)) {
|
||||
_update_spawn_visibility(0, oid);
|
||||
}
|
||||
}
|
||||
spawn_queue.clear();
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_despawn(Object *p_obj, Variant p_config) {
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
|
||||
MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(p_config.get_validated_object());
|
||||
ERR_FAIL_COND_V(!p_obj || !spawner, ERR_INVALID_PARAMETER);
|
||||
// Forcibly despawn to all peers that knowns me.
|
||||
int len = 0;
|
||||
Error err = _make_despawn_packet(node, len);
|
||||
ERR_FAIL_COND_V(err != OK, ERR_BUG);
|
||||
const ObjectID oid = p_obj->get_instance_id();
|
||||
for (const KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
if (!E.value.spawn_nodes.has(oid)) {
|
||||
continue;
|
||||
}
|
||||
_send_raw(packet_cache.ptr(), len, E.key, true);
|
||||
}
|
||||
// Also remove spawner tracking from the replication state.
|
||||
ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER);
|
||||
TrackedNode &tobj = _track(oid);
|
||||
ERR_FAIL_COND_V(tobj.spawner != spawner->get_instance_id(), ERR_INVALID_PARAMETER);
|
||||
tobj.spawner = ObjectID();
|
||||
spawned_nodes.erase(oid);
|
||||
for (KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
E.value.spawn_nodes.erase(oid);
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_replication_start(Object *p_obj, Variant p_config) {
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
|
||||
MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
|
||||
ERR_FAIL_NULL_V(sync, ERR_INVALID_PARAMETER);
|
||||
|
||||
// Add to synchronizer list.
|
||||
TrackedNode &tobj = _track(p_obj->get_instance_id());
|
||||
const ObjectID sid = sync->get_instance_id();
|
||||
tobj.synchronizers.insert(sid);
|
||||
sync_nodes.insert(sid);
|
||||
|
||||
// Update visibility.
|
||||
sync->connect(SceneStringName(visibility_changed), callable_mp(this, &SceneReplicationInterface::_visibility_changed).bind(sync->get_instance_id()));
|
||||
_update_sync_visibility(0, sync);
|
||||
|
||||
if (pending_spawn == p_obj->get_instance_id() && sync->get_multiplayer_authority() == pending_spawn_remote) {
|
||||
// Try to apply synchronizer Net ID
|
||||
ERR_FAIL_COND_V_MSG(pending_sync_net_ids.is_empty(), ERR_INVALID_DATA, vformat("The MultiplayerSynchronizer at path \"%s\" is unable to process the pending spawn since it has no network ID. This might happen when changing the multiplayer authority during the \"_ready\" callback. Make sure to only change the authority of multiplayer synchronizers during \"_enter_tree\" or the \"_spawn_custom\" callback of their multiplayer spawner.", sync->get_path()));
|
||||
ERR_FAIL_COND_V(!peers_info.has(pending_spawn_remote), ERR_INVALID_DATA);
|
||||
uint32_t net_id = pending_sync_net_ids.front()->get();
|
||||
pending_sync_net_ids.pop_front();
|
||||
peers_info[pending_spawn_remote].recv_sync_ids[net_id] = sync->get_instance_id();
|
||||
sync->set_net_id(net_id);
|
||||
|
||||
// Try to apply spawn state (before ready).
|
||||
if (pending_buffer_size > 0) {
|
||||
ERR_FAIL_COND_V(!node || !sync->get_replication_config_ptr(), ERR_UNCONFIGURED);
|
||||
int consumed = 0;
|
||||
const List<NodePath> props = sync->get_replication_config_ptr()->get_spawn_properties();
|
||||
Vector<Variant> vars;
|
||||
vars.resize(props.size());
|
||||
Error err = MultiplayerAPI::decode_and_decompress_variants(vars, pending_buffer, pending_buffer_size, consumed);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
if (consumed > 0) {
|
||||
pending_buffer += consumed;
|
||||
pending_buffer_size -= consumed;
|
||||
err = MultiplayerSynchronizer::set_state(props, node, vars);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_replication_stop(Object *p_obj, Variant p_config) {
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_COND_V(!node || p_config.get_type() != Variant::OBJECT, ERR_INVALID_PARAMETER);
|
||||
MultiplayerSynchronizer *sync = Object::cast_to<MultiplayerSynchronizer>(p_config.get_validated_object());
|
||||
ERR_FAIL_NULL_V(sync, ERR_INVALID_PARAMETER);
|
||||
sync->disconnect(SceneStringName(visibility_changed), callable_mp(this, &SceneReplicationInterface::_visibility_changed));
|
||||
// Untrack synchronizer.
|
||||
const ObjectID oid = node->get_instance_id();
|
||||
const ObjectID sid = sync->get_instance_id();
|
||||
ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_INVALID_PARAMETER);
|
||||
TrackedNode &tobj = _track(oid);
|
||||
tobj.synchronizers.erase(sid);
|
||||
sync_nodes.erase(sid);
|
||||
for (KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
E.value.sync_nodes.erase(sid);
|
||||
E.value.last_watch_usecs.erase(sid);
|
||||
if (sync->get_net_id()) {
|
||||
E.value.recv_sync_ids.erase(sync->get_net_id());
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::_visibility_changed(int p_peer, ObjectID p_sid) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(p_sid);
|
||||
ERR_FAIL_NULL(sync); // Bug.
|
||||
Node *node = sync->get_root_node();
|
||||
ERR_FAIL_NULL(node); // Bug.
|
||||
const ObjectID oid = node->get_instance_id();
|
||||
if (spawned_nodes.has(oid) && p_peer != multiplayer->get_unique_id()) {
|
||||
_update_spawn_visibility(p_peer, oid);
|
||||
}
|
||||
_update_sync_visibility(p_peer, sync);
|
||||
}
|
||||
|
||||
bool SceneReplicationInterface::is_rpc_visible(const ObjectID &p_oid, int p_peer) const {
|
||||
if (!tracked_nodes.has(p_oid)) {
|
||||
return true; // Untracked nodes are always visible to RPCs.
|
||||
}
|
||||
ERR_FAIL_COND_V(p_peer < 0, false);
|
||||
const TrackedNode &tnode = tracked_nodes[p_oid];
|
||||
if (tnode.synchronizers.is_empty()) {
|
||||
return true; // No synchronizers means no visibility restrictions.
|
||||
}
|
||||
if (tnode.remote_peer && uint32_t(p_peer) == tnode.remote_peer) {
|
||||
return true; // RPCs on spawned nodes are always visible to spawner.
|
||||
} else if (spawned_nodes.has(p_oid)) {
|
||||
// It's a spawned node we control, this can be fast.
|
||||
if (p_peer) {
|
||||
return peers_info.has(p_peer) && peers_info[p_peer].spawn_nodes.has(p_oid);
|
||||
} else {
|
||||
for (const KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
if (!E.value.spawn_nodes.has(p_oid)) {
|
||||
return false; // Not public.
|
||||
}
|
||||
}
|
||||
return true; // All peers have this node.
|
||||
}
|
||||
} else {
|
||||
// Cycle object synchronizers to check visibility.
|
||||
for (const ObjectID &sid : tnode.synchronizers) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
|
||||
ERR_CONTINUE(!sync);
|
||||
// RPC visibility is composed using OR when multiple synchronizers are present.
|
||||
// Note that we don't really care about authority here which may lead to unexpected
|
||||
// results when using multiple synchronizers to control the same node.
|
||||
if (sync->is_visible_to(p_peer)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false; // Not visible.
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::_update_sync_visibility(int p_peer, MultiplayerSynchronizer *p_sync) {
|
||||
ERR_FAIL_NULL_V(p_sync, ERR_BUG);
|
||||
if (!_has_authority(p_sync) || p_peer == multiplayer->get_unique_id()) {
|
||||
return OK;
|
||||
}
|
||||
|
||||
const ObjectID &sid = p_sync->get_instance_id();
|
||||
bool is_visible = p_sync->is_visible_to(p_peer);
|
||||
if (p_peer == 0) {
|
||||
for (KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
// Might be visible to this specific peer.
|
||||
bool is_visible_to_peer = is_visible || p_sync->is_visible_to(E.key);
|
||||
if (is_visible_to_peer == E.value.sync_nodes.has(sid)) {
|
||||
continue;
|
||||
}
|
||||
if (is_visible_to_peer) {
|
||||
E.value.sync_nodes.insert(sid);
|
||||
} else {
|
||||
E.value.sync_nodes.erase(sid);
|
||||
E.value.last_watch_usecs.erase(sid);
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
} else {
|
||||
ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER);
|
||||
if (is_visible == peers_info[p_peer].sync_nodes.has(sid)) {
|
||||
return OK;
|
||||
}
|
||||
if (is_visible) {
|
||||
peers_info[p_peer].sync_nodes.insert(sid);
|
||||
} else {
|
||||
peers_info[p_peer].sync_nodes.erase(sid);
|
||||
peers_info[p_peer].last_watch_usecs.erase(sid);
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::_update_spawn_visibility(int p_peer, const ObjectID &p_oid) {
|
||||
const TrackedNode *tnode = tracked_nodes.getptr(p_oid);
|
||||
ERR_FAIL_NULL_V(tnode, ERR_BUG);
|
||||
MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tnode->spawner);
|
||||
Node *node = get_id_as<Node>(p_oid);
|
||||
ERR_FAIL_NULL_V(node, ERR_BUG);
|
||||
ERR_FAIL_NULL_V(spawner, ERR_BUG);
|
||||
ERR_FAIL_COND_V(!_has_authority(spawner), ERR_BUG);
|
||||
ERR_FAIL_COND_V(!tracked_nodes.has(p_oid), ERR_BUG);
|
||||
const HashSet<ObjectID> synchronizers = tracked_nodes[p_oid].synchronizers;
|
||||
bool is_visible = true;
|
||||
for (const ObjectID &sid : synchronizers) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
|
||||
ERR_CONTINUE(!sync);
|
||||
if (!_has_authority(sync)) {
|
||||
continue;
|
||||
}
|
||||
// Spawn visibility is composed using OR when multiple synchronizers are present.
|
||||
if (sync->is_visible_to(p_peer)) {
|
||||
is_visible = true;
|
||||
break;
|
||||
}
|
||||
is_visible = false;
|
||||
}
|
||||
// Spawn (and despawn) when needed.
|
||||
HashSet<int> to_spawn;
|
||||
HashSet<int> to_despawn;
|
||||
if (p_peer) {
|
||||
ERR_FAIL_COND_V(!peers_info.has(p_peer), ERR_INVALID_PARAMETER);
|
||||
if (is_visible == peers_info[p_peer].spawn_nodes.has(p_oid)) {
|
||||
return OK;
|
||||
}
|
||||
if (is_visible) {
|
||||
to_spawn.insert(p_peer);
|
||||
} else {
|
||||
to_despawn.insert(p_peer);
|
||||
}
|
||||
} else {
|
||||
// Check visibility for each peers.
|
||||
for (const KeyValue<int, PeerInfo> &E : peers_info) {
|
||||
if (is_visible) {
|
||||
// This is fast, since the object is visible to everyone, we don't need to check each peer.
|
||||
if (E.value.spawn_nodes.has(p_oid)) {
|
||||
// Already spawned.
|
||||
continue;
|
||||
}
|
||||
to_spawn.insert(E.key);
|
||||
} else {
|
||||
// Need to check visibility for each peer.
|
||||
_update_spawn_visibility(E.key, p_oid);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (to_spawn.size()) {
|
||||
int len = 0;
|
||||
_make_spawn_packet(node, spawner, len);
|
||||
for (int pid : to_spawn) {
|
||||
ERR_CONTINUE(!peers_info.has(pid));
|
||||
int path_id;
|
||||
multiplayer_cache->send_object_cache(spawner, pid, path_id);
|
||||
_send_raw(packet_cache.ptr(), len, pid, true);
|
||||
peers_info[pid].spawn_nodes.insert(p_oid);
|
||||
}
|
||||
}
|
||||
if (to_despawn.size()) {
|
||||
int len = 0;
|
||||
_make_despawn_packet(node, len);
|
||||
for (int pid : to_despawn) {
|
||||
ERR_CONTINUE(!peers_info.has(pid));
|
||||
peers_info[pid].spawn_nodes.erase(p_oid);
|
||||
_send_raw(packet_cache.ptr(), len, pid, true);
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::_send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable) {
|
||||
ERR_FAIL_COND_V(!p_buffer || p_size < 1, ERR_INVALID_PARAMETER);
|
||||
|
||||
Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
|
||||
ERR_FAIL_COND_V(peer.is_null(), ERR_UNCONFIGURED);
|
||||
peer->set_transfer_channel(0);
|
||||
peer->set_transfer_mode(p_reliable ? MultiplayerPeer::TRANSFER_MODE_RELIABLE : MultiplayerPeer::TRANSFER_MODE_UNRELIABLE);
|
||||
return multiplayer->send_command(p_peer, p_buffer, p_size);
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::_make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len) {
|
||||
ERR_FAIL_COND_V(!multiplayer || !p_node || !p_spawner, ERR_BUG);
|
||||
|
||||
const ObjectID oid = p_node->get_instance_id();
|
||||
TrackedNode *tnode = tracked_nodes.getptr(oid);
|
||||
ERR_FAIL_NULL_V(tnode, ERR_INVALID_PARAMETER);
|
||||
|
||||
if (tnode->net_id == 0) {
|
||||
// Ensure the node has an ID.
|
||||
tnode->net_id = ++last_net_id;
|
||||
}
|
||||
uint32_t nid = tnode->net_id;
|
||||
ERR_FAIL_COND_V(!nid, ERR_UNCONFIGURED);
|
||||
|
||||
// Prepare custom arg and scene_id
|
||||
uint8_t scene_id = p_spawner->find_spawnable_scene_index_from_object(oid);
|
||||
bool is_custom = scene_id == MultiplayerSpawner::INVALID_ID;
|
||||
Variant spawn_arg = p_spawner->get_spawn_argument(oid);
|
||||
int spawn_arg_size = 0;
|
||||
if (is_custom) {
|
||||
Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, nullptr, spawn_arg_size, false);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
}
|
||||
|
||||
// Prepare spawn state.
|
||||
List<NodePath> state_props;
|
||||
List<uint32_t> sync_ids;
|
||||
const HashSet<ObjectID> synchronizers = tnode->synchronizers;
|
||||
for (const ObjectID &sid : synchronizers) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(sid);
|
||||
if (!_has_authority(sync)) {
|
||||
continue;
|
||||
}
|
||||
ERR_CONTINUE(!sync);
|
||||
ERR_FAIL_NULL_V(sync->get_replication_config_ptr(), ERR_BUG);
|
||||
for (const NodePath &prop : sync->get_replication_config_ptr()->get_spawn_properties()) {
|
||||
state_props.push_back(prop);
|
||||
}
|
||||
// Ensure the synchronizer has an ID.
|
||||
if (sync->get_net_id() == 0) {
|
||||
sync->set_net_id(++last_net_id);
|
||||
}
|
||||
sync_ids.push_back(sync->get_net_id());
|
||||
}
|
||||
int state_size = 0;
|
||||
Vector<Variant> state_vars;
|
||||
Vector<const Variant *> state_varp;
|
||||
if (state_props.size()) {
|
||||
Error err = MultiplayerSynchronizer::get_state(state_props, p_node, state_vars, state_varp);
|
||||
ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to retrieve spawn state.");
|
||||
err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), nullptr, state_size);
|
||||
ERR_FAIL_COND_V_MSG(err != OK, err, "Unable to encode spawn state.");
|
||||
}
|
||||
|
||||
// Encode scene ID, path ID, net ID, node name.
|
||||
int path_id = multiplayer_cache->make_object_cache(p_spawner);
|
||||
CharString cname = p_node->get_name().operator String().utf8();
|
||||
int nlen = encode_cstring(cname.get_data(), nullptr);
|
||||
MAKE_ROOM(1 + 1 + 4 + 4 + 4 + 4 * sync_ids.size() + 4 + nlen + (is_custom ? 4 + spawn_arg_size : 0) + state_size);
|
||||
uint8_t *ptr = packet_cache.ptrw();
|
||||
ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_SPAWN;
|
||||
ptr[1] = scene_id;
|
||||
int ofs = 2;
|
||||
ofs += encode_uint32(path_id, &ptr[ofs]);
|
||||
ofs += encode_uint32(nid, &ptr[ofs]);
|
||||
ofs += encode_uint32(sync_ids.size(), &ptr[ofs]);
|
||||
ofs += encode_uint32(nlen, &ptr[ofs]);
|
||||
for (uint32_t snid : sync_ids) {
|
||||
ofs += encode_uint32(snid, &ptr[ofs]);
|
||||
}
|
||||
ofs += encode_cstring(cname.get_data(), &ptr[ofs]);
|
||||
// Write args
|
||||
if (is_custom) {
|
||||
ofs += encode_uint32(spawn_arg_size, &ptr[ofs]);
|
||||
Error err = MultiplayerAPI::encode_and_compress_variant(spawn_arg, &ptr[ofs], spawn_arg_size, false);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
ofs += spawn_arg_size;
|
||||
}
|
||||
// Write state.
|
||||
if (state_size) {
|
||||
Error err = MultiplayerAPI::encode_and_compress_variants(state_varp.ptrw(), state_varp.size(), &ptr[ofs], state_size);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
ofs += state_size;
|
||||
}
|
||||
r_len = ofs;
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::_make_despawn_packet(Node *p_node, int &r_len) {
|
||||
const ObjectID oid = p_node->get_instance_id();
|
||||
const TrackedNode *tnode = tracked_nodes.getptr(oid);
|
||||
ERR_FAIL_NULL_V(tnode, ERR_INVALID_PARAMETER);
|
||||
MAKE_ROOM(5);
|
||||
uint8_t *ptr = packet_cache.ptrw();
|
||||
ptr[0] = (uint8_t)SceneMultiplayer::NETWORK_COMMAND_DESPAWN;
|
||||
int ofs = 1;
|
||||
uint32_t nid = tnode->net_id;
|
||||
ofs += encode_uint32(nid, &ptr[ofs]);
|
||||
r_len = ofs;
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_spawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
|
||||
ERR_FAIL_COND_V_MSG(p_buffer_len < 18, ERR_INVALID_DATA, "Invalid spawn packet received");
|
||||
int ofs = 1; // The spawn/despawn command.
|
||||
uint8_t scene_id = p_buffer[ofs];
|
||||
ofs += 1;
|
||||
uint32_t node_target = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
MultiplayerSpawner *spawner = Object::cast_to<MultiplayerSpawner>(multiplayer_cache->get_cached_object(p_from, node_target));
|
||||
ERR_FAIL_NULL_V(spawner, ERR_DOES_NOT_EXIST);
|
||||
ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
|
||||
|
||||
uint32_t net_id = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
uint32_t sync_len = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
uint32_t name_len = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
ERR_FAIL_COND_V_MSG(name_len + (sync_len * 4) > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA, vformat("Invalid spawn packet size: %d, wants: %d", p_buffer_len, ofs + name_len + (sync_len * 4)));
|
||||
List<uint32_t> sync_ids;
|
||||
for (uint32_t i = 0; i < sync_len; i++) {
|
||||
sync_ids.push_back(decode_uint32(&p_buffer[ofs]));
|
||||
ofs += 4;
|
||||
}
|
||||
ERR_FAIL_COND_V_MSG(name_len < 1, ERR_INVALID_DATA, "Zero spawn name size.");
|
||||
|
||||
// We need to make sure no trickery happens here, but we want to allow autogenerated ("@") node names.
|
||||
const String name = String::utf8((const char *)&p_buffer[ofs], name_len);
|
||||
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));
|
||||
ofs += name_len;
|
||||
|
||||
// Check that we can spawn.
|
||||
Node *parent = spawner->get_node_or_null(spawner->get_spawn_path());
|
||||
ERR_FAIL_NULL_V(parent, ERR_UNCONFIGURED);
|
||||
ERR_FAIL_COND_V(parent->has_node(name), ERR_INVALID_DATA);
|
||||
|
||||
Node *node = nullptr;
|
||||
if (scene_id == MultiplayerSpawner::INVALID_ID) {
|
||||
// Custom spawn.
|
||||
ERR_FAIL_COND_V(p_buffer_len - ofs < 4, ERR_INVALID_DATA);
|
||||
uint32_t arg_size = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
ERR_FAIL_COND_V(arg_size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
|
||||
Variant v;
|
||||
Error err = MultiplayerAPI::decode_and_decompress_variant(v, &p_buffer[ofs], arg_size, nullptr, false);
|
||||
ERR_FAIL_COND_V(err != OK, err);
|
||||
ofs += arg_size;
|
||||
node = spawner->instantiate_custom(v);
|
||||
} else {
|
||||
// Scene based spawn.
|
||||
node = spawner->instantiate_scene(scene_id);
|
||||
}
|
||||
ERR_FAIL_NULL_V(node, ERR_UNAUTHORIZED);
|
||||
node->set_name(name);
|
||||
|
||||
// Add and track remote
|
||||
ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAVAILABLE);
|
||||
ERR_FAIL_COND_V(peers_info[p_from].recv_nodes.has(net_id), ERR_ALREADY_IN_USE);
|
||||
ObjectID oid = node->get_instance_id();
|
||||
TrackedNode &tobj = _track(oid);
|
||||
tobj.spawner = spawner->get_instance_id();
|
||||
tobj.net_id = net_id;
|
||||
tobj.remote_peer = p_from;
|
||||
peers_info[p_from].recv_nodes[net_id] = oid;
|
||||
|
||||
// The initial state will be applied during the sync config (i.e. before _ready).
|
||||
pending_spawn = node->get_instance_id();
|
||||
pending_spawn_remote = p_from;
|
||||
pending_buffer_size = p_buffer_len - ofs;
|
||||
pending_buffer = pending_buffer_size > 0 ? &p_buffer[ofs] : nullptr;
|
||||
pending_sync_net_ids = sync_ids;
|
||||
|
||||
parent->add_child(node);
|
||||
spawner->emit_signal(SNAME("spawned"), node);
|
||||
|
||||
pending_spawn = ObjectID();
|
||||
pending_spawn_remote = 0;
|
||||
pending_buffer = nullptr;
|
||||
pending_buffer_size = 0;
|
||||
if (pending_sync_net_ids.size()) {
|
||||
pending_sync_net_ids.clear();
|
||||
ERR_FAIL_V(ERR_INVALID_DATA); // Should have been consumed.
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_despawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
|
||||
ERR_FAIL_COND_V_MSG(p_buffer_len < 5, ERR_INVALID_DATA, "Invalid spawn packet received");
|
||||
int ofs = 1; // The spawn/despawn command.
|
||||
uint32_t net_id = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
|
||||
// Untrack remote
|
||||
ERR_FAIL_COND_V(!peers_info.has(p_from), ERR_UNAUTHORIZED);
|
||||
PeerInfo &pinfo = peers_info[p_from];
|
||||
ERR_FAIL_COND_V(!pinfo.recv_nodes.has(net_id), ERR_UNAUTHORIZED);
|
||||
Node *node = get_id_as<Node>(pinfo.recv_nodes[net_id]);
|
||||
ERR_FAIL_NULL_V(node, ERR_BUG);
|
||||
pinfo.recv_nodes.erase(net_id);
|
||||
|
||||
const ObjectID oid = node->get_instance_id();
|
||||
ERR_FAIL_COND_V(!tracked_nodes.has(oid), ERR_BUG);
|
||||
MultiplayerSpawner *spawner = get_id_as<MultiplayerSpawner>(tracked_nodes[oid].spawner);
|
||||
ERR_FAIL_NULL_V(spawner, ERR_DOES_NOT_EXIST);
|
||||
ERR_FAIL_COND_V(p_from != spawner->get_multiplayer_authority(), ERR_UNAUTHORIZED);
|
||||
|
||||
if (node->get_parent() != nullptr) {
|
||||
node->get_parent()->remove_child(node);
|
||||
}
|
||||
node->queue_free();
|
||||
spawner->emit_signal(SNAME("despawned"), node);
|
||||
|
||||
return OK;
|
||||
}
|
||||
|
||||
bool SceneReplicationInterface::_verify_synchronizer(int p_peer, MultiplayerSynchronizer *p_sync, uint32_t &r_net_id) {
|
||||
r_net_id = p_sync->get_net_id();
|
||||
if (r_net_id == 0 || (r_net_id & 0x80000000)) {
|
||||
int path_id = 0;
|
||||
bool verified = multiplayer_cache->send_object_cache(p_sync, p_peer, path_id);
|
||||
ERR_FAIL_COND_V_MSG(path_id < 0, false, "This should never happen!");
|
||||
if (r_net_id == 0) {
|
||||
// First time path based ID.
|
||||
r_net_id = path_id | 0x80000000;
|
||||
p_sync->set_net_id(r_net_id | 0x80000000);
|
||||
}
|
||||
return verified;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
MultiplayerSynchronizer *SceneReplicationInterface::_find_synchronizer(int p_peer, uint32_t p_net_id) {
|
||||
MultiplayerSynchronizer *sync = nullptr;
|
||||
if (p_net_id & 0x80000000) {
|
||||
sync = Object::cast_to<MultiplayerSynchronizer>(multiplayer_cache->get_cached_object(p_peer, p_net_id & 0x7FFFFFFF));
|
||||
} else if (peers_info[p_peer].recv_sync_ids.has(p_net_id)) {
|
||||
const ObjectID &sid = peers_info[p_peer].recv_sync_ids[p_net_id];
|
||||
sync = get_id_as<MultiplayerSynchronizer>(sid);
|
||||
}
|
||||
return sync;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::_send_delta(int p_peer, const HashSet<ObjectID> &p_synchronizers, uint64_t p_usec, const HashMap<ObjectID, uint64_t> &p_last_watch_usecs) {
|
||||
MAKE_ROOM(/* header */ 1 + /* element */ 4 + 8 + 4 + delta_mtu);
|
||||
uint8_t *ptr = packet_cache.ptrw();
|
||||
ptr[0] = SceneMultiplayer::NETWORK_COMMAND_SYNC | (1 << SceneMultiplayer::CMD_FLAG_0_SHIFT);
|
||||
int ofs = 1;
|
||||
for (const ObjectID &oid : p_synchronizers) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
|
||||
ERR_CONTINUE(!sync || !sync->get_replication_config_ptr() || !_has_authority(sync));
|
||||
uint32_t net_id;
|
||||
if (!_verify_synchronizer(p_peer, sync, net_id)) {
|
||||
continue;
|
||||
}
|
||||
uint64_t last_usec = p_last_watch_usecs.has(oid) ? p_last_watch_usecs[oid] : 0;
|
||||
uint64_t indexes;
|
||||
List<Variant> delta = sync->get_delta_state(p_usec, last_usec, indexes);
|
||||
|
||||
if (!delta.size()) {
|
||||
continue; // Nothing to update.
|
||||
}
|
||||
|
||||
Vector<const Variant *> varp;
|
||||
varp.resize(delta.size());
|
||||
const Variant **vptr = varp.ptrw();
|
||||
int i = 0;
|
||||
for (const Variant &v : delta) {
|
||||
vptr[i] = &v;
|
||||
i++;
|
||||
}
|
||||
int size;
|
||||
Error err = MultiplayerAPI::encode_and_compress_variants(vptr, varp.size(), nullptr, size);
|
||||
ERR_CONTINUE_MSG(err != OK, "Unable to encode delta state.");
|
||||
|
||||
ERR_CONTINUE_MSG(size > delta_mtu, vformat("Synchronizer delta bigger than MTU will not be sent (%d > %d): %s", size, delta_mtu, sync->get_path()));
|
||||
|
||||
if (ofs + 4 + 8 + 4 + size > delta_mtu) {
|
||||
// Send what we got, and reset write.
|
||||
_send_raw(packet_cache.ptr(), ofs, p_peer, true);
|
||||
ofs = 1;
|
||||
}
|
||||
if (size) {
|
||||
ofs += encode_uint32(sync->get_net_id(), &ptr[ofs]);
|
||||
ofs += encode_uint64(indexes, &ptr[ofs]);
|
||||
ofs += encode_uint32(size, &ptr[ofs]);
|
||||
MultiplayerAPI::encode_and_compress_variants(vptr, varp.size(), &ptr[ofs], size);
|
||||
ofs += size;
|
||||
}
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_node_data("delta_out", oid, size);
|
||||
#endif
|
||||
peers_info[p_peer].last_watch_usecs[oid] = p_usec;
|
||||
}
|
||||
if (ofs > 1) {
|
||||
// Got some left over to send.
|
||||
_send_raw(packet_cache.ptr(), ofs, p_peer, true);
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_delta_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
|
||||
int ofs = 1;
|
||||
while (ofs + 4 + 8 + 4 < p_buffer_len) {
|
||||
uint32_t net_id = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
uint64_t indexes = decode_uint64(&p_buffer[ofs]);
|
||||
ofs += 8;
|
||||
uint32_t size = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
ERR_FAIL_COND_V(size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
|
||||
MultiplayerSynchronizer *sync = _find_synchronizer(p_from, net_id);
|
||||
Node *node = sync ? sync->get_root_node() : nullptr;
|
||||
if (!sync || sync->get_multiplayer_authority() != p_from || !node) {
|
||||
ofs += size;
|
||||
ERR_CONTINUE_MSG(true, "Ignoring delta for non-authority or invalid synchronizer.");
|
||||
}
|
||||
List<NodePath> props = sync->get_delta_properties(indexes);
|
||||
ERR_FAIL_COND_V(props.is_empty(), ERR_INVALID_DATA);
|
||||
Vector<Variant> vars;
|
||||
vars.resize(props.size());
|
||||
int consumed = 0;
|
||||
Error err = MultiplayerAPI::decode_and_decompress_variants(vars, p_buffer + ofs, size, consumed);
|
||||
ERR_FAIL_COND_V(err != OK, err);
|
||||
ERR_FAIL_COND_V(uint32_t(consumed) != size, ERR_INVALID_DATA);
|
||||
err = MultiplayerSynchronizer::set_state(props, node, vars);
|
||||
ERR_FAIL_COND_V(err != OK, err);
|
||||
ofs += size;
|
||||
sync->emit_signal(SNAME("delta_synchronized"));
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_node_data("delta_in", sync->get_instance_id(), size);
|
||||
#endif
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::_send_sync(int p_peer, const HashSet<ObjectID> &p_synchronizers, uint16_t p_sync_net_time, uint64_t p_usec) {
|
||||
MAKE_ROOM(/* header */ 3 + /* element */ 4 + 4 + sync_mtu);
|
||||
uint8_t *ptr = packet_cache.ptrw();
|
||||
ptr[0] = SceneMultiplayer::NETWORK_COMMAND_SYNC;
|
||||
int ofs = 1;
|
||||
ofs += encode_uint16(p_sync_net_time, &ptr[1]);
|
||||
// Can only send updates for already notified nodes.
|
||||
// This is a lazy implementation, we could optimize much more here with by grouping by replication config.
|
||||
for (const ObjectID &oid : p_synchronizers) {
|
||||
MultiplayerSynchronizer *sync = get_id_as<MultiplayerSynchronizer>(oid);
|
||||
ERR_CONTINUE(!sync || !sync->get_replication_config_ptr() || !_has_authority(sync));
|
||||
if (!sync->update_outbound_sync_time(p_usec)) {
|
||||
continue; // nothing to sync.
|
||||
}
|
||||
|
||||
Node *node = sync->get_root_node();
|
||||
ERR_CONTINUE(!node);
|
||||
uint32_t net_id = sync->get_net_id();
|
||||
if (!_verify_synchronizer(p_peer, sync, net_id)) {
|
||||
// The path based sync is not yet confirmed, skipping.
|
||||
continue;
|
||||
}
|
||||
int size;
|
||||
Vector<Variant> vars;
|
||||
Vector<const Variant *> varp;
|
||||
const List<NodePath> props = sync->get_replication_config_ptr()->get_sync_properties();
|
||||
Error err = MultiplayerSynchronizer::get_state(props, node, vars, varp);
|
||||
ERR_CONTINUE_MSG(err != OK, "Unable to retrieve sync state.");
|
||||
err = MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), nullptr, size);
|
||||
ERR_CONTINUE_MSG(err != OK, "Unable to encode sync state.");
|
||||
// TODO Handle single state above MTU.
|
||||
ERR_CONTINUE_MSG(size > sync_mtu, vformat("Node states bigger than MTU will not be sent (%d > %d): %s", size, sync_mtu, node->get_path()));
|
||||
if (ofs + 4 + 4 + size > sync_mtu) {
|
||||
// Send what we got, and reset write.
|
||||
_send_raw(packet_cache.ptr(), ofs, p_peer, false);
|
||||
ofs = 3;
|
||||
}
|
||||
if (size) {
|
||||
ofs += encode_uint32(sync->get_net_id(), &ptr[ofs]);
|
||||
ofs += encode_uint32(size, &ptr[ofs]);
|
||||
MultiplayerAPI::encode_and_compress_variants(varp.ptrw(), varp.size(), &ptr[ofs], size);
|
||||
ofs += size;
|
||||
}
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_node_data("sync_out", oid, size);
|
||||
#endif
|
||||
}
|
||||
if (ofs > 3) {
|
||||
// Got some left over to send.
|
||||
_send_raw(packet_cache.ptr(), ofs, p_peer, false);
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneReplicationInterface::on_sync_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len) {
|
||||
ERR_FAIL_COND_V_MSG(p_buffer_len < 11, ERR_INVALID_DATA, "Invalid sync packet received");
|
||||
bool is_delta = (p_buffer[0] & (1 << SceneMultiplayer::CMD_FLAG_0_SHIFT)) != 0;
|
||||
if (is_delta) {
|
||||
return on_delta_receive(p_from, p_buffer, p_buffer_len);
|
||||
}
|
||||
uint16_t time = decode_uint16(&p_buffer[1]);
|
||||
int ofs = 3;
|
||||
while (ofs + 8 < p_buffer_len) {
|
||||
uint32_t net_id = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
uint32_t size = decode_uint32(&p_buffer[ofs]);
|
||||
ofs += 4;
|
||||
ERR_FAIL_COND_V(size > uint32_t(p_buffer_len - ofs), ERR_INVALID_DATA);
|
||||
MultiplayerSynchronizer *sync = _find_synchronizer(p_from, net_id);
|
||||
if (!sync) {
|
||||
// Not received yet.
|
||||
ofs += size;
|
||||
continue;
|
||||
}
|
||||
Node *node = sync->get_root_node();
|
||||
if (sync->get_multiplayer_authority() != p_from || !node) {
|
||||
// Not valid for me.
|
||||
ofs += size;
|
||||
ERR_CONTINUE_MSG(true, "Ignoring sync data from non-authority or for missing node.");
|
||||
}
|
||||
if (!sync->update_inbound_sync_time(time)) {
|
||||
// State is too old.
|
||||
ofs += size;
|
||||
continue;
|
||||
}
|
||||
const List<NodePath> props = sync->get_replication_config_ptr()->get_sync_properties();
|
||||
Vector<Variant> vars;
|
||||
vars.resize(props.size());
|
||||
int consumed;
|
||||
Error err = MultiplayerAPI::decode_and_decompress_variants(vars, &p_buffer[ofs], size, consumed);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
err = MultiplayerSynchronizer::set_state(props, node, vars);
|
||||
ERR_FAIL_COND_V(err, err);
|
||||
ofs += size;
|
||||
sync->emit_signal(SNAME("synchronized"));
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_node_data("sync_in", sync->get_instance_id(), size);
|
||||
#endif
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::set_max_sync_packet_size(int p_size) {
|
||||
ERR_FAIL_COND_MSG(p_size < 128, "Sync maximum packet size must be at least 128 bytes.");
|
||||
sync_mtu = p_size;
|
||||
}
|
||||
|
||||
int SceneReplicationInterface::get_max_sync_packet_size() const {
|
||||
return sync_mtu;
|
||||
}
|
||||
|
||||
void SceneReplicationInterface::set_max_delta_packet_size(int p_size) {
|
||||
ERR_FAIL_COND_MSG(p_size < 128, "Sync maximum packet size must be at least 128 bytes.");
|
||||
delta_mtu = p_size;
|
||||
}
|
||||
|
||||
int SceneReplicationInterface::get_max_delta_packet_size() const {
|
||||
return delta_mtu;
|
||||
}
|
152
modules/multiplayer/scene_replication_interface.h
Normal file
152
modules/multiplayer/scene_replication_interface.h
Normal file
@@ -0,0 +1,152 @@
|
||||
/**************************************************************************/
|
||||
/* scene_replication_interface.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "multiplayer_spawner.h"
|
||||
#include "multiplayer_synchronizer.h"
|
||||
|
||||
#include "core/object/ref_counted.h"
|
||||
|
||||
class SceneMultiplayer;
|
||||
class SceneCacheInterface;
|
||||
|
||||
class SceneReplicationInterface : public RefCounted {
|
||||
GDCLASS(SceneReplicationInterface, RefCounted);
|
||||
|
||||
private:
|
||||
struct TrackedNode {
|
||||
ObjectID id;
|
||||
uint32_t net_id = 0;
|
||||
uint32_t remote_peer = 0;
|
||||
ObjectID spawner;
|
||||
HashSet<ObjectID> synchronizers;
|
||||
|
||||
bool operator==(const ObjectID &p_other) { return id == p_other; }
|
||||
|
||||
TrackedNode() {}
|
||||
TrackedNode(const ObjectID &p_id) { id = p_id; }
|
||||
TrackedNode(const ObjectID &p_id, uint32_t p_net_id) {
|
||||
id = p_id;
|
||||
net_id = p_net_id;
|
||||
}
|
||||
};
|
||||
|
||||
struct PeerInfo {
|
||||
HashSet<ObjectID> sync_nodes;
|
||||
HashSet<ObjectID> spawn_nodes;
|
||||
HashMap<ObjectID, uint64_t> last_watch_usecs;
|
||||
HashMap<uint32_t, ObjectID> recv_sync_ids;
|
||||
HashMap<uint32_t, ObjectID> recv_nodes;
|
||||
uint16_t last_sent_sync = 0;
|
||||
};
|
||||
|
||||
// Replication state.
|
||||
HashMap<int, PeerInfo> peers_info;
|
||||
uint32_t last_net_id = 0;
|
||||
HashMap<ObjectID, TrackedNode> tracked_nodes;
|
||||
RBSet<ObjectID> spawned_nodes;
|
||||
HashSet<ObjectID> sync_nodes;
|
||||
|
||||
// Pending local spawn information (handles spawning nested nodes during ready).
|
||||
HashSet<ObjectID> spawn_queue;
|
||||
|
||||
// Pending remote spawn information.
|
||||
ObjectID pending_spawn;
|
||||
int pending_spawn_remote = 0;
|
||||
const uint8_t *pending_buffer = nullptr;
|
||||
int pending_buffer_size = 0;
|
||||
List<uint32_t> pending_sync_net_ids;
|
||||
|
||||
// Replicator config.
|
||||
SceneMultiplayer *multiplayer = nullptr;
|
||||
SceneCacheInterface *multiplayer_cache = nullptr;
|
||||
PackedByteArray packet_cache;
|
||||
int sync_mtu = 1350; // Highly dependent on underlying protocol.
|
||||
int delta_mtu = 65535;
|
||||
|
||||
TrackedNode &_track(const ObjectID &p_id);
|
||||
void _untrack(const ObjectID &p_id);
|
||||
void _node_ready(const ObjectID &p_oid);
|
||||
|
||||
bool _has_authority(const Node *p_node);
|
||||
bool _verify_synchronizer(int p_peer, MultiplayerSynchronizer *p_sync, uint32_t &r_net_id);
|
||||
MultiplayerSynchronizer *_find_synchronizer(int p_peer, uint32_t p_net_ida);
|
||||
|
||||
void _send_sync(int p_peer, const HashSet<ObjectID> &p_synchronizers, uint16_t p_sync_net_time, uint64_t p_usec);
|
||||
void _send_delta(int p_peer, const HashSet<ObjectID> &p_synchronizers, uint64_t p_usec, const HashMap<ObjectID, uint64_t> &p_last_watch_usecs);
|
||||
Error _make_spawn_packet(Node *p_node, MultiplayerSpawner *p_spawner, int &r_len);
|
||||
Error _make_despawn_packet(Node *p_node, int &r_len);
|
||||
Error _send_raw(const uint8_t *p_buffer, int p_size, int p_peer, bool p_reliable);
|
||||
|
||||
void _visibility_changed(int p_peer, ObjectID p_oid);
|
||||
Error _update_sync_visibility(int p_peer, MultiplayerSynchronizer *p_sync);
|
||||
Error _update_spawn_visibility(int p_peer, const ObjectID &p_oid);
|
||||
void _free_remotes(const PeerInfo &p_info);
|
||||
|
||||
template <typename T>
|
||||
static T *get_id_as(const ObjectID &p_id) {
|
||||
return p_id.is_valid() ? ObjectDB::get_instance<T>(p_id) : nullptr;
|
||||
}
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ void _profile_node_data(const String &p_what, ObjectID p_id, int p_size);
|
||||
#endif
|
||||
|
||||
public:
|
||||
static void make_default();
|
||||
|
||||
void on_reset();
|
||||
void on_peer_change(int p_id, bool p_connected);
|
||||
|
||||
Error on_spawn(Object *p_obj, Variant p_config);
|
||||
Error on_despawn(Object *p_obj, Variant p_config);
|
||||
Error on_replication_start(Object *p_obj, Variant p_config);
|
||||
Error on_replication_stop(Object *p_obj, Variant p_config);
|
||||
void on_network_process();
|
||||
|
||||
Error on_spawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len);
|
||||
Error on_despawn_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len);
|
||||
Error on_sync_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len);
|
||||
Error on_delta_receive(int p_from, const uint8_t *p_buffer, int p_buffer_len);
|
||||
|
||||
bool is_rpc_visible(const ObjectID &p_oid, int p_peer) const;
|
||||
|
||||
void set_max_sync_packet_size(int p_size);
|
||||
int get_max_sync_packet_size() const;
|
||||
|
||||
void set_max_delta_packet_size(int p_size);
|
||||
int get_max_delta_packet_size() const;
|
||||
|
||||
SceneReplicationInterface(SceneMultiplayer *p_multiplayer, SceneCacheInterface *p_cache) {
|
||||
multiplayer = p_multiplayer;
|
||||
multiplayer_cache = p_cache;
|
||||
}
|
||||
};
|
519
modules/multiplayer/scene_rpc_interface.cpp
Normal file
519
modules/multiplayer/scene_rpc_interface.cpp
Normal file
@@ -0,0 +1,519 @@
|
||||
/**************************************************************************/
|
||||
/* scene_rpc_interface.cpp */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#include "scene_rpc_interface.h"
|
||||
|
||||
#include "scene_multiplayer.h"
|
||||
|
||||
#include "core/debugger/engine_debugger.h"
|
||||
#include "core/io/marshalls.h"
|
||||
#include "scene/main/multiplayer_api.h"
|
||||
#include "scene/main/node.h"
|
||||
#include "scene/main/window.h"
|
||||
|
||||
// The RPC meta is composed by a single byte that contains (starting from the least significant bit):
|
||||
// - `NetworkCommands` in the first four bits.
|
||||
// - `NetworkNodeIdCompression` in the next 2 bits.
|
||||
// - `NetworkNameIdCompression` in the next 1 bit.
|
||||
// - `byte_only_or_no_args` in the next 1 bit.
|
||||
#define NODE_ID_COMPRESSION_SHIFT SceneMultiplayer::CMD_FLAG_0_SHIFT
|
||||
#define NAME_ID_COMPRESSION_SHIFT SceneMultiplayer::CMD_FLAG_2_SHIFT
|
||||
#define BYTE_ONLY_OR_NO_ARGS_SHIFT SceneMultiplayer::CMD_FLAG_3_SHIFT
|
||||
|
||||
#define NODE_ID_COMPRESSION_FLAG ((1 << NODE_ID_COMPRESSION_SHIFT) | (1 << (NODE_ID_COMPRESSION_SHIFT + 1)))
|
||||
#define NAME_ID_COMPRESSION_FLAG (1 << NAME_ID_COMPRESSION_SHIFT)
|
||||
#define BYTE_ONLY_OR_NO_ARGS_FLAG (1 << BYTE_ONLY_OR_NO_ARGS_SHIFT)
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ void SceneRPCInterface::_profile_node_data(const String &p_what, ObjectID p_id, int p_size) {
|
||||
if (EngineDebugger::is_profiling("multiplayer:rpc")) {
|
||||
Array values = { p_what, p_id, p_size };
|
||||
EngineDebugger::profiler_add_frame_data("multiplayer:rpc", values);
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
// Returns the packet size stripping the node path added when the node is not yet cached.
|
||||
int get_packet_len(uint32_t p_node_target, int p_packet_len) {
|
||||
if (p_node_target & 0x80000000) {
|
||||
int ofs = p_node_target & 0x7FFFFFFF;
|
||||
return p_packet_len - (p_packet_len - ofs);
|
||||
} else {
|
||||
return p_packet_len;
|
||||
}
|
||||
}
|
||||
|
||||
void SceneRPCInterface::_parse_rpc_config(const Variant &p_config, bool p_for_node, RPCConfigCache &r_cache) {
|
||||
if (p_config.get_type() == Variant::NIL) {
|
||||
return;
|
||||
}
|
||||
ERR_FAIL_COND(p_config.get_type() != Variant::DICTIONARY);
|
||||
const Dictionary config = p_config;
|
||||
Array names = config.keys();
|
||||
names.sort_custom(callable_mp_static(&StringLikeVariantOrder::compare)); // Ensure ID order
|
||||
for (int i = 0; i < names.size(); i++) {
|
||||
ERR_CONTINUE(!names[i].is_string());
|
||||
String name = names[i].operator String();
|
||||
ERR_CONTINUE(config[name].get_type() != Variant::DICTIONARY);
|
||||
ERR_CONTINUE(!config[name].operator Dictionary().has("rpc_mode"));
|
||||
Dictionary dict = config[name];
|
||||
RPCConfig cfg;
|
||||
cfg.name = name;
|
||||
cfg.rpc_mode = ((MultiplayerAPI::RPCMode)dict.get("rpc_mode", MultiplayerAPI::RPC_MODE_AUTHORITY).operator int());
|
||||
cfg.transfer_mode = ((MultiplayerPeer::TransferMode)dict.get("transfer_mode", MultiplayerPeer::TRANSFER_MODE_RELIABLE).operator int());
|
||||
cfg.call_local = dict.get("call_local", false).operator bool();
|
||||
cfg.channel = dict.get("channel", 0).operator int();
|
||||
uint16_t id = ((uint16_t)i);
|
||||
if (p_for_node) {
|
||||
id |= (1 << 15);
|
||||
}
|
||||
r_cache.configs[id] = cfg;
|
||||
r_cache.ids[name] = id;
|
||||
}
|
||||
}
|
||||
|
||||
const SceneRPCInterface::RPCConfigCache &SceneRPCInterface::_get_node_config(const Node *p_node) {
|
||||
const ObjectID oid = p_node->get_instance_id();
|
||||
if (rpc_cache.has(oid)) {
|
||||
return rpc_cache[oid];
|
||||
}
|
||||
RPCConfigCache cache;
|
||||
_parse_rpc_config(p_node->get_node_rpc_config(), true, cache);
|
||||
if (p_node->get_script_instance()) {
|
||||
_parse_rpc_config(p_node->get_script_instance()->get_rpc_config(), false, cache);
|
||||
}
|
||||
rpc_cache[oid] = cache;
|
||||
return rpc_cache[oid];
|
||||
}
|
||||
|
||||
String SceneRPCInterface::get_rpc_md5(const Object *p_obj) {
|
||||
const Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_NULL_V(node, "");
|
||||
const RPCConfigCache cache = _get_node_config(node);
|
||||
String rpc_list;
|
||||
for (const KeyValue<uint16_t, RPCConfig> &config : cache.configs) {
|
||||
rpc_list += String(config.value.name);
|
||||
}
|
||||
return rpc_list.md5_text();
|
||||
}
|
||||
|
||||
Node *SceneRPCInterface::_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len) {
|
||||
Node *root_node = SceneTree::get_singleton()->get_root()->get_node(multiplayer->get_root_path());
|
||||
ERR_FAIL_NULL_V(root_node, nullptr);
|
||||
Node *node = nullptr;
|
||||
|
||||
if (p_node_target & 0x80000000) {
|
||||
// Use full path (not cached yet).
|
||||
int ofs = p_node_target & 0x7FFFFFFF;
|
||||
|
||||
ERR_FAIL_COND_V_MSG(ofs >= p_packet_len, nullptr, "Invalid packet received. Size smaller than declared.");
|
||||
|
||||
String paths = String::utf8((const char *)&p_packet[ofs], p_packet_len - ofs);
|
||||
|
||||
NodePath np = paths;
|
||||
|
||||
node = root_node->get_node(np);
|
||||
|
||||
if (!node) {
|
||||
ERR_PRINT("Failed to get path from RPC: " + String(np) + ".");
|
||||
}
|
||||
return node;
|
||||
} else {
|
||||
// Use cached path.
|
||||
return Object::cast_to<Node>(multiplayer_cache->get_cached_object(p_from, p_node_target));
|
||||
}
|
||||
}
|
||||
|
||||
void SceneRPCInterface::process_rpc(int p_from, const uint8_t *p_packet, int p_packet_len) {
|
||||
// Extract packet meta
|
||||
int packet_min_size = 1;
|
||||
int name_id_offset = 1;
|
||||
ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
|
||||
// Compute the meta size, which depends on the compression level.
|
||||
int node_id_compression = (p_packet[0] & NODE_ID_COMPRESSION_FLAG) >> NODE_ID_COMPRESSION_SHIFT;
|
||||
int name_id_compression = (p_packet[0] & NAME_ID_COMPRESSION_FLAG) >> NAME_ID_COMPRESSION_SHIFT;
|
||||
|
||||
switch (node_id_compression) {
|
||||
case NETWORK_NODE_ID_COMPRESSION_8:
|
||||
packet_min_size += 1;
|
||||
name_id_offset += 1;
|
||||
break;
|
||||
case NETWORK_NODE_ID_COMPRESSION_16:
|
||||
packet_min_size += 2;
|
||||
name_id_offset += 2;
|
||||
break;
|
||||
case NETWORK_NODE_ID_COMPRESSION_32:
|
||||
packet_min_size += 4;
|
||||
name_id_offset += 4;
|
||||
break;
|
||||
default:
|
||||
ERR_FAIL_MSG("Was not possible to extract the node id compression mode.");
|
||||
}
|
||||
switch (name_id_compression) {
|
||||
case NETWORK_NAME_ID_COMPRESSION_8:
|
||||
packet_min_size += 1;
|
||||
break;
|
||||
case NETWORK_NAME_ID_COMPRESSION_16:
|
||||
packet_min_size += 2;
|
||||
break;
|
||||
default:
|
||||
ERR_FAIL_MSG("Was not possible to extract the name id compression mode.");
|
||||
}
|
||||
ERR_FAIL_COND_MSG(p_packet_len < packet_min_size, "Invalid packet received. Size too small.");
|
||||
|
||||
uint32_t node_target = 0;
|
||||
switch (node_id_compression) {
|
||||
case NETWORK_NODE_ID_COMPRESSION_8:
|
||||
node_target = p_packet[1];
|
||||
break;
|
||||
case NETWORK_NODE_ID_COMPRESSION_16:
|
||||
node_target = decode_uint16(p_packet + 1);
|
||||
break;
|
||||
case NETWORK_NODE_ID_COMPRESSION_32:
|
||||
node_target = decode_uint32(p_packet + 1);
|
||||
break;
|
||||
default:
|
||||
// Unreachable, checked before.
|
||||
CRASH_NOW();
|
||||
}
|
||||
|
||||
Node *node = _process_get_node(p_from, p_packet, node_target, p_packet_len);
|
||||
ERR_FAIL_NULL_MSG(node, "Invalid packet received. Requested node was not found.");
|
||||
|
||||
uint16_t name_id = 0;
|
||||
switch (name_id_compression) {
|
||||
case NETWORK_NAME_ID_COMPRESSION_8:
|
||||
name_id = p_packet[name_id_offset];
|
||||
break;
|
||||
case NETWORK_NAME_ID_COMPRESSION_16:
|
||||
name_id = decode_uint16(p_packet + name_id_offset);
|
||||
break;
|
||||
default:
|
||||
// Unreachable, checked before.
|
||||
CRASH_NOW();
|
||||
}
|
||||
|
||||
const int packet_len = get_packet_len(node_target, p_packet_len);
|
||||
_process_rpc(node, name_id, p_from, p_packet, packet_len, packet_min_size);
|
||||
}
|
||||
|
||||
void SceneRPCInterface::_process_rpc(Node *p_node, const uint16_t p_rpc_method_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset) {
|
||||
ERR_FAIL_COND_MSG(p_offset > p_packet_len, "Invalid packet received. Size too small.");
|
||||
|
||||
// Check that remote can call the RPC on this node.
|
||||
const RPCConfigCache &cache_config = _get_node_config(p_node);
|
||||
ERR_FAIL_COND(!cache_config.configs.has(p_rpc_method_id));
|
||||
const RPCConfig &config = cache_config.configs[p_rpc_method_id];
|
||||
|
||||
bool can_call = false;
|
||||
switch (config.rpc_mode) {
|
||||
case MultiplayerAPI::RPC_MODE_DISABLED: {
|
||||
can_call = false;
|
||||
} break;
|
||||
case MultiplayerAPI::RPC_MODE_ANY_PEER: {
|
||||
can_call = true;
|
||||
} break;
|
||||
case MultiplayerAPI::RPC_MODE_AUTHORITY: {
|
||||
can_call = p_from == p_node->get_multiplayer_authority();
|
||||
} break;
|
||||
}
|
||||
|
||||
ERR_FAIL_COND_MSG(!can_call, "RPC '" + String(config.name) + "' is not allowed on node " + String(p_node->get_path()) + " from: " + itos(p_from) + ". Mode is " + itos((int)config.rpc_mode) + ", authority is " + itos(p_node->get_multiplayer_authority()) + ".");
|
||||
|
||||
int argc = 0;
|
||||
|
||||
const bool byte_only_or_no_args = p_packet[0] & BYTE_ONLY_OR_NO_ARGS_FLAG;
|
||||
if (byte_only_or_no_args) {
|
||||
if (p_offset < p_packet_len) {
|
||||
// This packet contains only bytes.
|
||||
argc = 1;
|
||||
}
|
||||
} else {
|
||||
// Normal variant, takes the argument count from the packet.
|
||||
ERR_FAIL_COND_MSG(p_offset >= p_packet_len, "Invalid packet received. Size too small.");
|
||||
argc = p_packet[p_offset];
|
||||
p_offset += 1;
|
||||
}
|
||||
|
||||
Vector<Variant> args;
|
||||
Vector<const Variant *> argp;
|
||||
args.resize(argc);
|
||||
argp.resize(argc);
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_node_data("rpc_in", p_node->get_instance_id(), p_packet_len);
|
||||
#endif
|
||||
|
||||
int out;
|
||||
MultiplayerAPI::decode_and_decompress_variants(args, &p_packet[p_offset], p_packet_len - p_offset, out, byte_only_or_no_args, multiplayer->is_object_decoding_allowed());
|
||||
for (int i = 0; i < argc; i++) {
|
||||
argp.write[i] = &args[i];
|
||||
}
|
||||
|
||||
Callable::CallError ce;
|
||||
|
||||
p_node->callp(config.name, (const Variant **)argp.ptr(), argc, ce);
|
||||
if (ce.error != Callable::CallError::CALL_OK) {
|
||||
String error = Variant::get_call_error_text(p_node, config.name, (const Variant **)argp.ptr(), argc, ce);
|
||||
error = "RPC - " + error;
|
||||
ERR_PRINT(error);
|
||||
}
|
||||
}
|
||||
|
||||
void SceneRPCInterface::_send_rpc(Node *p_node, int p_to, uint16_t p_rpc_id, const RPCConfig &p_config, const StringName &p_name, const Variant **p_arg, int p_argcount) {
|
||||
Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
|
||||
ERR_FAIL_COND_MSG(peer.is_null(), "Attempt to call RPC without active multiplayer peer.");
|
||||
|
||||
ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_CONNECTING, "Attempt to call RPC while multiplayer peer is not connected yet.");
|
||||
|
||||
ERR_FAIL_COND_MSG(peer->get_connection_status() == MultiplayerPeer::CONNECTION_DISCONNECTED, "Attempt to call RPC while multiplayer peer is disconnected.");
|
||||
|
||||
ERR_FAIL_COND_MSG(p_argcount > 255, "Too many arguments (>255).");
|
||||
|
||||
if (p_to != 0 && !multiplayer->get_connected_peers().has(Math::abs(p_to))) {
|
||||
ERR_FAIL_COND_MSG(p_to == multiplayer->get_unique_id(), "Attempt to call RPC on yourself! Peer unique ID: " + itos(multiplayer->get_unique_id()) + ".");
|
||||
|
||||
ERR_FAIL_MSG("Attempt to call RPC with unknown peer ID: " + itos(p_to) + ".");
|
||||
}
|
||||
|
||||
// See if all peers have cached path (if so, call can be fast) while building the RPC target list.
|
||||
HashSet<int> targets;
|
||||
int psc_id = -1;
|
||||
bool has_all_peers = true;
|
||||
const ObjectID oid = p_node->get_instance_id();
|
||||
if (p_to > 0) {
|
||||
ERR_FAIL_COND_MSG(!multiplayer_replicator->is_rpc_visible(oid, p_to), "Attempt to call an RPC to a peer that cannot see this node. Peer ID: " + itos(p_to));
|
||||
targets.insert(p_to);
|
||||
has_all_peers = multiplayer_cache->send_object_cache(p_node, p_to, psc_id);
|
||||
} else {
|
||||
bool restricted = !multiplayer_replicator->is_rpc_visible(oid, 0);
|
||||
for (const int &P : multiplayer->get_connected_peers()) {
|
||||
if (p_to < 0 && P == -p_to) {
|
||||
continue; // Excluded peer.
|
||||
}
|
||||
if (restricted && !multiplayer_replicator->is_rpc_visible(oid, P)) {
|
||||
continue; // Not visible to this peer.
|
||||
}
|
||||
targets.insert(P);
|
||||
bool has_peer = multiplayer_cache->send_object_cache(p_node, P, psc_id);
|
||||
has_all_peers = has_all_peers && has_peer;
|
||||
}
|
||||
}
|
||||
if (targets.is_empty()) {
|
||||
return; // No one in sight.
|
||||
}
|
||||
|
||||
// Create base packet, lots of hardcode because it must be tight.
|
||||
int ofs = 0;
|
||||
|
||||
#define MAKE_ROOM(m_amount) \
|
||||
if (packet_cache.size() < m_amount) \
|
||||
packet_cache.resize(m_amount);
|
||||
|
||||
// Encode meta.
|
||||
uint8_t command_type = SceneMultiplayer::NETWORK_COMMAND_REMOTE_CALL;
|
||||
uint8_t node_id_compression = UINT8_MAX;
|
||||
uint8_t name_id_compression = UINT8_MAX;
|
||||
bool byte_only_or_no_args = false;
|
||||
|
||||
MAKE_ROOM(1);
|
||||
// The meta is composed along the way, so just set 0 for now.
|
||||
packet_cache.write[0] = 0;
|
||||
ofs += 1;
|
||||
|
||||
// Encode Node ID.
|
||||
if (has_all_peers) {
|
||||
// Compress the node ID only if all the target peers already know it.
|
||||
if (psc_id >= 0 && psc_id <= 255) {
|
||||
// We can encode the id in 1 byte
|
||||
node_id_compression = NETWORK_NODE_ID_COMPRESSION_8;
|
||||
MAKE_ROOM(ofs + 1);
|
||||
packet_cache.write[ofs] = static_cast<uint8_t>(psc_id);
|
||||
ofs += 1;
|
||||
} else if (psc_id >= 0 && psc_id <= 65535) {
|
||||
// We can encode the id in 2 bytes
|
||||
node_id_compression = NETWORK_NODE_ID_COMPRESSION_16;
|
||||
MAKE_ROOM(ofs + 2);
|
||||
encode_uint16(static_cast<uint16_t>(psc_id), &(packet_cache.write[ofs]));
|
||||
ofs += 2;
|
||||
} else {
|
||||
// Too big, let's use 4 bytes.
|
||||
node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
|
||||
MAKE_ROOM(ofs + 4);
|
||||
encode_uint32(psc_id, &(packet_cache.write[ofs]));
|
||||
ofs += 4;
|
||||
}
|
||||
} else {
|
||||
// The targets don't know the node yet, so we need to use 32 bits int.
|
||||
node_id_compression = NETWORK_NODE_ID_COMPRESSION_32;
|
||||
MAKE_ROOM(ofs + 4);
|
||||
encode_uint32(psc_id, &(packet_cache.write[ofs]));
|
||||
ofs += 4;
|
||||
}
|
||||
|
||||
// Encode method ID
|
||||
if (p_rpc_id <= UINT8_MAX) {
|
||||
// The ID fits in 1 byte
|
||||
name_id_compression = NETWORK_NAME_ID_COMPRESSION_8;
|
||||
MAKE_ROOM(ofs + 1);
|
||||
packet_cache.write[ofs] = static_cast<uint8_t>(p_rpc_id);
|
||||
ofs += 1;
|
||||
} else {
|
||||
// The ID is larger, let's use 2 bytes
|
||||
name_id_compression = NETWORK_NAME_ID_COMPRESSION_16;
|
||||
MAKE_ROOM(ofs + 2);
|
||||
encode_uint16(p_rpc_id, &(packet_cache.write[ofs]));
|
||||
ofs += 2;
|
||||
}
|
||||
|
||||
int len;
|
||||
Error err = MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, nullptr, len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());
|
||||
ERR_FAIL_COND_MSG(err != OK, "Unable to encode RPC arguments. THIS IS LIKELY A BUG IN THE ENGINE!");
|
||||
if (byte_only_or_no_args) {
|
||||
MAKE_ROOM(ofs + len);
|
||||
} else {
|
||||
MAKE_ROOM(ofs + 1 + len);
|
||||
packet_cache.write[ofs] = p_argcount;
|
||||
ofs += 1;
|
||||
}
|
||||
if (len) {
|
||||
MultiplayerAPI::encode_and_compress_variants(p_arg, p_argcount, &packet_cache.write[ofs], len, &byte_only_or_no_args, multiplayer->is_object_decoding_allowed());
|
||||
ofs += len;
|
||||
}
|
||||
|
||||
ERR_FAIL_COND(command_type > 7);
|
||||
ERR_FAIL_COND(node_id_compression > 3);
|
||||
ERR_FAIL_COND(name_id_compression > 1);
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_profile_node_data("rpc_out", p_node->get_instance_id(), ofs);
|
||||
#endif
|
||||
|
||||
// We can now set the meta
|
||||
packet_cache.write[0] = command_type + (node_id_compression << NODE_ID_COMPRESSION_SHIFT) + (name_id_compression << NAME_ID_COMPRESSION_SHIFT) + (byte_only_or_no_args ? BYTE_ONLY_OR_NO_ARGS_FLAG : 0);
|
||||
|
||||
// Take chance and set transfer mode, since all send methods will use it.
|
||||
peer->set_transfer_channel(p_config.channel);
|
||||
peer->set_transfer_mode(p_config.transfer_mode);
|
||||
|
||||
if (has_all_peers) {
|
||||
for (const int P : targets) {
|
||||
multiplayer->send_command(P, packet_cache.ptr(), ofs);
|
||||
}
|
||||
} else {
|
||||
// Unreachable because the node ID is never compressed if the peers doesn't know it.
|
||||
CRASH_COND(node_id_compression != NETWORK_NODE_ID_COMPRESSION_32);
|
||||
|
||||
// Not all verified path, so send one by one.
|
||||
|
||||
// Append path at the end, since we will need it for some packets.
|
||||
CharString pname = String(multiplayer->get_root_path().rel_path_to(p_node->get_path())).utf8();
|
||||
int path_len = encode_cstring(pname.get_data(), nullptr);
|
||||
MAKE_ROOM(ofs + path_len);
|
||||
encode_cstring(pname.get_data(), &(packet_cache.write[ofs]));
|
||||
|
||||
// Not all verified path, so check which needs the longer packet.
|
||||
for (const int P : targets) {
|
||||
bool confirmed = multiplayer_cache->is_cache_confirmed(p_node, P);
|
||||
if (confirmed) {
|
||||
// This one confirmed path, so use id.
|
||||
encode_uint32(psc_id, &(packet_cache.write[1]));
|
||||
multiplayer->send_command(P, packet_cache.ptr(), ofs);
|
||||
} else {
|
||||
// This one did not confirm path yet, so use entire path (sorry!).
|
||||
encode_uint32(0x80000000 | ofs, &(packet_cache.write[1])); // Offset to path and flag.
|
||||
multiplayer->send_command(P, packet_cache.ptr(), ofs + path_len);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Error SceneRPCInterface::rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount) {
|
||||
Ref<MultiplayerPeer> peer = multiplayer->get_multiplayer_peer();
|
||||
ERR_FAIL_COND_V_MSG(peer.is_null(), ERR_UNCONFIGURED, "Trying to call an RPC while no multiplayer peer is active.");
|
||||
Node *node = Object::cast_to<Node>(p_obj);
|
||||
ERR_FAIL_COND_V_MSG(!node || !node->is_inside_tree(), ERR_INVALID_PARAMETER, "The object must be a valid Node inside the SceneTree");
|
||||
ERR_FAIL_COND_V_MSG(peer->get_connection_status() != MultiplayerPeer::CONNECTION_CONNECTED, ERR_CONNECTION_ERROR, "Trying to call an RPC via a multiplayer peer which is not connected.");
|
||||
|
||||
int caller_id = multiplayer->get_unique_id();
|
||||
bool call_local_native = false;
|
||||
bool call_local_script = false;
|
||||
const RPCConfigCache &config_cache = _get_node_config(node);
|
||||
uint16_t rpc_id = config_cache.ids.has(p_method) ? config_cache.ids[p_method] : UINT16_MAX;
|
||||
ERR_FAIL_COND_V_MSG(rpc_id == UINT16_MAX, ERR_INVALID_PARAMETER,
|
||||
vformat("Unable to get the RPC configuration for the function \"%s\" at path: \"%s\". This happens when the method is missing or not marked for RPCs in the local script.", p_method, node->get_path()));
|
||||
const RPCConfig &config = config_cache.configs[rpc_id];
|
||||
|
||||
ERR_FAIL_COND_V_MSG(p_peer_id == caller_id && !config.call_local, ERR_INVALID_PARAMETER, "RPC '" + p_method + "' on yourself is not allowed by selected mode.");
|
||||
|
||||
if (p_peer_id == 0 || p_peer_id == caller_id || (p_peer_id < 0 && p_peer_id != -caller_id)) {
|
||||
if (rpc_id & (1 << 15)) {
|
||||
call_local_native = config.call_local;
|
||||
} else {
|
||||
call_local_script = config.call_local;
|
||||
}
|
||||
}
|
||||
|
||||
if (p_peer_id != caller_id) {
|
||||
_send_rpc(node, p_peer_id, rpc_id, config, p_method, p_arg, p_argcount);
|
||||
}
|
||||
|
||||
if (call_local_native) {
|
||||
Callable::CallError ce;
|
||||
|
||||
multiplayer->set_remote_sender_override(multiplayer->get_unique_id());
|
||||
node->callp(p_method, p_arg, p_argcount, ce);
|
||||
multiplayer->set_remote_sender_override(0);
|
||||
|
||||
if (ce.error != Callable::CallError::CALL_OK) {
|
||||
String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);
|
||||
error = "rpc() aborted in local call: - " + error + ".";
|
||||
ERR_PRINT(error);
|
||||
return FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
if (call_local_script) {
|
||||
Callable::CallError ce;
|
||||
ce.error = Callable::CallError::CALL_OK;
|
||||
|
||||
multiplayer->set_remote_sender_override(multiplayer->get_unique_id());
|
||||
node->get_script_instance()->callp(p_method, p_arg, p_argcount, ce);
|
||||
multiplayer->set_remote_sender_override(0);
|
||||
|
||||
if (ce.error != Callable::CallError::CALL_OK) {
|
||||
String error = Variant::get_call_error_text(node, p_method, p_arg, p_argcount, ce);
|
||||
error = "rpc() aborted in script local call: - " + error + ".";
|
||||
ERR_PRINT(error);
|
||||
return FAILED;
|
||||
}
|
||||
}
|
||||
return OK;
|
||||
}
|
111
modules/multiplayer/scene_rpc_interface.h
Normal file
111
modules/multiplayer/scene_rpc_interface.h
Normal file
@@ -0,0 +1,111 @@
|
||||
/**************************************************************************/
|
||||
/* scene_rpc_interface.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "core/object/ref_counted.h"
|
||||
#include "scene/main/multiplayer_api.h"
|
||||
|
||||
class SceneMultiplayer;
|
||||
class SceneCacheInterface;
|
||||
class SceneReplicationInterface;
|
||||
class Node;
|
||||
|
||||
class SceneRPCInterface : public RefCounted {
|
||||
GDCLASS(SceneRPCInterface, RefCounted);
|
||||
|
||||
private:
|
||||
struct RPCConfig {
|
||||
StringName name;
|
||||
MultiplayerAPI::RPCMode rpc_mode = MultiplayerAPI::RPC_MODE_DISABLED;
|
||||
bool call_local = false;
|
||||
MultiplayerPeer::TransferMode transfer_mode = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
|
||||
int channel = 0;
|
||||
|
||||
bool operator==(RPCConfig const &p_other) const {
|
||||
return name == p_other.name;
|
||||
}
|
||||
};
|
||||
|
||||
struct RPCConfigCache {
|
||||
HashMap<uint16_t, RPCConfig> configs;
|
||||
HashMap<StringName, uint16_t> ids;
|
||||
};
|
||||
|
||||
struct SortRPCConfig {
|
||||
StringName::AlphCompare compare;
|
||||
bool operator()(const RPCConfig &p_a, const RPCConfig &p_b) const {
|
||||
return compare(p_a.name, p_b.name);
|
||||
}
|
||||
};
|
||||
|
||||
enum NetworkNodeIdCompression {
|
||||
NETWORK_NODE_ID_COMPRESSION_8 = 0,
|
||||
NETWORK_NODE_ID_COMPRESSION_16,
|
||||
NETWORK_NODE_ID_COMPRESSION_32,
|
||||
};
|
||||
|
||||
enum NetworkNameIdCompression {
|
||||
NETWORK_NAME_ID_COMPRESSION_8 = 0,
|
||||
NETWORK_NAME_ID_COMPRESSION_16,
|
||||
};
|
||||
|
||||
SceneMultiplayer *multiplayer = nullptr;
|
||||
SceneCacheInterface *multiplayer_cache = nullptr;
|
||||
SceneReplicationInterface *multiplayer_replicator = nullptr;
|
||||
|
||||
Vector<uint8_t> packet_cache;
|
||||
|
||||
HashMap<ObjectID, RPCConfigCache> rpc_cache;
|
||||
|
||||
#ifdef DEBUG_ENABLED
|
||||
_FORCE_INLINE_ void _profile_node_data(const String &p_what, ObjectID p_id, int p_size);
|
||||
#endif
|
||||
|
||||
protected:
|
||||
void _process_rpc(Node *p_node, const uint16_t p_rpc_method_id, int p_from, const uint8_t *p_packet, int p_packet_len, int p_offset);
|
||||
|
||||
void _send_rpc(Node *p_from, int p_to, uint16_t p_rpc_id, const RPCConfig &p_config, const StringName &p_name, const Variant **p_arg, int p_argcount);
|
||||
Node *_process_get_node(int p_from, const uint8_t *p_packet, uint32_t p_node_target, int p_packet_len);
|
||||
|
||||
void _parse_rpc_config(const Variant &p_config, bool p_for_node, RPCConfigCache &r_cache);
|
||||
const RPCConfigCache &_get_node_config(const Node *p_node);
|
||||
|
||||
public:
|
||||
Error rpcp(Object *p_obj, int p_peer_id, const StringName &p_method, const Variant **p_arg, int p_argcount);
|
||||
void process_rpc(int p_from, const uint8_t *p_packet, int p_packet_len);
|
||||
String get_rpc_md5(const Object *p_obj);
|
||||
|
||||
SceneRPCInterface(SceneMultiplayer *p_multiplayer, SceneCacheInterface *p_cache, SceneReplicationInterface *p_replicator) {
|
||||
multiplayer = p_multiplayer;
|
||||
multiplayer_cache = p_cache;
|
||||
multiplayer_replicator = p_replicator;
|
||||
}
|
||||
};
|
434
modules/multiplayer/tests/test_multiplayer_spawner.h
Normal file
434
modules/multiplayer/tests/test_multiplayer_spawner.h
Normal file
@@ -0,0 +1,434 @@
|
||||
/**************************************************************************/
|
||||
/* test_multiplayer_spawner.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "tests/test_macros.h"
|
||||
#include "tests/test_utils.h"
|
||||
|
||||
#include "../multiplayer_spawner.h"
|
||||
|
||||
namespace TestMultiplayerSpawner {
|
||||
class Wasp : public Node {
|
||||
GDCLASS(Wasp, Node);
|
||||
|
||||
int _size = 0;
|
||||
|
||||
public:
|
||||
int get_size() const {
|
||||
return _size;
|
||||
}
|
||||
void set_size(int p_size) {
|
||||
_size = p_size;
|
||||
}
|
||||
|
||||
Wasp() {
|
||||
set_name("Wasp");
|
||||
set_scene_file_path("wasp.tscn");
|
||||
}
|
||||
};
|
||||
|
||||
class SpawnWasps : public Object {
|
||||
GDCLASS(SpawnWasps, Object);
|
||||
|
||||
protected:
|
||||
static void _bind_methods() {
|
||||
ClassDB::bind_method(D_METHOD("wasp", "size"), &SpawnWasps::create_wasps);
|
||||
{
|
||||
MethodInfo mi;
|
||||
mi.name = "wasp_error";
|
||||
mi.arguments.push_back(PropertyInfo(Variant::INT, "size"));
|
||||
|
||||
ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "wasp_error", &SpawnWasps::create_wasps_error, mi, varray(), false);
|
||||
}
|
||||
ClassDB::bind_method(D_METHOD("echo", "size"), &SpawnWasps::echo_size);
|
||||
}
|
||||
|
||||
public:
|
||||
Wasp *create_wasps(int p_size) {
|
||||
Wasp *wasp = memnew(Wasp);
|
||||
wasp->set_size(p_size);
|
||||
return wasp;
|
||||
}
|
||||
|
||||
Wasp *create_wasps_error(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
|
||||
r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
int echo_size(int p_size) {
|
||||
return p_size;
|
||||
}
|
||||
};
|
||||
|
||||
TEST_CASE("[Multiplayer][MultiplayerSpawner] Defaults") {
|
||||
MultiplayerSpawner *multiplayer_spawner = memnew(MultiplayerSpawner);
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_configuration_warnings().size(), 1);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), nullptr);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene_count(), 0);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_path(), NodePath());
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_limit(), 0);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_function(), Callable());
|
||||
|
||||
memdelete(multiplayer_spawner);
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][MultiplayerSpawner][SceneTree] Spawn Path warning") {
|
||||
MultiplayerSpawner *multiplayer_spawner = memnew(MultiplayerSpawner);
|
||||
SceneTree::get_singleton()->get_root()->add_child(multiplayer_spawner);
|
||||
|
||||
// If there is no spawn path, there should be a warning.
|
||||
PackedStringArray warning_messages = multiplayer_spawner->get_configuration_warnings();
|
||||
REQUIRE_EQ(warning_messages.size(), 1);
|
||||
CHECK_MESSAGE(warning_messages[0].contains("\"Spawn Path\""), "Invalid configuration warning");
|
||||
|
||||
// If there is a spawn path, but it doesn't exist a node on it, there should be a warning.
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Foo"));
|
||||
warning_messages = multiplayer_spawner->get_configuration_warnings();
|
||||
REQUIRE_EQ(warning_messages.size(), 1);
|
||||
CHECK_MESSAGE(warning_messages[0].contains("\"Spawn Path\""), "Invalid configuration warning");
|
||||
|
||||
// If there is a spawn path and a node on it, shouldn't be a warning.
|
||||
Node *foo = memnew(Node);
|
||||
foo->set_name("Foo");
|
||||
SceneTree::get_singleton()->get_root()->add_child(foo);
|
||||
warning_messages = multiplayer_spawner->get_configuration_warnings();
|
||||
CHECK_EQ(warning_messages.size(), 0);
|
||||
|
||||
memdelete(foo);
|
||||
memdelete(multiplayer_spawner);
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][MultiplayerSpawner][SceneTree] Spawn node") {
|
||||
MultiplayerSpawner *multiplayer_spawner = memnew(MultiplayerSpawner);
|
||||
SceneTree::get_singleton()->get_root()->add_child(multiplayer_spawner);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), nullptr);
|
||||
|
||||
Node *foo = memnew(Node);
|
||||
foo->set_name("Foo");
|
||||
SceneTree::get_singleton()->get_root()->add_child(foo);
|
||||
|
||||
SUBCASE("nullptr if spawn path doesn't exists") {
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/NotExists"));
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), nullptr);
|
||||
}
|
||||
|
||||
SUBCASE("Get it after setting spawn path with no signal connections") {
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Foo"));
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), foo);
|
||||
CHECK_FALSE(foo->has_connections("child_entered_tree"));
|
||||
}
|
||||
|
||||
SUBCASE("Get it after setting spawn path with signal connections") {
|
||||
multiplayer_spawner->add_spawnable_scene("scene.tscn");
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Foo"));
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), foo);
|
||||
CHECK(foo->has_connections("child_entered_tree"));
|
||||
}
|
||||
|
||||
SUBCASE("Set a new one should disconnect signals from the old one") {
|
||||
multiplayer_spawner->add_spawnable_scene("scene.tscn");
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Foo"));
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), foo);
|
||||
CHECK(foo->has_connections("child_entered_tree"));
|
||||
|
||||
Node *bar = memnew(Node);
|
||||
bar->set_name("Bar");
|
||||
SceneTree::get_singleton()->get_root()->add_child(bar);
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Bar"));
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), bar);
|
||||
CHECK(bar->has_connections("child_entered_tree"));
|
||||
CHECK_FALSE(foo->has_connections("child_entered_tree"));
|
||||
|
||||
memdelete(bar);
|
||||
}
|
||||
|
||||
memdelete(foo);
|
||||
memdelete(multiplayer_spawner);
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][MultiplayerSpawner][SceneTree] Spawnable scene") {
|
||||
MultiplayerSpawner *multiplayer_spawner = memnew(MultiplayerSpawner);
|
||||
SceneTree::get_singleton()->get_root()->add_child(multiplayer_spawner);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene_count(), 0);
|
||||
|
||||
SUBCASE("Add one") {
|
||||
multiplayer_spawner->add_spawnable_scene("scene.tscn");
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene_count(), 1);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene(0), "scene.tscn");
|
||||
}
|
||||
|
||||
SUBCASE("Add one and if there is a valid spawn path add a connection to it") {
|
||||
Node *foo = memnew(Node);
|
||||
foo->set_name("Foo");
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Foo"));
|
||||
CHECK_FALSE(foo->has_connections("child_entered_tree"));
|
||||
|
||||
// Adding now foo to the tree to avoid set_spawn_path() making the connection.
|
||||
SceneTree::get_singleton()->get_root()->add_child(foo);
|
||||
multiplayer_spawner->notification(Node::NOTIFICATION_POST_ENTER_TREE);
|
||||
CHECK_FALSE(foo->has_connections("child_entered_tree"));
|
||||
multiplayer_spawner->add_spawnable_scene("scene.tscn");
|
||||
CHECK(foo->has_connections("child_entered_tree"));
|
||||
|
||||
memdelete(foo);
|
||||
}
|
||||
|
||||
SUBCASE("Add multiple") {
|
||||
multiplayer_spawner->add_spawnable_scene("scene.tscn");
|
||||
multiplayer_spawner->add_spawnable_scene("other_scene.tscn");
|
||||
multiplayer_spawner->add_spawnable_scene("yet_another_scene.tscn");
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene_count(), 3);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene(0), "scene.tscn");
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene(1), "other_scene.tscn");
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene(2), "yet_another_scene.tscn");
|
||||
}
|
||||
|
||||
SUBCASE("Clear") {
|
||||
Node *foo = memnew(Node);
|
||||
foo->set_name("Foo");
|
||||
SceneTree::get_singleton()->get_root()->add_child(foo);
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Foo"));
|
||||
|
||||
multiplayer_spawner->add_spawnable_scene("scene.tscn");
|
||||
multiplayer_spawner->add_spawnable_scene("other_scene.tscn");
|
||||
multiplayer_spawner->add_spawnable_scene("yet_another_scene.tscn");
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene_count(), 3);
|
||||
CHECK(foo->has_connections("child_entered_tree"));
|
||||
|
||||
multiplayer_spawner->clear_spawnable_scenes();
|
||||
|
||||
CHECK_EQ(multiplayer_spawner->get_spawnable_scene_count(), 0);
|
||||
CHECK_FALSE(foo->has_connections("child_entered_tree"));
|
||||
}
|
||||
|
||||
memdelete(multiplayer_spawner);
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][MultiplayerSpawner][SceneTree] Instantiate custom") {
|
||||
MultiplayerSpawner *multiplayer_spawner = memnew(MultiplayerSpawner);
|
||||
SceneTree::get_singleton()->get_root()->add_child(multiplayer_spawner);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), nullptr);
|
||||
|
||||
Node *nest = memnew(Node);
|
||||
nest->set_name("Nest");
|
||||
SceneTree::get_singleton()->get_root()->add_child(nest);
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Nest"));
|
||||
|
||||
SpawnWasps *spawn_wasps = memnew(SpawnWasps);
|
||||
|
||||
SUBCASE("Instantiates a node properly") {
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
Wasp *wasp = Object::cast_to<Wasp>(multiplayer_spawner->instantiate_custom(Variant(42)));
|
||||
CHECK_NE(wasp, nullptr);
|
||||
CHECK_EQ(wasp->get_name(), "Wasp");
|
||||
CHECK_EQ(wasp->get_size(), 42);
|
||||
|
||||
memdelete(wasp);
|
||||
}
|
||||
|
||||
SUBCASE("Instantiates multiple nodes properly if there is no spawn limit") {
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Wasp *wasp = Object::cast_to<Wasp>(multiplayer_spawner->instantiate_custom(Variant(i)));
|
||||
CHECK_NE(wasp, nullptr);
|
||||
CHECK_EQ(wasp->get_name(), "Wasp");
|
||||
CHECK_EQ(wasp->get_size(), i);
|
||||
nest->add_child(wasp, true);
|
||||
}
|
||||
}
|
||||
|
||||
SUBCASE("Fails if spawn limit is reached") {
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
|
||||
// This one works.
|
||||
Wasp *wasp = Object::cast_to<Wasp>(multiplayer_spawner->instantiate_custom(Variant(42)));
|
||||
CHECK_NE(wasp, nullptr);
|
||||
CHECK_EQ(wasp->get_name(), "Wasp");
|
||||
CHECK_EQ(wasp->get_size(), 42);
|
||||
// Adding to the spawner node to get it tracked.
|
||||
nest->add_child(wasp);
|
||||
|
||||
// This one fails because spawn limit is reached.
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->instantiate_custom(Variant(255)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
|
||||
memdelete(wasp);
|
||||
}
|
||||
|
||||
SUBCASE("Fails if spawn function is not set") {
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->instantiate_custom(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails when spawn function fails") {
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp_error"));
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->instantiate_custom(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails when spawn function not returns a node") {
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "echo"));
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->instantiate_custom(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
memdelete(spawn_wasps);
|
||||
memdelete(nest);
|
||||
memdelete(multiplayer_spawner);
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][MultiplayerSpawner][SceneTree] Spawn") {
|
||||
MultiplayerSpawner *multiplayer_spawner = memnew(MultiplayerSpawner);
|
||||
|
||||
SUBCASE("Fails because is not inside tree") {
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->spawn(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SceneTree::get_singleton()->get_root()->add_child(multiplayer_spawner);
|
||||
CHECK_EQ(multiplayer_spawner->get_spawn_node(), nullptr);
|
||||
|
||||
Node *nest = memnew(Node);
|
||||
nest->set_name("Nest");
|
||||
SceneTree::get_singleton()->get_root()->add_child(nest);
|
||||
multiplayer_spawner->set_spawn_path(NodePath("/root/Nest"));
|
||||
|
||||
SpawnWasps *spawn_wasps = memnew(SpawnWasps);
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
|
||||
SUBCASE("Spawns a node, track it and add it to spawn node") {
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
Wasp *wasp = Object::cast_to<Wasp>(multiplayer_spawner->spawn(Variant(42)));
|
||||
CHECK_NE(wasp, nullptr);
|
||||
CHECK_EQ(wasp->get_name(), "Wasp");
|
||||
CHECK_EQ(wasp->get_size(), 42);
|
||||
CHECK_EQ(wasp->get_parent(), nest);
|
||||
CHECK_EQ(nest->get_child_count(), 1);
|
||||
CHECK_EQ(nest->get_child(0), wasp);
|
||||
}
|
||||
|
||||
SUBCASE("Spawns multiple nodes properly if there is no spawn limit") {
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
Wasp *wasp = Object::cast_to<Wasp>(multiplayer_spawner->spawn(Variant(i)));
|
||||
CHECK_NE(wasp, nullptr);
|
||||
CHECK_EQ(wasp->get_name(), "Wasp" + String((i == 0) ? "" : itos(i + 1)));
|
||||
CHECK_EQ(wasp->get_size(), i);
|
||||
CHECK_EQ(wasp->get_parent(), nest);
|
||||
CHECK_EQ(nest->get_child_count(), i + 1);
|
||||
CHECK_EQ(nest->get_child(i), wasp);
|
||||
}
|
||||
}
|
||||
|
||||
SUBCASE("Fails if spawn limit is reached") {
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
|
||||
// This one works.
|
||||
Wasp *wasp = Object::cast_to<Wasp>(multiplayer_spawner->spawn(Variant(42)));
|
||||
CHECK_NE(wasp, nullptr);
|
||||
CHECK_EQ(wasp->get_name(), "Wasp");
|
||||
CHECK_EQ(wasp->get_size(), 42);
|
||||
CHECK_EQ(wasp->get_parent(), nest);
|
||||
CHECK_EQ(nest->get_child_count(), 1);
|
||||
CHECK_EQ(nest->get_child(0), wasp);
|
||||
|
||||
// This one fails because spawn limit is reached.
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->spawn(Variant(255)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
|
||||
memdelete(wasp);
|
||||
}
|
||||
|
||||
SUBCASE("Fails if spawn function is not set") {
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->spawn(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails if spawn node cannot be found") {
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "wasp"));
|
||||
multiplayer_spawner->set_spawn_path(NodePath(""));
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->spawn(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails when instantiate_custom not returns a node") {
|
||||
multiplayer_spawner->add_spawnable_scene("wasp.tscn");
|
||||
|
||||
multiplayer_spawner->set_spawn_limit(1);
|
||||
multiplayer_spawner->set_spawn_function(Callable(spawn_wasps, "echo"));
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(multiplayer_spawner->spawn(Variant(42)), nullptr);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
memdelete(spawn_wasps);
|
||||
memdelete(nest);
|
||||
memdelete(multiplayer_spawner);
|
||||
}
|
||||
|
||||
} // namespace TestMultiplayerSpawner
|
270
modules/multiplayer/tests/test_scene_multiplayer.h
Normal file
270
modules/multiplayer/tests/test_scene_multiplayer.h
Normal file
@@ -0,0 +1,270 @@
|
||||
/**************************************************************************/
|
||||
/* test_scene_multiplayer.h */
|
||||
/**************************************************************************/
|
||||
/* This file is part of: */
|
||||
/* GODOT ENGINE */
|
||||
/* https://godotengine.org */
|
||||
/**************************************************************************/
|
||||
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
|
||||
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
|
||||
/* */
|
||||
/* Permission is hereby granted, free of charge, to any person obtaining */
|
||||
/* a copy of this software and associated documentation files (the */
|
||||
/* "Software"), to deal in the Software without restriction, including */
|
||||
/* without limitation the rights to use, copy, modify, merge, publish, */
|
||||
/* distribute, sublicense, and/or sell copies of the Software, and to */
|
||||
/* permit persons to whom the Software is furnished to do so, subject to */
|
||||
/* the following conditions: */
|
||||
/* */
|
||||
/* The above copyright notice and this permission notice shall be */
|
||||
/* included in all copies or substantial portions of the Software. */
|
||||
/* */
|
||||
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
|
||||
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
|
||||
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
|
||||
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
|
||||
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
|
||||
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
|
||||
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
|
||||
/**************************************************************************/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include "tests/test_macros.h"
|
||||
#include "tests/test_utils.h"
|
||||
|
||||
#include "../scene_multiplayer.h"
|
||||
|
||||
namespace TestSceneMultiplayer {
|
||||
TEST_CASE("[Multiplayer][SceneMultiplayer] Defaults") {
|
||||
Ref<SceneMultiplayer> scene_multiplayer;
|
||||
scene_multiplayer.instantiate();
|
||||
|
||||
REQUIRE(scene_multiplayer->has_multiplayer_peer());
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
REQUIRE_MESSAGE(Object::cast_to<OfflineMultiplayerPeer>(multiplayer_peer.ptr()) != nullptr, "By default it must be an OfflineMultiplayerPeer instance.");
|
||||
CHECK_EQ(scene_multiplayer->poll(), Error::OK);
|
||||
CHECK_EQ(scene_multiplayer->get_unique_id(), MultiplayerPeer::TARGET_PEER_SERVER);
|
||||
CHECK_EQ(scene_multiplayer->get_peer_ids(), Vector<int>());
|
||||
CHECK_EQ(scene_multiplayer->get_remote_sender_id(), 0);
|
||||
CHECK_EQ(scene_multiplayer->get_root_path(), NodePath());
|
||||
CHECK(scene_multiplayer->get_connected_peers().is_empty());
|
||||
CHECK_FALSE(scene_multiplayer->is_refusing_new_connections());
|
||||
CHECK_FALSE(scene_multiplayer->is_object_decoding_allowed());
|
||||
CHECK(scene_multiplayer->is_server_relay_enabled());
|
||||
CHECK_EQ(scene_multiplayer->get_max_sync_packet_size(), 1350);
|
||||
CHECK_EQ(scene_multiplayer->get_max_delta_packet_size(), 65535);
|
||||
CHECK(scene_multiplayer->is_server());
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][SceneMultiplayer][SceneTree] SceneTree has a OfflineMultiplayerPeer by default") {
|
||||
Ref<SceneMultiplayer> scene_multiplayer = SceneTree::get_singleton()->get_multiplayer();
|
||||
REQUIRE(scene_multiplayer->has_multiplayer_peer());
|
||||
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
REQUIRE_MESSAGE(Object::cast_to<OfflineMultiplayerPeer>(multiplayer_peer.ptr()) != nullptr, "By default it must be an OfflineMultiplayerPeer instance.");
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][SceneMultiplayer][SceneTree] Object configuration add/remove") {
|
||||
Ref<SceneMultiplayer> scene_multiplayer;
|
||||
scene_multiplayer.instantiate();
|
||||
|
||||
SUBCASE("Returns invalid parameter") {
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_add(nullptr, "ImInvalid"), Error::ERR_INVALID_PARAMETER);
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_remove(nullptr, "ImInvalid"), Error::ERR_INVALID_PARAMETER);
|
||||
|
||||
NodePath foo_path("/Foo");
|
||||
NodePath bar_path("/Bar");
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_add(nullptr, foo_path), Error::OK);
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_remove(nullptr, bar_path), Error::ERR_INVALID_PARAMETER);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Sets root path") {
|
||||
NodePath foo_path("/Foo");
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_add(nullptr, foo_path), Error::OK);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->get_root_path(), foo_path);
|
||||
}
|
||||
|
||||
SUBCASE("Unsets root path") {
|
||||
NodePath foo_path("/Foo");
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_add(nullptr, foo_path), Error::OK);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_remove(nullptr, foo_path), Error::OK);
|
||||
CHECK_EQ(scene_multiplayer->get_root_path(), NodePath());
|
||||
}
|
||||
|
||||
SUBCASE("Add/Remove a MultiplayerSpawner") {
|
||||
Node2D *node = memnew(Node2D);
|
||||
MultiplayerSpawner *spawner = memnew(MultiplayerSpawner);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_add(node, spawner), Error::OK);
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_remove(node, spawner), Error::OK);
|
||||
|
||||
memdelete(spawner);
|
||||
memdelete(node);
|
||||
}
|
||||
|
||||
SUBCASE("Add/Remove a MultiplayerSynchronizer") {
|
||||
Node2D *node = memnew(Node2D);
|
||||
MultiplayerSynchronizer *synchronizer = memnew(MultiplayerSynchronizer);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_add(node, synchronizer), Error::OK);
|
||||
CHECK_EQ(scene_multiplayer->object_configuration_remove(node, synchronizer), Error::OK);
|
||||
|
||||
memdelete(synchronizer);
|
||||
memdelete(node);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][SceneMultiplayer] Root Path") {
|
||||
Ref<SceneMultiplayer> scene_multiplayer;
|
||||
scene_multiplayer.instantiate();
|
||||
|
||||
SUBCASE("Is set") {
|
||||
NodePath foo_path("/Foo");
|
||||
scene_multiplayer->set_root_path(foo_path);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->get_root_path(), foo_path);
|
||||
}
|
||||
|
||||
SUBCASE("Fails when path is empty") {
|
||||
ERR_PRINT_OFF;
|
||||
scene_multiplayer->set_root_path(NodePath());
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails when path is relative") {
|
||||
NodePath foo_path("Foo");
|
||||
ERR_PRINT_OFF;
|
||||
scene_multiplayer->set_root_path(foo_path);
|
||||
ERR_PRINT_ON;
|
||||
|
||||
CHECK_EQ(scene_multiplayer->get_root_path(), NodePath());
|
||||
}
|
||||
}
|
||||
|
||||
// This one could be a dummy callback because the current set of test is not actually testing the full auth flow.
|
||||
static Variant auth_callback(Variant sv, Variant pvav) {
|
||||
return Variant();
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][SceneMultiplayer][SceneTree] Send Authentication") {
|
||||
Ref<SceneMultiplayer> scene_multiplayer;
|
||||
scene_multiplayer.instantiate();
|
||||
SceneTree::get_singleton()->set_multiplayer(scene_multiplayer);
|
||||
scene_multiplayer->set_auth_callback(callable_mp_static(auth_callback));
|
||||
|
||||
SUBCASE("Is properly sent") {
|
||||
SIGNAL_WATCH(scene_multiplayer.ptr(), "peer_authenticating");
|
||||
|
||||
// Adding a peer to MultiplayerPeer.
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
int peer_id = 42;
|
||||
multiplayer_peer->emit_signal(SNAME("peer_connected"), peer_id);
|
||||
SIGNAL_CHECK("peer_authenticating", { { peer_id } });
|
||||
|
||||
CHECK_EQ(scene_multiplayer->send_auth(peer_id, String("It's me").to_ascii_buffer()), Error::OK);
|
||||
|
||||
Vector<int> expected_peer_ids = { peer_id };
|
||||
CHECK_EQ(scene_multiplayer->get_authenticating_peer_ids(), expected_peer_ids);
|
||||
|
||||
SIGNAL_UNWATCH(scene_multiplayer.ptr(), "peer_authenticating");
|
||||
}
|
||||
|
||||
SUBCASE("peer_authentication_failed is emitted when a peer is deleted before authentication is completed") {
|
||||
SIGNAL_WATCH(scene_multiplayer.ptr(), "peer_authentication_failed");
|
||||
|
||||
// Adding a peer to MultiplayerPeer.
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
int peer_id = 42;
|
||||
multiplayer_peer->emit_signal(SNAME("peer_connected"), peer_id);
|
||||
multiplayer_peer->emit_signal(SNAME("peer_disconnected"), peer_id);
|
||||
SIGNAL_CHECK("peer_authentication_failed", { { peer_id } });
|
||||
|
||||
SIGNAL_UNWATCH(scene_multiplayer.ptr(), "peer_authentication_failed");
|
||||
}
|
||||
|
||||
SUBCASE("peer_authentication_failed is emitted when authentication timeout") {
|
||||
SIGNAL_WATCH(scene_multiplayer.ptr(), "peer_authentication_failed");
|
||||
scene_multiplayer->set_auth_timeout(0.01);
|
||||
CHECK_EQ(scene_multiplayer->get_auth_timeout(), 0.01);
|
||||
|
||||
// Adding two peesr to MultiplayerPeer.
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
int first_peer_id = 42;
|
||||
int second_peer_id = 84;
|
||||
multiplayer_peer->emit_signal(SNAME("peer_connected"), first_peer_id);
|
||||
multiplayer_peer->emit_signal(SNAME("peer_connected"), second_peer_id);
|
||||
|
||||
// Let timeout happens.
|
||||
OS::get_singleton()->delay_usec(500000);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->poll(), Error::OK);
|
||||
|
||||
SIGNAL_CHECK("peer_authentication_failed", Array({ { first_peer_id }, { second_peer_id } }));
|
||||
|
||||
SIGNAL_UNWATCH(scene_multiplayer.ptr(), "peer_authentication_failed");
|
||||
}
|
||||
|
||||
SUBCASE("Fails when there is no MultiplayerPeer configured") {
|
||||
scene_multiplayer->set_multiplayer_peer(nullptr);
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(scene_multiplayer->send_auth(42, Vector<uint8_t>()), Error::ERR_UNCONFIGURED);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails when the peer to send the auth is not pending") {
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(scene_multiplayer->send_auth(42, String("It's me").to_ascii_buffer()), Error::ERR_INVALID_PARAMETER);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("[Multiplayer][SceneMultiplayer][SceneTree] Complete Authentication") {
|
||||
Ref<SceneMultiplayer> scene_multiplayer;
|
||||
scene_multiplayer.instantiate();
|
||||
SceneTree::get_singleton()->set_multiplayer(scene_multiplayer);
|
||||
scene_multiplayer->set_auth_callback(callable_mp_static(auth_callback));
|
||||
|
||||
SUBCASE("Is properly completed") {
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
int peer_id = 42;
|
||||
multiplayer_peer->emit_signal(SNAME("peer_connected"), peer_id);
|
||||
CHECK_EQ(scene_multiplayer->send_auth(peer_id, String("It's me").to_ascii_buffer()), Error::OK);
|
||||
|
||||
CHECK_EQ(scene_multiplayer->complete_auth(peer_id), Error::OK);
|
||||
}
|
||||
|
||||
SUBCASE("Fails when there is no MultiplayerPeer configured") {
|
||||
scene_multiplayer->set_multiplayer_peer(nullptr);
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(scene_multiplayer->complete_auth(42), Error::ERR_UNCONFIGURED);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails when the peer to complete the auth is not pending") {
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(scene_multiplayer->complete_auth(42), Error::ERR_INVALID_PARAMETER);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
|
||||
SUBCASE("Fails to send auth or completed for a second time") {
|
||||
Ref<MultiplayerPeer> multiplayer_peer = scene_multiplayer->get_multiplayer_peer();
|
||||
int peer_id = 42;
|
||||
multiplayer_peer->emit_signal(SNAME("peer_connected"), peer_id);
|
||||
CHECK_EQ(scene_multiplayer->send_auth(peer_id, String("It's me").to_ascii_buffer()), Error::OK);
|
||||
CHECK_EQ(scene_multiplayer->complete_auth(peer_id), Error::OK);
|
||||
|
||||
ERR_PRINT_OFF;
|
||||
CHECK_EQ(scene_multiplayer->send_auth(peer_id, String("It's me").to_ascii_buffer()), Error::ERR_FILE_CANT_WRITE);
|
||||
CHECK_EQ(scene_multiplayer->complete_auth(peer_id), Error::ERR_FILE_CANT_WRITE);
|
||||
ERR_PRINT_ON;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace TestSceneMultiplayer
|
Reference in New Issue
Block a user