updates
This commit is contained in:
parent
276d43613d
commit
4298caf5cb
552 changed files with 42990 additions and 776 deletions
868
addons/GD-Sync/Scripts/ConnectionController.gd
Normal file
868
addons/GD-Sync/Scripts/ConnectionController.gd
Normal file
|
|
@ -0,0 +1,868 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var GDSync
|
||||
var request_processor
|
||||
var https_controller
|
||||
var local_server
|
||||
var logger
|
||||
|
||||
const API_VERSION : int = 6
|
||||
const PLUGIN_VERSION : String = "1.0.2"
|
||||
|
||||
const KeyStore = preload("res://addons/GD-Sync/Scripts/KeyStore.gd")
|
||||
|
||||
var _PUBLIC_KEY : String = ""
|
||||
var _PRIVATE_KEY : String = ""
|
||||
var UNIQUE_USERNAMES : bool = false
|
||||
var PROTECTED : bool = true
|
||||
|
||||
var client : PacketPeer = ENetMultiplayerPeer.new()
|
||||
var client_id : int = -1
|
||||
var status : int = ENUMS.CONNECTION_STATUS.DISABLED
|
||||
var host : int = -1
|
||||
var connecting : bool = false
|
||||
var connection_i : int = 0
|
||||
var _connect_generation : int = 0
|
||||
var last_poll : float = 0.0
|
||||
var in_local_lobby : bool = false
|
||||
var attempt_tcp : bool = false
|
||||
var is_web_export : bool = false
|
||||
var web_hub_host : String = ""
|
||||
|
||||
var server_ip : String = ""
|
||||
var reliable_encryptor : AESContext = AESContext.new()
|
||||
var reliable_decryptor : AESContext = AESContext.new()
|
||||
var unreliable_encryptor : AESContext = AESContext.new()
|
||||
var unreliable_decryptor : AESContext = AESContext.new()
|
||||
|
||||
var _session_aes_key : PackedByteArray = PackedByteArray()
|
||||
var _session_crypto_ready : bool = false
|
||||
|
||||
var artificial_latency_ms : int = 0
|
||||
var _unreliable_throttle_ready : bool = false
|
||||
|
||||
const _LB_TIMEOUT_MS : int = 10000
|
||||
const _LB_MAX_ATTEMPTS : int = 3
|
||||
const _UDP_PING_EARLY_MS : int = 400
|
||||
const _UDP_PING_CAP_MS : int = 600
|
||||
const _CONNECT_TIMEOUT_S : float = 4.0
|
||||
const _SWITCH_CONNECT_TIMEOUT_S : float = 8.0
|
||||
|
||||
var load_balancers : PackedStringArray = [
|
||||
"lb1.gd-sync.com",
|
||||
"lb2.gd-sync.com",
|
||||
]
|
||||
|
||||
var web_servers : PackedStringArray = [
|
||||
"ws1.gd-sync.com",
|
||||
"ws2.gd-sync.com",
|
||||
]
|
||||
|
||||
func _ready() -> void:
|
||||
name = "ConnectionController"
|
||||
process_priority = -1000
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
request_processor = GDSync._request_processor
|
||||
https_controller = GDSync._https_controller
|
||||
local_server = GDSync._local_server
|
||||
logger = GDSync._logger
|
||||
is_web_export = OS.has_feature("web")
|
||||
|
||||
var keys : Dictionary = KeyStore.load_keys()
|
||||
_PUBLIC_KEY = keys["PublicKey"]
|
||||
_PRIVATE_KEY = keys["PrivateKey"]
|
||||
|
||||
if ProjectSettings.has_setting("GD-Sync/protectedMode"):
|
||||
PROTECTED = ProjectSettings.get_setting("GD-Sync/protectedMode")
|
||||
if ProjectSettings.has_setting("GD-Sync/uniqueUsername"):
|
||||
UNIQUE_USERNAMES = ProjectSettings.get_setting("GD-Sync/uniqueUsername")
|
||||
|
||||
logger.register_redacted_value(_PUBLIC_KEY)
|
||||
logger.register_redacted_value(_PRIVATE_KEY)
|
||||
|
||||
if _PUBLIC_KEY == "" || _PRIVATE_KEY == "":
|
||||
logger.write_error("No Public or Private key was entered in the GD-Sync settings. Please add one under Project->Tools->GD-Sync. If you are using local multiplayer only, you can ignore this error.")
|
||||
|
||||
func is_active() -> bool:
|
||||
return status >= ENUMS.CONNECTION_STATUS.CONNECTING
|
||||
|
||||
func is_local() -> bool:
|
||||
return status == ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION
|
||||
|
||||
func is_local_check() -> bool:
|
||||
if status == ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION:
|
||||
logger.write_error("Some features are not available when using GD-Sync in local mode.")
|
||||
return true
|
||||
return false
|
||||
|
||||
func valid_connection() -> bool:
|
||||
var own_id : int = GDSync.get_client_id()
|
||||
if own_id < 0:
|
||||
logger.write_error("No valid connection. Please connect using GDSync.start_multiplayer() first")
|
||||
return false
|
||||
return true
|
||||
|
||||
func reset_multiplayer(force_disconnect_signal : bool = false) -> void:
|
||||
var emit_disconnect : bool = force_disconnect_signal or (status > ENUMS.CONNECTION_STATUS.CONNECTED and status != ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION)
|
||||
_connect_generation += 1
|
||||
|
||||
client.close()
|
||||
local_server.reset_multiplayer()
|
||||
_reset_session_crypto()
|
||||
_unreliable_throttle_ready = false
|
||||
|
||||
status = ENUMS.CONNECTION_STATUS.DISABLED
|
||||
client_id = -1
|
||||
host = -1
|
||||
in_local_lobby = false
|
||||
attempt_tcp = false
|
||||
|
||||
if emit_disconnect: GDSync.disconnected.emit()
|
||||
|
||||
func reset_session_keep_socket() -> void:
|
||||
connection_i += 1
|
||||
_reset_session_crypto()
|
||||
client_id = -1
|
||||
host = -1
|
||||
in_local_lobby = false
|
||||
status = ENUMS.CONNECTION_STATUS.CONNECTING
|
||||
logger.write_log("Reset session crypto for web tunnel handshake.")
|
||||
|
||||
func _reset_session_crypto() -> void:
|
||||
reliable_encryptor.finish()
|
||||
reliable_decryptor.finish()
|
||||
unreliable_encryptor.finish()
|
||||
unreliable_decryptor.finish()
|
||||
_session_crypto_ready = false
|
||||
|
||||
func start_multiplayer() -> void:
|
||||
logger.write_log("Starting multiplayer.")
|
||||
if status != ENUMS.CONNECTION_STATUS.DISABLED:
|
||||
logger.write_error("Multiplayer has already been started.")
|
||||
return
|
||||
|
||||
reset_multiplayer()
|
||||
var gen : int = _connect_generation
|
||||
last_poll = Time.get_unix_time_from_system()
|
||||
|
||||
if is_web_export:
|
||||
await _start_web_connect(gen)
|
||||
else:
|
||||
await _start_native_connect(gen)
|
||||
|
||||
func _connect_is_current(gen : int) -> bool:
|
||||
return gen == _connect_generation
|
||||
|
||||
func _fail_connect(gen : int, error : int, message : String) -> void:
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
logger.write_error(message)
|
||||
reset_multiplayer()
|
||||
GDSync.connection_failed.emit(error)
|
||||
|
||||
func _start_native_connect(gen : int) -> void:
|
||||
status = ENUMS.CONNECTION_STATUS.FINDING_LB
|
||||
var lb_result : Dictionary = await _fetch_game_servers(gen)
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
var servers : Array = lb_result.get("servers", [])
|
||||
if servers.is_empty():
|
||||
if lb_result.get("invalid_key", false):
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY,
|
||||
"Load balancer request failed, incorrect public key.")
|
||||
else:
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "No response from load balancers.")
|
||||
return
|
||||
|
||||
status = ENUMS.CONNECTION_STATUS.PINGING_SERVERS
|
||||
var ranked : Array = await _rank_game_servers(servers, gen)
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
if ranked.is_empty():
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "No pings received from any server.")
|
||||
return
|
||||
|
||||
status = ENUMS.CONNECTION_STATUS.CONNECTING
|
||||
var best : String = ranked[0]
|
||||
for server in ranked:
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
client.close()
|
||||
client = ENetMultiplayerPeer.new()
|
||||
if await _try_connect(server, gen, _CONNECT_TIMEOUT_S):
|
||||
return
|
||||
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
logger.write_log("Attempting TCP connection.")
|
||||
attempt_tcp = true
|
||||
client.close()
|
||||
client = WebSocketMultiplayerPeer.new()
|
||||
if await _try_connect(best, gen, _CONNECT_TIMEOUT_S):
|
||||
return
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "Connection timeout, server did not respond.")
|
||||
|
||||
func _start_web_connect(gen : int) -> void:
|
||||
client = WebSocketPeer.new()
|
||||
status = ENUMS.CONNECTION_STATUS.PINGING_SERVERS
|
||||
var lb_state : Dictionary = { "done": false, "invalid_key": false }
|
||||
_resolve_lb_for_web(gen, lb_state)
|
||||
var ranked : Array = await _rank_web_servers(gen)
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
if ranked.is_empty():
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "No reachable web servers.")
|
||||
return
|
||||
|
||||
var lb_wait_budget_ms : int = _LB_TIMEOUT_MS * _LB_MAX_ATTEMPTS
|
||||
var waited_ms : int = 0
|
||||
while !lb_state.done and waited_ms < lb_wait_budget_ms:
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
await get_tree().create_timer(0.05).timeout
|
||||
waited_ms += 50
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
if lb_state.invalid_key:
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY,
|
||||
"Load balancer request failed, incorrect public key.")
|
||||
return
|
||||
|
||||
status = ENUMS.CONNECTION_STATUS.CONNECTING
|
||||
for host in ranked:
|
||||
if !_connect_is_current(gen):
|
||||
return
|
||||
client.close()
|
||||
client = WebSocketPeer.new()
|
||||
web_hub_host = host
|
||||
if await _try_connect("wss://"+host, gen, _CONNECT_TIMEOUT_S):
|
||||
return
|
||||
_fail_connect(gen, ENUMS.CONNECTION_FAILED.TIMEOUT, "Connection timeout, server did not respond.")
|
||||
|
||||
func _resolve_lb_for_web(gen : int, lb_state : Dictionary) -> void:
|
||||
var lb_result : Dictionary = await _fetch_game_servers(gen)
|
||||
if !_connect_is_current(gen):
|
||||
lb_state.done = true
|
||||
return
|
||||
lb_state.invalid_key = lb_result.get("invalid_key", false)
|
||||
lb_state.done = true
|
||||
if https_controller.active_lb.is_empty() and !lb_state.invalid_key:
|
||||
logger.write_error("No load balancer resolved for web HTTPS API.")
|
||||
|
||||
func start_local_multiplayer() -> void:
|
||||
logger.write_log("Starting local multiplayer.")
|
||||
if status != ENUMS.CONNECTION_STATUS.DISABLED: return
|
||||
reset_multiplayer()
|
||||
status = ENUMS.CONNECTION_STATUS.LOCAL_CONNECTION
|
||||
|
||||
var rng : RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
rng.randomize()
|
||||
# Harvest Season patch: targeted calls carry the client id in 30 bits (RequestProcessor
|
||||
# encode_target_client), so a random 32-bit local id was cut off and the call reached nobody.
|
||||
client_id = rng.randi_range(1, 0x3FFFFFFE)
|
||||
logger.write_log("Local client id generated. <"+str(client_id)+">")
|
||||
|
||||
if local_server.start_local_peer():
|
||||
logger.write_log("Local multiplayer started.")
|
||||
GDSync.client_id_changed.emit.call_deferred(client_id)
|
||||
GDSync.connected.emit.call_deferred()
|
||||
else:
|
||||
logger.write_error("Local multiplayer failed to start, port is in use.")
|
||||
reset_multiplayer()
|
||||
GDSync.connection_failed.emit.call_deferred(ENUMS.CONNECTION_FAILED.LOCAL_PORT_ERROR)
|
||||
|
||||
func stop_multiplayer() -> void:
|
||||
logger.write_log("Stopping multiplayer.")
|
||||
reset_multiplayer(true)
|
||||
|
||||
func leave_local_lobby_client() -> void:
|
||||
in_local_lobby = false
|
||||
host = -1
|
||||
if client is MultiplayerPeer:
|
||||
client.close()
|
||||
client = ENetMultiplayerPeer.new()
|
||||
|
||||
func _fetch_game_servers(gen : int) -> Dictionary:
|
||||
var empty : Dictionary = { "servers": [], "invalid_key": false }
|
||||
if load_balancers.is_empty():
|
||||
return empty
|
||||
|
||||
for attempt in _LB_MAX_ATTEMPTS:
|
||||
if !_connect_is_current(gen):
|
||||
return empty
|
||||
if attempt > 0:
|
||||
logger.write_log("Retrying load balancer request. <attempt "+str(attempt + 1)+"/"+str(_LB_MAX_ATTEMPTS)+">")
|
||||
await get_tree().create_timer(0.5).timeout
|
||||
if !_connect_is_current(gen):
|
||||
return empty
|
||||
|
||||
var result : Dictionary = await _fetch_game_servers_once(gen)
|
||||
if !_connect_is_current(gen):
|
||||
return result
|
||||
if result.get("invalid_key", false) or !result.get("servers", []).is_empty():
|
||||
return result
|
||||
|
||||
return empty
|
||||
|
||||
func _fetch_game_servers_once(gen : int) -> Dictionary:
|
||||
var result : Dictionary = { "servers": [], "invalid_key": false }
|
||||
var lbs : Array = load_balancers.duplicate()
|
||||
lbs.shuffle()
|
||||
if lbs.is_empty():
|
||||
return result
|
||||
|
||||
logger.write_log("Requesting servers from load balancers.")
|
||||
var winner : Dictionary = { "taken": false }
|
||||
var finished : int = 0
|
||||
var inflight : Array = []
|
||||
|
||||
for address in lbs:
|
||||
_query_load_balancer(str(address), gen, result, winner, inflight, func(): finished += 1)
|
||||
|
||||
var waited_ms : int = 0
|
||||
while waited_ms < _LB_TIMEOUT_MS:
|
||||
if !_connect_is_current(gen):
|
||||
break
|
||||
if result.invalid_key or winner.taken:
|
||||
break
|
||||
if finished >= lbs.size():
|
||||
break
|
||||
await get_tree().create_timer(0.05).timeout
|
||||
waited_ms += 50
|
||||
|
||||
_cancel_http_requests(inflight)
|
||||
return result
|
||||
|
||||
func _query_load_balancer(
|
||||
address : String,
|
||||
gen : int,
|
||||
result : Dictionary,
|
||||
winner : Dictionary,
|
||||
inflight : Array,
|
||||
on_done : Callable
|
||||
) -> void:
|
||||
logger.write_log("Requesting servers from "+address)
|
||||
var request : HTTPRequest = HTTPRequest.new()
|
||||
request.timeout = _LB_TIMEOUT_MS / 1000.0
|
||||
add_child(request)
|
||||
inflight.append(request)
|
||||
|
||||
var err : Error = request.request(
|
||||
"https://"+address+"/connect",
|
||||
["Content-Type: text/plain"],
|
||||
HTTPClient.METHOD_POST,
|
||||
_PUBLIC_KEY)
|
||||
if err != OK:
|
||||
logger.write_error("Load balancer request failed to start. <"+address+"><"+str(err)+">")
|
||||
inflight.erase(request)
|
||||
request.queue_free()
|
||||
on_done.call()
|
||||
return
|
||||
|
||||
var completed : Array = await request.request_completed
|
||||
inflight.erase(request)
|
||||
if is_instance_valid(request):
|
||||
request.queue_free()
|
||||
if !_connect_is_current(gen):
|
||||
on_done.call()
|
||||
return
|
||||
|
||||
var response_code : int = completed[1]
|
||||
logger.write_log("Load balancer completed. <"+address+"><"+str(response_code)+">")
|
||||
if response_code == 401:
|
||||
if !winner.taken:
|
||||
result.invalid_key = true
|
||||
on_done.call()
|
||||
return
|
||||
if response_code != 200:
|
||||
logger.write_error("Load balancer request failed. <"+str(response_code)+">")
|
||||
on_done.call()
|
||||
return
|
||||
|
||||
var parsed : Variant = str_to_var(completed[3].get_string_from_ascii())
|
||||
if typeof(parsed) != TYPE_ARRAY or parsed.is_empty():
|
||||
logger.write_error("Load balancer request did not return any servers. <"+address+">")
|
||||
on_done.call()
|
||||
return
|
||||
if winner.taken:
|
||||
on_done.call()
|
||||
return
|
||||
|
||||
winner.taken = true
|
||||
result.servers = parsed
|
||||
https_controller.active_lb = "https://"+address
|
||||
logger.write_log("Received servers decoded. <"+str(parsed)+">")
|
||||
on_done.call()
|
||||
|
||||
func _cancel_http_requests(inflight : Array) -> void:
|
||||
for request in inflight:
|
||||
if request is HTTPRequest and is_instance_valid(request):
|
||||
request.cancel_request()
|
||||
|
||||
func _rank_game_servers(servers : Array, gen : int) -> Array:
|
||||
logger.write_log("Pinging game servers. <"+str(servers)+">")
|
||||
var replies : Dictionary = {}
|
||||
for server in servers:
|
||||
_ping_game_server(str(server), replies, gen)
|
||||
|
||||
var waited_ms : int = 0
|
||||
while waited_ms < _UDP_PING_CAP_MS:
|
||||
if !_connect_is_current(gen):
|
||||
return []
|
||||
if _all_servers_replied(servers, replies):
|
||||
break
|
||||
if waited_ms >= _UDP_PING_EARLY_MS and replies.size() > 0:
|
||||
break
|
||||
await get_tree().create_timer(0.02).timeout
|
||||
waited_ms += 20
|
||||
|
||||
logger.write_log("Finding best server <"+str(replies)+">")
|
||||
if replies.is_empty():
|
||||
return []
|
||||
|
||||
var ranked : Array = []
|
||||
for server in replies:
|
||||
ranked.append({ "server": server, "ping": float(replies[server].total) / replies[server].count })
|
||||
ranked.sort_custom(func(a, b): return a.ping < b.ping)
|
||||
|
||||
var hosts : Array = []
|
||||
for entry in ranked:
|
||||
hosts.append(entry.server)
|
||||
logger.write_log("Game server ping. <"+str(entry.server)+"><"+str(entry.ping)+"ms>")
|
||||
return hosts
|
||||
|
||||
func _all_servers_replied(servers : Array, replies : Dictionary) -> bool:
|
||||
if servers.is_empty():
|
||||
return false
|
||||
for server in servers:
|
||||
if !replies.has(str(server)):
|
||||
return false
|
||||
return true
|
||||
|
||||
func _ping_game_server(server : String, replies : Dictionary, gen : int) -> void:
|
||||
logger.write_log("Pinging game server. <"+server+">")
|
||||
var peer : PacketPeerUDP = PacketPeerUDP.new()
|
||||
peer.connect_to_host(server, 8081)
|
||||
|
||||
var total : int = 0
|
||||
var count : int = 0
|
||||
var sends : int = 0
|
||||
var elapsed_ms : int = 0
|
||||
while _connect_is_current(gen) and status == ENUMS.CONNECTION_STATUS.PINGING_SERVERS and elapsed_ms < _UDP_PING_CAP_MS:
|
||||
if sends < 3 and elapsed_ms >= sends * 50:
|
||||
peer.put_var(Time.get_ticks_msec())
|
||||
sends += 1
|
||||
while peer.get_available_packet_count() > 0:
|
||||
var sent_at : Variant = peer.get_var()
|
||||
if typeof(sent_at) == TYPE_INT:
|
||||
total += Time.get_ticks_msec() - int(sent_at)
|
||||
count += 1
|
||||
logger.write_log("Ping received. <"+server+">")
|
||||
await get_tree().create_timer(0.02).timeout
|
||||
elapsed_ms += 20
|
||||
peer.close()
|
||||
if count > 0 and _connect_is_current(gen):
|
||||
replies[server] = { "total": total, "count": count }
|
||||
|
||||
func connect_to_server(server : String) -> void:
|
||||
logger.write_log("Connecting to server. <"+server+">")
|
||||
_begin_client_connect(server)
|
||||
last_poll = Time.get_unix_time_from_system()
|
||||
connection_i += 1
|
||||
var current_i : int = connection_i
|
||||
var gen : int = _connect_generation
|
||||
if status != ENUMS.CONNECTION_STATUS.LOBBY_SWITCH:
|
||||
status = ENUMS.CONNECTION_STATUS.CONNECTING
|
||||
server_ip = server
|
||||
|
||||
var elapsed : float = 0.0
|
||||
while elapsed < _SWITCH_CONNECT_TIMEOUT_S:
|
||||
if current_i != connection_i or !_connect_is_current(gen):
|
||||
return
|
||||
if status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
|
||||
return
|
||||
if elapsed >= 0.3 and _client_connect_lost():
|
||||
break
|
||||
await get_tree().create_timer(0.05).timeout
|
||||
elapsed += 0.05
|
||||
|
||||
if current_i != connection_i or !_connect_is_current(gen):
|
||||
return
|
||||
if status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
|
||||
return
|
||||
|
||||
logger.write_error("Connection timeout, server did not respond.")
|
||||
if GDSync._server_switch_controller.transport_failed():
|
||||
return
|
||||
GDSync.connection_failed.emit(ENUMS.CONNECTION_FAILED.TIMEOUT)
|
||||
reset_multiplayer()
|
||||
|
||||
func _try_connect(address : String, gen : int, timeout_s : float) -> bool:
|
||||
if !_connect_is_current(gen):
|
||||
return false
|
||||
logger.write_log("Connecting to server. <"+address+">")
|
||||
_begin_client_connect(address)
|
||||
last_poll = Time.get_unix_time_from_system()
|
||||
server_ip = address
|
||||
if status != ENUMS.CONNECTION_STATUS.LOBBY_SWITCH:
|
||||
status = ENUMS.CONNECTION_STATUS.CONNECTING
|
||||
connection_i += 1
|
||||
var current_i : int = connection_i
|
||||
|
||||
var elapsed : float = 0.0
|
||||
while elapsed < timeout_s:
|
||||
if !_connect_is_current(gen) or current_i != connection_i:
|
||||
return false
|
||||
if status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED:
|
||||
return true
|
||||
if elapsed >= 0.3 and _client_connect_lost():
|
||||
return false
|
||||
await get_tree().create_timer(0.05).timeout
|
||||
elapsed += 0.05
|
||||
return _connect_is_current(gen) and current_i == connection_i and status == ENUMS.CONNECTION_STATUS.CONNECTION_SECURED
|
||||
|
||||
func _client_connect_lost() -> bool:
|
||||
if client is MultiplayerPeer:
|
||||
return client.get_connection_status() == MultiplayerPeer.CONNECTION_DISCONNECTED
|
||||
if client is WebSocketPeer:
|
||||
return client.get_ready_state() == WebSocketPeer.STATE_CLOSED
|
||||
return false
|
||||
|
||||
func _begin_client_connect(server : String) -> void:
|
||||
if client is WebSocketPeer:
|
||||
logger.write_log("Connecting using TCP.")
|
||||
client.connect_to_url(server)
|
||||
elif client is WebSocketMultiplayerPeer:
|
||||
logger.write_log("Connecting using TCP multiplayer.")
|
||||
client.create_client(server)
|
||||
else:
|
||||
logger.write_log("Connecting using UDP.")
|
||||
client.create_client(server, 8080)
|
||||
|
||||
func connect_to_local_server(server : String, port : int) -> int:
|
||||
logger.write_log("Connecting to local server. <"+server+":"+str(port)+">")
|
||||
|
||||
client.close()
|
||||
client = ENetMultiplayerPeer.new()
|
||||
return client.create_client(server, port)
|
||||
|
||||
func _rank_web_servers(gen : int) -> Array:
|
||||
logger.write_log("HTTPS pinging web servers. <"+str(web_servers)+">")
|
||||
var server_pings : Dictionary = {}
|
||||
var tasks_done : int = 0
|
||||
var total : int = web_servers.size()
|
||||
|
||||
for host in web_servers:
|
||||
_ping_web_server(host, server_pings, gen, func(): tasks_done += 1)
|
||||
|
||||
var waited_ms : int = 0
|
||||
while tasks_done < total and waited_ms < 4500:
|
||||
if !_connect_is_current(gen):
|
||||
return []
|
||||
await get_tree().create_timer(0.05).timeout
|
||||
waited_ms += 50
|
||||
|
||||
if !_connect_is_current(gen) or server_pings.is_empty():
|
||||
logger.write_error("No HTTPS pings received from web servers.")
|
||||
return []
|
||||
|
||||
var pings : Array = server_pings.keys()
|
||||
pings.sort()
|
||||
var ranked : Array = []
|
||||
for ping in pings:
|
||||
ranked.append(server_pings[ping])
|
||||
logger.write_log("Web server ping. <"+str(server_pings[ping])+"><"+str(ping)+"ms>")
|
||||
logger.write_log("Best web server selected. <"+str(ranked[0])+"><"+str(pings[0])+"ms>")
|
||||
return ranked
|
||||
|
||||
func _ping_web_server(host : String, server_pings : Dictionary, gen : int, on_done : Callable) -> void:
|
||||
var latency_ms : float = await https_controller.ping_https("https://"+host+"/ping", 3.0)
|
||||
if !_connect_is_current(gen):
|
||||
on_done.call()
|
||||
return
|
||||
if latency_ms >= 0.0:
|
||||
var key : float = latency_ms
|
||||
while server_pings.has(key):
|
||||
key += 0.001
|
||||
server_pings[key] = host
|
||||
logger.write_log("Web server ping. <"+host+"><"+str(latency_ms)+"ms>")
|
||||
on_done.call()
|
||||
|
||||
func switch_server(server: String, use_websocket: bool = false) -> void:
|
||||
logger.write_log("Switching server. <"+server+">")
|
||||
status = ENUMS.CONNECTION_STATUS.LOBBY_SWITCH
|
||||
reset_multiplayer()
|
||||
attempt_tcp = false
|
||||
if is_web_export:
|
||||
client = WebSocketPeer.new()
|
||||
var hub := web_hub_host
|
||||
if hub.is_empty():
|
||||
logger.write_error("Web hub host missing during server switch.")
|
||||
connect_to_server("wss://"+server)
|
||||
return
|
||||
logger.write_log("Reconnecting to web hub. <"+hub+">")
|
||||
connect_to_server("wss://"+hub)
|
||||
return
|
||||
client = WebSocketMultiplayerPeer.new() if use_websocket else ENetMultiplayerPeer.new()
|
||||
var destination := server
|
||||
if use_websocket and !destination.begins_with("ws://") and !destination.begins_with("wss://"):
|
||||
destination = "wss://"+destination
|
||||
connect_to_server(destination)
|
||||
|
||||
func set_artificial_latency(latency_ms : int) -> void:
|
||||
artificial_latency_ms = maxi(latency_ms, 0)
|
||||
|
||||
func get_artificial_latency() -> int:
|
||||
return artificial_latency_ms
|
||||
|
||||
func _await_artificial_latency() -> void:
|
||||
if artificial_latency_ms <= 0:
|
||||
return
|
||||
await get_tree().create_timer(artificial_latency_ms / 1000.0).timeout
|
||||
|
||||
func _receive_packet(bytes : PackedByteArray, packet_channel : int) -> void:
|
||||
await _await_artificial_latency()
|
||||
if status < ENUMS.CONNECTION_STATUS.CONNECTING:
|
||||
return
|
||||
request_processor.unpack_packet(bytes, packet_channel)
|
||||
|
||||
func _configure_unreliable_throttle() -> void:
|
||||
if _unreliable_throttle_ready or !(client is ENetMultiplayerPeer):
|
||||
return
|
||||
if client.get_connection_status() != MultiplayerPeer.CONNECTION_CONNECTED:
|
||||
return
|
||||
var enet_peer : ENetPacketPeer = client.get_peer(1)
|
||||
if enet_peer == null:
|
||||
return
|
||||
enet_peer.throttle_configure(5000, 2, 0)
|
||||
_unreliable_throttle_ready = true
|
||||
|
||||
func _send_multiplayer_packet(bytes : PackedByteArray, transfer_mode : int, transfer_channel : int) -> void:
|
||||
await _await_artificial_latency()
|
||||
if !(client is MultiplayerPeer) or client.get_connection_status() != MultiplayerPeer.CONNECTION_CONNECTED:
|
||||
return
|
||||
client.transfer_mode = transfer_mode
|
||||
client.transfer_channel = transfer_channel
|
||||
client.put_packet(bytes)
|
||||
|
||||
func _send_websocket_packet(bytes : PackedByteArray) -> void:
|
||||
await _await_artificial_latency()
|
||||
if !(client is WebSocketPeer) or client.get_ready_state() != WebSocketPeer.STATE_OPEN:
|
||||
return
|
||||
client.send(bytes)
|
||||
|
||||
func _process(delta) -> void:
|
||||
if status >= ENUMS.CONNECTION_STATUS.CONNECTED and !is_local() and !is_web_export:
|
||||
var current_time : float = Time.get_unix_time_from_system()
|
||||
if current_time - last_poll >= 10:
|
||||
logger.write_error("Client did not poll for over 10 seconds, disconnect.")
|
||||
reset_multiplayer()
|
||||
last_poll = current_time
|
||||
|
||||
if client is MultiplayerPeer:
|
||||
match(client.get_connection_status()):
|
||||
MultiplayerPeer.CONNECTION_DISCONNECTED:
|
||||
if is_local():
|
||||
if in_local_lobby:
|
||||
logger.write_log("Local lobby connection lost, leaving lobby.")
|
||||
in_local_lobby = false
|
||||
GDSync.kicked.emit("")
|
||||
GDSync.lobby_leave.call_deferred()
|
||||
elif status >= ENUMS.CONNECTION_STATUS.CONNECTED:
|
||||
logger.write_error("MultiplayerPeer lost its connection.")
|
||||
if GDSync._server_switch_controller.transport_failed():
|
||||
return
|
||||
reset_multiplayer()
|
||||
MultiplayerPeer.CONNECTION_CONNECTING:
|
||||
client.poll()
|
||||
MultiplayerPeer.CONNECTION_CONNECTED:
|
||||
_configure_unreliable_throttle()
|
||||
client.poll()
|
||||
|
||||
while client.get_available_packet_count() > 0:
|
||||
var packet_channel : int = client.get_packet_channel()
|
||||
var bytes : PackedByteArray = client.get_packet()
|
||||
_receive_packet(bytes, packet_channel)
|
||||
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SETUP):
|
||||
_send_multiplayer_packet(
|
||||
request_processor.package_requests(ENUMS.PACKET_CHANNEL.SETUP),
|
||||
MultiplayerPeer.TRANSFER_MODE_RELIABLE,
|
||||
0
|
||||
)
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SERVER):
|
||||
_send_multiplayer_packet(
|
||||
request_processor.package_requests(ENUMS.PACKET_CHANNEL.SERVER),
|
||||
MultiplayerPeer.TRANSFER_MODE_RELIABLE,
|
||||
0
|
||||
)
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.RELIABLE):
|
||||
_send_multiplayer_packet(
|
||||
request_processor.package_requests(ENUMS.PACKET_CHANNEL.RELIABLE),
|
||||
MultiplayerPeer.TRANSFER_MODE_RELIABLE,
|
||||
0
|
||||
)
|
||||
var unreliable_packets : int = 8
|
||||
while unreliable_packets > 0 and request_processor.has_packets(ENUMS.PACKET_CHANNEL.UNRELIABLE):
|
||||
unreliable_packets -= 1
|
||||
_send_multiplayer_packet(
|
||||
request_processor.package_requests(ENUMS.PACKET_CHANNEL.UNRELIABLE),
|
||||
MultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED,
|
||||
1
|
||||
)
|
||||
|
||||
elif client is WebSocketPeer:
|
||||
match(client.get_ready_state()):
|
||||
WebSocketPeer.STATE_CLOSED:
|
||||
if !is_local() or in_local_lobby:
|
||||
if GDSync._server_switch_controller.is_active():
|
||||
logger.write_error("WebSocketPeer lost its connection during server switch.")
|
||||
GDSync._server_switch_controller.transport_failed()
|
||||
elif status >= ENUMS.CONNECTION_STATUS.CONNECTED:
|
||||
logger.write_error("WebSocketPeer lost its connection.")
|
||||
reset_multiplayer()
|
||||
WebSocketPeer.STATE_CLOSING:
|
||||
client.poll()
|
||||
WebSocketPeer.STATE_CONNECTING:
|
||||
client.poll()
|
||||
WebSocketPeer.STATE_OPEN:
|
||||
client.poll()
|
||||
|
||||
while client.get_available_packet_count() > 0:
|
||||
var bytes : PackedByteArray = client.get_packet()
|
||||
_receive_packet(bytes, 0)
|
||||
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SETUP):
|
||||
_send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.SETUP))
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.SERVER):
|
||||
_send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.SERVER))
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.RELIABLE):
|
||||
_send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.RELIABLE))
|
||||
if request_processor.has_packets(ENUMS.PACKET_CHANNEL.UNRELIABLE):
|
||||
_send_websocket_packet(request_processor.package_requests(ENUMS.PACKET_CHANNEL.UNRELIABLE))
|
||||
|
||||
func set_client_id(client_id : int) -> void:
|
||||
logger.write_log("Client id received from server. <"+str(client_id)+">")
|
||||
logger.register_profiler_data("client_id", client_id)
|
||||
self.client_id = client_id
|
||||
GDSync.client_id_changed.emit(client_id)
|
||||
status = ENUMS.CONNECTION_STATUS.CONNECTED
|
||||
request_processor.validate_public_key()
|
||||
|
||||
func set_client_key(client_key: String) -> void:
|
||||
logger.write_log("Client key received from server. <" + client_key + ">")
|
||||
if client_key.is_empty():
|
||||
logger.write_error("Client key was empty or public key invalid.")
|
||||
reset_multiplayer()
|
||||
GDSync.emit_signal("connection_failed", ENUMS.CONNECTION_FAILED.INVALID_PUBLIC_KEY)
|
||||
return
|
||||
|
||||
request_processor.apply_settings()
|
||||
request_processor.secure_connection()
|
||||
|
||||
var key_utf8 : PackedByteArray = _PRIVATE_KEY.to_utf8_buffer()
|
||||
var client_utf8 : PackedByteArray = client_key.to_utf8_buffer()
|
||||
_session_crypto_ready = false
|
||||
unreliable_encryptor.finish()
|
||||
unreliable_decryptor.finish()
|
||||
|
||||
_session_aes_key = _derive_session_aes_key(key_utf8, client_utf8)
|
||||
var iv16 : PackedByteArray = _derive_session_iv(client_utf8)
|
||||
reliable_encryptor.finish()
|
||||
reliable_decryptor.finish()
|
||||
reliable_encryptor.start(AESContext.MODE_CBC_ENCRYPT, _session_aes_key, iv16)
|
||||
reliable_decryptor.start(AESContext.MODE_CBC_DECRYPT, _session_aes_key, iv16)
|
||||
unreliable_encryptor.start(AESContext.MODE_ECB_ENCRYPT, _session_aes_key)
|
||||
unreliable_decryptor.start(AESContext.MODE_ECB_DECRYPT, _session_aes_key)
|
||||
_session_crypto_ready = true
|
||||
|
||||
func is_session_crypto_ready() -> bool:
|
||||
return _session_crypto_ready
|
||||
|
||||
func _derive_session_aes_key(key_utf8 : PackedByteArray, client_key_utf8 : PackedByteArray) -> PackedByteArray:
|
||||
var ctx : HashingContext = HashingContext.new()
|
||||
ctx.start(HashingContext.HASH_SHA256)
|
||||
ctx.update(key_utf8)
|
||||
ctx.update(client_key_utf8)
|
||||
return ctx.finish()
|
||||
|
||||
func _derive_session_iv(client_key_utf8 : PackedByteArray) -> PackedByteArray:
|
||||
var label : PackedByteArray = "gdsync:v3:aes-cbc:iv".to_utf8_buffer()
|
||||
var ctx : HashingContext = HashingContext.new()
|
||||
ctx.start(HashingContext.HASH_SHA256)
|
||||
ctx.update(label)
|
||||
ctx.update(client_key_utf8)
|
||||
var h : PackedByteArray = ctx.finish()
|
||||
return h.slice(0, 16)
|
||||
|
||||
func _pkcs7_pad(blocks : PackedByteArray) -> PackedByteArray:
|
||||
var n : int = 16 - (blocks.size() % 16)
|
||||
if n == 0:
|
||||
n = 16
|
||||
var outb : PackedByteArray = blocks.duplicate()
|
||||
for i in range(n):
|
||||
outb.append(n)
|
||||
return outb
|
||||
|
||||
func _pkcs7_unpad(blocks : PackedByteArray) -> PackedByteArray:
|
||||
if blocks.is_empty() or (blocks.size() % 16) != 0:
|
||||
return PackedByteArray()
|
||||
var n : int = blocks[blocks.size() - 1]
|
||||
if n < 1 or n > 16 or n > blocks.size():
|
||||
return PackedByteArray()
|
||||
for i in range(n):
|
||||
if blocks[blocks.size() - 1 - i] != n:
|
||||
return PackedByteArray()
|
||||
return blocks.slice(0, blocks.size() - n)
|
||||
|
||||
func encrypt_secured_payload(plain : PackedByteArray, reliable_channel : bool) -> PackedByteArray:
|
||||
if !_session_crypto_ready:
|
||||
logger.write_error("encrypt_secured_payload called before session crypto is ready.")
|
||||
return plain
|
||||
var padded : PackedByteArray = _pkcs7_pad(plain)
|
||||
if reliable_channel:
|
||||
return reliable_encryptor.update(padded)
|
||||
return unreliable_encryptor.update(padded)
|
||||
|
||||
func decrypt_secured_payload(cipher : PackedByteArray, reliable_channel : bool) -> PackedByteArray:
|
||||
if !_session_crypto_ready:
|
||||
logger.write_error("decrypt_secured_payload called before session crypto is ready.")
|
||||
return PackedByteArray()
|
||||
if reliable_channel:
|
||||
var dec : PackedByteArray = reliable_decryptor.update(cipher)
|
||||
return _pkcs7_unpad(dec)
|
||||
var dec2 : PackedByteArray = unreliable_decryptor.update(cipher)
|
||||
return _pkcs7_unpad(dec2)
|
||||
|
||||
func set_host(host : int) -> void:
|
||||
logger.write_log("Host changed. <"+str(host)+">")
|
||||
self.host = host
|
||||
var is_host : bool = host == GDSync.get_client_id()
|
||||
logger.register_profiler_data("is_host", is_host)
|
||||
logger.register_profiler_data("host", host)
|
||||
get_parent().emit_signal("host_changed", is_host, host)
|
||||
1
addons/GD-Sync/Scripts/ConnectionController.gd.uid
Normal file
1
addons/GD-Sync/Scripts/ConnectionController.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b1kfyqmb115wg
|
||||
640
addons/GD-Sync/Scripts/DataController.gd
Normal file
640
addons/GD-Sync/Scripts/DataController.gd
Normal file
|
|
@ -0,0 +1,640 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var https_controller
|
||||
var connection_controller
|
||||
var session_controller
|
||||
var GDSync
|
||||
|
||||
var login_email : String
|
||||
var login_token : String
|
||||
var previous_token : String
|
||||
var logged_in : bool = false
|
||||
var safe_quit : bool = false
|
||||
|
||||
var status_ping_timer : float = 0.0
|
||||
|
||||
func _ready() -> void:
|
||||
name = "DataController"
|
||||
GDSync = get_node("/root/GDSync")
|
||||
https_controller = GDSync._https_controller
|
||||
connection_controller = GDSync._connection_controller
|
||||
session_controller = GDSync._session_controller
|
||||
|
||||
if !DirAccess.dir_exists_absolute("user://GD-Sync"):
|
||||
DirAccess.make_dir_absolute("user://GD-Sync")
|
||||
|
||||
load_config()
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if logged_in:
|
||||
status_ping_timer -= delta
|
||||
|
||||
if status_ping_timer <= 0.0:
|
||||
status_ping_timer = 300
|
||||
set_friend_status()
|
||||
|
||||
func _notification(what : int) -> void:
|
||||
if what == NOTIFICATION_WM_CLOSE_REQUEST:
|
||||
quit()
|
||||
|
||||
func quit() -> void:
|
||||
if logged_in:
|
||||
GDSync.lobby_leave()
|
||||
await set_friend_status()
|
||||
|
||||
safe_quit = true
|
||||
save_config()
|
||||
get_tree().quit()
|
||||
|
||||
func log_in(username : String = "") -> void:
|
||||
logged_in = true
|
||||
safe_quit = false
|
||||
get_tree().set_auto_accept_quit(false)
|
||||
GDSync.account_logged_in.emit.call_deferred(username)
|
||||
|
||||
func load_config() -> void:
|
||||
var dir = DirAccess.open("user://")
|
||||
if !dir.file_exists("user://GD-Sync/DataController.conf"): return
|
||||
|
||||
var file = FileAccess.open_encrypted_with_pass("user://GD-Sync/DataController.conf", FileAccess.READ, connection_controller._PRIVATE_KEY)
|
||||
if file == null: return
|
||||
var data : Dictionary = bytes_to_var(file.get_buffer(file.get_length()))
|
||||
file.close()
|
||||
|
||||
if data.has("LoginEmail"): login_email = data["LoginEmail"]
|
||||
if data.has("LoginToken"): previous_token = data["LoginToken"]
|
||||
|
||||
safe_quit = true
|
||||
if data.has("SafeQuit"):
|
||||
if !data["SafeQuit"]:
|
||||
push_error("GD-Sync did not close correctly. Please use GD-Sync.quit() instead of get_tree().quit().")
|
||||
|
||||
save_config()
|
||||
|
||||
func save_config() -> void:
|
||||
var file = FileAccess.open_encrypted_with_pass("user://GD-Sync/DataController.conf", FileAccess.WRITE, connection_controller._PRIVATE_KEY)
|
||||
file.store_buffer(var_to_bytes({
|
||||
"LoginEmail" : login_email,
|
||||
"LoginToken" : login_token,
|
||||
"SafeQuit" : safe_quit
|
||||
}))
|
||||
file.close()
|
||||
|
||||
func set_friend_status() -> int:
|
||||
if !logged_in: return 0
|
||||
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"setfriendstatus",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Data" :
|
||||
{
|
||||
"LobbyName" : session_controller.lobby_name,
|
||||
"HasPassword" : session_controller.lobby_password != ""
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func create_account(email : String, username : String, password : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"createaccount",
|
||||
{
|
||||
"Email" : email,
|
||||
"Username" : username,
|
||||
"Password" : password
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func delete_account(email : String, password : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"deleteaccount",
|
||||
{
|
||||
"Email" : email,
|
||||
"Password" : password
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func verify_account(email : String, code : String, valid_time : float) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"verifyaccount",
|
||||
{
|
||||
"Email" : email,
|
||||
"Code" : code,
|
||||
"ValidTime" : valid_time
|
||||
}
|
||||
)
|
||||
|
||||
login_email = email
|
||||
|
||||
if result["Code"] == ENUMS.ACCOUNT_VERIFICATION_RESPONSE_CODE.SUCCESS:
|
||||
login_token = result["Result"]
|
||||
save_config()
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func login(email : String, password : String, valid_time : float) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"login",
|
||||
{
|
||||
"Email" : email,
|
||||
"Password" : password,
|
||||
"ValidTime" : valid_time
|
||||
}
|
||||
)
|
||||
|
||||
login_email = email
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"]
|
||||
}
|
||||
|
||||
if result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.SUCCESS:
|
||||
login_token = result["Result"]
|
||||
log_in(result["Username"])
|
||||
save_config()
|
||||
GDSync.player_set_username(result["Username"])
|
||||
elif result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.BANNED:
|
||||
var ban_time : float = result["BanTime"]
|
||||
if ban_time-Time.get_unix_time_from_system() >= 86400000:
|
||||
ban_time = -1
|
||||
data["BanTime"] = ban_time
|
||||
|
||||
return data
|
||||
|
||||
func login_from_session(valid_time : int) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"loginfromsession",
|
||||
{
|
||||
"Email" : login_email,
|
||||
"Token" : previous_token,
|
||||
"ValidTime" : valid_time
|
||||
}
|
||||
)
|
||||
|
||||
if result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.SUCCESS:
|
||||
login_token = result["Result"]
|
||||
log_in(result["Username"])
|
||||
GDSync.player_set_username(result["Username"])
|
||||
else:
|
||||
login_token = ""
|
||||
save_config()
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func resend_verification_code(email : String, password : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"resendverificationcode",
|
||||
{
|
||||
"Email" : email,
|
||||
"Password" : password
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func is_verified(username : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"isverified",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Username" : username
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else false
|
||||
}
|
||||
return data
|
||||
|
||||
func logout() -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"logout",
|
||||
{
|
||||
"Email" : login_email,
|
||||
"Token" : login_token
|
||||
}
|
||||
)
|
||||
|
||||
var was_logged_in : bool = logged_in
|
||||
login_token = ""
|
||||
login_email = ""
|
||||
logged_in = false
|
||||
save_config()
|
||||
|
||||
if was_logged_in:
|
||||
GDSync.account_logged_out.emit.call_deferred()
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func change_username(new_username : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"changeusername",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Username" : new_username
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func change_password(email : String, password : String, new_password : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"changepassword",
|
||||
{
|
||||
"Email" : email,
|
||||
"Password" : password,
|
||||
"NewPassword" : new_password
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func request_password_reset(email : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"requestpasswordreset",
|
||||
{
|
||||
"Email" : email
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func reset_password(email : String, reset_code : String, new_password : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"resetpassword",
|
||||
{
|
||||
"Email" : email,
|
||||
"ResetCode" : reset_code,
|
||||
"NewPassword" : new_password
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func set_player_document(path : String, data : Dictionary, externally_visible : bool) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"setplayerdocument",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Path" : path,
|
||||
"Data" : data,
|
||||
"ExternallyVisible" : externally_visible
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func set_external_visible(path : String, externally_visible : bool) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"setexternalvisible",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Path" : path,
|
||||
"ExternallyVisible" : externally_visible
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func get_player_document(path : String, external_username : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"getplayerdocument",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Path" : path,
|
||||
"ExternalUsername" : external_username
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else {}
|
||||
}
|
||||
return data
|
||||
|
||||
func browse_player_collection(path : String, external_username : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"browseplayercollection",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Path" : path,
|
||||
"ExternalUsername" : external_username
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 and result["Result"] != null else []
|
||||
}
|
||||
return data
|
||||
|
||||
func has_player_document(path : String, external_username : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"hasplayerdocument",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Path" : path,
|
||||
"ExternalUsername" : external_username
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else false
|
||||
}
|
||||
return data
|
||||
|
||||
func delete_player_document(path : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"deleteplayerdocument",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Path" : path
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func report_user(user : String, report : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"createreport",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Against" : user,
|
||||
"Report" : report
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func has_leaderboard(leaderboard : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"hasleaderboard",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Leaderboard" : leaderboard
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else false
|
||||
}
|
||||
return data
|
||||
|
||||
func get_leaderboards() -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"getleaderboardstoken",
|
||||
{
|
||||
"Token" : login_token
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else []
|
||||
}
|
||||
return data
|
||||
|
||||
func browse_leaderboard(leaderboard : String, page_size : int, page : int) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"browseleaderboardtoken",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Leaderboard" : leaderboard,
|
||||
"Page" : page,
|
||||
"PageSize" : page_size
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"FinalPage" : result["FinalPage"] if result.has("FinalPage") else 0,
|
||||
"Result" : result["Result"] if result.has("Result") else []
|
||||
}
|
||||
return data
|
||||
|
||||
func get_leaderboard_score(leaderboard : String, username : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"getleaderboardscore",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Leaderboard" : leaderboard,
|
||||
"Username" : username
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else {"Rank" : -1, "Score" : 0, "Data" : {}}
|
||||
}
|
||||
return data
|
||||
|
||||
func submit_score(leaderboard : String, score : int, data : Dictionary) -> int:
|
||||
if var_to_bytes(data).size() > 2048:
|
||||
return ENUMS.LEADERBOARD_SUBMIT_SCORE_RESPONSE_CODE.DATA_TOO_LAGE
|
||||
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"submitscore",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Leaderboard" : leaderboard,
|
||||
"Score" : score,
|
||||
"Data" : data
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func delete_score(leaderboard : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"deletescore",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Leaderboard" : leaderboard
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func send_friend_request(friend : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"sendfriendrequest",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Friend" : friend
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func get_friend_status(friend : String) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"getfriendstatus",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Friend" : friend
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else {}
|
||||
}
|
||||
return data
|
||||
|
||||
func get_friends() -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"getfriends",
|
||||
{
|
||||
"Token" : login_token
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else 0
|
||||
}
|
||||
return data
|
||||
|
||||
func accept_friend_request(friend : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"acceptfriendrequest",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Friend" : friend
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func remove_friend(friend : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"removefriend",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Friend" : friend
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func invite_friend_to_lobby(friend : String) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"invitefriendtolobby",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"Friend" : friend,
|
||||
"Data" : {
|
||||
"LobbyName" : session_controller.lobby_name,
|
||||
"Password" : session_controller.lobby_password
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func get_lobby_invitations() -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"getlobbyinvitations",
|
||||
{
|
||||
"Token" : login_token
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"],
|
||||
"Result" : result["Result"] if result.size() > 1 else []
|
||||
}
|
||||
return data
|
||||
|
||||
func link_steam_account(auth_ticket : PackedByteArray, app_id : int) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"linksteamaccount",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"AuthTicket" : auth_ticket,
|
||||
"AppID" : app_id
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func unlink_steam_account() -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"unlinksteamaccount",
|
||||
{
|
||||
"Token" : login_token
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
|
||||
func steam_login(auth_ticket : PackedByteArray, app_id : int, valid_time : float) -> Dictionary:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"steamlogin",
|
||||
{
|
||||
"AuthTicket" : auth_ticket,
|
||||
"AppID" : app_id,
|
||||
"ValidTime" : valid_time
|
||||
}
|
||||
)
|
||||
|
||||
var data : Dictionary = {
|
||||
"Code" : result["Code"]
|
||||
}
|
||||
|
||||
if result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.SUCCESS:
|
||||
login_token = result["Result"]
|
||||
log_in(result["Username"])
|
||||
save_config()
|
||||
GDSync.player_set_username(result["Username"])
|
||||
elif result["Code"] == ENUMS.ACCOUNT_LOGIN_RESPONSE_CODE.BANNED:
|
||||
var ban_time : float = result["BanTime"]
|
||||
if ban_time-Time.get_unix_time_from_system() >= 86400000:
|
||||
ban_time = -1
|
||||
data["BanTime"] = ban_time
|
||||
|
||||
return data
|
||||
|
||||
func ban_account(ban_time : float) -> int:
|
||||
var result : Dictionary = await https_controller.perform_https_request(
|
||||
"banaccount",
|
||||
{
|
||||
"Token" : login_token,
|
||||
"BanTime" : ban_time
|
||||
}
|
||||
)
|
||||
|
||||
return result["Code"]
|
||||
1
addons/GD-Sync/Scripts/DataController.gd.uid
Normal file
1
addons/GD-Sync/Scripts/DataController.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bikhttkxiialg
|
||||
720
addons/GD-Sync/Scripts/Enums/Enums.gd
Normal file
720
addons/GD-Sync/Scripts/Enums/Enums.gd
Normal file
|
|
@ -0,0 +1,720 @@
|
|||
class_name ENUMS
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
enum CONNECTION_STATUS
|
||||
{
|
||||
LOBBY_SWITCH = -1,
|
||||
DISABLED,
|
||||
FINDING_LB,
|
||||
PINGING_SERVERS,
|
||||
CONNECTING,
|
||||
CONNECTED,
|
||||
CONNECTION_SECURED,
|
||||
LOCAL_CONNECTION
|
||||
}
|
||||
|
||||
enum PACKET_CHANNEL
|
||||
{
|
||||
SETUP,
|
||||
SERVER,
|
||||
RELIABLE,
|
||||
UNRELIABLE,
|
||||
INTERNAL,
|
||||
}
|
||||
|
||||
enum PACKET_VALUE
|
||||
{
|
||||
PADDING,
|
||||
CLIENT_REQUESTS,
|
||||
SERVER_REQUESTS,
|
||||
INTERNAL_REQUESTS,
|
||||
}
|
||||
|
||||
enum REQUEST_TYPE
|
||||
{
|
||||
VALIDATE_KEY,
|
||||
SECURE_CONNECTION,
|
||||
MESSAGE,
|
||||
SET_VARIABLE,
|
||||
CALL_FUNCTION,
|
||||
SET_VARIABLE_CACHED,
|
||||
CALL_FUNCTION_CACHED,
|
||||
CACHE_NODE_PATH,
|
||||
ERASE_NODE_PATH_CACHE,
|
||||
CACHE_NAME,
|
||||
ERASE_NAME_CACHE,
|
||||
SET_GDSYNC_OWNER,
|
||||
CREATE_LOBBY,
|
||||
JOIN_LOBBY,
|
||||
LEAVE_LOBBY,
|
||||
OPEN_LOBBY,
|
||||
CLOSE_LOBBY,
|
||||
SET_LOBBY_TAG,
|
||||
ERASE_LOBBY_TAG,
|
||||
SET_LOBBY_DATA,
|
||||
ERASE_LOBBY_DATA,
|
||||
SET_LOBBY_VISIBILITY,
|
||||
SET_LOBBY_PLAYER_LIMIT,
|
||||
SET_LOBBY_PASSWORD,
|
||||
GET_PUBLIC_LOBBIES,
|
||||
SET_PLAYER_USERNAME,
|
||||
SET_PLAYER_DATA,
|
||||
ERASE_PLAYER_DATA,
|
||||
SET_CONNECT_TIME,
|
||||
SET_SETTING,
|
||||
SET_CLIENT_ID,
|
||||
KICK_PLAYER,
|
||||
CHANGE_PASSWORD,
|
||||
GET_PUBLIC_LOBBY,
|
||||
CHANGE_LOBBY_NAME,
|
||||
SET_HOST,
|
||||
START_MATCHMAKING,
|
||||
CANCEL_MATCHMAKING,
|
||||
JOIN_LOBBY_WITH_TICKET,
|
||||
COMMIT_SERVER_SWITCH,
|
||||
TUNNEL_TO,
|
||||
}
|
||||
|
||||
enum MESSAGE_TYPE
|
||||
{
|
||||
CRITICAL_ERROR,
|
||||
CLIENT_ID_RECEIVED,
|
||||
CLIENT_KEY_RECEIVED,
|
||||
INVALID_PUBLIC_KEY,
|
||||
SET_NODE_PATH_CACHE,
|
||||
ERASE_NODE_PATH_CACHE,
|
||||
SET_NAME_CACHE,
|
||||
ERASE_NAME_CACHE,
|
||||
SET_GDSYNC_OWNER,
|
||||
HOST_CHANGED,
|
||||
LOBBY_CREATED,
|
||||
LOBBY_CREATION_FAILED,
|
||||
LOBBY_JOINED,
|
||||
SWITCH_SERVER,
|
||||
LOBBY_JOIN_FAILED,
|
||||
LOBBIES_RECEIVED,
|
||||
LOBBY_DATA_RECEIVED,
|
||||
LOBBY_DATA_CHANGED,
|
||||
LOBBY_TAGS_CHANGED,
|
||||
PLAYER_DATA_RECEIVED,
|
||||
PLAYER_DATA_CHANGED,
|
||||
CLIENT_JOINED,
|
||||
CLIENT_LEFT,
|
||||
SET_CONNECT_TIME,
|
||||
SET_SENDER_ID,
|
||||
SET_DATA_USAGE,
|
||||
KICKED,
|
||||
LOBBY_RECEIVED,
|
||||
LOBBY_NAME_CHANGED,
|
||||
LOBBY_NAME_CHANGE_FAILED,
|
||||
MATCHMAKING_STARTED,
|
||||
MATCHMAKING_STATUS_CHANGED,
|
||||
MATCHMAKING_MATCH_FOUND,
|
||||
MATCHMAKING_FAILED,
|
||||
MATCHMAKING_CANCELLED,
|
||||
SWITCH_SERVER_PREPARED,
|
||||
MATCHMAKING_SWITCH_PREPARED,
|
||||
TUNNEL_READY,
|
||||
TUNNEL_FAILED,
|
||||
TUNNEL_LOCAL,
|
||||
}
|
||||
|
||||
enum SETTING
|
||||
{
|
||||
API_VERSION,
|
||||
USE_SENDER_ID,
|
||||
}
|
||||
|
||||
enum EXPOSE_PERMISSION
|
||||
{
|
||||
ANYONE = 0,
|
||||
HOST = 1,
|
||||
CLIENT = 2,
|
||||
}
|
||||
|
||||
enum DATA
|
||||
{
|
||||
REQUEST_TYPE,
|
||||
NAME,
|
||||
VALUE,
|
||||
TARGET_CLIENT = 3,
|
||||
}
|
||||
|
||||
enum LOBBY_DATA
|
||||
{
|
||||
NAME = 1,
|
||||
PASSWORD = 2,
|
||||
PARAMETERS = 1,
|
||||
VISIBILITY = 1,
|
||||
VALUE = 2,
|
||||
}
|
||||
|
||||
enum FUNCTION_DATA
|
||||
{
|
||||
NODE_PATH = 1,
|
||||
NAME = 2,
|
||||
PARAMETERS = 4
|
||||
}
|
||||
|
||||
enum VAR_DATA
|
||||
{
|
||||
NODE_PATH = 1,
|
||||
NAME = 2,
|
||||
VALUE = 4
|
||||
}
|
||||
|
||||
enum MESSAGE_DATA
|
||||
{
|
||||
TYPE = 1,
|
||||
VALUE = 2,
|
||||
ERROR = 3,
|
||||
VALUE2 = 3,
|
||||
}
|
||||
|
||||
enum CRITICAL_ERROR
|
||||
{
|
||||
LOBBY_DATA_FULL,
|
||||
LOBBY_TAGS_FULL,
|
||||
PLAYER_DATA_FULL,
|
||||
REQUEST_TOO_LARGE,
|
||||
OBJECT_IN_REQUEST,
|
||||
}
|
||||
|
||||
enum INTERNAL_MESSAGE
|
||||
{
|
||||
LOBBY_UPDATED,
|
||||
LOBBY_DELETED,
|
||||
REQUEST_LOBBIES,
|
||||
INCREASE_DATA_USAGE,
|
||||
}
|
||||
|
||||
enum CONNECTION_FAILED
|
||||
{
|
||||
INVALID_PUBLIC_KEY,
|
||||
TIMEOUT,
|
||||
LOCAL_PORT_ERROR,
|
||||
}
|
||||
|
||||
enum LOBBY_CREATION_ERROR
|
||||
{
|
||||
LOBBY_ALREADY_EXISTS,
|
||||
NAME_TOO_SHORT,
|
||||
NAME_TOO_LONG,
|
||||
PASSWORD_TOO_LONG,
|
||||
TAGS_TOO_LARGE,
|
||||
DATA_TOO_LARGE,
|
||||
ON_COOLDOWN,
|
||||
LOCAL_PORT_ERROR,
|
||||
}
|
||||
|
||||
enum LOBBY_JOIN_ERROR
|
||||
{
|
||||
LOBBY_DOES_NOT_EXIST,
|
||||
LOBBY_IS_CLOSED,
|
||||
LOBBY_IS_FULL,
|
||||
INCORRECT_PASSWORD,
|
||||
DUPLICATE_USERNAME,
|
||||
}
|
||||
|
||||
enum LOBBY_NAME_CHANGE_ERROR {
|
||||
NAME_ALREADY_EXISTS,
|
||||
NAME_TOO_SHORT,
|
||||
NAME_TOO_LONG,
|
||||
ON_COOLDOWN,
|
||||
}
|
||||
|
||||
enum MATCHMAKING_SEARCH_MODE {
|
||||
PUBLIC_ONLY,
|
||||
PUBLIC_THEN_MATCHMAKE,
|
||||
MATCHMAKE_ONLY,
|
||||
}
|
||||
|
||||
enum MATCHMAKING_STATUS {
|
||||
INACTIVE,
|
||||
SEARCHING_PUBLIC,
|
||||
WAITING_FOR_PLAYERS,
|
||||
MATCH_FOUND,
|
||||
JOINING,
|
||||
}
|
||||
|
||||
enum MATCHMAKING_ERROR {
|
||||
INVALID_REQUEST,
|
||||
ALREADY_IN_LOBBY,
|
||||
NO_MATCH,
|
||||
TIMEOUT,
|
||||
UNSUPPORTED_LOCAL,
|
||||
JOIN_FAILED,
|
||||
}
|
||||
|
||||
enum LOBBY_SWITCH_ERROR {
|
||||
INVALID_RESERVATION,
|
||||
RESERVATION_EXPIRED,
|
||||
DESTINATION_UNREACHABLE,
|
||||
JOIN_FAILED,
|
||||
ROLLBACK_FAILED,
|
||||
}
|
||||
|
||||
enum NODE_REPLICATION_SETTINGS
|
||||
{
|
||||
INSTANTIATOR,
|
||||
SYNC_STARTING_CHANGES,
|
||||
EXCLUDED_PROPERTIES,
|
||||
SCENE,
|
||||
TARGET,
|
||||
ORIGINAL_PROPERTIES,
|
||||
}
|
||||
|
||||
enum NODE_REPLICATION_DATA
|
||||
{
|
||||
ID,
|
||||
CHANGED_PROPERTIES,
|
||||
}
|
||||
|
||||
enum ACCOUNT_CREATION_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
STORAGE_FULL,
|
||||
INVALID_EMAIL,
|
||||
INVALID_USERNAME,
|
||||
EMAIL_ALREADY_EXISTS,
|
||||
USERNAME_ALREADY_EXISTS,
|
||||
USERNAME_TOO_SHORT,
|
||||
USERNAME_TOO_LONG,
|
||||
PASSWORD_TOO_SHORT,
|
||||
PASSWORD_TOO_LONG,
|
||||
}
|
||||
|
||||
enum ACCOUNT_DELETION_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
EMAIL_OR_PASSWORD_INCORRECT,
|
||||
}
|
||||
|
||||
enum ACCOUNT_RESEND_VERIFICATION_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
VERIFICATION_DISABLED,
|
||||
ON_COOLDOWN,
|
||||
ALREADY_VERIFIED,
|
||||
EMAIL_OR_PASSWORD_INCORRECT,
|
||||
BANNED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_VERIFICATION_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
INCORRECT_CODE,
|
||||
CODE_EXPIRED,
|
||||
ALREADY_VERIFIED,
|
||||
BANNED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_IS_VERIFIED_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
USER_DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum ACCOUNT_LOGIN_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
EMAIL_OR_PASSWORD_INCORRECT,
|
||||
NOT_VERIFIED,
|
||||
EXPIRED_SESSION,
|
||||
BANNED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_LOGOUT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
}
|
||||
|
||||
enum ACCOUNT_CHANGE_PASSWORD_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
ON_COOLDOWN,
|
||||
EMAIL_OR_PASSWORD_INCORRECT,
|
||||
NOT_VERIFIED,
|
||||
BANNED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_CHANGE_USERNAME_RESPONSE_CODE
|
||||
{
|
||||
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
ON_COOLDOWN,
|
||||
USERNAME_ALREADY_EXISTS,
|
||||
USERNAME_TOO_SHORT,
|
||||
USERNAME_TOO_LONG,
|
||||
INVALID_USERNAME
|
||||
}
|
||||
|
||||
enum ACCOUNT_RESET_PASSWORD_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
EMAIL_OR_CODE_INCORRECT,
|
||||
CODE_EXPIRED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_REQUEST_PASSWORD_RESET_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
ON_COOLDOWN,
|
||||
EMAIL_DOESNT_EXIST,
|
||||
BANNED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_DOCUMENT_SET_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
}
|
||||
|
||||
enum ACCOUNT_GET_DOCUMENT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum ACCOUNT_BROWSE_COLLECTION_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum ACCOUNT_DOCUMENT_SET_EXTERNAL_VISIBLE_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
DOESNT_EXIST,
|
||||
}
|
||||
|
||||
|
||||
enum ACCOUNT_HAS_DOCUMENT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
}
|
||||
|
||||
enum ACCOUNT_DELETE_DOCUMENT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum ACCOUNT_CREATE_REPORT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
REPORT_TOO_LONG,
|
||||
TOO_MANY_REPORTS,
|
||||
USER_DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum LEADERBOARD_SUBMIT_SCORE_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
LEADERBOARD_DOESNT_EXIST,
|
||||
DATA_TOO_LAGE
|
||||
}
|
||||
|
||||
enum LEADERBOARD_DELETE_SCORE_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
LEADERBOARD_DOESNT_EXIST
|
||||
}
|
||||
|
||||
enum LEADERBOARD_GET_ALL_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
}
|
||||
|
||||
enum LEADERBOARD_EXISTS_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN
|
||||
}
|
||||
|
||||
enum LEADERBOARD_BROWSE_SCORES_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
LEADERBOARD_DOESNT_EXIST
|
||||
}
|
||||
|
||||
enum LEADERBOARD_GET_SCORE_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
LEADERBOARD_DOESNT_EXIST,
|
||||
USER_DOESNT_EXIST
|
||||
}
|
||||
|
||||
enum ACCOUNT_SEND_FRIEND_REQUEST_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
USER_DOESNT_EXIST,
|
||||
FRIEND_ALREADY_ADDED,
|
||||
FRIENDS_LIST_FULL,
|
||||
}
|
||||
|
||||
enum ACCOUNT_ACCEPT_FRIEND_REQUEST_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
FRIEND_NOT_FOUND,
|
||||
}
|
||||
|
||||
enum ACCOUNT_REMOVE_FRIEND_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
FRIEND_DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum ACCOUNT_GET_FRIENDS_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
}
|
||||
|
||||
enum ACCOUNT_GET_FRIEND_STATUS_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
USER_DOESNT_EXIST,
|
||||
}
|
||||
|
||||
enum ACCOUNT_INVITE_FRIEND_TO_LOBBY_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
USER_DOESNT_EXIST,
|
||||
NOT_FRIEND,
|
||||
NOT_IN_LOBBY,
|
||||
}
|
||||
|
||||
enum ACCOUNT_GET_LOBBY_INVITATIONS_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
}
|
||||
|
||||
enum FRIEND_STATUS
|
||||
{
|
||||
NONE,
|
||||
INCOMING_REQUEST,
|
||||
FRIEND,
|
||||
WAITING_FOR_REPLY,
|
||||
}
|
||||
|
||||
enum LINK_STEAM_ACCOUNT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
ALREADY_LINKED,
|
||||
STEAM_ERROR,
|
||||
}
|
||||
|
||||
enum UNLINK_STEAM_ACCOUNT_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STEAM_ERROR,
|
||||
}
|
||||
|
||||
enum STEAM_LOGIN_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
STEAM_ERROR,
|
||||
NOT_LINKED,
|
||||
NOT_VERIFIED,
|
||||
BANNED,
|
||||
}
|
||||
|
||||
enum ACCOUNT_BAN_RESPONSE_CODE
|
||||
{
|
||||
SUCCESS,
|
||||
NO_RESPONSE_FROM_SERVER,
|
||||
DATA_CAP_REACHED,
|
||||
RATE_LIMIT_EXCEEDED,
|
||||
NO_DATABASE,
|
||||
NOT_LOGGED_IN,
|
||||
STORAGE_FULL,
|
||||
}
|
||||
1
addons/GD-Sync/Scripts/Enums/Enums.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Enums/Enums.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://cvm8hol2ndcgr
|
||||
102
addons/GD-Sync/Scripts/HTTPSController.gd
Normal file
102
addons/GD-Sync/Scripts/HTTPSController.gd
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var GDSync
|
||||
var connection_controller
|
||||
var data_controller
|
||||
var logger
|
||||
|
||||
var active_lb : String = ""
|
||||
|
||||
func _ready():
|
||||
GDSync = get_node("/root/GDSync")
|
||||
name = "HTTPSController"
|
||||
connection_controller = GDSync._connection_controller
|
||||
data_controller = GDSync._data_controller
|
||||
logger = GDSync._logger
|
||||
|
||||
func perform_https_request(endpoint : String, message : Dictionary) -> Dictionary:
|
||||
logger.write_log("Making HTTP request. <"+endpoint+"><"+str(message)+">", "[HTTP]")
|
||||
|
||||
if !GDSync.is_active():
|
||||
logger.write_error("Failed HTTP request as the plugin is not active. <"+endpoint+">", "[HTTP]")
|
||||
push_error("You must first start the plugin using GDSync.start_multiplayer() before using any cloudstorage functions.")
|
||||
return {"Code" : 1}
|
||||
|
||||
if active_lb.is_empty():
|
||||
logger.write_error("Failed HTTP request, no load balancer resolved. <"+endpoint+">", "[HTTP]")
|
||||
return {"Code" : 1}
|
||||
|
||||
var request : HTTPRequest = HTTPRequest.new()
|
||||
request.timeout = 20
|
||||
add_child(request)
|
||||
|
||||
message["PublicKey"] = connection_controller._PUBLIC_KEY
|
||||
|
||||
request.request(
|
||||
active_lb+"/"+endpoint,
|
||||
["Content-Type: text/plain"],
|
||||
HTTPClient.METHOD_POST,
|
||||
var_to_str(message)
|
||||
)
|
||||
|
||||
var result = await request.request_completed
|
||||
|
||||
logger.write_log("Completed HTTP request. <"+endpoint+"><"+str(result[1])+">", "[HTTP]")
|
||||
|
||||
if result[1] == 200:
|
||||
var text : String = result[3].get_string_from_ascii()
|
||||
var received_message : Dictionary = str_to_var(text)
|
||||
logger.write_log("Successful HTTP request. <"+endpoint+"><"+text+">", "[HTTP]")
|
||||
return received_message
|
||||
else:
|
||||
logger.write_error("Failed HTTP request. <"+endpoint+"><"+str(result[1])+">", "[HTTP]")
|
||||
return {"Code" : 1 if result[1] != 503 else 3}
|
||||
|
||||
func ping_https(url : String, timeout_seconds : float = 3.0) -> float:
|
||||
logger.write_log("HTTPS ping. <"+url+">", "[HTTP]")
|
||||
var request : HTTPRequest = HTTPRequest.new()
|
||||
request.timeout = timeout_seconds
|
||||
add_child(request)
|
||||
|
||||
var started_ms : int = Time.get_ticks_msec()
|
||||
var error : Error = request.request(url, [], HTTPClient.METHOD_GET)
|
||||
if error != OK:
|
||||
request.queue_free()
|
||||
logger.write_error("HTTPS ping failed to start. <"+url+"><"+str(error)+">", "[HTTP]")
|
||||
return -1.0
|
||||
|
||||
var result = await request.request_completed
|
||||
var elapsed_ms : float = float(Time.get_ticks_msec() - started_ms)
|
||||
request.queue_free()
|
||||
|
||||
var response_code : int = result[1]
|
||||
if response_code <= 0:
|
||||
logger.write_error("HTTPS ping failed. <"+url+"><"+str(response_code)+">", "[HTTP]")
|
||||
return -1.0
|
||||
|
||||
logger.write_log("HTTPS ping complete. <"+url+"><"+str(elapsed_ms)+"ms><"+str(response_code)+">", "[HTTP]")
|
||||
return elapsed_ms
|
||||
1
addons/GD-Sync/Scripts/HTTPSController.gd.uid
Normal file
1
addons/GD-Sync/Scripts/HTTPSController.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://d16jsc5k0bs3j
|
||||
472
addons/GD-Sync/Scripts/InterestManager.gd
Normal file
472
addons/GD-Sync/Scripts/InterestManager.gd
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
extends Node
|
||||
|
||||
# Copyright (c) 2023-present GD-Sync.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source form, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# 2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
# SUCH DAMAGE.
|
||||
|
||||
const DEFAULT_CELL_SIZE : float = 128.0
|
||||
|
||||
var GDSync
|
||||
|
||||
var _viewers : Dictionary = {}
|
||||
var _objects : Dictionary = {}
|
||||
var _object_grid : Dictionary = {}
|
||||
var _viewer_memberships : Dictionary = {}
|
||||
var _recipient_cache : Dictionary = {}
|
||||
var _ambiguous_object_branches : Dictionary = {}
|
||||
|
||||
func _ready() -> void:
|
||||
name = "InterestManager"
|
||||
GDSync.expose_func(_receive_viewer_update)
|
||||
GDSync.expose_func(_remove_viewer)
|
||||
GDSync.expose_func(_receive_object_update)
|
||||
GDSync.expose_func(_remove_object)
|
||||
GDSync.expose_func(_set_object_recipients_remote)
|
||||
GDSync.expose_func(_apply_object_recipient_delta_remote)
|
||||
GDSync.client_joined.connect(_client_joined)
|
||||
GDSync.client_left.connect(_client_left)
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
|
||||
func clear() -> void:
|
||||
_viewers.clear()
|
||||
_objects.clear()
|
||||
_object_grid.clear()
|
||||
_viewer_memberships.clear()
|
||||
_recipient_cache.clear()
|
||||
_ambiguous_object_branches.clear()
|
||||
|
||||
func call_function(callable : Callable, parameters : Array, reliable : bool) -> void:
|
||||
var object : Object = callable.get_object()
|
||||
var interest_object : Node = _find_interest_object(object) if object is Node else null
|
||||
if interest_object == null:
|
||||
GDSync._request_processor.create_function_call_request(callable, parameters, -1, reliable)
|
||||
return
|
||||
|
||||
for client_id in interest_object._get_gdsync_interest_object_recipients():
|
||||
if client_id == GDSync.get_client_id():
|
||||
continue
|
||||
GDSync._request_processor.create_function_call_request(callable, parameters, client_id, reliable)
|
||||
|
||||
func sync_variable(object : Object, variable_name : String, reliable : bool) -> void:
|
||||
var interest_object : Node = _find_interest_object(object) if object is Node else null
|
||||
if interest_object == null:
|
||||
GDSync._request_processor.create_set_var_request(object, variable_name, -1, reliable)
|
||||
return
|
||||
|
||||
for client_id in interest_object._get_gdsync_interest_object_recipients():
|
||||
if client_id == GDSync.get_client_id():
|
||||
continue
|
||||
GDSync._request_processor.create_set_var_request(object, variable_name, client_id, reliable)
|
||||
|
||||
func get_relevant_clients(object : Object, include_self : bool = false) -> Array:
|
||||
var clients : Array
|
||||
var interest_object : Node = _find_interest_object(object) if object is Node else null
|
||||
if interest_object == null:
|
||||
clients = GDSync.lobby_get_all_clients().duplicate()
|
||||
else:
|
||||
clients = interest_object._get_gdsync_interest_object_recipients().duplicate()
|
||||
if !include_self:
|
||||
clients.erase(GDSync.get_client_id())
|
||||
return clients
|
||||
|
||||
func has_interest_object(context : Node) -> bool:
|
||||
return _find_interest_object(context) != null
|
||||
|
||||
func get_interest_object(context : Node) -> Node:
|
||||
return _find_interest_object(context)
|
||||
|
||||
func apply_cached_recipients(interest_object : Node) -> void:
|
||||
var object_path := str(interest_object.get_path())
|
||||
if _recipient_cache.has(object_path):
|
||||
interest_object._set_gdsync_interest_object_recipients(_recipient_cache[object_path])
|
||||
|
||||
func report_viewer(
|
||||
viewer_path : String,
|
||||
client_id : int,
|
||||
position : Vector3,
|
||||
dimension : int,
|
||||
layers : int
|
||||
) -> void:
|
||||
if GDSync.is_host():
|
||||
_receive_viewer_update(viewer_path, client_id, position, dimension, layers)
|
||||
else:
|
||||
GDSync.call_func_on_unreliable(
|
||||
GDSync.get_host(),
|
||||
_receive_viewer_update,
|
||||
viewer_path,
|
||||
client_id,
|
||||
position,
|
||||
dimension,
|
||||
layers
|
||||
)
|
||||
|
||||
func unregister_viewer(viewer_path : String, client_id : int) -> void:
|
||||
if !GDSync.is_active():
|
||||
return
|
||||
if GDSync.is_host():
|
||||
_remove_viewer(viewer_path, client_id)
|
||||
else:
|
||||
GDSync.call_func_on(GDSync.get_host(), _remove_viewer, viewer_path, client_id)
|
||||
|
||||
func report_object(
|
||||
object_path : String,
|
||||
authority_id : int,
|
||||
position : Vector3,
|
||||
dimension : int,
|
||||
visibility_radius : float,
|
||||
exit_margin : float,
|
||||
layers : int,
|
||||
host_receives_state : bool
|
||||
) -> void:
|
||||
if GDSync.is_host():
|
||||
_receive_object_update(
|
||||
object_path,
|
||||
authority_id,
|
||||
position,
|
||||
dimension,
|
||||
visibility_radius,
|
||||
exit_margin,
|
||||
layers,
|
||||
host_receives_state
|
||||
)
|
||||
else:
|
||||
GDSync.call_func_on(
|
||||
GDSync.get_host(),
|
||||
_receive_object_update,
|
||||
object_path,
|
||||
authority_id,
|
||||
position,
|
||||
dimension,
|
||||
visibility_radius,
|
||||
exit_margin,
|
||||
layers,
|
||||
host_receives_state
|
||||
)
|
||||
|
||||
func unregister_object(object_path : String, authority_id : int) -> void:
|
||||
if !GDSync.is_active():
|
||||
return
|
||||
if GDSync.is_host():
|
||||
_remove_object(object_path, authority_id)
|
||||
else:
|
||||
GDSync.call_func_on(GDSync.get_host(), _remove_object, object_path, authority_id)
|
||||
|
||||
func _receive_viewer_update(
|
||||
viewer_path : String,
|
||||
client_id : int,
|
||||
position : Vector3,
|
||||
dimension : int,
|
||||
layers : int
|
||||
) -> void:
|
||||
if !GDSync.is_host():
|
||||
return
|
||||
|
||||
var viewer_key := _viewer_key(viewer_path, client_id)
|
||||
_viewers[viewer_key] = {
|
||||
"client_id": client_id,
|
||||
"position": position,
|
||||
"dimension": dimension,
|
||||
"layers": layers,
|
||||
}
|
||||
_update_viewer_memberships(viewer_key)
|
||||
|
||||
func _remove_viewer(viewer_path : String, client_id : int) -> void:
|
||||
if !GDSync.is_host():
|
||||
return
|
||||
|
||||
var viewer_key := _viewer_key(viewer_path, client_id)
|
||||
var memberships : Dictionary = _viewer_memberships.get(viewer_key, {})
|
||||
_viewers.erase(viewer_key)
|
||||
_viewer_memberships.erase(viewer_key)
|
||||
for object_path in memberships:
|
||||
_refresh_object_recipients(object_path)
|
||||
|
||||
func _receive_object_update(
|
||||
object_path : String,
|
||||
authority_id : int,
|
||||
position : Vector3,
|
||||
dimension : int,
|
||||
visibility_radius : float,
|
||||
exit_margin : float,
|
||||
layers : int,
|
||||
host_receives_state : bool
|
||||
) -> void:
|
||||
if !GDSync.is_host():
|
||||
return
|
||||
|
||||
if _objects.has(object_path):
|
||||
_remove_object_from_grid(object_path)
|
||||
|
||||
var previous_recipients : Array = _objects.get(object_path, {}).get("recipients", [])
|
||||
_objects[object_path] = {
|
||||
"authority_id": authority_id,
|
||||
"position": position,
|
||||
"dimension": dimension,
|
||||
"visibility_radius": maxf(visibility_radius, 0.0),
|
||||
"exit_margin": maxf(exit_margin, 0.0),
|
||||
"layers": layers,
|
||||
"host_receives_state": host_receives_state,
|
||||
"recipients": previous_recipients,
|
||||
"cells": [],
|
||||
}
|
||||
_add_object_to_grid(object_path)
|
||||
|
||||
for viewer_key in _viewers:
|
||||
_update_membership(viewer_key, object_path, false)
|
||||
_refresh_object_recipients(object_path)
|
||||
|
||||
func _remove_object(object_path : String, authority_id : int) -> void:
|
||||
if !GDSync.is_host() or !_objects.has(object_path):
|
||||
return
|
||||
if _objects[object_path]["authority_id"] != authority_id:
|
||||
return
|
||||
|
||||
var previous : Array = _objects[object_path]["recipients"]
|
||||
if !previous.is_empty():
|
||||
_apply_object_recipient_delta_remote(object_path, [], previous)
|
||||
for client_id in GDSync.lobby_get_all_clients():
|
||||
if client_id != GDSync.get_client_id():
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
_apply_object_recipient_delta_remote,
|
||||
object_path,
|
||||
[],
|
||||
previous
|
||||
)
|
||||
_remove_object_from_grid(object_path)
|
||||
_objects.erase(object_path)
|
||||
for memberships in _viewer_memberships.values():
|
||||
memberships.erase(object_path)
|
||||
|
||||
func _update_viewer_memberships(viewer_key : String) -> void:
|
||||
var viewer : Dictionary = _viewers[viewer_key]
|
||||
var candidates : Dictionary = _viewer_memberships.get(viewer_key, {}).duplicate()
|
||||
var cell_key := _cell_key(viewer["position"], viewer["dimension"])
|
||||
for object_path in _object_grid.get(cell_key, {}):
|
||||
candidates[object_path] = true
|
||||
|
||||
for object_path in candidates:
|
||||
_update_membership(viewer_key, object_path)
|
||||
|
||||
func _update_membership(viewer_key : String, object_path : String, publish : bool = true) -> void:
|
||||
if !_viewers.has(viewer_key):
|
||||
return
|
||||
|
||||
var memberships : Dictionary = _viewer_memberships.get_or_add(viewer_key, {})
|
||||
var was_relevant : bool = memberships.has(object_path)
|
||||
if !_objects.has(object_path):
|
||||
memberships.erase(object_path)
|
||||
return
|
||||
|
||||
var viewer : Dictionary = _viewers[viewer_key]
|
||||
var interest_object : Dictionary = _objects[object_path]
|
||||
var relevant := false
|
||||
if (
|
||||
viewer["dimension"] == interest_object["dimension"]
|
||||
and (viewer["layers"] & interest_object["layers"]) != 0
|
||||
):
|
||||
var distance_squared := _distance_squared(
|
||||
viewer["position"],
|
||||
interest_object["position"],
|
||||
interest_object["dimension"]
|
||||
)
|
||||
var threshold : float = interest_object["visibility_radius"]
|
||||
if was_relevant:
|
||||
threshold += interest_object["exit_margin"]
|
||||
relevant = distance_squared <= threshold * threshold
|
||||
|
||||
if relevant == was_relevant:
|
||||
return
|
||||
if relevant:
|
||||
memberships[object_path] = true
|
||||
else:
|
||||
memberships.erase(object_path)
|
||||
if publish:
|
||||
_refresh_object_recipients(object_path)
|
||||
|
||||
func _refresh_object_recipients(object_path : String) -> void:
|
||||
if !_objects.has(object_path):
|
||||
return
|
||||
|
||||
var recipients : Dictionary = {}
|
||||
for viewer_key in _viewer_memberships:
|
||||
if _viewer_memberships[viewer_key].has(object_path) and _viewers.has(viewer_key):
|
||||
recipients[_viewers[viewer_key]["client_id"]] = true
|
||||
|
||||
var interest_object : Dictionary = _objects[object_path]
|
||||
if interest_object["host_receives_state"] and GDSync.get_host() >= 0:
|
||||
recipients[GDSync.get_host()] = true
|
||||
|
||||
var recipient_list : Array[int] = []
|
||||
for client_id in recipients:
|
||||
recipient_list.append(client_id)
|
||||
recipient_list.sort()
|
||||
|
||||
if interest_object["recipients"] == recipient_list:
|
||||
return
|
||||
var previous : Array = interest_object["recipients"]
|
||||
var entered : Array = []
|
||||
var exited : Array = []
|
||||
for client_id in recipient_list:
|
||||
if !previous.has(client_id):
|
||||
entered.append(client_id)
|
||||
for client_id in previous:
|
||||
if !recipient_list.has(client_id):
|
||||
exited.append(client_id)
|
||||
interest_object["recipients"] = recipient_list
|
||||
|
||||
_apply_object_recipient_delta_remote(object_path, entered, exited)
|
||||
for client_id in GDSync.lobby_get_all_clients():
|
||||
if client_id != GDSync.get_client_id():
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
_apply_object_recipient_delta_remote,
|
||||
object_path,
|
||||
entered,
|
||||
exited
|
||||
)
|
||||
|
||||
func _set_object_recipients_remote(object_path : String, recipients : Array) -> void:
|
||||
var updated : Array[int] = []
|
||||
for client_id in recipients:
|
||||
updated.append(int(client_id))
|
||||
_recipient_cache[object_path] = updated
|
||||
var interest_object := get_node_or_null(object_path)
|
||||
if (
|
||||
interest_object != null
|
||||
and interest_object.has_method("_set_gdsync_interest_object_recipients")
|
||||
):
|
||||
interest_object._set_gdsync_interest_object_recipients(updated)
|
||||
|
||||
func _apply_object_recipient_delta_remote(object_path : String, entered : Array, exited : Array) -> void:
|
||||
var updated : Array = _recipient_cache.get(object_path, []).duplicate()
|
||||
for client_id in exited:
|
||||
updated.erase(int(client_id))
|
||||
for client_id in entered:
|
||||
if !updated.has(int(client_id)):
|
||||
updated.append(int(client_id))
|
||||
_recipient_cache[object_path] = updated
|
||||
var interest_object := get_node_or_null(object_path)
|
||||
if (
|
||||
interest_object != null
|
||||
and interest_object.has_method("_set_gdsync_interest_object_recipients")
|
||||
):
|
||||
interest_object._set_gdsync_interest_object_recipients(updated)
|
||||
|
||||
func _add_object_to_grid(object_path : String) -> void:
|
||||
var interest_object : Dictionary = _objects[object_path]
|
||||
var radius : float = interest_object["visibility_radius"] + interest_object["exit_margin"]
|
||||
var min_cell := _cell_coordinates(interest_object["position"] - Vector3.ONE * radius)
|
||||
var max_cell := _cell_coordinates(interest_object["position"] + Vector3.ONE * radius)
|
||||
if interest_object["dimension"] == 2:
|
||||
min_cell.z = 0
|
||||
max_cell.z = 0
|
||||
|
||||
var cells : Array = []
|
||||
for x in range(min_cell.x, max_cell.x + 1):
|
||||
for y in range(min_cell.y, max_cell.y + 1):
|
||||
for z in range(min_cell.z, max_cell.z + 1):
|
||||
var key := "%s:%s:%s:%s" % [interest_object["dimension"], x, y, z]
|
||||
var bucket : Dictionary = _object_grid.get_or_add(key, {})
|
||||
bucket[object_path] = true
|
||||
cells.append(key)
|
||||
interest_object["cells"] = cells
|
||||
|
||||
func _remove_object_from_grid(object_path : String) -> void:
|
||||
for key in _objects[object_path].get("cells", []):
|
||||
if !_object_grid.has(key):
|
||||
continue
|
||||
_object_grid[key].erase(object_path)
|
||||
if _object_grid[key].is_empty():
|
||||
_object_grid.erase(key)
|
||||
|
||||
func _find_interest_object(context : Node) -> Node:
|
||||
var current := context
|
||||
while current != null:
|
||||
if current.has_method("_get_gdsync_interest_object_recipients"):
|
||||
return current if current._is_gdsync_interest_object_enabled() else null
|
||||
var sibling_objects : Array[Node] = []
|
||||
for child in current.get_children():
|
||||
if child.has_method("_get_gdsync_interest_object_recipients"):
|
||||
sibling_objects.append(child)
|
||||
if !sibling_objects.is_empty():
|
||||
if sibling_objects.size() > 1:
|
||||
var branch_id := current.get_instance_id()
|
||||
if !_ambiguous_object_branches.has(branch_id):
|
||||
_ambiguous_object_branches[branch_id] = true
|
||||
push_error(
|
||||
(
|
||||
"GD-Sync found multiple sibling InterestObjects under %s. "
|
||||
+ "The first sibling is used; an entity should have exactly one."
|
||||
) % current.get_path()
|
||||
)
|
||||
var interest_object := sibling_objects[0]
|
||||
return interest_object if interest_object._is_gdsync_interest_object_enabled() else null
|
||||
current = current.get_parent()
|
||||
return null
|
||||
|
||||
func _viewer_key(viewer_path : String, client_id : int) -> String:
|
||||
return "%s:%s" % [client_id, viewer_path]
|
||||
|
||||
func _cell_coordinates(position : Vector3) -> Vector3i:
|
||||
return Vector3i(
|
||||
floori(position.x / DEFAULT_CELL_SIZE),
|
||||
floori(position.y / DEFAULT_CELL_SIZE),
|
||||
floori(position.z / DEFAULT_CELL_SIZE)
|
||||
)
|
||||
|
||||
func _cell_key(position : Vector3, dimension : int) -> String:
|
||||
var cell := _cell_coordinates(position)
|
||||
if dimension == 2:
|
||||
cell.z = 0
|
||||
return "%s:%s:%s:%s" % [dimension, cell.x, cell.y, cell.z]
|
||||
|
||||
func _distance_squared(a : Vector3, b : Vector3, dimension : int) -> float:
|
||||
if dimension == 2:
|
||||
return Vector2(a.x, a.y).distance_squared_to(Vector2(b.x, b.y))
|
||||
return a.distance_squared_to(b)
|
||||
|
||||
func _client_left(client_id : int) -> void:
|
||||
if !GDSync.is_host():
|
||||
return
|
||||
for viewer_key in _viewers.keys():
|
||||
if _viewers[viewer_key]["client_id"] == client_id:
|
||||
var viewer_path : String = viewer_key.trim_prefix("%s:" % client_id)
|
||||
_remove_viewer(viewer_path, client_id)
|
||||
|
||||
func _client_joined(client_id : int) -> void:
|
||||
if !GDSync.is_host() or client_id == GDSync.get_client_id():
|
||||
return
|
||||
await get_tree().create_timer(0.5).timeout
|
||||
for object_path in _objects:
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
_set_object_recipients_remote,
|
||||
object_path,
|
||||
_objects[object_path]["recipients"]
|
||||
)
|
||||
|
||||
func _host_changed(is_host : bool, _new_host_id : int) -> void:
|
||||
clear()
|
||||
if is_host:
|
||||
get_tree().call_group("_gdsync_interest", "_force_interest_report")
|
||||
1
addons/GD-Sync/Scripts/InterestManager.gd.uid
Normal file
1
addons/GD-Sync/Scripts/InterestManager.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://2jbx0lbddcpo
|
||||
170
addons/GD-Sync/Scripts/KeyStore.gd
Normal file
170
addons/GD-Sync/Scripts/KeyStore.gd
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
@tool
|
||||
extends RefCounted
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
const KEYS_PATH : String = "res://addons/GD-Sync/keys.cfg"
|
||||
const KEYS_SECTION : String = "keys"
|
||||
const PUBLIC_ENTRY : String = "publicKey"
|
||||
const PRIVATE_ENTRY : String = "privateKey"
|
||||
|
||||
const GITIGNORE_PATH : String = "res://.gitignore"
|
||||
const GITIGNORE_ENTRY : String = "addons/GD-Sync/keys.cfg"
|
||||
const GITIGNORE_COMMENT : String = "# GD-Sync API keys. Never commit these."
|
||||
|
||||
const PUBLIC_KEY_ENV : String = "GDSYNC_PUBLIC_KEY"
|
||||
const PRIVATE_KEY_ENV : String = "GDSYNC_PRIVATE_KEY"
|
||||
const PROJECT_FILE : String = "res://project.godot"
|
||||
const PROJECT_PUBLIC : String = "GD-Sync/publicKey"
|
||||
const PROJECT_PRIVATE : String = "GD-Sync/privateKey"
|
||||
|
||||
static func load_keys() -> Dictionary:
|
||||
var keys : Dictionary = {"PublicKey" : "", "PrivateKey" : ""}
|
||||
var config : ConfigFile = ConfigFile.new()
|
||||
if config.load(KEYS_PATH) == OK or config.load(_os(KEYS_PATH)) == OK:
|
||||
keys["PublicKey"] = str(config.get_value(KEYS_SECTION, PUBLIC_ENTRY, ""))
|
||||
keys["PrivateKey"] = str(config.get_value(KEYS_SECTION, PRIVATE_ENTRY, ""))
|
||||
if keys["PublicKey"].is_empty():
|
||||
keys["PublicKey"] = OS.get_environment(PUBLIC_KEY_ENV)
|
||||
if keys["PrivateKey"].is_empty():
|
||||
keys["PrivateKey"] = OS.get_environment(PRIVATE_KEY_ENV)
|
||||
return keys
|
||||
|
||||
static func save_keys(public_key : String, private_key : String) -> void:
|
||||
var config : ConfigFile = ConfigFile.new()
|
||||
config.load(KEYS_PATH)
|
||||
config.set_value(KEYS_SECTION, PUBLIC_ENTRY, public_key)
|
||||
config.set_value(KEYS_SECTION, PRIVATE_ENTRY, private_key)
|
||||
if config.save(KEYS_PATH) != OK and config.save(_os(KEYS_PATH)) != OK:
|
||||
push_error("GD-Sync was unable to save the API keys to "+KEYS_PATH+".")
|
||||
|
||||
static func has_keys() -> bool:
|
||||
var keys : Dictionary = load_keys()
|
||||
return !keys["PublicKey"].is_empty() and !keys["PrivateKey"].is_empty()
|
||||
|
||||
static func encode_keys(public_key : String, private_key : String) -> PackedByteArray:
|
||||
var config : ConfigFile = ConfigFile.new()
|
||||
config.set_value(KEYS_SECTION, PUBLIC_ENTRY, public_key)
|
||||
config.set_value(KEYS_SECTION, PRIVATE_ENTRY, private_key)
|
||||
return config.encode_to_text().to_utf8_buffer()
|
||||
|
||||
static func needs_migrate() -> bool:
|
||||
if ProjectSettings.has_setting(PROJECT_PUBLIC) or ProjectSettings.has_setting(PROJECT_PRIVATE):
|
||||
return true
|
||||
var project : ConfigFile = ConfigFile.new()
|
||||
if project.load(PROJECT_FILE) != OK:
|
||||
project.load(_os(PROJECT_FILE))
|
||||
return project.has_section_key("GD-Sync", PUBLIC_ENTRY) or project.has_section_key("GD-Sync", PRIVATE_ENTRY)
|
||||
|
||||
static func migrate() -> bool:
|
||||
if !needs_migrate():
|
||||
return false
|
||||
|
||||
var existing : Dictionary = load_keys()
|
||||
var public_key : String = str(ProjectSettings.get_setting(PROJECT_PUBLIC, existing["PublicKey"]))
|
||||
var private_key : String = str(ProjectSettings.get_setting(PROJECT_PRIVATE, existing["PrivateKey"]))
|
||||
|
||||
var project : ConfigFile = ConfigFile.new()
|
||||
if project.load(PROJECT_FILE) == OK or project.load(_os(PROJECT_FILE)) == OK:
|
||||
if public_key.is_empty():
|
||||
public_key = str(project.get_value("GD-Sync", PUBLIC_ENTRY, ""))
|
||||
if private_key.is_empty():
|
||||
private_key = str(project.get_value("GD-Sync", PRIVATE_ENTRY, ""))
|
||||
|
||||
save_keys(public_key, private_key)
|
||||
|
||||
if ProjectSettings.has_setting(PROJECT_PUBLIC):
|
||||
ProjectSettings.clear(PROJECT_PUBLIC)
|
||||
if ProjectSettings.has_setting(PROJECT_PRIVATE):
|
||||
ProjectSettings.clear(PROJECT_PRIVATE)
|
||||
_strip_keys_from_project_file()
|
||||
ProjectSettings.save()
|
||||
return true
|
||||
|
||||
static func ensure_gitignore() -> void:
|
||||
var path : String = _os(GITIGNORE_PATH)
|
||||
var content : String = _read_text(path)
|
||||
if content.is_empty():
|
||||
content = _read_text(GITIGNORE_PATH)
|
||||
if _gitignore_has_entry(content):
|
||||
return
|
||||
if !content.is_empty() and !content.ends_with("\n"):
|
||||
content += "\n"
|
||||
if !content.is_empty():
|
||||
content += "\n"
|
||||
content += GITIGNORE_COMMENT+"\n"+GITIGNORE_ENTRY+"\n"
|
||||
if !_write_text(path, content):
|
||||
_write_text(GITIGNORE_PATH, content)
|
||||
|
||||
static func _os(res_path : String) -> String:
|
||||
return ProjectSettings.globalize_path(res_path)
|
||||
|
||||
static func _read_text(path : String) -> String:
|
||||
if !FileAccess.file_exists(path):
|
||||
return ""
|
||||
return FileAccess.get_file_as_string(path)
|
||||
|
||||
static func _write_text(path : String, content : String) -> bool:
|
||||
var file : FileAccess = FileAccess.open(path, FileAccess.WRITE)
|
||||
if file == null:
|
||||
return false
|
||||
file.store_string(content)
|
||||
file.close()
|
||||
return true
|
||||
|
||||
static func _gitignore_has_entry(content : String) -> bool:
|
||||
for line in content.split("\n"):
|
||||
var trimmed : String = line.strip_edges()
|
||||
if trimmed.begins_with("#") or trimmed.is_empty():
|
||||
continue
|
||||
if trimmed == GITIGNORE_ENTRY or trimmed == "/"+GITIGNORE_ENTRY:
|
||||
return true
|
||||
return false
|
||||
|
||||
static func _strip_keys_from_project_file() -> void:
|
||||
var path : String = _os(PROJECT_FILE)
|
||||
var text : String = _read_text(path)
|
||||
if text.is_empty():
|
||||
text = _read_text(PROJECT_FILE)
|
||||
path = PROJECT_FILE
|
||||
if text.is_empty():
|
||||
return
|
||||
|
||||
var section : String = ""
|
||||
var kept : PackedStringArray = PackedStringArray()
|
||||
var removed : bool = false
|
||||
for line in text.split("\n"):
|
||||
var trimmed : String = line.strip_edges()
|
||||
if trimmed.begins_with("[") and trimmed.ends_with("]"):
|
||||
section = trimmed.substr(1, trimmed.length() - 2)
|
||||
kept.append(line)
|
||||
continue
|
||||
if section == "GD-Sync" and (trimmed.begins_with("publicKey=") or trimmed.begins_with("privateKey=")):
|
||||
removed = true
|
||||
continue
|
||||
kept.append(line)
|
||||
|
||||
if removed:
|
||||
_write_text(path, "\n".join(kept))
|
||||
1
addons/GD-Sync/Scripts/KeyStore.gd.uid
Normal file
1
addons/GD-Sync/Scripts/KeyStore.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://cj8mturlqjcfd
|
||||
729
addons/GD-Sync/Scripts/LocalServer.gd
Normal file
729
addons/GD-Sync/Scripts/LocalServer.gd
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var min_port_range : int = 42354
|
||||
var max_port_range : int = min_port_range + 20
|
||||
var min_game_port : int = 42400
|
||||
var max_game_port : int = min_game_port + 20
|
||||
|
||||
var GDSync
|
||||
var connection_controller
|
||||
var request_processor
|
||||
var session_controller
|
||||
var logger
|
||||
|
||||
var local_lobby_name : String = ""
|
||||
var local_lobby_password : String = ""
|
||||
var local_lobby_public : bool = false
|
||||
var local_lobby_open : bool = true
|
||||
var local_lobby_player_limit : int = 0
|
||||
var local_lobby_port : int = -1
|
||||
|
||||
var local_lobby_data : Dictionary = {}
|
||||
var local_lobby_tags : Dictionary = {}
|
||||
var local_owner_cache : Dictionary = {}
|
||||
|
||||
const _UNRELIABLE_WIRE_LIMIT : int = 1200
|
||||
|
||||
var local_server : ENetMultiplayerPeer = ENetMultiplayerPeer.new()
|
||||
var local_peer : PacketPeerUDP = PacketPeerUDP.new()
|
||||
var local_lobby_timer : Timer = Timer.new()
|
||||
|
||||
var found_lobbies : Dictionary = {}
|
||||
|
||||
var peer_client_table : Dictionary = {}
|
||||
var lobby_client_table : Dictionary = {}
|
||||
var _lobby_host_id : int = -1
|
||||
var _creating_local_lobby : bool = false
|
||||
|
||||
class Client extends RefCounted:
|
||||
var valid : bool = false
|
||||
var client_id : int = -1
|
||||
var peer_id : int = -1
|
||||
var peer : ENetPacketPeer
|
||||
var username : String
|
||||
var player_data : Dictionary = {}
|
||||
|
||||
var requests_RUDP : Array = []
|
||||
var requests_UDP : Array = []
|
||||
var lobby_targets : Array = []
|
||||
|
||||
func construct_lobby_targets(clients : Dictionary) -> void:
|
||||
lobby_targets = clients.values()
|
||||
lobby_targets.erase(self)
|
||||
|
||||
func collect_player_data() -> Dictionary:
|
||||
var data : Dictionary = player_data.duplicate()
|
||||
data["ID"] = client_id
|
||||
data["Username"] = username
|
||||
return data
|
||||
|
||||
func _ready() -> void:
|
||||
GDSync = get_node("/root/GDSync")
|
||||
name = "LocalServer"
|
||||
connection_controller = GDSync._connection_controller
|
||||
request_processor = GDSync._request_processor
|
||||
session_controller = GDSync._session_controller
|
||||
logger = GDSync._logger
|
||||
|
||||
_bind_local_server_signals()
|
||||
|
||||
local_lobby_timer.wait_time = 0.5
|
||||
local_lobby_timer.timeout.connect(perform_local_scan)
|
||||
add_child(local_lobby_timer)
|
||||
|
||||
set_process(false)
|
||||
|
||||
func reset_multiplayer() -> void:
|
||||
logger.write_log("Closing local multiplayer.", "[LocalServer]")
|
||||
local_peer.close()
|
||||
local_lobby_timer.stop()
|
||||
set_process(false)
|
||||
|
||||
found_lobbies.clear()
|
||||
|
||||
clear_lobby_data()
|
||||
|
||||
func clear_lobby_data() -> void:
|
||||
logger.write_log("Clear lobby data.", "[LocalServer]")
|
||||
_clear_lobby_state()
|
||||
local_server.close()
|
||||
|
||||
func _clear_lobby_state() -> void:
|
||||
local_lobby_name = ""
|
||||
local_lobby_password = ""
|
||||
local_lobby_public = false
|
||||
local_lobby_open = true
|
||||
local_lobby_player_limit = 0
|
||||
local_lobby_port = -1
|
||||
local_lobby_data.clear()
|
||||
local_lobby_tags.clear()
|
||||
local_owner_cache.clear()
|
||||
peer_client_table.clear()
|
||||
lobby_client_table.clear()
|
||||
_lobby_host_id = -1
|
||||
|
||||
func _bind_local_server_signals() -> void:
|
||||
if !local_server.peer_connected.is_connected(peer_connected):
|
||||
local_server.peer_connected.connect(peer_connected)
|
||||
if !local_server.peer_disconnected.is_connected(peer_disconnected):
|
||||
local_server.peer_disconnected.connect(peer_disconnected)
|
||||
|
||||
func _close_lobby_server() -> void:
|
||||
logger.write_log("Closing local lobby server.", "[LocalServer]")
|
||||
set_process(false)
|
||||
if local_lobby_name != "":
|
||||
found_lobbies.erase(local_lobby_name)
|
||||
_clear_lobby_state()
|
||||
local_server.close()
|
||||
local_server = ENetMultiplayerPeer.new()
|
||||
_bind_local_server_signals()
|
||||
|
||||
func leave_local_lobby() -> void:
|
||||
if local_lobby_name == "":
|
||||
return
|
||||
logger.write_log("Leaving hosted local lobby.", "[LocalServer]")
|
||||
for client_id in lobby_client_table:
|
||||
var other_client : Client = lobby_client_table[client_id]
|
||||
if other_client.client_id != GDSync.get_client_id():
|
||||
send_message(ENUMS.MESSAGE_TYPE.KICKED, other_client)
|
||||
_flush_outgoing_requests()
|
||||
_close_lobby_server()
|
||||
|
||||
func start_local_peer() -> bool:
|
||||
logger.write_log("Starting local peer.", "[LocalServer]")
|
||||
for port in range(min_port_range, max_port_range):
|
||||
var bind_error : int = local_peer.bind(port)
|
||||
if bind_error == OK:
|
||||
logger.write_log("Local peer binded to port. <"+str(port)+">", "[LocalServer]")
|
||||
local_lobby_timer.start()
|
||||
return true
|
||||
|
||||
logger.write_error("Local peer war unable to bind to a port.", "[LocalServer]")
|
||||
return false
|
||||
|
||||
func _bind_game_server() -> int:
|
||||
for port in range(min_game_port, max_game_port):
|
||||
local_server.close()
|
||||
local_server = ENetMultiplayerPeer.new()
|
||||
if local_server.create_server(port) == OK:
|
||||
_bind_local_server_signals()
|
||||
logger.write_log("Local lobby server binded to port. <"+str(port)+">", "[LocalServer]")
|
||||
return port
|
||||
_bind_local_server_signals()
|
||||
return -1
|
||||
|
||||
func create_local_lobby(name : String, password : String = "", public : bool = true, player_limit : int = 0, tags : Dictionary = {}, data : Dictionary = {}) -> void:
|
||||
logger.write_log("Creating local lobby.", "[LocalServer]")
|
||||
var result : int = -1
|
||||
|
||||
if name.length() < 3: result = ENUMS.LOBBY_CREATION_ERROR.NAME_TOO_SHORT
|
||||
elif name.length() > 32: result = ENUMS.LOBBY_CREATION_ERROR.NAME_TOO_LONG
|
||||
elif password.length() > 16: result = ENUMS.LOBBY_CREATION_ERROR.PASSWORD_TOO_LONG
|
||||
elif var_to_bytes(tags).size() > 2048: result = ENUMS.LOBBY_CREATION_ERROR.TAGS_TOO_LARGE
|
||||
elif var_to_bytes(data).size() > 2048: result = ENUMS.LOBBY_CREATION_ERROR.DATA_TOO_LARGE
|
||||
|
||||
if result != -1:
|
||||
GDSync.lobby_creation_failed.emit.call_deferred(name, result)
|
||||
return
|
||||
if _creating_local_lobby or local_lobby_name != "":
|
||||
GDSync.lobby_creation_failed.emit.call_deferred(name, ENUMS.LOBBY_CREATION_ERROR.LOBBY_ALREADY_EXISTS)
|
||||
return
|
||||
|
||||
_creating_local_lobby = true
|
||||
_ingest_local_broadcasts()
|
||||
if !_network_name_taken(name):
|
||||
await get_tree().create_timer(0.6).timeout
|
||||
_ingest_local_broadcasts()
|
||||
_creating_local_lobby = false
|
||||
if _network_name_taken(name) or local_lobby_name != "":
|
||||
GDSync.lobby_creation_failed.emit.call_deferred(name, ENUMS.LOBBY_CREATION_ERROR.LOBBY_ALREADY_EXISTS)
|
||||
return
|
||||
|
||||
local_peer.set_broadcast_enabled(true)
|
||||
|
||||
var bound_port : int = _bind_game_server()
|
||||
if bound_port < 0:
|
||||
GDSync.lobby_creation_failed.emit.call_deferred(name, ENUMS.LOBBY_CREATION_ERROR.LOCAL_PORT_ERROR)
|
||||
return
|
||||
|
||||
local_lobby_name = name
|
||||
local_lobby_password = password
|
||||
local_lobby_public = public
|
||||
local_lobby_player_limit = player_limit
|
||||
local_lobby_port = bound_port
|
||||
local_lobby_tags = tags
|
||||
local_lobby_data = data
|
||||
|
||||
var lobby_dict : Dictionary = get_lobby_dictionary()
|
||||
lobby_dict["IP"] = "127.0.0.1"
|
||||
lobby_dict["DetectionTime"] = Time.get_unix_time_from_system()
|
||||
found_lobbies[local_lobby_name] = lobby_dict
|
||||
|
||||
_lobby_host_id = GDSync.get_client_id()
|
||||
connection_controller.set_host(_lobby_host_id)
|
||||
session_controller.lobby_created()
|
||||
|
||||
set_process(true)
|
||||
GDSync.lobby_created.emit.call_deferred(name)
|
||||
|
||||
func join_lobby(name : String, password : String) -> void:
|
||||
logger.write_log("Joining local lobby. <"+name+">", "[LocalServer]")
|
||||
|
||||
var tries : int = 0
|
||||
while !found_lobbies.has(name) and tries < 5:
|
||||
logger.write_error("Local lobby not found. <"+name+">", "[LocalServer]")
|
||||
tries += 1
|
||||
await get_tree().create_timer(1.0).timeout
|
||||
|
||||
if found_lobbies.has(name):
|
||||
var lobby_data : Dictionary = found_lobbies[name]
|
||||
var lobby_port : int = lobby_data.get("Port", min_game_port)
|
||||
var connect_err : int = connection_controller.connect_to_local_server(lobby_data["IP"], lobby_port)
|
||||
|
||||
if connect_err == OK:
|
||||
logger.write_log("Connected to local lobby host.", "[LocalServer]")
|
||||
request_processor.send_client_id()
|
||||
session_controller.broadcast_player_data()
|
||||
request_processor.create_join_lobby_request(name, password)
|
||||
return
|
||||
else:
|
||||
logger.write_error("Unable to connect to discovered lobby. <"+str(lobby_data["IP"])+">", "[LocalServer]")
|
||||
|
||||
GDSync.lobby_join_failed.emit.call_deferred(name, ENUMS.LOBBY_JOIN_ERROR.LOBBY_DOES_NOT_EXIST)
|
||||
|
||||
func get_public_lobbies() -> void:
|
||||
var lobbies : Array = []
|
||||
for lobby_data in found_lobbies.values():
|
||||
if lobby_data["Public"]:
|
||||
lobbies.append(lobby_data)
|
||||
|
||||
GDSync.lobbies_received.emit.call_deferred(lobbies)
|
||||
|
||||
func get_public_lobby(lobby_name : String) -> void:
|
||||
for lobby_data in found_lobbies.values():
|
||||
if lobby_data["Public"] and lobby_data["Name"] == lobby_name:
|
||||
GDSync.lobby_received.emit.call_deferred(lobby_data)
|
||||
return
|
||||
|
||||
GDSync.lobby_received.emit.call_deferred({})
|
||||
|
||||
func _network_name_taken(lobby_name : String) -> bool:
|
||||
if lobby_name == local_lobby_name or !found_lobbies.has(lobby_name):
|
||||
return false
|
||||
var lobby_data : Dictionary = found_lobbies[lobby_name]
|
||||
if !lobby_data.has("DetectionTime"):
|
||||
return true
|
||||
return Time.get_unix_time_from_system() - float(lobby_data["DetectionTime"]) <= 2.0
|
||||
|
||||
func _is_local_address(ip : String) -> bool:
|
||||
if ip == "127.0.0.1" or ip == "::1":
|
||||
return true
|
||||
return IP.get_local_addresses().has(ip)
|
||||
|
||||
func _ingest_local_broadcasts() -> void:
|
||||
while local_peer.get_available_packet_count() > 0:
|
||||
var server_ip : String = local_peer.get_packet_ip()
|
||||
var port : int = local_peer.get_packet_port()
|
||||
var bytes : PackedByteArray = local_peer.get_packet()
|
||||
|
||||
if server_ip == '' or port <= 0:
|
||||
continue
|
||||
var parsed = bytes_to_var(bytes)
|
||||
if typeof(parsed) != TYPE_DICTIONARY or !parsed.has("Name"):
|
||||
continue
|
||||
var lobby_data : Dictionary = parsed
|
||||
var heard_name : String = str(lobby_data["Name"])
|
||||
if local_lobby_name != "" and heard_name == local_lobby_name:
|
||||
if _is_local_address(server_ip) and int(lobby_data.get("Port", -1)) == local_lobby_port:
|
||||
if found_lobbies.has(heard_name):
|
||||
found_lobbies[heard_name]["DetectionTime"] = Time.get_unix_time_from_system()
|
||||
continue
|
||||
if !found_lobbies.has(heard_name):
|
||||
logger.write_log("Discovered local lobby. <"+server_ip+"><"+heard_name+">", "[LocalServer]")
|
||||
lobby_data["IP"] = server_ip
|
||||
lobby_data["DetectionTime"] = Time.get_unix_time_from_system()
|
||||
found_lobbies[heard_name] = lobby_data
|
||||
|
||||
func perform_local_scan() -> void:
|
||||
local_lobby_timer.start()
|
||||
_ingest_local_broadcasts()
|
||||
|
||||
var expired : Array = []
|
||||
for lobby_name in found_lobbies:
|
||||
var lobby_data : Dictionary = found_lobbies[lobby_name]
|
||||
if !lobby_data.has("DetectionTime"): continue
|
||||
if Time.get_unix_time_from_system() - lobby_data["DetectionTime"] > 2.0:
|
||||
expired.append(lobby_name)
|
||||
for lobby_name in expired:
|
||||
found_lobbies.erase(lobby_name)
|
||||
logger.write_log("Local lobby lost. <"+lobby_name+">", "[LocalServer]")
|
||||
|
||||
if local_lobby_name != "":
|
||||
if found_lobbies.has(local_lobby_name):
|
||||
var lobby_dict : Dictionary = get_lobby_dictionary()
|
||||
lobby_dict["IP"] = found_lobbies[local_lobby_name].get("IP", "127.0.0.1")
|
||||
lobby_dict["DetectionTime"] = Time.get_unix_time_from_system()
|
||||
found_lobbies[local_lobby_name] = lobby_dict
|
||||
for port in range(min_port_range, max_port_range):
|
||||
var bind_error : int = local_peer.set_dest_address("255.255.255.255", port)
|
||||
if bind_error == OK:
|
||||
local_peer.put_packet(var_to_bytes(get_lobby_dictionary()))
|
||||
|
||||
func is_local_server() -> bool:
|
||||
return local_lobby_name != ""
|
||||
|
||||
func peer_connected(id : int) -> void:
|
||||
logger.write_log("Peer connected.", "[LocalServer]")
|
||||
var client : Client = Client.new()
|
||||
client.peer = local_server.get_peer(id)
|
||||
client.peer_id = id
|
||||
if client.peer != null:
|
||||
client.peer.throttle_configure(5000, 2, 0)
|
||||
peer_client_table[id] = client
|
||||
|
||||
func peer_disconnected(id : int) -> void:
|
||||
logger.write_log("Peer disconnected.", "[LocalServer]")
|
||||
if peer_client_table.has(id):
|
||||
var client : Client = peer_client_table[id]
|
||||
leave_lobby_request(client)
|
||||
|
||||
func _take_unreliable_batch(requests : Array) -> Array:
|
||||
var fit : int = 1
|
||||
var lo : int = 1
|
||||
var hi : int = requests.size()
|
||||
while lo <= hi:
|
||||
var mid : int = (lo + hi) >> 1
|
||||
if var_to_bytes(requests.slice(0, mid)).size() <= _UNRELIABLE_WIRE_LIMIT:
|
||||
fit = mid
|
||||
lo = mid + 1
|
||||
else:
|
||||
hi = mid - 1
|
||||
var batch : Array = []
|
||||
for i in fit:
|
||||
batch.append(requests[i])
|
||||
for i in fit:
|
||||
requests.pop_front()
|
||||
return batch
|
||||
|
||||
func _flush_outgoing_requests() -> void:
|
||||
if local_server.get_connection_status() != MultiplayerPeer.CONNECTION_CONNECTED:
|
||||
return
|
||||
for peer in peer_client_table:
|
||||
var client : Client = peer_client_table[peer]
|
||||
if client.requests_RUDP.size() > 0:
|
||||
local_server.transfer_mode = MultiplayerPeer.TRANSFER_MODE_RELIABLE
|
||||
local_server.set_target_peer(client.peer_id)
|
||||
local_server.put_packet(var_to_bytes(client.requests_RUDP))
|
||||
client.requests_RUDP.clear()
|
||||
if client.requests_UDP.size() > 0:
|
||||
local_server.transfer_mode = MultiplayerPeer.TRANSFER_MODE_UNRELIABLE_ORDERED
|
||||
local_server.set_target_peer(client.peer_id)
|
||||
var unreliable_packets : int = 8
|
||||
while unreliable_packets > 0 and client.requests_UDP.size() > 0:
|
||||
unreliable_packets -= 1
|
||||
local_server.put_packet(var_to_bytes(_take_unreliable_batch(client.requests_UDP)))
|
||||
local_server.poll()
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
match(local_server.get_connection_status()):
|
||||
MultiplayerPeer.CONNECTION_DISCONNECTED:
|
||||
return
|
||||
MultiplayerPeer.CONNECTION_CONNECTING:
|
||||
local_server.poll()
|
||||
MultiplayerPeer.CONNECTION_CONNECTED:
|
||||
local_server.poll()
|
||||
_flush_outgoing_requests()
|
||||
|
||||
while local_server.get_available_packet_count() > 0:
|
||||
var channel : int = local_server.get_packet_channel()
|
||||
var peer_id : int = local_server.get_packet_peer()
|
||||
var bytes : PackedByteArray = local_server.get_packet()
|
||||
|
||||
if !peer_client_table.has(peer_id):
|
||||
continue
|
||||
|
||||
var from : Client = peer_client_table[peer_id]
|
||||
var message : Dictionary = bytes_to_var(bytes)
|
||||
|
||||
if message.has(ENUMS.PACKET_VALUE.SERVER_REQUESTS):
|
||||
for request in message[ENUMS.PACKET_VALUE.SERVER_REQUESTS]:
|
||||
var request_type : int = request[ENUMS.DATA.REQUEST_TYPE]
|
||||
logger.write_log("Received server request. <"+str(from.client_id)+"><"+str(ENUMS.REQUEST_TYPE.keys()[request_type])+"><"+str(request)+">", "[LocalServer]")
|
||||
match(request_type):
|
||||
ENUMS.REQUEST_TYPE.SET_CLIENT_ID:
|
||||
from.client_id = request[ENUMS.DATA.NAME]
|
||||
ENUMS.REQUEST_TYPE.JOIN_LOBBY:
|
||||
join_lobby_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.LEAVE_LOBBY:
|
||||
leave_lobby_request(from)
|
||||
ENUMS.REQUEST_TYPE.OPEN_LOBBY:
|
||||
open_lobby_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.CLOSE_LOBBY:
|
||||
close_lobby_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.SET_GDSYNC_OWNER:
|
||||
set_owner_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.SET_LOBBY_TAG:
|
||||
set_lobby_tag_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.ERASE_LOBBY_TAG:
|
||||
erase_lobby_tag_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.SET_LOBBY_DATA:
|
||||
set_lobby_data_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.ERASE_LOBBY_DATA:
|
||||
erase_lobby_data_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.SET_LOBBY_VISIBILITY:
|
||||
set_lobby_visibility_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.SET_PLAYER_USERNAME:
|
||||
set_player_username_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.SET_PLAYER_DATA:
|
||||
set_player_data_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.ERASE_PLAYER_DATA:
|
||||
erase_player_data_request(from, request)
|
||||
ENUMS.REQUEST_TYPE.KICK_PLAYER:
|
||||
kick_player(from, request)
|
||||
ENUMS.REQUEST_TYPE.CHANGE_PASSWORD:
|
||||
change_password(from, request)
|
||||
ENUMS.REQUEST_TYPE.CHANGE_LOBBY_NAME:
|
||||
change_lobby_name(from, request)
|
||||
|
||||
if message.has(ENUMS.PACKET_VALUE.CLIENT_REQUESTS):
|
||||
for request in message[ENUMS.PACKET_VALUE.CLIENT_REQUESTS]:
|
||||
broadcast_request(request, from, channel == 0)
|
||||
|
||||
const _TARGET_CLIENT_ID_MASK : int = 0x3FFFFFFF
|
||||
const _TARGET_PERMISSION_SHIFT : int = 30
|
||||
|
||||
func _decode_target_client(encoded : int) -> int:
|
||||
var id_part : int = encoded & _TARGET_CLIENT_ID_MASK
|
||||
return -1 if id_part == _TARGET_CLIENT_ID_MASK else id_part
|
||||
|
||||
func broadcast_request(request : Array, from : Client, reliable : bool) -> void:
|
||||
if !from.valid: return
|
||||
|
||||
request = request_processor.stamp_caller_id(request, from.client_id)
|
||||
var peers : Array = get_target_peers(request, from)
|
||||
for client in peers:
|
||||
put_request(request, client, reliable)
|
||||
|
||||
func get_target_peers(request : Array, from : Client) -> Array:
|
||||
var targets : Array = []
|
||||
if from.valid:
|
||||
var encoded_target : int = int(request[int(ENUMS.DATA.TARGET_CLIENT)])
|
||||
var target_client : int = _decode_target_client(encoded_target)
|
||||
if target_client >= 0:
|
||||
if lobby_client_table.has(target_client):
|
||||
targets.append(lobby_client_table[target_client])
|
||||
else:
|
||||
return from.lobby_targets
|
||||
return targets
|
||||
|
||||
func send_message(message : int, client : Client, value = null, value2 = null, value3 = null) -> void:
|
||||
if client == null:
|
||||
return
|
||||
if value3 != null:
|
||||
put_request([
|
||||
int(ENUMS.REQUEST_TYPE.MESSAGE),
|
||||
message,
|
||||
value,
|
||||
value2,
|
||||
value3
|
||||
], client, true)
|
||||
elif value2 != null:
|
||||
put_request([
|
||||
int(ENUMS.REQUEST_TYPE.MESSAGE),
|
||||
message,
|
||||
value,
|
||||
value2
|
||||
], client, true)
|
||||
elif value != null:
|
||||
put_request([
|
||||
int(ENUMS.REQUEST_TYPE.MESSAGE),
|
||||
message,
|
||||
value
|
||||
], client, true)
|
||||
else:
|
||||
put_request([
|
||||
int(ENUMS.REQUEST_TYPE.MESSAGE),
|
||||
message
|
||||
], client, true)
|
||||
|
||||
func put_request(request : Array, client : Client, reliable : bool) -> void:
|
||||
if reliable:
|
||||
client.requests_RUDP.append(request)
|
||||
else:
|
||||
client.requests_UDP.append(request)
|
||||
|
||||
func join_lobby_request(from : Client, request : Array) -> void:
|
||||
if local_lobby_name == "": return
|
||||
|
||||
if !local_lobby_open:
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.LOBBY_IS_CLOSED)
|
||||
return
|
||||
if local_lobby_player_limit > 0 and lobby_client_table.size() >= local_lobby_player_limit:
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.LOBBY_IS_FULL)
|
||||
return
|
||||
|
||||
var password : String = request[ENUMS.LOBBY_DATA.PASSWORD]
|
||||
if local_lobby_password != "" and password != local_lobby_password:
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.INCORRECT_PASSWORD)
|
||||
return
|
||||
|
||||
if connection_controller.UNIQUE_USERNAMES:
|
||||
for client in lobby_client_table.values():
|
||||
if client.username == from.username:
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOIN_FAILED, from, local_lobby_name, ENUMS.LOBBY_JOIN_ERROR.DUPLICATE_USERNAME)
|
||||
return
|
||||
|
||||
from.valid = true
|
||||
lobby_client_table[from.client_id] = from
|
||||
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_JOINED, from, local_lobby_name)
|
||||
send_message(ENUMS.MESSAGE_TYPE.HOST_CHANGED, from, GDSync.get_client_id())
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, from, get_lobby_dictionary(true))
|
||||
|
||||
for client_id in lobby_client_table:
|
||||
var client : Client = lobby_client_table[client_id]
|
||||
client.construct_lobby_targets(lobby_client_table)
|
||||
|
||||
if client != from:
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, from, client.collect_player_data())
|
||||
send_message(ENUMS.MESSAGE_TYPE.CLIENT_JOINED, client, from.client_id)
|
||||
|
||||
send_message(ENUMS.MESSAGE_TYPE.CLIENT_JOINED, from, client.client_id)
|
||||
|
||||
for node_path in local_owner_cache:
|
||||
send_message(ENUMS.MESSAGE_TYPE.SET_GDSYNC_OWNER, from, node_path, local_owner_cache[node_path])
|
||||
|
||||
func leave_lobby_request(from : Client) -> void:
|
||||
logger.write_log(" <"+str(from.client_id)+">", "[LocalServer]")
|
||||
if lobby_client_table.has(from.client_id):
|
||||
lobby_client_table.erase(from.client_id)
|
||||
|
||||
if from.client_id != GDSync.get_client_id():
|
||||
for client_id in lobby_client_table:
|
||||
var other_client : Client = lobby_client_table[client_id]
|
||||
other_client.construct_lobby_targets(lobby_client_table)
|
||||
|
||||
if other_client != from:
|
||||
send_message(ENUMS.MESSAGE_TYPE.CLIENT_LEFT, other_client, from.client_id)
|
||||
else:
|
||||
for client_id in lobby_client_table:
|
||||
var other_client : Client = lobby_client_table[client_id]
|
||||
if other_client != from:
|
||||
send_message(ENUMS.MESSAGE_TYPE.KICKED, other_client)
|
||||
_flush_outgoing_requests()
|
||||
_close_lobby_server()
|
||||
return
|
||||
|
||||
if peer_client_table.has(from.peer_id):
|
||||
peer_client_table.erase(from.peer_id)
|
||||
|
||||
if local_server.get_peer(from.peer_id) != null:
|
||||
local_server.disconnect_peer(from.peer_id)
|
||||
|
||||
func open_lobby_request(from : Client, request : Array) -> void:
|
||||
if !from.valid: return
|
||||
local_lobby_open = true
|
||||
|
||||
func close_lobby_request(from : Client, request : Array) -> void:
|
||||
if !from.valid: return
|
||||
local_lobby_open = false
|
||||
|
||||
func set_owner_request(from : Client, request : Array) -> void:
|
||||
if !from.valid: return
|
||||
|
||||
var node_path = request[ENUMS.DATA.NAME]
|
||||
var owner = request[ENUMS.DATA.VALUE]
|
||||
if owner == null or owner == -1:
|
||||
if local_owner_cache.has(node_path):
|
||||
local_owner_cache.erase(node_path)
|
||||
else:
|
||||
local_owner_cache[node_path] = owner
|
||||
|
||||
for client_id in lobby_client_table:
|
||||
send_message(ENUMS.MESSAGE_TYPE.SET_GDSYNC_OWNER, lobby_client_table[client_id], node_path, owner)
|
||||
|
||||
func set_lobby_tag_request(from : Client, request : Array) -> void:
|
||||
var key = request[ENUMS.LOBBY_DATA.NAME]
|
||||
var value = request[ENUMS.LOBBY_DATA.VALUE]
|
||||
|
||||
local_lobby_tags[key] = value
|
||||
|
||||
for client in lobby_client_table.values():
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_TAGS_CHANGED, client, key)
|
||||
|
||||
func erase_lobby_tag_request(from : Client, request : Array) -> void:
|
||||
var key = request[ENUMS.LOBBY_DATA.NAME]
|
||||
|
||||
if local_lobby_tags.has(key):
|
||||
local_lobby_tags.erase(key)
|
||||
for client in lobby_client_table.values():
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_TAGS_CHANGED, client, key)
|
||||
|
||||
func set_lobby_data_request(from : Client, request : Array) -> void:
|
||||
var key = request[ENUMS.LOBBY_DATA.NAME]
|
||||
var value = request[ENUMS.LOBBY_DATA.VALUE]
|
||||
|
||||
local_lobby_data[key] = value
|
||||
|
||||
for client in lobby_client_table.values():
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_CHANGED, client, key)
|
||||
|
||||
func erase_lobby_data_request(from : Client, request : Array) -> void:
|
||||
var key = request[ENUMS.LOBBY_DATA.NAME]
|
||||
|
||||
if local_lobby_data.has(key):
|
||||
local_lobby_data.erase(key)
|
||||
for client in lobby_client_table.values():
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_RECEIVED, client, get_lobby_dictionary(true))
|
||||
send_message(ENUMS.MESSAGE_TYPE.LOBBY_DATA_CHANGED, client, key)
|
||||
|
||||
func set_lobby_visibility_request(from : Client, request : Array) -> void:
|
||||
local_lobby_public = request[ENUMS.LOBBY_DATA.VISIBILITY]
|
||||
|
||||
func set_player_username_request(from : Client, request : Array) -> void:
|
||||
from.username = request[ENUMS.DATA.NAME]
|
||||
|
||||
for client in from.lobby_targets:
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED, client, from.client_id, "Username")
|
||||
|
||||
func set_player_data_request(from : Client, request : Array) -> void:
|
||||
var key = request[ENUMS.DATA.NAME]
|
||||
from.player_data[key] = request[ENUMS.DATA.VALUE]
|
||||
|
||||
for client in from.lobby_targets:
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED, client, from.client_id, key)
|
||||
|
||||
func erase_player_data_request(from : Client, request : Array) -> void:
|
||||
var key = request[ENUMS.DATA.NAME]
|
||||
|
||||
if from.player_data.has(key):
|
||||
from.player_data.erase(key)
|
||||
|
||||
for client in from.lobby_targets:
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_RECEIVED, client, from.collect_player_data())
|
||||
send_message(ENUMS.MESSAGE_TYPE.PLAYER_DATA_CHANGED, client, from.client_id, key)
|
||||
|
||||
func kick_player(from : Client, request : Array) -> void:
|
||||
var client_id : int = request[ENUMS.DATA.NAME]
|
||||
var reason : String = ""
|
||||
if request.size() >= 3:
|
||||
reason = str(request[ENUMS.DATA.VALUE])
|
||||
|
||||
if(from.client_id != GDSync.get_client_id()): return
|
||||
|
||||
var kicked_client : Client = lobby_client_table.get(client_id, null)
|
||||
if kicked_client == null: return
|
||||
|
||||
lobby_client_table.erase(client_id)
|
||||
if reason.is_empty():
|
||||
send_message(ENUMS.MESSAGE_TYPE.KICKED, kicked_client)
|
||||
else:
|
||||
send_message(ENUMS.MESSAGE_TYPE.KICKED, kicked_client, reason)
|
||||
await get_tree().process_frame
|
||||
await get_tree().process_frame
|
||||
kicked_client.peer.peer_disconnect()
|
||||
|
||||
func change_password(from : Client, request : Array) -> void:
|
||||
if(from.client_id != GDSync.get_client_id()): return
|
||||
var password : String = request[ENUMS.DATA.NAME]
|
||||
local_lobby_password = password
|
||||
|
||||
func change_lobby_name(from : Client, request : Array) -> void:
|
||||
if(from.client_id != GDSync.get_client_id()): return
|
||||
var name : String = request[ENUMS.DATA.NAME]
|
||||
local_lobby_name = name
|
||||
|
||||
func _get_lobby_player_count() -> int:
|
||||
var count : int = lobby_client_table.size()
|
||||
var host_id : int = GDSync.get_client_id()
|
||||
if host_id >= 0 and !lobby_client_table.has(host_id):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
func get_lobby_dictionary(with_data : bool = false) -> Dictionary:
|
||||
var dict : Dictionary = {
|
||||
"Name" : local_lobby_name,
|
||||
"PlayerCount" : _get_lobby_player_count(),
|
||||
"PlayerLimit" : local_lobby_player_limit,
|
||||
"Public" : local_lobby_public,
|
||||
"Open" : local_lobby_open,
|
||||
"Tags" : local_lobby_tags,
|
||||
"HasPassword" : local_lobby_password != "",
|
||||
"Host" : GDSync.player_get_data(GDSync.get_client_id(), "Username", ""),
|
||||
"Port" : local_lobby_port
|
||||
}
|
||||
|
||||
if with_data:
|
||||
dict["Data"] = local_lobby_data
|
||||
|
||||
return dict
|
||||
1
addons/GD-Sync/Scripts/LocalServer.gd.uid
Normal file
1
addons/GD-Sync/Scripts/LocalServer.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://ceovwtxh0ol4y
|
||||
208
addons/GD-Sync/Scripts/Logger.gd
Normal file
208
addons/GD-Sync/Scripts/Logger.gd
Normal file
|
|
@ -0,0 +1,208 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
const LOG_PATH : String = "user://GD-Sync/Logs"
|
||||
var GDSync
|
||||
|
||||
var logging_enabled : bool = true
|
||||
var session_id : String
|
||||
|
||||
var redacted_values : PackedStringArray = PackedStringArray()
|
||||
|
||||
var logs : PackedStringArray
|
||||
|
||||
var original_log_times : Dictionary = {}
|
||||
var recent_log_times : Dictionary = {}
|
||||
var recent_log_counts : Dictionary = {}
|
||||
|
||||
var log_timer : float = 0.0
|
||||
var new_logs : bool = false
|
||||
|
||||
var use_profiler : bool = false
|
||||
var monitor_connections : bool = false
|
||||
var connection_timer : float = 0.0
|
||||
var profiler_data : Dictionary = {}
|
||||
var profiler_message_queue : Array = []
|
||||
var debugger_singleton
|
||||
|
||||
func _ready() -> void:
|
||||
name = "Logger"
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
logging_enabled = OS.is_debug_build()
|
||||
set_process(logging_enabled)
|
||||
|
||||
if OS.has_feature("editor") and EngineDebugger.is_active(): # Harvest Season patch: only with a debugger attached
|
||||
debugger_singleton = Engine.get_singleton("EngineDebugger")
|
||||
debugger_singleton.register_message_capture("gdsyncprofiler", _capture)
|
||||
debugger_singleton.send_message("gdsyncprofiler:gamestart", [])
|
||||
|
||||
GDSync.client_joined.connect(func(client_id : int):
|
||||
register_profiler_message("clientjoined", [client_id]))
|
||||
GDSync.client_left.connect(func(client_id : int):
|
||||
register_profiler_message("clientleft", [client_id]))
|
||||
|
||||
if !logging_enabled: return
|
||||
var time : float = Time.get_unix_time_from_system()
|
||||
session_id = str(ceili(time)/86400)+str(ceili(time*1000.0)%86400000)
|
||||
|
||||
if !DirAccess.dir_exists_absolute(LOG_PATH):
|
||||
DirAccess.make_dir_absolute(LOG_PATH)
|
||||
|
||||
var files : PackedStringArray = DirAccess.get_files_at(LOG_PATH)
|
||||
if files.size() > 4:
|
||||
var file_times : Dictionary = {}
|
||||
for file in files:
|
||||
file_times[FileAccess.get_modified_time(LOG_PATH+"/"+file)] = file
|
||||
|
||||
var keys : Array = file_times.keys()
|
||||
keys.sort()
|
||||
for i in range(files.size()-4):
|
||||
var log_time : int = keys[i]
|
||||
DirAccess.remove_absolute(LOG_PATH+"/"+file_times[log_time])
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
log_timer -= delta
|
||||
_process_logs()
|
||||
_write_logs()
|
||||
_monitor_connections(delta)
|
||||
|
||||
func _monitor_connections(delta : float) -> void:
|
||||
if !monitor_connections:
|
||||
return
|
||||
|
||||
connection_timer -= delta
|
||||
if connection_timer <= 0.0:
|
||||
connection_timer += 1.0
|
||||
|
||||
for client_id in GDSync.lobby_get_all_clients():
|
||||
_monitor_connection(client_id)
|
||||
|
||||
func _monitor_connection(client_id : int) -> void:
|
||||
if GDSync.get_client_id() == client_id: return
|
||||
|
||||
var ping : float = await GDSync.get_client_ping(client_id)
|
||||
var perceived_ping : float = await GDSync.get_client_perceived_ping(client_id)
|
||||
register_profiler_message("pingmeasured", [client_id, ping, perceived_ping])
|
||||
|
||||
func _process_logs() -> void:
|
||||
var current_time : float = Time.get_unix_time_from_system()
|
||||
for log in recent_log_times:
|
||||
var time : float = recent_log_times[log]
|
||||
var count : int = recent_log_counts[log]
|
||||
if current_time - time > 1.0 or count >= 100:
|
||||
|
||||
var original_time : float = original_log_times[log]
|
||||
original_log_times.erase(log)
|
||||
recent_log_times.erase(log)
|
||||
recent_log_counts.erase(log)
|
||||
|
||||
var print_time : String = str(snappedf(fmod(original_time, 1000.0), 0.01)).pad_decimals(2)
|
||||
|
||||
new_logs = true
|
||||
if count == 1:
|
||||
logs.append("["+print_time+"]"+log+"\n")
|
||||
else:
|
||||
logs.append("["+print_time+"][x"+str(count)+"]"+log+"\n")
|
||||
|
||||
func _write_logs() -> void:
|
||||
if log_timer > 0.0: return
|
||||
log_timer = 1.0
|
||||
if !new_logs: return
|
||||
new_logs = false
|
||||
|
||||
var log_path : String = LOG_PATH+"/GDLog"+session_id+".txt"
|
||||
var file := FileAccess.open(log_path, FileAccess.READ_WRITE)
|
||||
if file == null:
|
||||
file = FileAccess.open(log_path, FileAccess.WRITE)
|
||||
if file == null:
|
||||
return
|
||||
|
||||
file.seek_end()
|
||||
for log in logs:
|
||||
file.store_string(log)
|
||||
logs.clear()
|
||||
file.close()
|
||||
|
||||
func register_redacted_value(value : String) -> void:
|
||||
if redacted_values.has(value): return
|
||||
redacted_values.append(value)
|
||||
|
||||
func redact(log : String) -> String:
|
||||
for value in redacted_values:
|
||||
log = log.replace(value, "[REDACTED]")
|
||||
return log
|
||||
|
||||
func write_log(log : String, prefix : String = "") -> void:
|
||||
if !logging_enabled: return
|
||||
|
||||
log = redact(prefix+" "+log)
|
||||
|
||||
if !original_log_times.has(log): original_log_times[log] = Time.get_unix_time_from_system()
|
||||
recent_log_times[log] = Time.get_unix_time_from_system()
|
||||
recent_log_counts[log] = recent_log_counts.get(log, 0)+1
|
||||
|
||||
func write_error(error : String, prefix : String = "") -> void:
|
||||
write_log(error, prefix+"[ERROR]")
|
||||
|
||||
func _capture(message : String, data : Array) -> bool:
|
||||
if message == "start":
|
||||
use_profiler = true
|
||||
debugger_singleton.send_message("gdsyncprofiler:setdata", [profiler_data])
|
||||
|
||||
for message_data in profiler_message_queue:
|
||||
debugger_singleton.send_message("gdsyncprofiler:"+message_data[0], message_data[1])
|
||||
profiler_message_queue.clear()
|
||||
return true
|
||||
if message == "stop":
|
||||
use_profiler = false
|
||||
return true
|
||||
if message == "start_monitoring_connections":
|
||||
monitor_connections = true
|
||||
return true
|
||||
if message == "stop_monitoring_connections":
|
||||
monitor_connections = false
|
||||
return true
|
||||
if message == "set_artificial_latency":
|
||||
if data.size() > 0:
|
||||
GDSync.set_artificial_latency(int(data[0]))
|
||||
return true
|
||||
return false
|
||||
|
||||
func register_profiler_data(key : String, value) -> void:
|
||||
profiler_data[key] = value
|
||||
if !use_profiler: return
|
||||
debugger_singleton.send_message("gdsyncprofiler:setdata", [profiler_data])
|
||||
|
||||
func register_profiler_message(message : String, values : Array) -> void:
|
||||
if !use_profiler:
|
||||
profiler_message_queue.append([message, values])
|
||||
return
|
||||
debugger_singleton.send_message("gdsyncprofiler:"+message, values)
|
||||
|
||||
func register_transfer_usage(origin : Dictionary, byte_count : int, upload : bool, details : String) -> void:
|
||||
if !use_profiler: return
|
||||
debugger_singleton.send_message("gdsyncprofiler:registertransfer", [GDSync.get_client_id(), origin, byte_count, upload, details])
|
||||
1
addons/GD-Sync/Scripts/Logger.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Logger.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dlxrcaucmagh6
|
||||
156
addons/GD-Sync/Scripts/MatchmakingController.gd
Normal file
156
addons/GD-Sync/Scripts/MatchmakingController.gd
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var GDSync
|
||||
|
||||
var request_processor
|
||||
var connection_controller
|
||||
|
||||
var active: bool = false
|
||||
var status: int = ENUMS.MATCHMAKING_STATUS.INACTIVE
|
||||
var details: Dictionary = {}
|
||||
var request_id: int = 0
|
||||
var cancellation_pending: bool = false
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
name = "MatchmakingController"
|
||||
request_processor = GDSync._request_processor
|
||||
connection_controller = GDSync._connection_controller
|
||||
GDSync.disconnected.connect(disconnected)
|
||||
|
||||
|
||||
func start(request: MatchmakingRequest) -> void:
|
||||
if !connection_controller.valid_connection():
|
||||
return
|
||||
if connection_controller.is_local_check():
|
||||
GDSync.matchmaking_failed.emit(ENUMS.MATCHMAKING_ERROR.UNSUPPORTED_LOCAL)
|
||||
return
|
||||
if GDSync.lobby_get_name() != "":
|
||||
GDSync.matchmaking_failed.emit(ENUMS.MATCHMAKING_ERROR.ALREADY_IN_LOBBY)
|
||||
return
|
||||
if request == null or !request._is_valid():
|
||||
GDSync.matchmaking_failed.emit(ENUMS.MATCHMAKING_ERROR.INVALID_REQUEST)
|
||||
return
|
||||
if active:
|
||||
request_processor.create_cancel_matchmaking_request(request_id)
|
||||
request_id += 1
|
||||
cancellation_pending = false
|
||||
active = true
|
||||
status = ENUMS.MATCHMAKING_STATUS.INACTIVE
|
||||
var parameters := request._to_dictionary()
|
||||
parameters["RequestId"] = request_id
|
||||
request_processor.create_start_matchmaking_request(parameters)
|
||||
|
||||
|
||||
func cancel() -> void:
|
||||
if !connection_controller.valid_connection() or !active:
|
||||
return
|
||||
request_processor.create_cancel_matchmaking_request(request_id)
|
||||
cancellation_pending = true
|
||||
active = false
|
||||
status = ENUMS.MATCHMAKING_STATUS.INACTIVE
|
||||
details.clear()
|
||||
|
||||
|
||||
func is_active() -> bool:
|
||||
return active
|
||||
|
||||
|
||||
func get_status() -> int:
|
||||
return status
|
||||
|
||||
|
||||
func get_status_details() -> Dictionary:
|
||||
return details.duplicate(true)
|
||||
|
||||
|
||||
func started(received_request_id: int) -> void:
|
||||
if received_request_id != request_id or cancellation_pending:
|
||||
return
|
||||
active = true
|
||||
GDSync.matchmaking_started.emit()
|
||||
|
||||
|
||||
func status_changed(received_request_id: int, new_status: int, new_details: Dictionary) -> void:
|
||||
if received_request_id != request_id or cancellation_pending:
|
||||
return
|
||||
status = new_status
|
||||
details = new_details.duplicate(true)
|
||||
GDSync.matchmaking_status_changed.emit(status, details)
|
||||
|
||||
|
||||
func match_found(received_request_id: int, lobby_name: String) -> void:
|
||||
if received_request_id != request_id or cancellation_pending or !active:
|
||||
return
|
||||
status = ENUMS.MATCHMAKING_STATUS.JOINING
|
||||
GDSync.matchmaking_match_found.emit(lobby_name)
|
||||
if received_request_id == request_id and active:
|
||||
GDSync.lobby_join(lobby_name)
|
||||
|
||||
|
||||
func remote_match_found(received_request_id: int, lobby_name: String) -> void:
|
||||
if received_request_id != request_id or cancellation_pending or !active:
|
||||
return
|
||||
status = ENUMS.MATCHMAKING_STATUS.JOINING
|
||||
GDSync.matchmaking_match_found.emit(lobby_name)
|
||||
|
||||
|
||||
func failed(received_request_id: int, error: int) -> void:
|
||||
if received_request_id != request_id:
|
||||
return
|
||||
cancellation_pending = false
|
||||
reset()
|
||||
GDSync.matchmaking_failed.emit(error)
|
||||
|
||||
|
||||
func cancelled(received_request_id: int) -> void:
|
||||
if received_request_id != request_id:
|
||||
return
|
||||
cancellation_pending = false
|
||||
reset()
|
||||
GDSync.matchmaking_cancelled.emit()
|
||||
|
||||
|
||||
func lobby_joined() -> void:
|
||||
cancellation_pending = false
|
||||
reset()
|
||||
|
||||
|
||||
func lobby_join_failed() -> void:
|
||||
if status == ENUMS.MATCHMAKING_STATUS.JOINING:
|
||||
failed(request_id, ENUMS.MATCHMAKING_ERROR.JOIN_FAILED)
|
||||
|
||||
|
||||
func disconnected() -> void:
|
||||
cancellation_pending = false
|
||||
reset()
|
||||
|
||||
|
||||
func reset() -> void:
|
||||
active = false
|
||||
status = ENUMS.MATCHMAKING_STATUS.INACTIVE
|
||||
details.clear()
|
||||
1
addons/GD-Sync/Scripts/MatchmakingController.gd.uid
Normal file
1
addons/GD-Sync/Scripts/MatchmakingController.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bdpl3n36a1bui
|
||||
305
addons/GD-Sync/Scripts/NodeTracker.gd
Normal file
305
addons/GD-Sync/Scripts/NodeTracker.gd
Normal file
|
|
@ -0,0 +1,305 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var INSTANTIATOR_SCENE : GDScript = load("res://addons/GD-Sync/Scripts/Types/NodeInstantiator.gd")
|
||||
|
||||
var GDSync
|
||||
var request_processor
|
||||
var logger
|
||||
|
||||
var replication_cache : Dictionary = {}
|
||||
var replication_settings : Dictionary = {}
|
||||
var root_instantiator
|
||||
var instantiator_regex : RegEx
|
||||
|
||||
var instantiator_lib : Dictionary = {}
|
||||
|
||||
var lobby_i : int = 0
|
||||
|
||||
func _ready() -> void:
|
||||
name = "NodeTracker"
|
||||
GDSync = get_node("/root/GDSync")
|
||||
request_processor = GDSync._request_processor
|
||||
logger = GDSync._logger
|
||||
|
||||
root_instantiator = INSTANTIATOR_SCENE.new()
|
||||
root_instantiator.spawn_type = 1
|
||||
root_instantiator.name = "RootInstantiator"
|
||||
add_child(root_instantiator)
|
||||
|
||||
instantiator_regex = RegEx.new()
|
||||
instantiator_regex.compile("[^a-z0-9]")
|
||||
|
||||
GDSync.expose_func(replicate_remote)
|
||||
GDSync.expose_func(create_instantiator_remote)
|
||||
GDSync.expose_func(multiplayer_queue_free_remote)
|
||||
GDSync.client_joined.connect(client_joined)
|
||||
|
||||
func lobby_left() -> void:
|
||||
lobby_i += 1
|
||||
|
||||
for instantiator in instantiator_lib.values():
|
||||
if is_instance_valid(instantiator):
|
||||
instantiator.queue_free()
|
||||
|
||||
instantiator_lib.clear()
|
||||
replication_cache.clear()
|
||||
replication_settings.clear()
|
||||
|
||||
func client_joined(client_id : int) -> void:
|
||||
if client_id == GDSync.get_client_id(): return
|
||||
if !GDSync.is_host(): return
|
||||
create_instantiators(client_id)
|
||||
broadcast_replication(client_id)
|
||||
|
||||
func create_instantiators(client_id : int) -> void:
|
||||
for settings_key in instantiator_lib:
|
||||
var instantiator = instantiator_lib[settings_key]
|
||||
GDSync.call_func_on(client_id, create_instantiator_remote,
|
||||
instantiator.scene.resource_path,
|
||||
str(instantiator.target.get_path()),
|
||||
instantiator.sync_starting_changes,
|
||||
instantiator.excluded_properties,
|
||||
instantiator.replicate_on_join
|
||||
)
|
||||
|
||||
func broadcast_replication(client_id : int) -> void:
|
||||
for instantiator_path in replication_cache:
|
||||
var nodes_to_replicate : Array = replication_cache[instantiator_path].duplicate()
|
||||
|
||||
while nodes_to_replicate.size() > 0:
|
||||
create_replication_requests(client_id, instantiator_path, nodes_to_replicate)
|
||||
|
||||
func create_replication_requests(client_id : int, instantiator_path : String, nodes_to_replicate : Array) -> void:
|
||||
var settings : Array = replication_settings[instantiator_path]
|
||||
|
||||
logger.write_log("Creating remote replication requests. <"+str(client_id)+"><"+str(instantiator_path)+"><"+str(settings)+">", "[NodeTracker]")
|
||||
|
||||
var sync_starting_changes : bool = settings[ENUMS.NODE_REPLICATION_SETTINGS.SYNC_STARTING_CHANGES]
|
||||
var original_properties : Dictionary = settings[ENUMS.NODE_REPLICATION_SETTINGS.ORIGINAL_PROPERTIES]
|
||||
var excluded_properties : PackedStringArray = settings[ENUMS.NODE_REPLICATION_SETTINGS.EXCLUDED_PROPERTIES]
|
||||
|
||||
var replication_data : Array = []
|
||||
|
||||
var replication_counter : int = 0
|
||||
while nodes_to_replicate.size() > 0 and replication_counter < 32:
|
||||
var node : Node = nodes_to_replicate.pop_front()
|
||||
replication_counter += 1
|
||||
if !is_instance_valid(node):
|
||||
logger.write_error("Failed to create remote replication request, Node was invalid. <"+str(client_id)+"><"+str(instantiator_path)+">", "[NodeTracker]")
|
||||
continue
|
||||
if !node.is_inside_tree():
|
||||
logger.write_error("Failed to create remote replication request, Node is not inside the tree. <"+str(client_id)+"><"+str(instantiator_path)+">", "[NodeTracker]")
|
||||
continue
|
||||
|
||||
var id : int = node.get_meta("GDID")
|
||||
var changed_properties : Dictionary = {}
|
||||
|
||||
if sync_starting_changes:
|
||||
var starting_properties : Dictionary = original_properties
|
||||
var new_properties : Dictionary = root_instantiator._get_properties_as_bytes(node)
|
||||
|
||||
for property_name in starting_properties:
|
||||
if new_properties[property_name] != starting_properties[property_name]:
|
||||
var new_value = bytes_to_var(new_properties[property_name])
|
||||
var type : int = typeof(new_value)
|
||||
match(type):
|
||||
TYPE_OBJECT: continue
|
||||
TYPE_CALLABLE: continue
|
||||
TYPE_SIGNAL: continue
|
||||
TYPE_RID: continue
|
||||
if root_instantiator._PERMANENT_EXCLUDED_PROPERTIES.has(property_name): continue
|
||||
if excluded_properties.has(property_name): continue
|
||||
if root_instantiator._contains_object(new_value): continue
|
||||
changed_properties[property_name] = new_value
|
||||
|
||||
replication_data.append([id, changed_properties])
|
||||
|
||||
GDSync.call_func_on(client_id, replicate_remote,
|
||||
settings,
|
||||
replication_data
|
||||
)
|
||||
|
||||
func replicate_remote(settings : Array, replication_data : Array) -> void:
|
||||
var instantiator : Node = get_node_or_null(settings[ENUMS.NODE_REPLICATION_SETTINGS.INSTANTIATOR])
|
||||
var target : Node = get_node_or_null(settings[ENUMS.NODE_REPLICATION_SETTINGS.TARGET])
|
||||
|
||||
var tries : int = 0
|
||||
var current_lobby_i : int = lobby_i
|
||||
while target == null:
|
||||
tries += 1
|
||||
await get_tree().create_timer(0.6).timeout
|
||||
logger.write_error("Remote replication failed, target Node was not found. Trying again. <"+str(settings)+">", "[NodeTracker]")
|
||||
target = get_node_or_null(settings[ENUMS.NODE_REPLICATION_SETTINGS.TARGET])
|
||||
|
||||
if tries >= 100:
|
||||
logger.write_error("Remote replication failed, target Node was not found. <"+str(settings)+">", "[NodeTracker]")
|
||||
return
|
||||
|
||||
if current_lobby_i != lobby_i:
|
||||
return
|
||||
|
||||
if instantiator == null:
|
||||
logger.write_log("Remote replication did not find the target Instantiator, falling back to the root Instantiator. <"+str(settings)+">", "[NodeTracker]")
|
||||
var scene : PackedScene = load(settings[ENUMS.NODE_REPLICATION_SETTINGS.SCENE])
|
||||
root_instantiator.scene = scene
|
||||
root_instantiator.target = target
|
||||
root_instantiator.replicate_settings = settings
|
||||
instantiator = root_instantiator
|
||||
|
||||
logger.write_log("Replicating Nodes. <"+str(settings)+"><"+str(replication_data)+">", "[NodeTracker]")
|
||||
for node_replication_data in replication_data:
|
||||
instantiator._instantiate_remote(
|
||||
node_replication_data[ENUMS.NODE_REPLICATION_DATA.ID],
|
||||
node_replication_data[ENUMS.NODE_REPLICATION_DATA.CHANGED_PROPERTIES]
|
||||
)
|
||||
|
||||
func register_replication(node : Node, instantiator_path : String, settings : Array) -> void:
|
||||
if !replication_cache.has(instantiator_path):
|
||||
replication_cache[instantiator_path] = []
|
||||
replication_settings[instantiator_path] = settings
|
||||
|
||||
replication_cache[instantiator_path].append(node)
|
||||
|
||||
func deregister_replication(node : Node) -> void:
|
||||
var instantiator_path : String = node.get_meta("Instantiator")
|
||||
if replication_cache.has(instantiator_path):
|
||||
replication_cache[instantiator_path].erase(node)
|
||||
|
||||
func multiplayer_instantiate(
|
||||
scene : PackedScene,
|
||||
parent : Node,
|
||||
sync_starting_changes : bool,
|
||||
excluded_properties : PackedStringArray,
|
||||
replicate_on_join : bool) -> Node:
|
||||
|
||||
if parent == null:
|
||||
parent = get_tree().current_scene
|
||||
|
||||
var settings_key : StringName = StringName(
|
||||
str(scene.resource_path, sync_starting_changes, excluded_properties, replicate_on_join
|
||||
))
|
||||
|
||||
logger.write_log("Multiplayer Instantiate. <"+settings_key+">", "[NodeTracker]")
|
||||
|
||||
var instantiator : Node
|
||||
if !instantiator_lib.has(settings_key):
|
||||
logger.write_log("Creating Instantiator.", "[NodeTracker]")
|
||||
instantiator = INSTANTIATOR_SCENE.new()
|
||||
instantiator.name = instantiator_regex.sub(scene.resource_path.to_lower(), "", true)
|
||||
instantiator.spawn_type = 1
|
||||
instantiator.scene = scene
|
||||
instantiator.sync_starting_changes = sync_starting_changes
|
||||
instantiator.excluded_properties = excluded_properties
|
||||
instantiator.replicate_on_join = replicate_on_join
|
||||
add_child(instantiator)
|
||||
|
||||
instantiator_lib[settings_key] = instantiator
|
||||
|
||||
GDSync.call_func(create_instantiator_remote,
|
||||
scene.resource_path,
|
||||
str(parent.get_path()),
|
||||
sync_starting_changes,
|
||||
excluded_properties,
|
||||
replicate_on_join
|
||||
)
|
||||
else:
|
||||
instantiator = instantiator_lib[settings_key]
|
||||
logger.write_log("Using existing Instantiator.", "[NodeTracker]")
|
||||
|
||||
instantiator.target = parent
|
||||
instantiator.target_path = str(parent.get_path())
|
||||
|
||||
GDSync.call_func(instantiator._set_target_remote, instantiator.target_path)
|
||||
|
||||
return instantiator.instantiate_node()
|
||||
|
||||
func create_instantiator_remote(
|
||||
scene_path : String,
|
||||
parent_path : NodePath,
|
||||
sync_starting_changes : bool,
|
||||
excluded_properties : PackedStringArray,
|
||||
replicate_on_join : bool
|
||||
) -> void:
|
||||
|
||||
var scene : PackedScene = load(scene_path)
|
||||
var parent : Node = get_node_or_null(parent_path)
|
||||
|
||||
if scene == null:
|
||||
logger.write_error("Failed to create remote Instaniator, invalid scene path. <"+scene_path+">", "[NodeTracker]")
|
||||
push_error("Remote instantiate failed, invalid scene path.")
|
||||
return
|
||||
|
||||
var tries : int = 0
|
||||
var current_lobby_i : int = lobby_i
|
||||
while parent == null:
|
||||
tries += 1
|
||||
await get_tree().create_timer(0.6).timeout
|
||||
logger.write_error("Failed to create remote Instantiator, parent Node not found. Trying again. <"+str(parent_path)+">", "[NodeTracker]")
|
||||
|
||||
if tries >= 100:
|
||||
logger.write_error("Failed to create remote Instantiator, parent Node not found. <"+str(parent_path)+">", "[NodeTracker]")
|
||||
return
|
||||
|
||||
if current_lobby_i != lobby_i:
|
||||
return
|
||||
|
||||
var settings_key : StringName = StringName(
|
||||
str(scene_path, sync_starting_changes, excluded_properties, replicate_on_join
|
||||
))
|
||||
|
||||
logger.write_log("Created remote Instaniator. <"+settings_key+">", "[NodeTracker]")
|
||||
|
||||
if !instantiator_lib.has(settings_key):
|
||||
var instantiator : Node = INSTANTIATOR_SCENE.new()
|
||||
instantiator.name = instantiator_regex.sub(scene_path.to_lower(), "", true)
|
||||
instantiator.spawn_type = 1
|
||||
instantiator.scene = scene
|
||||
instantiator.sync_starting_changes = sync_starting_changes
|
||||
instantiator.excluded_properties = excluded_properties
|
||||
instantiator.replicate_on_join = replicate_on_join
|
||||
add_child(instantiator)
|
||||
|
||||
instantiator.target = parent
|
||||
instantiator.target_path = str(parent.get_path())
|
||||
|
||||
instantiator_lib[settings_key] = instantiator
|
||||
|
||||
func multiplayer_queue_free(node : Node) -> void:
|
||||
if !is_instance_valid(node) || !node.is_inside_tree(): return
|
||||
node.queue_free()
|
||||
|
||||
logger.write_log("Creating remote free request. <"+str(node.get_path())+">", "[NodeTracker]")
|
||||
GDSync.call_func(multiplayer_queue_free_remote, node.get_path())
|
||||
|
||||
func multiplayer_queue_free_remote(node_path : NodePath) -> void:
|
||||
var node : Node = get_node_or_null(node_path)
|
||||
if node == null:
|
||||
logger.write_error("Failed to remotely free, Node not found. <"+str(node_path)+">", "[NodeTracker]")
|
||||
return
|
||||
|
||||
logger.write_log("Remotely freed Node. <"+str(node_path)+">", "[NodeTracker]")
|
||||
node.queue_free()
|
||||
1
addons/GD-Sync/Scripts/NodeTracker.gd.uid
Normal file
1
addons/GD-Sync/Scripts/NodeTracker.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://caeuxki7ks0bq
|
||||
1332
addons/GD-Sync/Scripts/RequestProcessor.gd
Normal file
1332
addons/GD-Sync/Scripts/RequestProcessor.gd
Normal file
File diff suppressed because it is too large
Load diff
1
addons/GD-Sync/Scripts/RequestProcessor.gd.uid
Normal file
1
addons/GD-Sync/Scripts/RequestProcessor.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dwrfpxiksh3ve
|
||||
287
addons/GD-Sync/Scripts/ServerSwitchController.gd
Normal file
287
addons/GD-Sync/Scripts/ServerSwitchController.gd
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
enum _SwitchState {
|
||||
IDLE,
|
||||
CONNECTING_DESTINATION,
|
||||
TUNNELING,
|
||||
JOINING_DESTINATION,
|
||||
ROLLING_BACK,
|
||||
TUNNELING_ROLLBACK,
|
||||
RESTORING_SOURCE,
|
||||
}
|
||||
|
||||
const _STATE_TIMEOUT_MS : int = 20000
|
||||
|
||||
var GDSync
|
||||
var connection_controller
|
||||
var request_processor
|
||||
var session_controller
|
||||
var matchmaking_controller
|
||||
var logger
|
||||
|
||||
var state: _SwitchState = _SwitchState.IDLE
|
||||
var _state_deadline: int = 0
|
||||
var _reservation_deadline: int = 0
|
||||
var source_address: String = ""
|
||||
var destination_address: String = ""
|
||||
var reservation_id: String = ""
|
||||
var proof: String = ""
|
||||
var lobby_name: String = ""
|
||||
var connect_time: float = 0.0
|
||||
var fallback_reservation_id: String = ""
|
||||
var rollback_error: int = ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE
|
||||
var use_websocket: bool = false
|
||||
var pending_tunnel_address: String = ""
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
name = "ServerSwitchController"
|
||||
connection_controller = GDSync._connection_controller
|
||||
request_processor = GDSync._request_processor
|
||||
session_controller = GDSync._session_controller
|
||||
matchmaking_controller = GDSync._matchmaking_controller
|
||||
logger = GDSync._logger
|
||||
|
||||
|
||||
func begin(data: Dictionary) -> void:
|
||||
reset()
|
||||
source_address = str(data.get("SourceAddress", connection_controller.server_ip))
|
||||
destination_address = str(data.get("Address", ""))
|
||||
reservation_id = str(data.get("ReservationId", ""))
|
||||
proof = str(data.get("Proof", ""))
|
||||
lobby_name = str(data.get("LobbyName", ""))
|
||||
connect_time = float(data.get("ConnectTime", 0.0))
|
||||
fallback_reservation_id = str(data.get("FallbackReservationId", ""))
|
||||
use_websocket = (
|
||||
connection_controller.client is WebSocketPeer
|
||||
or connection_controller.client is WebSocketMultiplayerPeer
|
||||
or connection_controller.is_web_export
|
||||
)
|
||||
if destination_address.is_empty() or reservation_id.is_empty() or proof.is_empty():
|
||||
fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.INVALID_RESERVATION)
|
||||
return
|
||||
|
||||
var expires_in := maxf(float(data.get("ExpiresIn", 20.0)), 1.0)
|
||||
_reservation_deadline = Time.get_ticks_msec() + int(expires_in * 1000.0)
|
||||
_set_state(_SwitchState.CONNECTING_DESTINATION)
|
||||
pending_tunnel_address = destination_address
|
||||
request_processor.clear_for_server_switch()
|
||||
connection_controller.switch_server(destination_address, use_websocket)
|
||||
|
||||
|
||||
func is_active() -> bool:
|
||||
return state != _SwitchState.IDLE
|
||||
|
||||
|
||||
func _process(_delta : float) -> void:
|
||||
if state == _SwitchState.IDLE: return
|
||||
|
||||
var now : int = Time.get_ticks_msec()
|
||||
|
||||
if _reservation_deadline > 0 and now >= _reservation_deadline:
|
||||
_reservation_deadline = 0
|
||||
_timed_out(ENUMS.LOBBY_SWITCH_ERROR.RESERVATION_EXPIRED)
|
||||
return
|
||||
|
||||
if _state_deadline > 0 and now >= _state_deadline:
|
||||
_timed_out(ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE)
|
||||
|
||||
|
||||
func _set_state(new_state : _SwitchState) -> void:
|
||||
state = new_state
|
||||
|
||||
if new_state == _SwitchState.IDLE:
|
||||
_state_deadline = 0
|
||||
_reservation_deadline = 0
|
||||
return
|
||||
|
||||
_refresh_state_deadline()
|
||||
|
||||
|
||||
func _refresh_state_deadline() -> void:
|
||||
_state_deadline = Time.get_ticks_msec() + _STATE_TIMEOUT_MS
|
||||
|
||||
|
||||
func _is_rollback_state() -> bool:
|
||||
return (
|
||||
state == _SwitchState.ROLLING_BACK
|
||||
or state == _SwitchState.TUNNELING_ROLLBACK
|
||||
or state == _SwitchState.RESTORING_SOURCE
|
||||
)
|
||||
|
||||
|
||||
func _timed_out(error : int) -> void:
|
||||
logger.write_error("Server switch timed out. <"+str(_SwitchState.keys()[state])+">")
|
||||
|
||||
if _is_rollback_state():
|
||||
fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.ROLLBACK_FAILED)
|
||||
return
|
||||
|
||||
if state == _SwitchState.JOINING_DESTINATION:
|
||||
rollback(ENUMS.LOBBY_SWITCH_ERROR.JOIN_FAILED)
|
||||
return
|
||||
|
||||
rollback(error)
|
||||
|
||||
|
||||
func _should_web_tunnel() -> bool:
|
||||
return connection_controller.is_web_export
|
||||
|
||||
|
||||
func connection_secured() -> bool:
|
||||
if state == _SwitchState.CONNECTING_DESTINATION:
|
||||
if _should_web_tunnel():
|
||||
_set_state(_SwitchState.TUNNELING)
|
||||
request_processor.create_tunnel_to_request(pending_tunnel_address)
|
||||
return true
|
||||
_join_destination()
|
||||
return true
|
||||
if state == _SwitchState.TUNNELING:
|
||||
_join_destination()
|
||||
return true
|
||||
if state == _SwitchState.ROLLING_BACK:
|
||||
if _should_web_tunnel():
|
||||
_set_state(_SwitchState.TUNNELING_ROLLBACK)
|
||||
request_processor.create_tunnel_to_request(pending_tunnel_address)
|
||||
return true
|
||||
return _restore_source_after_secure()
|
||||
if state == _SwitchState.TUNNELING_ROLLBACK:
|
||||
return _restore_source_after_secure()
|
||||
return false
|
||||
|
||||
|
||||
func tunnel_ready() -> void:
|
||||
if state != _SwitchState.TUNNELING and state != _SwitchState.TUNNELING_ROLLBACK:
|
||||
return
|
||||
request_processor.clear_for_server_switch()
|
||||
_refresh_state_deadline()
|
||||
connection_controller.reset_session_keep_socket()
|
||||
|
||||
|
||||
func tunnel_local() -> void:
|
||||
if state == _SwitchState.TUNNELING:
|
||||
_join_destination()
|
||||
return
|
||||
if state == _SwitchState.TUNNELING_ROLLBACK:
|
||||
_restore_source_after_secure()
|
||||
|
||||
|
||||
func tunnel_failed() -> void:
|
||||
transport_failed()
|
||||
|
||||
|
||||
func transport_failed() -> bool:
|
||||
if state == _SwitchState.CONNECTING_DESTINATION or state == _SwitchState.JOINING_DESTINATION or state == _SwitchState.TUNNELING:
|
||||
rollback(ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE)
|
||||
return true
|
||||
if state == _SwitchState.ROLLING_BACK or state == _SwitchState.TUNNELING_ROLLBACK or state == _SwitchState.RESTORING_SOURCE:
|
||||
fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.ROLLBACK_FAILED)
|
||||
return true
|
||||
return false
|
||||
|
||||
|
||||
func lobby_joined() -> void:
|
||||
if state == _SwitchState.RESTORING_SOURCE:
|
||||
finish_rollback()
|
||||
return
|
||||
if state != _SwitchState.JOINING_DESTINATION:
|
||||
return
|
||||
if !fallback_reservation_id.is_empty():
|
||||
request_processor.create_commit_server_switch_request(
|
||||
source_address,
|
||||
fallback_reservation_id)
|
||||
reset()
|
||||
|
||||
|
||||
func lobby_join_failed() -> bool:
|
||||
if state == _SwitchState.RESTORING_SOURCE:
|
||||
fail_permanently(ENUMS.LOBBY_SWITCH_ERROR.ROLLBACK_FAILED)
|
||||
return true
|
||||
if state != _SwitchState.JOINING_DESTINATION:
|
||||
return false
|
||||
rollback(ENUMS.LOBBY_SWITCH_ERROR.JOIN_FAILED)
|
||||
return true
|
||||
|
||||
|
||||
func rollback(error: int) -> void:
|
||||
if state == _SwitchState.IDLE or _is_rollback_state():
|
||||
return
|
||||
rollback_error = error
|
||||
_reservation_deadline = 0
|
||||
_set_state(_SwitchState.ROLLING_BACK)
|
||||
pending_tunnel_address = source_address
|
||||
request_processor.clear_for_server_switch()
|
||||
connection_controller.switch_server(source_address, use_websocket)
|
||||
|
||||
|
||||
func finish_rollback() -> void:
|
||||
var error := rollback_error
|
||||
reset()
|
||||
GDSync.lobby_switch_failed.emit(error)
|
||||
matchmaking_controller.lobby_join_failed()
|
||||
|
||||
|
||||
func fail_permanently(error: int) -> void:
|
||||
var was_switching : bool = state != _SwitchState.IDLE
|
||||
reset()
|
||||
|
||||
if was_switching:
|
||||
connection_controller.reset_multiplayer(true)
|
||||
|
||||
GDSync.lobby_switch_failed.emit(error)
|
||||
matchmaking_controller.lobby_join_failed()
|
||||
|
||||
|
||||
func _join_destination() -> void:
|
||||
_set_state(_SwitchState.JOINING_DESTINATION)
|
||||
session_controller.broadcast_player_data()
|
||||
if connect_time > 0.0:
|
||||
request_processor.set_connect_time(connect_time)
|
||||
request_processor.create_join_lobby_with_ticket_request(reservation_id, proof)
|
||||
|
||||
|
||||
func _restore_source_after_secure() -> bool:
|
||||
if !fallback_reservation_id.is_empty():
|
||||
_set_state(_SwitchState.RESTORING_SOURCE)
|
||||
request_processor.create_join_lobby_with_ticket_request(fallback_reservation_id, proof)
|
||||
return true
|
||||
finish_rollback()
|
||||
return false
|
||||
|
||||
|
||||
func reset() -> void:
|
||||
_set_state(_SwitchState.IDLE)
|
||||
source_address = ""
|
||||
destination_address = ""
|
||||
reservation_id = ""
|
||||
proof = ""
|
||||
lobby_name = ""
|
||||
connect_time = 0.0
|
||||
fallback_reservation_id = ""
|
||||
rollback_error = ENUMS.LOBBY_SWITCH_ERROR.DESTINATION_UNREACHABLE
|
||||
use_websocket = false
|
||||
pending_tunnel_address = ""
|
||||
1
addons/GD-Sync/Scripts/ServerSwitchController.gd.uid
Normal file
1
addons/GD-Sync/Scripts/ServerSwitchController.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://blyo1ojsnf7au
|
||||
871
addons/GD-Sync/Scripts/SessionController.gd
Normal file
871
addons/GD-Sync/Scripts/SessionController.gd
Normal file
|
|
@ -0,0 +1,871 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
signal scene_ready
|
||||
|
||||
var request_processor
|
||||
var connection_controller
|
||||
var logger
|
||||
var GDSync
|
||||
|
||||
var current_client_id : int = -1
|
||||
var sender_id : int = -1
|
||||
var player_data : Dictionary = {}
|
||||
var lobby_data : Dictionary = {}
|
||||
|
||||
var node_path_cache : Dictionary = {}
|
||||
var node_path_index_cache : Dictionary = {}
|
||||
var name_cache : Dictionary = {}
|
||||
var name_index_cache : Dictionary = {}
|
||||
var resource_reference_cache : Dictionary = {}
|
||||
var reference_resource_cache : Dictionary = {}
|
||||
|
||||
var owner_cache : Dictionary = {}
|
||||
|
||||
var lobby_name : String = ""
|
||||
var lobby_password : String = ""
|
||||
var own_lobby : bool = false
|
||||
var synced_time : float = 0.0
|
||||
var multiplayer_clock_synced : bool = false
|
||||
var remote_time : float = 0.0
|
||||
var remote_time_counter : int = 0
|
||||
var remote_time_latency : float = 0.0
|
||||
var synced_time_cooldown : float = 0.0
|
||||
var events : Array[Dictionary] = []
|
||||
|
||||
var current_scene : Node
|
||||
var active_scene_change : String = ""
|
||||
var scene_ready_list : Array[int] = []
|
||||
var _scene_change_elapsed : float = 0.0
|
||||
var _scene_change_resolved : bool = false
|
||||
|
||||
const _SCENE_CHANGE_TIMEOUT : float = 30.0
|
||||
const _SCENE_CHANGE_CLIENT_TIMEOUT : float = 40.0
|
||||
|
||||
var ping_sessions : Dictionary = {}
|
||||
|
||||
func _ready() -> void:
|
||||
name = "SessionController"
|
||||
GDSync = get_node("/root/GDSync")
|
||||
request_processor = GDSync._request_processor
|
||||
connection_controller = GDSync._connection_controller
|
||||
logger = GDSync._logger
|
||||
|
||||
GDSync.expose_func(sync_timer)
|
||||
GDSync.expose_func(get_timer_latency)
|
||||
GDSync.expose_func(timer_latency_callback)
|
||||
GDSync.expose_func(register_event)
|
||||
GDSync.expose_func(load_scene)
|
||||
GDSync.expose_func(mark_scene_ready)
|
||||
GDSync.expose_func(switch_scene_success)
|
||||
GDSync.expose_func(switch_scene_failed)
|
||||
GDSync.expose_func(ping_send)
|
||||
GDSync.expose_func(ping_return)
|
||||
GDSync.expose_func(emit_signal_remote)
|
||||
|
||||
GDSync.client_joined.connect(client_joined)
|
||||
GDSync.client_left.connect(client_left)
|
||||
GDSync.client_id_changed.connect(client_id_changed)
|
||||
GDSync.host_changed.connect(host_changed)
|
||||
|
||||
get_tree().scene_changed.connect(_on_scene_change)
|
||||
current_scene = get_tree().current_scene
|
||||
if current_scene != null: # Harvest Season patch: no current scene in --script runs (tests, tools)
|
||||
current_scene.tree_exiting.connect(_on_old_scene_exiting)
|
||||
|
||||
randomize()
|
||||
synced_time = randf_range(0, 1000)
|
||||
|
||||
func _process(delta):
|
||||
_process_scene_change(delta)
|
||||
if !GDSync.is_active(): return
|
||||
handle_events(delta)
|
||||
|
||||
func handle_events(delta : float) -> void:
|
||||
synced_time += delta
|
||||
remote_time += delta
|
||||
|
||||
for event in events:
|
||||
if synced_time >= event["Time"]:
|
||||
GDSync.synced_event_triggered.emit(event["Name"], event["Parameters"])
|
||||
events.erase(event)
|
||||
|
||||
if !GDSync.is_active() || !GDSync.is_host(): return
|
||||
|
||||
synced_time_cooldown -= delta
|
||||
if synced_time_cooldown <= 0.0:
|
||||
synced_time_cooldown = 30.0
|
||||
GDSync.call_func(sync_timer, synced_time)
|
||||
|
||||
func sync_timer(time : float) -> void:
|
||||
remote_time = time
|
||||
remote_time_counter = 0
|
||||
remote_time_latency = 0.0
|
||||
multiplayer_clock_synced = true
|
||||
|
||||
if(abs(time - synced_time) > 0.5): synced_time = remote_time
|
||||
|
||||
for i in range(5):
|
||||
await get_tree().process_frame
|
||||
GDSync.call_func_on(GDSync.get_host(), get_timer_latency, GDSync.get_client_id(), Time.get_unix_time_from_system())
|
||||
|
||||
func get_timer_latency(client : int, timestamp : float) -> void:
|
||||
GDSync.call_func_on(client, timer_latency_callback, timestamp)
|
||||
|
||||
func timer_latency_callback(timestamp : float) -> void:
|
||||
remote_time_counter += 1
|
||||
remote_time_latency += (Time.get_unix_time_from_system()-timestamp)/2.0
|
||||
|
||||
if remote_time_counter >= 5:
|
||||
synced_time = remote_time + remote_time_latency/remote_time_counter
|
||||
|
||||
func register_event(event_name : String, time : float, parameters : Array, local : bool = false) -> void:
|
||||
events.append({
|
||||
"Name" : event_name,
|
||||
"Time" : time,
|
||||
"Parameters" : parameters
|
||||
})
|
||||
|
||||
if local:
|
||||
GDSync.call_func(register_event, event_name, time, parameters)
|
||||
|
||||
func client_id_changed(client_id : int) -> void:
|
||||
var own_data = null
|
||||
if player_data.has(current_client_id):
|
||||
own_data = player_data[current_client_id]
|
||||
player_data.erase(current_client_id)
|
||||
else:
|
||||
own_data = {
|
||||
"ID" : client_id,
|
||||
"Username" : ""
|
||||
}
|
||||
|
||||
current_client_id = client_id
|
||||
player_data[client_id] = own_data
|
||||
|
||||
func broadcast_player_data() -> void:
|
||||
var own_id : int = GDSync.get_client_id()
|
||||
GDSync.player_set_username(get_player_data(own_id, "Username", ""))
|
||||
|
||||
var own_data : Dictionary = GDSync.player_get_all_data(own_id)
|
||||
for key in own_data:
|
||||
if key != "Username":
|
||||
GDSync.player_set_data(key, own_data[key])
|
||||
|
||||
func set_lobby_data(name : String, password : String) -> void:
|
||||
synced_time = 0.0
|
||||
multiplayer_clock_synced = false
|
||||
lobby_name = name
|
||||
lobby_password = password
|
||||
|
||||
logger.register_profiler_data("lobby_name", lobby_name)
|
||||
logger.register_profiler_data("lobby_password", password)
|
||||
|
||||
func lobby_created() -> void:
|
||||
own_lobby = true
|
||||
|
||||
func lobby_left() -> void:
|
||||
var own_id = GDSync.get_client_id()
|
||||
|
||||
lobby_data.clear()
|
||||
node_path_cache.clear()
|
||||
node_path_index_cache.clear()
|
||||
name_cache.clear()
|
||||
name_index_cache.clear()
|
||||
owner_cache.clear()
|
||||
events.clear()
|
||||
sender_id = -1
|
||||
_incoming_caller_id = -1
|
||||
|
||||
lobby_name = ""
|
||||
lobby_password = ""
|
||||
own_lobby = false
|
||||
|
||||
synced_time = 0.0
|
||||
multiplayer_clock_synced = false
|
||||
request_processor.clear_unreliable_nonces()
|
||||
|
||||
if active_scene_change != "":
|
||||
logger.write_error("Scene change aborted, the lobby was left. <"+active_scene_change+">")
|
||||
switch_scene_failed()
|
||||
|
||||
for id in player_data.keys():
|
||||
if id != own_id:
|
||||
player_data.erase(id)
|
||||
|
||||
func client_joined(client_id : int) -> void:
|
||||
if client_id == GDSync.get_client_id(): return
|
||||
|
||||
if GDSync.is_host():
|
||||
synced_time_cooldown = 0.0
|
||||
|
||||
for event in events:
|
||||
GDSync.call_func_on(client_id, register_event,
|
||||
event["Name"],
|
||||
event["Time"],
|
||||
event["Parameters"]
|
||||
)
|
||||
|
||||
if active_scene_change != "":
|
||||
GDSync.call_func(load_scene, active_scene_change)
|
||||
|
||||
func client_left(id : int) -> void:
|
||||
if player_data.has(id): player_data.erase(id)
|
||||
if scene_ready_list.has(id): scene_ready_list.erase(id)
|
||||
check_scene_ready()
|
||||
|
||||
func host_changed(is_host : bool, _new_host_id : int) -> void:
|
||||
if is_host:
|
||||
multiplayer_clock_synced = true
|
||||
check_scene_ready()
|
||||
|
||||
func get_all_clients() -> Array:
|
||||
return player_data.keys()
|
||||
|
||||
func set_sender_id(id : int) -> void:
|
||||
sender_id = id
|
||||
|
||||
func get_sender_id() -> int:
|
||||
return sender_id
|
||||
|
||||
var _incoming_caller_id : int = -1
|
||||
|
||||
func begin_incoming_request(caller_id : int) -> void:
|
||||
_incoming_caller_id = caller_id
|
||||
if caller_id >= 0:
|
||||
sender_id = caller_id
|
||||
|
||||
func end_incoming_request() -> void:
|
||||
_incoming_caller_id = -1
|
||||
|
||||
func is_caller_permitted(permission : int, caller_id : int = -1) -> bool:
|
||||
if permission == ENUMS.EXPOSE_PERMISSION.ANYONE:
|
||||
return true
|
||||
if caller_id < 0:
|
||||
caller_id = _incoming_caller_id
|
||||
if caller_id < 0:
|
||||
return false
|
||||
var host_id : int = connection_controller.host
|
||||
match permission:
|
||||
ENUMS.EXPOSE_PERMISSION.HOST:
|
||||
return caller_id == host_id
|
||||
ENUMS.EXPOSE_PERMISSION.CLIENT:
|
||||
return host_id >= 0 and caller_id != host_id
|
||||
return true
|
||||
|
||||
func nodepath_is_cached(node_path : String) -> bool:
|
||||
return node_path_cache.has(node_path)
|
||||
|
||||
func name_is_cached(name : String) -> bool:
|
||||
return name_cache.has(name)
|
||||
|
||||
func get_nodepath_index(node_path : String) -> int:
|
||||
return node_path_cache[node_path]
|
||||
|
||||
func get_name_index(name : String) -> int:
|
||||
return name_cache[name]
|
||||
|
||||
func get_nodepath_from_index(index : int) -> String:
|
||||
return node_path_index_cache[index]
|
||||
|
||||
func get_name_from_index(index : int) -> String:
|
||||
return name_index_cache[index]
|
||||
|
||||
func has_nodepath_from_index(index : int) -> bool:
|
||||
return node_path_index_cache.has(index)
|
||||
|
||||
func has_name_from_index(index : int) -> bool:
|
||||
return name_index_cache.has(index)
|
||||
|
||||
func cache_nodepath(node_path : String, index : int) -> void:
|
||||
if node_path_index_cache.has(index):
|
||||
var oldCachePath : String = node_path_index_cache[index]
|
||||
node_path_cache.erase(oldCachePath)
|
||||
|
||||
node_path_cache[node_path] = index
|
||||
node_path_index_cache[index] = node_path
|
||||
|
||||
var node : Node = get_node_or_null(node_path)
|
||||
if node:
|
||||
var tree : SceneTree = get_tree()
|
||||
await node.tree_exiting
|
||||
|
||||
if !is_instance_valid(tree) or !is_instance_valid(node):
|
||||
return
|
||||
|
||||
await tree.process_frame
|
||||
await tree.process_frame
|
||||
request_processor.create_erase_nodepath_cache_request(index)
|
||||
|
||||
func erase_nodepath_cache(index : int) -> void:
|
||||
if node_path_index_cache.has(index):
|
||||
var node_path : String = node_path_index_cache[index]
|
||||
node_path_cache.erase(node_path)
|
||||
node_path_index_cache.erase(index)
|
||||
|
||||
func cache_name(name : String, index : int) -> void:
|
||||
if name_index_cache.has(index):
|
||||
var oldCachePath : String = name_index_cache[index]
|
||||
name_cache.erase(oldCachePath)
|
||||
|
||||
name_cache[name] = index
|
||||
name_index_cache[index] = name
|
||||
|
||||
func erase_name_cache(index : int) -> void:
|
||||
if name_index_cache.has(index):
|
||||
var name : String = name_index_cache[index]
|
||||
name_cache.erase(name)
|
||||
name_index_cache.erase(index)
|
||||
|
||||
func create_resource_reference(resource : RefCounted, id : String) -> void:
|
||||
reference_resource_cache[id] = resource
|
||||
resource_reference_cache[resource] = id
|
||||
|
||||
func erase_resource_reference(resource : RefCounted) -> void:
|
||||
if resource_reference_cache.has(resource):
|
||||
var id : String = resource_reference_cache[resource]
|
||||
resource_reference_cache.erase(resource)
|
||||
reference_resource_cache.erase(id)
|
||||
|
||||
func has_resource_reference(resource : RefCounted) -> bool:
|
||||
return resource_reference_cache.has(resource)
|
||||
|
||||
func get_resource_reference(resource : RefCounted) -> String:
|
||||
return resource_reference_cache[resource]
|
||||
|
||||
func has_resource_by_reference(id : String) -> bool:
|
||||
return reference_resource_cache.has(id)
|
||||
|
||||
func get_resource_by_reference(id : String) -> RefCounted:
|
||||
return reference_resource_cache[id]
|
||||
|
||||
func set_player_data(key : String, value) -> void:
|
||||
player_data[GDSync.get_client_id()][key] = value
|
||||
player_data_changed(GDSync.get_client_id(), key)
|
||||
|
||||
func player_data_changed(client_id : int, key : String) -> void:
|
||||
if !player_data.has(client_id): return
|
||||
var data : Dictionary = player_data[client_id]
|
||||
if data.has(key):
|
||||
GDSync.player_data_changed.emit(client_id, key, data[key])
|
||||
else:
|
||||
GDSync.player_data_changed.emit(client_id, key, null)
|
||||
|
||||
logger.register_profiler_data("player_data", player_data)
|
||||
|
||||
func erase_player_data(key : String) -> void:
|
||||
if player_data[GDSync.get_client_id()].has(key):
|
||||
player_data[GDSync.get_client_id()].erase(key)
|
||||
player_data_changed(GDSync.get_client_id(), key)
|
||||
|
||||
func get_player_data(client_id : int, key : String, default):
|
||||
if player_data.has(client_id):
|
||||
var data : Dictionary = player_data[client_id]
|
||||
if data.has(key):
|
||||
return data[key]
|
||||
return default
|
||||
|
||||
func has_player_data(client_id : int, key : String, default) -> bool:
|
||||
if player_data.has(client_id):
|
||||
var data : Dictionary = player_data[client_id]
|
||||
if data.has(key):
|
||||
return true
|
||||
return false
|
||||
|
||||
func get_all_player_data(client_id : int) -> Dictionary:
|
||||
if player_data.has(client_id):
|
||||
var data : Dictionary = player_data[client_id]
|
||||
return data
|
||||
return {}
|
||||
|
||||
func override_player_data(data : Dictionary) -> void:
|
||||
var id = data["ID"]
|
||||
data.erase(id)
|
||||
if player_data.has(id):
|
||||
player_data[id].clear()
|
||||
else:
|
||||
player_data[id] = {}
|
||||
|
||||
for key in data:
|
||||
player_data[id][key] = data[key]
|
||||
|
||||
func override_lobby_data(data : Dictionary) -> void:
|
||||
lobby_data = data
|
||||
logger.register_profiler_data("lobby_data", lobby_data)
|
||||
|
||||
func get_lobby_player_limit() -> int:
|
||||
if !lobby_data.has("PlayerLimit"): return 0
|
||||
return lobby_data["PlayerLimit"]
|
||||
|
||||
func get_lobby_visibility() -> bool:
|
||||
if !lobby_data.has("Public"): return false
|
||||
return lobby_data["Public"]
|
||||
|
||||
func lobby_has_password() -> bool:
|
||||
if lobby_data.has("HasPassword"):
|
||||
return lobby_data["HasPassword"]
|
||||
return false
|
||||
|
||||
func lobby_data_changed(key : String) -> void:
|
||||
if !lobby_data.has("Data"): return
|
||||
var data : Dictionary = lobby_data["Data"]
|
||||
if !data.has(key):
|
||||
GDSync.lobby_data_changed.emit(key, null)
|
||||
else:
|
||||
GDSync.lobby_data_changed.emit(key, data[key])
|
||||
|
||||
func lobby_tags_changed(key : String) -> void:
|
||||
if !lobby_data.has("Tags"): return
|
||||
var tags : Dictionary = lobby_data["Tags"]
|
||||
if !tags.has(key):
|
||||
GDSync.lobby_tag_changed.emit(key, null)
|
||||
else:
|
||||
GDSync.lobby_tag_changed.emit(key, tags[key])
|
||||
|
||||
func has_lobby_data(key : String) -> bool:
|
||||
if !lobby_data.has("Data"): return false
|
||||
var data : Dictionary = lobby_data["Data"]
|
||||
return data.has(key)
|
||||
|
||||
func has_lobby_tag(key : String) -> bool:
|
||||
if !lobby_data.has("Tags"): return false
|
||||
var tags : Dictionary = lobby_data["Tags"]
|
||||
return tags.has(key)
|
||||
|
||||
func get_lobby_data(key : String, default):
|
||||
if !lobby_data.has("Data"): return
|
||||
var data : Dictionary = lobby_data["Data"]
|
||||
if !data.has(key):
|
||||
return default
|
||||
else:
|
||||
return data[key]
|
||||
|
||||
func get_lobby_tag(key : String, default):
|
||||
if !lobby_data.has("Tags"): return
|
||||
var tags : Dictionary = lobby_data["Tags"]
|
||||
if !tags.has(key):
|
||||
return default
|
||||
else:
|
||||
return tags[key]
|
||||
|
||||
func get_all_lobby_data() -> Dictionary:
|
||||
if lobby_data.has("Data"):
|
||||
return lobby_data["Data"]
|
||||
else:
|
||||
return {}
|
||||
|
||||
func get_all_lobby_tags() -> Dictionary:
|
||||
if lobby_data.has("Tags"):
|
||||
return lobby_data["Tags"]
|
||||
else:
|
||||
return {}
|
||||
|
||||
func expose_object(object : Object) -> void:
|
||||
object.set_meta("Exposed", true)
|
||||
|
||||
func hide_object(object : Object) -> void:
|
||||
object.set_meta("Exposed", false)
|
||||
|
||||
func object_is_exposed(object : Object) -> bool:
|
||||
return object.get_meta("Exposed", false)
|
||||
|
||||
func expose_func(function : Callable, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
|
||||
var object : Object = function.get_object()
|
||||
var functionName : String = function.get_method()
|
||||
var exposedArray : Array = object.get_meta("ExposedFunctions", [])
|
||||
if !exposedArray.has(functionName):
|
||||
exposedArray.append(functionName)
|
||||
object.set_meta("ExposedFunctions", exposedArray)
|
||||
|
||||
var permissions : Dictionary = object.get_meta("ExposedFunctionPermissions", {})
|
||||
permissions[functionName] = permission
|
||||
object.set_meta("ExposedFunctionPermissions", permissions)
|
||||
|
||||
if object is GDScript:
|
||||
create_resource_reference(object, object.resource_path)
|
||||
|
||||
func hide_func(function : Callable) -> void:
|
||||
var object : Object = function.get_object()
|
||||
var functionName : String = function.get_method()
|
||||
var exposedArray : Array = object.get_meta("ExposedFunctions", [])
|
||||
if exposedArray.has(functionName): exposedArray.erase(functionName)
|
||||
var permissions : Dictionary = object.get_meta("ExposedFunctionPermissions", {})
|
||||
if permissions.has(functionName): permissions.erase(functionName)
|
||||
|
||||
func function_is_exposed(object : Object, function_name : String) -> bool:
|
||||
var exposedArray : Array = object.get_meta("ExposedFunctions", [])
|
||||
return exposedArray.has(function_name)
|
||||
|
||||
func get_function_permission(object : Object, function_name : String) -> int:
|
||||
return object.get_meta("ExposedFunctionPermissions", {}).get(function_name, ENUMS.EXPOSE_PERMISSION.ANYONE)
|
||||
|
||||
func expose_signal(target_signal : Signal, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
|
||||
var object : Object = target_signal.get_object()
|
||||
var signal_name : StringName = target_signal.get_name()
|
||||
var exposedArray : Array = object.get_meta("ExposedSignals", [])
|
||||
if !exposedArray.has(signal_name):
|
||||
exposedArray.append(signal_name)
|
||||
object.set_meta("ExposedSignals", exposedArray)
|
||||
|
||||
var permissions : Dictionary = object.get_meta("ExposedSignalPermissions", {})
|
||||
permissions[signal_name] = permission
|
||||
object.set_meta("ExposedSignalPermissions", permissions)
|
||||
|
||||
func signal_is_exposed(object : Object, signal_name : StringName) -> bool:
|
||||
var exposedArray : Array = object.get_meta("ExposedSignals", [])
|
||||
return exposedArray.has(signal_name)
|
||||
|
||||
func get_signal_permission(object : Object, signal_name : StringName) -> int:
|
||||
return object.get_meta("ExposedSignalPermissions", {}).get(signal_name, ENUMS.EXPOSE_PERMISSION.ANYONE)
|
||||
|
||||
func hide_signal(target_signal : Signal) -> void:
|
||||
var exposedArray : Array = target_signal.get_object().get_meta("ExposedSignals", [])
|
||||
var signal_name : StringName = target_signal.get_name()
|
||||
if exposedArray.has(signal_name): exposedArray.erase(signal_name)
|
||||
var permissions : Dictionary = target_signal.get_object().get_meta("ExposedSignalPermissions", {})
|
||||
if permissions.has(signal_name): permissions.erase(signal_name)
|
||||
|
||||
func expose_property(object : Object, property_name : String, permission : int = ENUMS.EXPOSE_PERMISSION.ANYONE) -> void:
|
||||
var exposedArray : Array = object.get_meta("ExposedProperties", [])
|
||||
if !exposedArray.has(property_name):
|
||||
exposedArray.append(property_name)
|
||||
object.set_meta("ExposedProperties", exposedArray)
|
||||
|
||||
var permissions : Dictionary = object.get_meta("ExposedPropertyPermissions", {})
|
||||
permissions[property_name] = permission
|
||||
object.set_meta("ExposedPropertyPermissions", permissions)
|
||||
|
||||
func hide_property(object : Object, propertyName : String) -> void:
|
||||
var exposedArray : Array = object.get_meta("ExposedProperties", [])
|
||||
if exposedArray.has(propertyName): exposedArray.erase(propertyName)
|
||||
var permissions : Dictionary = object.get_meta("ExposedPropertyPermissions", {})
|
||||
if permissions.has(propertyName): permissions.erase(propertyName)
|
||||
|
||||
func property_is_exposed(object : Object, propertyName : String) -> bool:
|
||||
var exposedArray : Array = object.get_meta("ExposedProperties", [])
|
||||
return exposedArray.has(propertyName)
|
||||
|
||||
func get_property_permission(object : Object, property_name : String) -> int:
|
||||
return object.get_meta("ExposedPropertyPermissions", {}).get(property_name, ENUMS.EXPOSE_PERMISSION.ANYONE)
|
||||
|
||||
func set_gdsync_owner(node : Node, owner) -> void:
|
||||
if owner == null:
|
||||
owner = -1
|
||||
if node.get_meta("gdsyncOwner", -1) == owner:
|
||||
return
|
||||
set_gdsync_owner_remote(node, owner)
|
||||
request_processor.set_gdsync_owner(node, owner)
|
||||
|
||||
func set_gdsync_owner_remote(node : Node, owner) -> void:
|
||||
if owner == null:
|
||||
owner = -1
|
||||
var previous_owner = node.get_meta("gdsyncOwner", -1)
|
||||
if previous_owner == owner:
|
||||
return
|
||||
|
||||
var path_string : String = str(node.get_path())
|
||||
if owner_cache.has(path_string): owner_cache.erase(path_string)
|
||||
|
||||
node.set_meta("gdsyncOwner", owner)
|
||||
emit_gdsync_owner_changed(node, owner)
|
||||
|
||||
func set_gdsync_owner_delayed(node_path : String, owner) -> void:
|
||||
owner_cache[node_path] = owner
|
||||
|
||||
await get_tree().process_frame
|
||||
|
||||
set_from_owner_cache(node_path)
|
||||
|
||||
func set_from_owner_cache(node_path : String) -> void:
|
||||
if !owner_cache.has(node_path): return
|
||||
var owner = owner_cache[node_path]
|
||||
var node : Node = get_node_or_null(node_path)
|
||||
owner_cache.erase(node_path)
|
||||
if node == null: return
|
||||
set_gdsync_owner_remote(node, owner)
|
||||
|
||||
func emit_gdsync_owner_changed(node : Node, owner) -> void:
|
||||
if node.has_user_signal("gdsync_owner_changed"): node.emit_signal("gdsync_owner_changed", owner)
|
||||
for child in node.get_children():
|
||||
emit_gdsync_owner_changed(child, owner)
|
||||
|
||||
func get_gdsync_owner(node : Node) -> int:
|
||||
if node.is_inside_tree():
|
||||
var path_string : String = str(node.get_path())
|
||||
if owner_cache.has(path_string):
|
||||
set_gdsync_owner_remote(node, owner_cache[path_string])
|
||||
|
||||
var ownerID : int = -1
|
||||
var p : Node = node
|
||||
while p != null and ownerID < 0:
|
||||
if p.has_meta("gdsyncOwner"):
|
||||
var id = p.get_meta("gdsyncOwner", null)
|
||||
if id != null: ownerID = id
|
||||
p = p.get_parent()
|
||||
return ownerID
|
||||
|
||||
func is_gdsync_owner(node : Node) -> bool:
|
||||
return get_gdsync_owner(node) == GDSync.get_client_id()
|
||||
|
||||
func connect_gdsync_owner_changed(node : Node, callable : Callable) -> void:
|
||||
if !node.has_user_signal("gdsync_owner_changed"):
|
||||
node.add_user_signal("gdsync_owner_changed", ["owner"])
|
||||
node.connect("gdsync_owner_changed", callable)
|
||||
|
||||
func disconnect_gdsync_owner_changed(node : Node, callable : Callable) -> void:
|
||||
node.disconnect("gdsync_owner_changed", callable)
|
||||
|
||||
func _on_scene_change() -> void:
|
||||
request_processor.end_scene_swap()
|
||||
current_scene = get_tree().current_scene
|
||||
current_scene.tree_exiting.connect(_on_old_scene_exiting)
|
||||
|
||||
func _on_old_scene_exiting() -> void:
|
||||
current_scene.tree_exiting.disconnect(_on_old_scene_exiting)
|
||||
request_processor.begin_scene_swap()
|
||||
|
||||
func change_scene(scene_path : String) -> void:
|
||||
GDSync.call_func(load_scene, scene_path)
|
||||
load_scene(scene_path)
|
||||
|
||||
func load_scene(scene_path : String) -> void:
|
||||
if active_scene_change != "":
|
||||
push_error("Another scene change is already in progress.")
|
||||
return
|
||||
|
||||
scene_ready_list.clear()
|
||||
active_scene_change = scene_path
|
||||
_scene_change_elapsed = 0.0
|
||||
_scene_change_resolved = false
|
||||
GDSync.change_scene_called.emit(scene_path)
|
||||
|
||||
var tree : SceneTree = get_tree()
|
||||
var packed_scene : PackedScene = await load_resource_threaded(tree, scene_path)
|
||||
var new_scene : Node = await instantiate_threaded(tree, packed_scene)
|
||||
|
||||
if new_scene == null:
|
||||
GDSync.call_func(switch_scene_failed)
|
||||
switch_scene_failed()
|
||||
return
|
||||
|
||||
if scene_path != active_scene_change:
|
||||
new_scene.queue_free()
|
||||
return
|
||||
|
||||
var own_id : int = GDSync.get_client_id()
|
||||
GDSync.call_func(mark_scene_ready, own_id)
|
||||
mark_scene_ready(own_id)
|
||||
|
||||
await scene_ready
|
||||
if scene_path != active_scene_change:
|
||||
new_scene.queue_free()
|
||||
return
|
||||
|
||||
var old_scene : Node = tree.current_scene
|
||||
|
||||
new_scene.tree_entered.connect(
|
||||
func set_current_scene() -> void:
|
||||
tree.current_scene = new_scene
|
||||
)
|
||||
|
||||
tree.root.add_child(new_scene)
|
||||
tree.root.remove_child(old_scene)
|
||||
old_scene.free()
|
||||
|
||||
tree.current_scene = new_scene
|
||||
|
||||
active_scene_change = ""
|
||||
request_processor.end_scene_swap()
|
||||
|
||||
func _process_scene_change(delta : float) -> void:
|
||||
if active_scene_change == "" or _scene_change_resolved: return
|
||||
|
||||
if !GDSync.is_active():
|
||||
logger.write_error("Scene change aborted, the connection was lost. <"+active_scene_change+">")
|
||||
switch_scene_failed()
|
||||
return
|
||||
|
||||
_scene_change_elapsed += delta
|
||||
var timeout : float = _SCENE_CHANGE_TIMEOUT if GDSync.is_host() else _SCENE_CHANGE_CLIENT_TIMEOUT
|
||||
if _scene_change_elapsed < timeout: return
|
||||
|
||||
logger.write_error("Scene change timed out, not all clients reported ready. <"+active_scene_change+">")
|
||||
if GDSync.is_host(): GDSync.call_func(switch_scene_failed)
|
||||
switch_scene_failed()
|
||||
|
||||
func mark_scene_ready(client_id : int) -> void:
|
||||
if active_scene_change == "": return
|
||||
if !scene_ready_list.has(client_id): scene_ready_list.append(client_id)
|
||||
check_scene_ready()
|
||||
|
||||
func check_scene_ready() -> void:
|
||||
if active_scene_change == "" or _scene_change_resolved: return
|
||||
if !GDSync.is_host(): return
|
||||
|
||||
for client in get_all_clients():
|
||||
if !scene_ready_list.has(client): return
|
||||
|
||||
GDSync.call_func(switch_scene_success)
|
||||
switch_scene_success()
|
||||
|
||||
func switch_scene_success() -> void:
|
||||
if active_scene_change == "": return
|
||||
_scene_change_resolved = true
|
||||
scene_ready_list.clear()
|
||||
GDSync.change_scene_success.emit(active_scene_change)
|
||||
request_processor.begin_scene_swap()
|
||||
scene_ready.emit.call_deferred()
|
||||
|
||||
func switch_scene_failed() -> void:
|
||||
if active_scene_change == "": return
|
||||
var scene_path : String = active_scene_change
|
||||
_scene_change_resolved = true
|
||||
scene_ready_list.clear()
|
||||
active_scene_change = ""
|
||||
request_processor.cancel_scene_swap()
|
||||
GDSync.change_scene_failed.emit(scene_path)
|
||||
scene_ready.emit.call_deferred()
|
||||
|
||||
func load_resource_threaded(tree : SceneTree, path : String) -> Resource:
|
||||
if connection_controller.is_web_export:
|
||||
return load(path)
|
||||
else:
|
||||
if ResourceLoader.load_threaded_request(path) == OK:
|
||||
while ResourceLoader.load_threaded_get_status(path) == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_IN_PROGRESS:
|
||||
await tree.create_timer(0.05).timeout
|
||||
|
||||
if ResourceLoader.load_threaded_get_status(path) == ResourceLoader.ThreadLoadStatus.THREAD_LOAD_LOADED:
|
||||
return ResourceLoader.load_threaded_get(path)
|
||||
|
||||
return null
|
||||
|
||||
func instantiate_threaded(tree : SceneTree, packed_scene : PackedScene) -> Node:
|
||||
if packed_scene == null: return null
|
||||
|
||||
if connection_controller.is_web_export:
|
||||
return packed_scene.instantiate()
|
||||
else:
|
||||
var thread : Thread = Thread.new()
|
||||
|
||||
var callable : Callable = func instantiate(packed_scene : PackedScene):
|
||||
return packed_scene.instantiate()
|
||||
|
||||
thread.start(
|
||||
callable.bind(packed_scene)
|
||||
)
|
||||
|
||||
while thread.is_alive():
|
||||
await tree.create_timer(0.02).timeout
|
||||
|
||||
return thread.wait_to_finish()
|
||||
|
||||
func emit_signal_on_clients(clients : Array, target_signal : Signal, params : Array) -> void:
|
||||
var id : String
|
||||
var object : Object = target_signal.get_object()
|
||||
var signal_name : StringName = target_signal.get_name()
|
||||
|
||||
if object is Node:
|
||||
id = String(object.get_path())
|
||||
|
||||
for i in range(10):
|
||||
if object.has_meta("PauseSync"):
|
||||
await get_tree().process_frame
|
||||
elif object is RefCounted:
|
||||
if !has_resource_reference(object):
|
||||
logger.write_error("Creating emit signal request failed, the Resource was not registered. <"+str(object)+"><"+signal_name+">")
|
||||
push_error("Resource must be registered using GDSync.register_resource()")
|
||||
return
|
||||
|
||||
for client in clients:
|
||||
if client == GDSync.get_client_id():
|
||||
emit_signal_remote(id, signal_name, params)
|
||||
else:
|
||||
var permission : int = get_signal_permission(object, signal_name)
|
||||
request_processor.create_function_call_request(emit_signal_remote, [id, signal_name, params], client, true, permission)
|
||||
|
||||
func emit_signal_remote(id : String, signal_name : String, params : Array) -> void:
|
||||
var object : Object
|
||||
if has_resource_by_reference(id):
|
||||
object = get_resource_by_reference(id)
|
||||
else:
|
||||
object = get_node_or_null(id)
|
||||
|
||||
if object == null:
|
||||
logger.write_error("Emit signal failed since the Node or Resource was not found. <"+String(id)+"><"+signal_name+">")
|
||||
push_error("Attempted to call nonexistent function \""+signal_name+"\" on "+String(id))
|
||||
return
|
||||
|
||||
if connection_controller.PROTECTED:
|
||||
if !object_is_exposed(object) and !signal_is_exposed(object, signal_name):
|
||||
logger.write_error("Emit signal failed since the object or signal was not exposed. <"+id+"><"+signal_name+">")
|
||||
push_error("Attempted to emit a protected signal \""+signal_name+"\" on "+id+", please expose it using GDSync.expose_signal() or GDSync.expose_node()/GDSync.expose_resource().")
|
||||
return
|
||||
if !object_is_exposed(object):
|
||||
if !is_caller_permitted(get_signal_permission(object, signal_name)):
|
||||
return
|
||||
|
||||
if !object.has_signal(signal_name):
|
||||
logger.write_error("Emit signal failed since the Node or Resource does not contain the specified signal. <"+String(id)+"><"+signal_name+">")
|
||||
push_error("Attempted to emit nonexistent signal \""+signal_name+"\" on "+String(id))
|
||||
return
|
||||
|
||||
var signal_data : Array = [signal_name]
|
||||
signal_data.append_array(params)
|
||||
object.callv("emit_signal", signal_data)
|
||||
|
||||
func get_ping(client_id : int, remove_frame_latency : bool) -> float:
|
||||
var rng : RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
rng.randomize()
|
||||
var session_id : int = rng.randi()
|
||||
|
||||
var session_data : Dictionary = {"ping" : 0.0, "count" : 0}
|
||||
ping_sessions[session_id] = session_data
|
||||
|
||||
for i in range(5):
|
||||
var time : float = Time.get_ticks_msec()/1000.0
|
||||
GDSync.call_func_on(client_id, ping_send, GDSync.get_client_id(), session_id, time+(1.0/Engine.get_frames_per_second()) if remove_frame_latency else time, remove_frame_latency)
|
||||
await get_tree().create_timer(0.02).timeout
|
||||
|
||||
for i in range(5):
|
||||
await get_tree().create_timer(0.1).timeout
|
||||
if session_data["count"] == 5: break
|
||||
|
||||
ping_sessions.erase(session_id)
|
||||
|
||||
if session_data["count"] == 0:
|
||||
return -1
|
||||
else:
|
||||
return session_data["ping"]/float(session_data["count"])
|
||||
|
||||
func ping_send(origin_client : int, session_id : int, time : float, remove_frame_latency : bool) -> void:
|
||||
GDSync.call_func_on(origin_client, ping_return, session_id, time+(1.0/Engine.get_frames_per_second()) if remove_frame_latency else time, remove_frame_latency)
|
||||
|
||||
func ping_return(session_id : int, time : float, remove_frame_latency : bool) -> void:
|
||||
if !ping_sessions.has(session_id): return
|
||||
var ping : float = Time.get_ticks_msec()/1000.0 - (time+(1.0/Engine.get_frames_per_second())) if remove_frame_latency else Time.get_ticks_msec()/1000.0 - time
|
||||
var session_data : Dictionary = ping_sessions[session_id]
|
||||
session_data["count"] = session_data["count"] + 1
|
||||
session_data["ping"] = session_data["ping"] + ping
|
||||
1
addons/GD-Sync/Scripts/SessionController.gd.uid
Normal file
1
addons/GD-Sync/Scripts/SessionController.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bjit187f25lrk
|
||||
138
addons/GD-Sync/Scripts/Steam.gd
Normal file
138
addons/GD-Sync/Scripts/Steam.gd
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
extends Node
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
var GDSync
|
||||
var data_controller
|
||||
var session_controller
|
||||
|
||||
var steam_integration_enabled : bool = false
|
||||
var steam
|
||||
|
||||
var steam_lobby_id : int = 0
|
||||
|
||||
func _ready() -> void:
|
||||
name = "Steam"
|
||||
GDSync = get_node("/root/GDSync")
|
||||
data_controller = GDSync._data_controller
|
||||
session_controller = GDSync._session_controller
|
||||
|
||||
steam_integration_enabled = Engine.has_singleton("Steam")
|
||||
if steam_integration_enabled: init_steam()
|
||||
|
||||
func init_steam() -> void:
|
||||
steam = Engine.get_singleton("Steam")
|
||||
|
||||
steam.join_requested.connect(_on_lobby_join_requested)
|
||||
|
||||
GDSync.lobby_joined.connect(lobby_joined)
|
||||
|
||||
func steam_initialized() -> bool:
|
||||
return steam_integration_enabled and steam.loggedOn()
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if steam_integration_enabled:
|
||||
steam.run_callbacks()
|
||||
|
||||
func link_steam_account() -> int:
|
||||
if !steam_initialized():
|
||||
return ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
|
||||
|
||||
var ticket_code : int = steam.getAuthTicketForWebApi("gdsync")
|
||||
|
||||
if ticket_code == 0:
|
||||
return ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
|
||||
|
||||
var ticket : Array = await steam.get_ticket_for_web_api
|
||||
|
||||
if ticket.size() == 0:
|
||||
return ENUMS.LINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
|
||||
|
||||
var rawTicket : PackedByteArray = ticket[3]
|
||||
var result : int = await data_controller.link_steam_account(rawTicket, steam.getAppID())
|
||||
|
||||
steam.cancelAuthTicket(ticket_code)
|
||||
|
||||
return result
|
||||
|
||||
func unlink_steam_account() -> int:
|
||||
if !steam_initialized():
|
||||
return ENUMS.UNLINK_STEAM_ACCOUNT_RESPONSE_CODE.STEAM_ERROR
|
||||
|
||||
return await data_controller.unlink_steam_account()
|
||||
|
||||
func steam_login(valid_time : float) -> Dictionary:
|
||||
if !steam_initialized():
|
||||
return {"Code" : ENUMS.STEAM_LOGIN_RESPONSE_CODE.STEAM_ERROR}
|
||||
|
||||
var ticket_code : int = steam.getAuthTicketForWebApi("gdsync")
|
||||
|
||||
if ticket_code == 0:
|
||||
return {"Code" : ENUMS.STEAM_LOGIN_RESPONSE_CODE.STEAM_ERROR}
|
||||
|
||||
var ticket : Array = await steam.get_ticket_for_web_api
|
||||
|
||||
if ticket.size() == 0:
|
||||
return {"Code" : ENUMS.STEAM_LOGIN_RESPONSE_CODE.STEAM_ERROR}
|
||||
|
||||
var rawTicket : PackedByteArray = ticket[3]
|
||||
var result : Dictionary = await data_controller.steam_login(rawTicket, steam.getAppID(), valid_time)
|
||||
|
||||
steam.cancelAuthTicket(ticket_code)
|
||||
|
||||
return result
|
||||
|
||||
func create_steam_lobby() -> void:
|
||||
if !steam_initialized(): return
|
||||
steam.createLobby(steam.LOBBY_TYPE_FRIENDS_ONLY, 250)
|
||||
|
||||
var result : Array = await steam.lobby_created
|
||||
|
||||
if result[0] == 1:
|
||||
steam_lobby_id = result[1]
|
||||
|
||||
steam.setLobbyJoinable(steam_lobby_id, true)
|
||||
steam.setLobbyData(steam_lobby_id, "gdsyncid", session_controller.lobby_name)
|
||||
steam.setLobbyData(steam_lobby_id, "haspassword", str(session_controller.lobby_password != ""))
|
||||
|
||||
func leave_steam_lobby() -> void:
|
||||
if !steam_initialized(): return
|
||||
steam.leaveLobby(steam_lobby_id)
|
||||
steam_lobby_id = 0
|
||||
|
||||
func _on_lobby_join_requested(lobby_id: int, friend_id: int) -> void:
|
||||
var owner_name : String = steam.getFriendPersonaName(friend_id)
|
||||
|
||||
steam.requestLobbyData(lobby_id)
|
||||
await steam.lobby_data_update
|
||||
|
||||
var lobby_name : String = steam.getLobbyData(lobby_id, "gdsyncid")
|
||||
var has_password : bool = steam.getLobbyData(lobby_id, "haspassword") == "true"
|
||||
|
||||
GDSync.steam_join_request.emit(lobby_name, has_password)
|
||||
|
||||
func lobby_joined(lobby_name : String) -> void:
|
||||
if session_controller.own_lobby:
|
||||
create_steam_lobby()
|
||||
1
addons/GD-Sync/Scripts/Steam.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Steam.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://dtlmxw5k7qdqa
|
||||
412
addons/GD-Sync/Scripts/Types/InterestObject.gd
Normal file
412
addons/GD-Sync/Scripts/Types/InterestObject.gd
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/InterestObject.png")
|
||||
extends Node
|
||||
class_name InterestObject
|
||||
|
||||
# Copyright (c) 2023-present GD-Sync.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source form, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# 2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
# SUCH DAMAGE.
|
||||
|
||||
## Makes a synchronized entity send its state only to nearby players instead of
|
||||
## to everyone. This is the main tool for scaling large worlds without wasting bandwidth.
|
||||
## [br][br]Add one InterestObject to every entity you want filtered. That includes players, enemies,
|
||||
## projectiles, vehicles, and so on. Players also need an [InterestViewer] so the host
|
||||
## knows where they are for distance checks. Spawning is never affected.
|
||||
## [NodeInstantiator] always reaches everyone.
|
||||
|
||||
signal client_entered(client_id : int)
|
||||
signal client_exited(client_id : int)
|
||||
|
||||
## Turns range-based filtering on or off for this entity.
|
||||
## [br][br]When off, "relevant" calls behave like normal GD-Sync calls and reach every player.
|
||||
## Turning this off never affects spawning.
|
||||
@export var enabled : bool = true :
|
||||
set(value):
|
||||
enabled = value
|
||||
_force_interest_report()
|
||||
## The Node whose position is used as the center of this object.
|
||||
## [br][br]Leave this empty to use this node's parent. It must be a [Node2D] or [Node3D].
|
||||
## Every synchronizer inside this entity shares this one InterestObject.
|
||||
@export var target : NodePath :
|
||||
set(value):
|
||||
target = value
|
||||
_force_interest_report()
|
||||
## How far away a player can be and still receive this object's state, in world units (pixels in 2D, meters in 3D).
|
||||
## [br][br]The host compares this radius against each player's [InterestViewer] position.
|
||||
## Use a larger value for big or important objects, and a smaller one for minor props.
|
||||
@export_range(0.0, 1000000.0, 0.1, "or_greater", "suffix:m") var visibility_radius : float = 100.0 :
|
||||
set(value):
|
||||
visibility_radius = value
|
||||
_force_interest_report()
|
||||
## Extra distance a player can drift past the radius before this object stops sending to them.
|
||||
## [br][br]This stops the object from rapidly starting and stopping updates when a player lingers
|
||||
## right at the edge of [member visibility_radius]. Players still have to come within the normal
|
||||
## radius to start receiving; they only stop once they move beyond the radius plus this margin.
|
||||
@export_range(0.0, 1000000.0, 0.1, "or_greater", "suffix:m") var exit_margin : float = 10.0 :
|
||||
set(value):
|
||||
exit_margin = value
|
||||
_force_interest_report()
|
||||
## Which categories this object belongs to.
|
||||
## [br][br]A player receives this object only if their [member InterestViewer.interest_layers]
|
||||
## shares at least one enabled layer. Use layers to separate things like world objects,
|
||||
## indoor areas, teams, or spectator-only content.
|
||||
@export_flags_3d_physics var interest_layers : int = 1 :
|
||||
set(value):
|
||||
interest_layers = value
|
||||
_force_interest_report()
|
||||
## How many times per second this object rechecks its position to update who is in range.
|
||||
## [br][br]Higher values keep the list of nearby players more up to date as the object moves,
|
||||
## at a small bandwidth cost. This is ignored when [member is_static] is enabled.
|
||||
@export_range(1.0, 30.0, 1.0, "or_greater") var update_rate : float = 5.0
|
||||
## Keeps the host receiving this object's state even when the host is out of range.
|
||||
## [br][br]Enable this when the host runs authoritative logic such as physics, validation, or
|
||||
## anti-cheat and needs every object's state at all times. Disable it when the host is just
|
||||
## another player that doesn't need distant objects. Position reports still reach the host either way.
|
||||
@export var host_receives_state : bool = true :
|
||||
set(value):
|
||||
host_receives_state = value
|
||||
_force_interest_report()
|
||||
## Marks this object as never moving, so it stops re-reporting its position after the first setup.
|
||||
## [br][br]Ideal for buildings, pickups, and other fixed props; players moving in and out of range
|
||||
## are still handled correctly. Leave this off for anything that can move, such as players,
|
||||
## enemies, vehicles, or projectiles.
|
||||
@export var is_static : bool = false :
|
||||
set(value):
|
||||
is_static = value
|
||||
_force_interest_report()
|
||||
## Hides this entity's parent on your client when you are out of range.
|
||||
## [br][br]Works when the parent is a [Node2D], [Node3D], or other [CanvasItem].
|
||||
## Does nothing on nodes that cannot be hidden. Your own owned entities are never hidden.
|
||||
@export var hide_parent_out_of_range : bool = false :
|
||||
set(value):
|
||||
hide_parent_out_of_range = value
|
||||
notify_property_list_changed()
|
||||
_update_parent_visibility()
|
||||
## How long to wait before showing the parent again after you come back in range.
|
||||
## [br][br]Only used when [member hide_parent_out_of_range] is enabled. This gives synchronized
|
||||
## state time to catch up so the object does not flash at its old position for a frame.
|
||||
var show_parent_delay : float = 0.1 :
|
||||
set(value):
|
||||
show_parent_delay = value
|
||||
|
||||
var GDSync
|
||||
var _recipients : Array[int] = []
|
||||
var _cooldown : float = 0.0
|
||||
var _force_report : bool = true
|
||||
var _last_position : Vector3 = Vector3.INF
|
||||
var _last_authority : int = -1
|
||||
var _last_settings_hash : int = 0
|
||||
var _hid_parent : bool = false
|
||||
var _show_parent_token : int = 0
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
if Engine.is_editor_hint():
|
||||
set_process(false)
|
||||
update_configuration_warnings()
|
||||
return
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
add_to_group("_gdsync_interest")
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
GDSync._interest_manager.apply_cached_recipients(self)
|
||||
_force_interest_report()
|
||||
_update_parent_visibility()
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
if Engine.is_editor_hint():
|
||||
return
|
||||
_cancel_scheduled_show()
|
||||
_show_parent_now()
|
||||
if GDSync == null or _last_authority < 0:
|
||||
return
|
||||
GDSync._interest_manager.unregister_object(str(get_path()), _last_authority)
|
||||
|
||||
|
||||
func _process(delta : float) -> void:
|
||||
if !GDSync.is_active():
|
||||
return
|
||||
if is_static and !_force_report:
|
||||
return
|
||||
|
||||
var authority_id := _get_authority()
|
||||
if !enabled:
|
||||
if _last_authority == GDSync.get_client_id():
|
||||
GDSync._interest_manager.unregister_object(str(get_path()), _last_authority)
|
||||
_last_authority = -1
|
||||
_recipients.clear()
|
||||
_update_parent_visibility()
|
||||
return
|
||||
if authority_id != GDSync.get_client_id():
|
||||
return
|
||||
|
||||
_cooldown -= delta
|
||||
if !_force_report and _cooldown > 0.0:
|
||||
return
|
||||
_cooldown = 1.0 / maxf(update_rate, 1.0)
|
||||
|
||||
var target_node := _get_target()
|
||||
if target_node == null:
|
||||
return
|
||||
var object_dimension := _get_dimension(target_node)
|
||||
if object_dimension == 0:
|
||||
return
|
||||
var current_position := _get_position(target_node)
|
||||
var settings_hash := hash([
|
||||
object_dimension,
|
||||
visibility_radius,
|
||||
exit_margin,
|
||||
interest_layers,
|
||||
host_receives_state,
|
||||
])
|
||||
if (
|
||||
!_force_report
|
||||
and current_position.is_equal_approx(_last_position)
|
||||
and authority_id == _last_authority
|
||||
and settings_hash == _last_settings_hash
|
||||
):
|
||||
return
|
||||
|
||||
_force_report = false
|
||||
_last_position = current_position
|
||||
_last_authority = authority_id
|
||||
_last_settings_hash = settings_hash
|
||||
GDSync._interest_manager.report_object(
|
||||
str(get_path()),
|
||||
authority_id,
|
||||
current_position,
|
||||
object_dimension,
|
||||
visibility_radius,
|
||||
exit_margin,
|
||||
interest_layers,
|
||||
host_receives_state
|
||||
)
|
||||
|
||||
|
||||
func _is_gdsync_interest_object_enabled() -> bool:
|
||||
return enabled and GDSync != null and GDSync.is_active()
|
||||
|
||||
|
||||
func _get_gdsync_interest_object_recipients() -> Array[int]:
|
||||
return _recipients
|
||||
|
||||
|
||||
func _set_gdsync_interest_object_recipients(recipients : Array) -> void:
|
||||
var updated : Array[int] = []
|
||||
for client_id in recipients:
|
||||
updated.append(int(client_id))
|
||||
|
||||
for client_id in updated:
|
||||
if !_recipients.has(client_id):
|
||||
client_entered.emit(client_id)
|
||||
if client_id == GDSync.get_client_id():
|
||||
_notify_synchronized_nodes("_interest_object_local_entered", client_id)
|
||||
elif _last_authority == GDSync.get_client_id():
|
||||
_notify_synchronized_nodes("_interest_object_client_entered", client_id)
|
||||
for client_id in _recipients:
|
||||
if !updated.has(client_id):
|
||||
client_exited.emit(client_id)
|
||||
if client_id != GDSync.get_client_id() and _last_authority == GDSync.get_client_id():
|
||||
_notify_synchronized_nodes("_interest_object_client_exited", client_id)
|
||||
_recipients = updated
|
||||
_update_parent_visibility()
|
||||
|
||||
|
||||
func _update_parent_visibility() -> void:
|
||||
if Engine.is_editor_hint() or GDSync == null or !GDSync.is_active():
|
||||
return
|
||||
|
||||
if !hide_parent_out_of_range or !enabled:
|
||||
_restore_parent_visibility()
|
||||
return
|
||||
|
||||
var parent_node := get_parent()
|
||||
if parent_node == null or !_can_hide_node(parent_node):
|
||||
return
|
||||
|
||||
if _get_authority() == GDSync.get_client_id():
|
||||
_restore_parent_visibility()
|
||||
return
|
||||
|
||||
var in_range := _recipients.has(GDSync.get_client_id())
|
||||
if in_range:
|
||||
if _hid_parent:
|
||||
_schedule_show_parent()
|
||||
else:
|
||||
_cancel_scheduled_show()
|
||||
_hide_parent_now()
|
||||
|
||||
|
||||
func _hide_parent_now() -> void:
|
||||
var parent_node := get_parent()
|
||||
if parent_node == null or !_can_hide_node(parent_node):
|
||||
return
|
||||
if !_hid_parent:
|
||||
_set_node_visible(parent_node, false)
|
||||
_hid_parent = true
|
||||
|
||||
|
||||
func _schedule_show_parent() -> void:
|
||||
_show_parent_token += 1
|
||||
var token := _show_parent_token
|
||||
var delay := maxf(show_parent_delay, 0.0)
|
||||
if delay <= 0.0:
|
||||
_show_parent_now()
|
||||
return
|
||||
_await_show_parent(token, delay)
|
||||
|
||||
|
||||
func _await_show_parent(token : int, delay : float) -> void:
|
||||
await get_tree().create_timer(delay).timeout
|
||||
if token != _show_parent_token:
|
||||
return
|
||||
if GDSync == null or !GDSync.is_active() or !hide_parent_out_of_range or !enabled:
|
||||
return
|
||||
if _get_authority() == GDSync.get_client_id():
|
||||
return
|
||||
if !_recipients.has(GDSync.get_client_id()):
|
||||
return
|
||||
_show_parent_now()
|
||||
|
||||
|
||||
func _cancel_scheduled_show() -> void:
|
||||
_show_parent_token += 1
|
||||
|
||||
|
||||
func _show_parent_now() -> void:
|
||||
if !_hid_parent:
|
||||
return
|
||||
var parent_node := get_parent()
|
||||
if parent_node != null and _can_hide_node(parent_node):
|
||||
_set_node_visible(parent_node, true)
|
||||
_hid_parent = false
|
||||
|
||||
|
||||
func _restore_parent_visibility() -> void:
|
||||
_cancel_scheduled_show()
|
||||
_show_parent_now()
|
||||
|
||||
|
||||
func _can_hide_node(node : Node) -> bool:
|
||||
return node is CanvasItem or node is Node3D
|
||||
|
||||
|
||||
func _set_node_visible(node : Node, visible : bool) -> void:
|
||||
if node is CanvasItem:
|
||||
(node as CanvasItem).visible = visible
|
||||
elif node is Node3D:
|
||||
(node as Node3D).visible = visible
|
||||
|
||||
|
||||
func _force_interest_report() -> void:
|
||||
_force_report = true
|
||||
_cooldown = 0.0
|
||||
|
||||
|
||||
func _notify_synchronized_nodes(method : StringName, client_id : int) -> void:
|
||||
var branch := get_parent()
|
||||
var candidates : Array[Node] = [branch]
|
||||
candidates.append_array(branch.find_children("*", "", true, false))
|
||||
for candidate in candidates:
|
||||
if (
|
||||
candidate.has_method(method)
|
||||
and GDSync._interest_manager.get_interest_object(candidate) == self
|
||||
):
|
||||
candidate.call(method, client_id)
|
||||
|
||||
|
||||
func _get_authority() -> int:
|
||||
var owner_id : int = GDSync.get_gdsync_owner(self)
|
||||
if owner_id >= 0 and GDSync.lobby_get_all_clients().has(owner_id):
|
||||
return owner_id
|
||||
return GDSync.get_host()
|
||||
|
||||
|
||||
func _get_target() -> Node:
|
||||
if target.is_empty():
|
||||
return get_parent()
|
||||
return get_node_or_null(target)
|
||||
|
||||
|
||||
func _get_dimension(target_node : Node) -> int:
|
||||
if target_node is Node2D:
|
||||
return 2
|
||||
if target_node is Node3D:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
|
||||
func _get_position(target_node : Node) -> Vector3:
|
||||
if target_node is Node2D:
|
||||
var position_2d : Vector2 = target_node.global_position
|
||||
return Vector3(position_2d.x, position_2d.y, 0.0)
|
||||
if target_node is Node3D:
|
||||
return target_node.global_position
|
||||
return Vector3.ZERO
|
||||
|
||||
|
||||
func _owner_changed(_owner_id : int) -> void:
|
||||
_force_interest_report()
|
||||
|
||||
|
||||
func _host_changed(_is_host : bool, _host_id : int) -> void:
|
||||
_recipients.clear()
|
||||
_force_interest_report()
|
||||
_update_parent_visibility()
|
||||
|
||||
|
||||
func _get_property_list() -> Array[Dictionary]:
|
||||
var properties : Array[Dictionary] = []
|
||||
if !hide_parent_out_of_range:
|
||||
return properties
|
||||
|
||||
properties.append({
|
||||
"name": "show_parent_delay",
|
||||
"type": TYPE_FLOAT,
|
||||
"usage": PROPERTY_USAGE_DEFAULT,
|
||||
"hint": PROPERTY_HINT_RANGE,
|
||||
"hint_string": "0,2,0.01,or_greater,suffix:s",
|
||||
})
|
||||
return properties
|
||||
|
||||
|
||||
func _get_configuration_warnings() -> PackedStringArray:
|
||||
var warnings : PackedStringArray = []
|
||||
var target_node := _get_target()
|
||||
if target_node == null:
|
||||
warnings.append("Target Node was not found.")
|
||||
elif !(target_node is Node2D) and !(target_node is Node3D):
|
||||
warnings.append("Target must be a Node2D or Node3D.")
|
||||
|
||||
if get_parent() != null:
|
||||
var sibling_count := 0
|
||||
for sibling in get_parent().get_children():
|
||||
if sibling is InterestObject:
|
||||
sibling_count += 1
|
||||
if sibling_count > 1:
|
||||
warnings.append("An entity may have only one sibling InterestObject.")
|
||||
if hide_parent_out_of_range and !_can_hide_node(get_parent()):
|
||||
warnings.append("hide_parent_out_of_range is enabled but the parent cannot be hidden (must be Node2D, Node3D, or CanvasItem).")
|
||||
return warnings
|
||||
1
addons/GD-Sync/Scripts/Types/InterestObject.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/InterestObject.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b4rlnnxsj8eak
|
||||
1
addons/GD-Sync/Scripts/Types/InterestSource.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/InterestSource.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bgowo0c22nfup
|
||||
141
addons/GD-Sync/Scripts/Types/InterestViewer.gd
Normal file
141
addons/GD-Sync/Scripts/Types/InterestViewer.gd
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/InterestViewer.png")
|
||||
extends Node
|
||||
class_name InterestViewer
|
||||
|
||||
# Copyright (c) 2023-present GD-Sync.
|
||||
# All rights reserved.
|
||||
#
|
||||
# Redistribution and use in source form, with or without modification,
|
||||
# are permitted provided that the following conditions are met:
|
||||
#
|
||||
# 1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
# 2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
# SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
# SUCH DAMAGE.
|
||||
|
||||
## Reports where one player is in the world so the host can run distance checks.
|
||||
## [br][br]Add this to every player alongside an [InterestObject]. It only provides the
|
||||
## player's viewing position. Range is controlled entirely by each [InterestObject]'s
|
||||
## [member InterestObject.visibility_radius]. Enemies, projectiles, and other entities
|
||||
## do not need an InterestViewer. They only need an [InterestObject].
|
||||
|
||||
## The Node whose position marks where this player is in the world.
|
||||
## [br][br]Leave this empty to use this node's parent. It must be a [Node2D] or [Node3D].
|
||||
## Only the position is read here, the node itself is never moved or synchronized.
|
||||
@export var target : NodePath
|
||||
## How many times per second this player's position is sent to the host.
|
||||
## [br][br]The host uses this to decide which objects are in range. Higher values make
|
||||
## objects appear and disappear more smoothly as the player moves, at a small bandwidth cost.
|
||||
## This has nothing to do with how often your actual game state is synchronized.
|
||||
@export_range(1.0, 30.0, 1.0, "or_greater") var update_rate : float = 5.0
|
||||
## Which categories of objects this player is allowed to receive.
|
||||
## [br][br]An [InterestObject] reaches this player only if they share at least one enabled layer.
|
||||
## Use layers to group things like world objects, indoor areas, teams, or spectator-only content.
|
||||
## Leave every layer enabled if you don't need this kind of separation.
|
||||
@export_flags_3d_physics var interest_layers : int = 1
|
||||
|
||||
var GDSync
|
||||
var _cooldown : float = 0.0
|
||||
var _force_report : bool = true
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
if Engine.is_editor_hint():
|
||||
set_process(false)
|
||||
update_configuration_warnings()
|
||||
return
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
add_to_group("_gdsync_interest")
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
_force_interest_report()
|
||||
|
||||
func _exit_tree() -> void:
|
||||
if Engine.is_editor_hint() or GDSync == null:
|
||||
return
|
||||
var owner_id : int = GDSync.get_gdsync_owner(self)
|
||||
if owner_id >= 0:
|
||||
GDSync._interest_manager.unregister_viewer(str(get_path()), owner_id)
|
||||
|
||||
func _process(delta : float) -> void:
|
||||
if !GDSync.is_active() or !_is_local_viewer():
|
||||
return
|
||||
|
||||
_cooldown -= delta
|
||||
if !_force_report and _cooldown > 0.0:
|
||||
return
|
||||
|
||||
_force_report = false
|
||||
_cooldown = 1.0 / maxf(update_rate, 1.0)
|
||||
var target_node := _get_target()
|
||||
if target_node == null:
|
||||
return
|
||||
|
||||
var viewer_dimension := _get_dimension(target_node)
|
||||
if viewer_dimension == 0:
|
||||
return
|
||||
|
||||
GDSync._interest_manager.report_viewer(
|
||||
str(get_path()),
|
||||
GDSync.get_client_id(),
|
||||
_get_position(target_node),
|
||||
viewer_dimension,
|
||||
interest_layers
|
||||
)
|
||||
|
||||
func _force_interest_report() -> void:
|
||||
_force_report = true
|
||||
_cooldown = 0.0
|
||||
|
||||
func _is_local_viewer() -> bool:
|
||||
var owner_id : int = GDSync.get_gdsync_owner(self)
|
||||
return owner_id >= 0 and owner_id == GDSync.get_client_id()
|
||||
|
||||
func _get_target() -> Node:
|
||||
if target.is_empty():
|
||||
return get_parent()
|
||||
return get_node_or_null(target)
|
||||
|
||||
func _get_dimension(target_node : Node) -> int:
|
||||
if target_node is Node2D:
|
||||
return 2
|
||||
if target_node is Node3D:
|
||||
return 3
|
||||
return 0
|
||||
|
||||
func _get_position(target_node : Node) -> Vector3:
|
||||
if target_node is Node2D:
|
||||
var position_2d : Vector2 = target_node.global_position
|
||||
return Vector3(position_2d.x, position_2d.y, 0.0)
|
||||
if target_node is Node3D:
|
||||
return target_node.global_position
|
||||
return Vector3.ZERO
|
||||
|
||||
func _owner_changed(_owner_id : int) -> void:
|
||||
_force_interest_report()
|
||||
|
||||
func _host_changed(_is_host : bool, _host_id : int) -> void:
|
||||
_force_interest_report()
|
||||
|
||||
func _get_configuration_warnings() -> PackedStringArray:
|
||||
var target_node := _get_target()
|
||||
if target_node == null:
|
||||
return ["Target Node was not found."]
|
||||
if !(target_node is Node2D) and !(target_node is Node3D):
|
||||
return ["Target must be a Node2D or Node3D."]
|
||||
return []
|
||||
1
addons/GD-Sync/Scripts/Types/InterestViewer.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/InterestViewer.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://8f78sl5p1jc5
|
||||
188
addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd
Normal file
188
addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
## Builder for a matchmaking search passed to [method MultiplayerClient.matchmaking_start].
|
||||
## [br][br]Construct a request, optionally chain configuration methods, then start matchmaking and handle
|
||||
## [signal MultiplayerClient.matchmaking_started], [signal MultiplayerClient.matchmaking_status_changed],
|
||||
## [signal MultiplayerClient.matchmaking_match_found], [signal MultiplayerClient.matchmaking_failed], and
|
||||
## [signal MultiplayerClient.matchmaking_cancelled]. Starting a new request cancels any active one. Closed
|
||||
## lobbies are never joined.
|
||||
## [br][br]The constructor [code]player_limit[/code] is the maximum lobby size. [method set_min_players]
|
||||
## controls how many queued players are required before a match lobby is created (default: equal to the
|
||||
## player limit). After creation, more matching players can join while the lobby stays open.
|
||||
## [br][br][b]Methods:[/b] [method set_required_tags], [method set_search_mode],
|
||||
## [method set_min_players], [method set_timeout], [method set_skill_rating], [method set_skill_range],
|
||||
## [method clear_skill_matching], [method set_lobby_data]. Configuration
|
||||
## methods return this request so calls can be chained.
|
||||
## [br][br][codeblock]
|
||||
## var request := MatchmakingRequest.new(8)
|
||||
## request.set_min_players(2)
|
||||
## request.set_required_tags({"Mode": "PvP"})
|
||||
## request.set_timeout(60.0)
|
||||
## GDSync.matchmaking_start(request)
|
||||
## [/codeblock]
|
||||
class_name MatchmakingRequest
|
||||
extends RefCounted
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## Where a request may find players.
|
||||
enum SearchMode {
|
||||
## Only join existing public lobbies that match tags and player limit. Fails with
|
||||
## [code]NO_MATCH[/code] if none are available.
|
||||
PUBLIC_ONLY,
|
||||
## Try public lobbies first, then wait in the matchmaking queue. This is the default.
|
||||
PUBLIC_THEN_MATCHMAKE,
|
||||
## Skip public lobbies and only use the matchmaking queue.
|
||||
MATCHMAKE_ONLY,
|
||||
}
|
||||
|
||||
var _player_limit: int
|
||||
var _min_players: int = 0
|
||||
var _required_tags: Dictionary = {}
|
||||
var _search_mode: SearchMode = SearchMode.PUBLIC_THEN_MATCHMAKE
|
||||
var _timeout_seconds: float = 0.0
|
||||
var _initial_lobby_data: Dictionary = {}
|
||||
var _uses_skill: bool = false
|
||||
var _skill_rating: float = 0.0
|
||||
var _initial_skill_range: float = 0.0
|
||||
var _maximum_skill_range: float = 0.0
|
||||
var _skill_expansion_per_second: float = 0.0
|
||||
|
||||
|
||||
## Creates a request whose lobbies hold up to [param player_limit] players.
|
||||
## [br][br]Until [method set_min_players] is called, the minimum to create a lobby equals
|
||||
## [param player_limit]. Must be greater than [code]0[/code] and within your plan limit.
|
||||
func _init(player_limit: int) -> void:
|
||||
_player_limit = player_limit
|
||||
_min_players = player_limit
|
||||
|
||||
|
||||
## Sets all required tags at once, matching [method MultiplayerClient.lobby_create] tags.
|
||||
## [br][br]Public lobbies and queued players must include every entry. Replaces any previously
|
||||
## set tags. Pass an empty dictionary to clear. Returns this request for chaining.
|
||||
func set_required_tags(tags: Dictionary) -> MatchmakingRequest:
|
||||
_required_tags = tags.duplicate(true)
|
||||
return self
|
||||
|
||||
|
||||
## Sets whether to search public lobbies, the matchmaking queue, or both.
|
||||
## [br][br]See [enum SearchMode]. Defaults to [constant SearchMode.PUBLIC_THEN_MATCHMAKE].
|
||||
## Returns this request for chaining.
|
||||
func set_search_mode(mode: SearchMode) -> MatchmakingRequest:
|
||||
_search_mode = mode
|
||||
return self
|
||||
|
||||
|
||||
## Sets how many queued players are required before a match lobby is created.
|
||||
## [br][br]Lobby capacity remains the constructor player limit. For example, a limit of [code]8[/code]
|
||||
## with a minimum of [code]2[/code] creates a lobby at two players; others may join until the lobby
|
||||
## is full or closed. Must be between [code]1[/code] and the player limit. Defaults to the full
|
||||
## player limit. Returns this request for chaining.
|
||||
func set_min_players(min_players: int) -> MatchmakingRequest:
|
||||
_min_players = min_players
|
||||
return self
|
||||
|
||||
|
||||
## Sets how long to wait before failing with [code]TIMEOUT[/code].
|
||||
## [br][br]Use [code]0.0[/code] to wait indefinitely. Returns this request for chaining.
|
||||
func set_timeout(seconds: float) -> MatchmakingRequest:
|
||||
_timeout_seconds = seconds
|
||||
return self
|
||||
|
||||
|
||||
## Enables skill-based matching using this player's rating.
|
||||
## [br][br]If never called, skill is ignored. Use with [method set_skill_range]. Returns this request
|
||||
## for chaining.
|
||||
func set_skill_rating(rating: float) -> MatchmakingRequest:
|
||||
_uses_skill = true
|
||||
_skill_rating = rating
|
||||
return self
|
||||
|
||||
|
||||
## Configures the allowed skill distance from [method set_skill_rating].
|
||||
## [br][br]The allowed range starts at [param initial] and may grow toward [param maximum] by
|
||||
## [param expansion_per_second] while waiting. Expansion is applied when candidates are evaluated.
|
||||
## Returns this request for chaining.
|
||||
func set_skill_range(initial: float, maximum: float, expansion_per_second: float = 0.0) -> MatchmakingRequest:
|
||||
_initial_skill_range = initial
|
||||
_maximum_skill_range = maximum
|
||||
_skill_expansion_per_second = expansion_per_second
|
||||
return self
|
||||
|
||||
|
||||
## Disables skill matching so only tags, limits, and search mode apply.
|
||||
## [br][br]Returns this request for chaining.
|
||||
func clear_skill_matching() -> MatchmakingRequest:
|
||||
_uses_skill = false
|
||||
return self
|
||||
|
||||
|
||||
## Sets private lobby data at once, matching [method MultiplayerClient.lobby_create] data.
|
||||
## [br][br]Applied only to lobbies created by matchmaking (not when joining public lobbies).
|
||||
## Replaces any previously set data. Pass an empty dictionary to clear. Returns this request for chaining.
|
||||
func set_lobby_data(data: Dictionary) -> MatchmakingRequest:
|
||||
_initial_lobby_data = data.duplicate(true)
|
||||
return self
|
||||
|
||||
|
||||
## Returns whether this request can be started. Used internally by the plugin.
|
||||
## [br][br]Invalid requests fail with [code]INVALID_REQUEST[/code].
|
||||
func _is_valid() -> bool:
|
||||
if _player_limit <= 0:
|
||||
return false
|
||||
var min_players := _min_players if _min_players > 0 else _player_limit
|
||||
if min_players <= 0 or min_players > _player_limit:
|
||||
return false
|
||||
if _search_mode < SearchMode.PUBLIC_ONLY or _search_mode > SearchMode.MATCHMAKE_ONLY:
|
||||
return false
|
||||
if _timeout_seconds < 0.0:
|
||||
return false
|
||||
if var_to_bytes(_required_tags).size() > 2048:
|
||||
return false
|
||||
if var_to_bytes(_initial_lobby_data).size() > 8192:
|
||||
return false
|
||||
if _initial_skill_range < 0.0 or _maximum_skill_range < _initial_skill_range:
|
||||
return false
|
||||
if _skill_expansion_per_second < 0.0:
|
||||
return false
|
||||
return true
|
||||
|
||||
|
||||
## Serializes this request for the server. Used internally by the plugin.
|
||||
func _to_dictionary() -> Dictionary:
|
||||
var min_players := _min_players if _min_players > 0 else _player_limit
|
||||
var request := {
|
||||
"PlayerLimit": _player_limit,
|
||||
"MinPlayers": min_players,
|
||||
"RequiredTags": _required_tags.duplicate(true),
|
||||
"SearchMode": int(_search_mode),
|
||||
"TimeoutSeconds": _timeout_seconds,
|
||||
"InitialLobbyData": _initial_lobby_data.duplicate(true),
|
||||
"UsesSkill": _uses_skill,
|
||||
}
|
||||
if _uses_skill:
|
||||
request["SkillRating"] = _skill_rating
|
||||
request["InitialSkillRange"] = _initial_skill_range
|
||||
request["MaximumSkillRange"] = _maximum_skill_range
|
||||
request["SkillExpansionPerSecond"] = _skill_expansion_per_second
|
||||
return request
|
||||
1
addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/MatchmakingRequest.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://bai6ti32yg0sj
|
||||
287
addons/GD-Sync/Scripts/Types/NodeInstantiator.gd
Normal file
287
addons/GD-Sync/Scripts/Types/NodeInstantiator.gd
Normal file
|
|
@ -0,0 +1,287 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/NodeInstantiator.png")
|
||||
extends Node
|
||||
class_name NodeInstantiator
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
func instantiate_node() -> Node:
|
||||
var node : Node = scene.instantiate()
|
||||
read_original_properties(node)
|
||||
var id : int = _assign_instance_id(node)
|
||||
node.name = str(id)
|
||||
node.propagate_call("set_meta", ["PauseSync", false])
|
||||
|
||||
if target:
|
||||
target.add_child(node)
|
||||
else:
|
||||
add_child(node)
|
||||
|
||||
_send_remote_instantiate.call_deferred(node, _original_properties)
|
||||
_call_multiplayer_ready(node)
|
||||
node_instantiated.emit(node)
|
||||
return node
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
enum SPAWN_TYPE {
|
||||
## Adds instantiated Nodes to the selected [member target_location].
|
||||
NODE_PATH,
|
||||
## Adds instantiated Nodes to the current scene.
|
||||
SCENE_ROOT
|
||||
}
|
||||
|
||||
signal node_instantiated(node : Node)
|
||||
|
||||
## Decides where the instantiated Node is added.
|
||||
@export var spawn_type : SPAWN_TYPE = SPAWN_TYPE.SCENE_ROOT : set = _set_spawn_type
|
||||
## The Node which instantiated Nodes are added to.
|
||||
var target_location : NodePath
|
||||
var target : Node
|
||||
var target_path : String
|
||||
## The [PackedScene] which will be instantiated.
|
||||
var scene : PackedScene
|
||||
## If enabled, when a new Client joins the lobby the NodeInstantiator will make sure
|
||||
## to spawn in any Nodes that were spawned in before the Client joined.
|
||||
var replicate_on_join : bool = true
|
||||
## If enabled, any changes made to the instantiated Node within the same frame will
|
||||
## automatically be synchronized across all clients. Changes are only synchronized on the parent Node,
|
||||
## not chilren. Also works in combination with [member replicate_on_join].
|
||||
## [br][br]As an example, this setting can be useful for when setting the position, direction and
|
||||
## speed of a bullet, doing this will set those values on all clients.
|
||||
## [br][br]This setting will only synchronize variants, not Objects like Nodes or Resources.
|
||||
## If the plugin detects an [Array] or [Dictionary] with an Object in it, it will also not be synchronized.
|
||||
var sync_starting_changes : bool = true :
|
||||
set(value):
|
||||
sync_starting_changes = value
|
||||
notify_property_list_changed()
|
||||
## Excludes properties from being synced with [member sync_starting_changes].
|
||||
var excluded_properties : PackedStringArray = []
|
||||
|
||||
const _PERMANENT_EXCLUDED_PROPERTIES : PackedStringArray = [
|
||||
"position",
|
||||
"rotation",
|
||||
"scale"
|
||||
]
|
||||
|
||||
var GDSync
|
||||
|
||||
var _rng : RandomNumberGenerator = RandomNumberGenerator.new()
|
||||
var _node_id_list : Dictionary = {}
|
||||
|
||||
var _original_properties = null
|
||||
|
||||
var replicate_settings = null
|
||||
|
||||
func _ready() -> void:
|
||||
if Engine.is_editor_hint(): return
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
GDSync.expose_func(_instantiate_remote)
|
||||
GDSync.expose_func(_set_target_remote)
|
||||
_rng.randomize()
|
||||
|
||||
if spawn_type == SPAWN_TYPE.SCENE_ROOT:
|
||||
target = get_tree().current_scene
|
||||
elif spawn_type == SPAWN_TYPE.NODE_PATH:
|
||||
target = get_node(target_location)
|
||||
|
||||
if target == null: # Harvest Season patch: no current scene in --script runs (tests, tools)
|
||||
return
|
||||
target_path = str(target.get_path())
|
||||
|
||||
if replicate_settings == null:
|
||||
replicate_settings = [
|
||||
get_path(),
|
||||
sync_starting_changes,
|
||||
excluded_properties,
|
||||
scene.resource_path if scene != null else null,
|
||||
target.get_path(),
|
||||
{}
|
||||
]
|
||||
|
||||
func _call_multiplayer_ready(node : Node) -> void:
|
||||
await get_tree().process_frame
|
||||
if is_instance_valid(node):
|
||||
node.propagate_call("_multiplayer_ready")
|
||||
|
||||
func _get_random_id() -> int:
|
||||
var id : int = _rng.randi()
|
||||
if _node_id_list.has(id):
|
||||
return _get_random_id()
|
||||
return id
|
||||
|
||||
func _assign_instance_id(node : Node) -> int:
|
||||
var id : int = _get_random_id()
|
||||
var instantiator_path : String = str(get_path())
|
||||
_node_id_list[id] = node
|
||||
node.set_meta("GDID", id)
|
||||
node.set_meta("Instantiator", instantiator_path)
|
||||
|
||||
if replicate_on_join:
|
||||
GDSync._node_tracker.register_replication(node, instantiator_path, replicate_settings)
|
||||
|
||||
_await_id_deletion(node)
|
||||
return id
|
||||
|
||||
func _await_id_deletion(node : Node) -> void:
|
||||
await node.tree_exiting
|
||||
var id : int = node.get_meta("GDID")
|
||||
|
||||
if _node_id_list.has(id):
|
||||
_node_id_list.erase(id)
|
||||
|
||||
if replicate_on_join:
|
||||
GDSync._node_tracker.deregister_replication(node)
|
||||
|
||||
func _send_remote_instantiate(node : Node, starting_properties : Dictionary) -> void:
|
||||
var changed_properties : Dictionary = {}
|
||||
|
||||
if sync_starting_changes:
|
||||
var new_properties : Dictionary = _get_properties_as_bytes(node)
|
||||
|
||||
for name in starting_properties:
|
||||
if new_properties[name] != starting_properties[name]:
|
||||
var new_value = bytes_to_var(new_properties[name])
|
||||
var type : int = typeof(new_value)
|
||||
match(type):
|
||||
TYPE_OBJECT: continue
|
||||
TYPE_CALLABLE: continue
|
||||
TYPE_SIGNAL: continue
|
||||
TYPE_RID: continue
|
||||
if _PERMANENT_EXCLUDED_PROPERTIES.has(name): continue
|
||||
if excluded_properties.has(name): continue
|
||||
if _contains_object(new_value): continue
|
||||
changed_properties[name] = new_value
|
||||
|
||||
GDSync.call_func(_instantiate_remote, node.get_meta("GDID"), changed_properties)
|
||||
node.propagate_call("remove_meta", ["PauseSync"])
|
||||
|
||||
func _contains_object(value) -> bool:
|
||||
if value is Object: return true
|
||||
|
||||
if value is Array:
|
||||
for element in value:
|
||||
if _contains_object(element):
|
||||
return true
|
||||
|
||||
if value is Dictionary:
|
||||
for key in value:
|
||||
if _contains_object(key) or _contains_object(value[key]):
|
||||
return true
|
||||
|
||||
return false
|
||||
|
||||
func _set_target_remote(target_path : String) -> void:
|
||||
self.target_path = target_path
|
||||
target = get_node_or_null(target_path)
|
||||
|
||||
func _instantiate_remote(id : int, changed_properties : Dictionary) -> void:
|
||||
var instantiator_path : String = str(get_path())
|
||||
var node : Node = scene.instantiate()
|
||||
read_original_properties(node)
|
||||
_node_id_list[id] = node
|
||||
node.set_meta("GDID", id)
|
||||
node.set_meta("Instantiator", instantiator_path)
|
||||
if replicate_on_join:
|
||||
GDSync._node_tracker.register_replication(node, instantiator_path, replicate_settings)
|
||||
_await_id_deletion(node)
|
||||
node.name = str(id)
|
||||
|
||||
if !is_instance_valid(target):
|
||||
target = get_node_or_null(target_path)
|
||||
if target == null:
|
||||
push_error("Instantiate failed, target not found")
|
||||
return
|
||||
|
||||
if target:
|
||||
target.add_child(node)
|
||||
else:
|
||||
add_child(node)
|
||||
|
||||
for name in changed_properties:
|
||||
node.set(name, changed_properties[name])
|
||||
|
||||
node.propagate_call("_multiplayer_ready")
|
||||
node_instantiated.emit(node)
|
||||
|
||||
func _get_properties_as_bytes(node : Node) -> Dictionary:
|
||||
var property_values : Dictionary = {}
|
||||
for property in node.get_property_list():
|
||||
var property_name : String = property["name"]
|
||||
if property_name.begins_with("global_"):
|
||||
continue
|
||||
property_values[property_name] = var_to_bytes(node.get(property_name))
|
||||
|
||||
return property_values
|
||||
|
||||
func read_original_properties(node : Node) -> void:
|
||||
if _original_properties == null:
|
||||
_original_properties = _get_properties_as_bytes(node)
|
||||
replicate_settings[ENUMS.NODE_REPLICATION_SETTINGS.ORIGINAL_PROPERTIES] = _original_properties
|
||||
|
||||
func _set_spawn_type(t : int) -> void:
|
||||
spawn_type = t
|
||||
notify_property_list_changed()
|
||||
|
||||
func _get_property_list() -> Array[Dictionary]:
|
||||
var properties : Array[Dictionary] = []
|
||||
|
||||
properties.append({
|
||||
"name" : "target_location",
|
||||
"type" : TYPE_NODE_PATH,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT if spawn_type == SPAWN_TYPE.NODE_PATH else PROPERTY_USAGE_NO_EDITOR
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "scene",
|
||||
"type" : TYPE_OBJECT,
|
||||
"hint": PROPERTY_HINT_RESOURCE_TYPE,
|
||||
"hint_string" : "PackedScene"
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "replicate_on_join",
|
||||
"type" : TYPE_BOOL,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "sync_starting_changes",
|
||||
"type" : TYPE_BOOL,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "excluded_properties",
|
||||
"type" : TYPE_PACKED_STRING_ARRAY,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT if sync_starting_changes else PROPERTY_USAGE_NO_EDITOR
|
||||
})
|
||||
|
||||
return properties
|
||||
1
addons/GD-Sync/Scripts/Types/NodeInstantiator.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/NodeInstantiator.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://xe2loijthdk6
|
||||
711
addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd
Normal file
711
addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd
Normal file
|
|
@ -0,0 +1,711 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizeIcon.png")
|
||||
extends Node
|
||||
class_name PropertySynchronizer
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## Allows you to manually synchronize a property. This function will only synchronize if the
|
||||
## property has actually changed.
|
||||
## [br][br]If [param forced] is true, it will synchronize regardless of if the property has changed.
|
||||
func synchronize(forced : bool = true, force_reliable : bool = false) -> void:
|
||||
for property_index in range(_property_paths.size()):
|
||||
var property_name : String = _property_paths[property_index]
|
||||
if !_property_lookup.has(property_name): continue
|
||||
|
||||
var property_data : Dictionary = _property_lookup[property_name]
|
||||
var new_property = _get_sync_value(property_name)
|
||||
if forced or _check_property_changed(property_data, new_property):
|
||||
var parameters : Array = [
|
||||
_sync_received,
|
||||
property_index,
|
||||
new_property,
|
||||
GDSync.get_multiplayer_time(),
|
||||
]
|
||||
if force_reliable or reliable:
|
||||
GDSync.call_func_relevant.callv(parameters)
|
||||
else:
|
||||
GDSync.call_func_relevant_unreliable.callv(parameters)
|
||||
|
||||
## Temporarily pauses interpolation for [param seconds]. Useful when teleporting a Node from one spot to another to prevent it from gliding there.
|
||||
func pause_interpolation(seconds : float) -> void:
|
||||
_pause_interpolation_remote(seconds)
|
||||
GDSync.call_func_relevant(_pause_interpolation_remote, seconds)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
enum BROADCAST_MODE {
|
||||
## Broadcast when you are the host of this lobby.
|
||||
WHEN_HOST,
|
||||
## Broadcast when you are the not host of this lobby.
|
||||
WHEN_CLIENT,
|
||||
## Broadcast when you are the owner of this Node or any parent Node.
|
||||
WHEN_OWNER,
|
||||
## Broadcast on the last valid owner this Node had. If the last valid owner leaves or if no owner was ever assigned, it broadcasts on the host.
|
||||
WHEN_HOST_OR_LAST_VALID_OWNER,
|
||||
## Broadcast when you are the host of this lobby and this Node has no owner. If it does have an owner, only the owner broadcasts.
|
||||
## [br]Useful for scenario's like picking up and holding objects, where you want the owner to broadcast
|
||||
## when the item is picked up. When it is dropped and the owner is removed, the lobby
|
||||
## host goes back to broadcasting it.
|
||||
WHEN_HOST_AND_NO_OWNER_OR_OWNER,
|
||||
## Always broadcast. Never recommended.
|
||||
ALWAYS,
|
||||
## Never broadcast.
|
||||
NEVER,
|
||||
}
|
||||
|
||||
signal value_changed(property_name : String, new_value)
|
||||
|
||||
enum PROCESS_MODE {
|
||||
## Broadcast during _process().
|
||||
PROCESS,
|
||||
## Broadcast during _physics_process().
|
||||
PHYSICS_PROCESS,
|
||||
}
|
||||
|
||||
## Decides when to broadcast the properties to other clients.
|
||||
@export var broadcast: BROADCAST_MODE : set = _set_broadcast
|
||||
## Whether the properties should synchronize during [method _process] or [method _physics_process].
|
||||
@export var process : PROCESS_MODE
|
||||
## How many times per second the properties should be synchronized.
|
||||
@export var refresh_rate : int = 30
|
||||
## The Node on which you want to synchronize properties.
|
||||
@export var node_path : NodePath :
|
||||
set(value):
|
||||
node_path = value
|
||||
node = get_node_or_null(node_path)
|
||||
_refresh_property_list()
|
||||
update_configuration_warnings()
|
||||
|
||||
## If reliable is enabled, packets that are lost will be
|
||||
## resend. We never recommend turning this on unless
|
||||
## the synchronized properties are crucial.
|
||||
## Enabling this can induce extra latency and data usage.
|
||||
@export var reliable : bool = false
|
||||
|
||||
## A list of properties you want to synchronize.
|
||||
## Supports indexed component paths such as [code]rotation:y[/code] and [code]position:x[/code].
|
||||
## Property indices sent over the network are derived from this list's order.
|
||||
@export var properties : PackedStringArray = [] : set = _set_properties
|
||||
|
||||
## If enabled, properties will be interpolated. This will smooth out the synchronization.
|
||||
## Interpolation is only applied to types that support interpolation.
|
||||
## [br][br]
|
||||
## Interpolation may be temporarily paused with [method pause_interpolation].
|
||||
## Useful when teleporting a Node from one spot to another to prevent it from gliding there.
|
||||
var interpolated : bool = false :
|
||||
set(value):
|
||||
interpolated = value
|
||||
notify_property_list_changed()
|
||||
|
||||
## How fast the chosen property is interpolated.
|
||||
## [br][br]It is recommended to keep
|
||||
## this number the same or slightly higher than the [member refresh_rate].
|
||||
var interpolation_speed : float = 1.0
|
||||
|
||||
## If enabled, properties will be extrapolated. This will attempt to slightly mask latency by predicting the next value of the synchronized properties.
|
||||
## Extrapolation is applied to floats, Vector2, Vector3, Vector4 and rotation properties.
|
||||
var extrapolated : bool = false :
|
||||
set(value):
|
||||
extrapolated = value
|
||||
notify_property_list_changed()
|
||||
|
||||
## The maximum amount of time in seconds that extrapolation may predict.
|
||||
var max_extrapolation_time : float = 0.2
|
||||
|
||||
var GDSync
|
||||
|
||||
var node : Node
|
||||
|
||||
var _cooldown : float = 0.0
|
||||
var _current_cooldown : float = 0.0
|
||||
var _interval_cooldown : float = 0.0
|
||||
var _should_broadcast : bool = false
|
||||
var _last_owner : int = -1
|
||||
var _user_wants_interpolation : bool = false
|
||||
var _interest_reentry_restore_token : int = 0
|
||||
|
||||
var _property_lookup : Dictionary = {}
|
||||
var _property_paths : PackedStringArray = []
|
||||
|
||||
const _VECTOR2_COMPONENTS : Array[String] = ["x", "y"]
|
||||
const _VECTOR3_COMPONENTS : Array[String] = ["x", "y", "z"]
|
||||
const _VECTOR4_COMPONENTS : Array[String] = ["x", "y", "z", "w"]
|
||||
const _COLOR_COMPONENTS : Array[String] = ["r", "g", "b", "a", "h", "s", "v"]
|
||||
|
||||
func _ready() -> void:
|
||||
node = get_node_or_null(node_path)
|
||||
if Engine.is_editor_hint():
|
||||
set_process(false)
|
||||
set_physics_process(false)
|
||||
_refresh_property_lookup()
|
||||
_refresh_property_list()
|
||||
else:
|
||||
assert(node != null, "PropertySynchronizer Node is null")
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
_cooldown = 1.0/refresh_rate
|
||||
_last_owner = GDSync.get_gdsync_owner(self)
|
||||
|
||||
GDSync.expose_func(_sync_received)
|
||||
GDSync.expose_func(_pause_interpolation_remote)
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.client_joined.connect(_client_joined)
|
||||
GDSync.client_left.connect(_client_left)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
|
||||
_refresh_property_lookup()
|
||||
_clean_property_lookup()
|
||||
_update_sync_mode()
|
||||
set_process(process == PROCESS_MODE.PROCESS)
|
||||
set_physics_process(process == PROCESS_MODE.PHYSICS_PROCESS)
|
||||
|
||||
if interpolated:
|
||||
interpolated = false
|
||||
await value_changed
|
||||
interpolated = true
|
||||
_user_wants_interpolation = true
|
||||
else:
|
||||
extrapolated = false
|
||||
_user_wants_interpolation = false
|
||||
|
||||
func _pause_interpolation_remote(seconds : float) -> void:
|
||||
interpolated = false
|
||||
await get_tree().create_timer(seconds).timeout
|
||||
interpolated = true
|
||||
|
||||
func _set_properties(p : PackedStringArray) -> void:
|
||||
properties = p
|
||||
_refresh_property_lookup()
|
||||
update_configuration_warnings()
|
||||
|
||||
func _set_broadcast(mode : int) -> void:
|
||||
broadcast = mode
|
||||
_update_sync_mode()
|
||||
|
||||
func _owner_changed(owner) -> void:
|
||||
if owner >= 0: _last_owner = owner
|
||||
_update_sync_mode()
|
||||
|
||||
func _host_changed(is_host : bool, new_host_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _update_sync_mode() -> void:
|
||||
if Engine.is_editor_hint() || GDSync == null: return
|
||||
var is_host : bool = GDSync.is_host()
|
||||
var is_owner : bool = GDSync.is_gdsync_owner(self)
|
||||
match (broadcast):
|
||||
BROADCAST_MODE.WHEN_HOST:
|
||||
_should_broadcast = is_host
|
||||
BROADCAST_MODE.WHEN_CLIENT:
|
||||
_should_broadcast = !is_host
|
||||
BROADCAST_MODE.WHEN_OWNER:
|
||||
_should_broadcast = is_owner
|
||||
BROADCAST_MODE.WHEN_HOST_OR_LAST_VALID_OWNER:
|
||||
var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
|
||||
_should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
|
||||
BROADCAST_MODE.WHEN_HOST_AND_NO_OWNER_OR_OWNER:
|
||||
_should_broadcast = (is_host and GDSync.get_gdsync_owner(self) < 0) || is_owner
|
||||
BROADCAST_MODE.ALWAYS:
|
||||
_should_broadcast = true
|
||||
BROADCAST_MODE.NEVER:
|
||||
_should_broadcast = false
|
||||
|
||||
func _process(delta : float) -> void:
|
||||
_check_property_states(delta)
|
||||
|
||||
func _physics_process(delta : float) -> void:
|
||||
_check_property_states(delta)
|
||||
|
||||
func _check_property_states(delta : float) -> void:
|
||||
if !GDSync.is_active(): return
|
||||
if _should_broadcast:
|
||||
if _may_synchronize(delta):
|
||||
synchronize(false)
|
||||
else:
|
||||
if interpolated: _interpolate(delta)
|
||||
if extrapolated: _extrapolate(delta)
|
||||
|
||||
func _check_property_changed(property_data : Dictionary, new_property) -> bool:
|
||||
if property_data["Type"] == TYPE_DICTIONARY:
|
||||
if property_data["TargetValue"] == null or !new_property.recursive_equal(property_data["TargetValue"], 5):
|
||||
property_data["TargetValue"] = new_property.duplicate(true)
|
||||
return true
|
||||
|
||||
if property_data["Type"] == TYPE_ARRAY:
|
||||
if new_property != property_data["TargetValue"]:
|
||||
property_data["TargetValue"] = new_property.duplicate(true)
|
||||
return true
|
||||
|
||||
if new_property != property_data["TargetValue"]:
|
||||
property_data["TargetValue"] = new_property
|
||||
return true
|
||||
|
||||
return false
|
||||
|
||||
func _may_synchronize(delta : float) -> bool:
|
||||
_current_cooldown -= delta
|
||||
if _current_cooldown <= 0:
|
||||
_current_cooldown += _cooldown
|
||||
return true
|
||||
return false
|
||||
|
||||
func _client_joined(client_id : int) -> void:
|
||||
if GDSync._interest_manager.has_interest_object(self):
|
||||
return
|
||||
if _should_broadcast:
|
||||
synchronize(true, true)
|
||||
|
||||
func _interest_object_local_entered(_client_id : int) -> void:
|
||||
if _should_broadcast or !_user_wants_interpolation:
|
||||
return
|
||||
_interest_reentry_restore_token += 1
|
||||
var token := _interest_reentry_restore_token
|
||||
interpolated = false
|
||||
await get_tree().create_timer(0.5).timeout
|
||||
if token != _interest_reentry_restore_token:
|
||||
return
|
||||
if !_should_broadcast and _user_wants_interpolation:
|
||||
interpolated = true
|
||||
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !_should_broadcast:
|
||||
return
|
||||
for property_index in range(_property_paths.size()):
|
||||
var property_name : String = _property_paths[property_index]
|
||||
if !_property_lookup.has(property_name):
|
||||
continue
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
_sync_received,
|
||||
property_index,
|
||||
_get_sync_value(property_name),
|
||||
GDSync.get_multiplayer_time(),
|
||||
true
|
||||
)
|
||||
|
||||
func _client_left(client_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _sync_received(property_index : int, new_value, send_time : float, force_snap : bool = false) -> void:
|
||||
if property_index < 0 or property_index >= _property_paths.size(): return
|
||||
|
||||
var property_name : String = _property_paths[property_index]
|
||||
if !_property_lookup.has(property_name): return
|
||||
|
||||
var property_data : Dictionary = _property_lookup[property_name]
|
||||
property_data["LastValue"] = property_data["TargetValue"]
|
||||
property_data["TargetValue"] = new_value
|
||||
property_data["ReceivedValue"] = new_value
|
||||
property_data["LastSyncTime"] = send_time
|
||||
|
||||
if force_snap:
|
||||
_interest_reentry_restore_token += 1
|
||||
property_data["LastValue"] = new_value
|
||||
_set_sync_value(property_name, new_value)
|
||||
value_changed.emit(property_name, new_value)
|
||||
call_deferred("_restore_interpolation_after_interest_reentry")
|
||||
return
|
||||
|
||||
if !interpolated || !property_data["IsFloating"]:
|
||||
_set_sync_value(property_name, new_value)
|
||||
value_changed.emit(property_name, new_value)
|
||||
|
||||
|
||||
func _restore_interpolation_after_interest_reentry() -> void:
|
||||
if _should_broadcast or !_user_wants_interpolation:
|
||||
return
|
||||
interpolated = true
|
||||
|
||||
func _is_indexed_property_path(property_path : String) -> bool:
|
||||
return property_path.contains(":")
|
||||
|
||||
func _parse_indexed_property_path(property_path : String) -> Dictionary:
|
||||
var parts : PackedStringArray = property_path.split(":", false, 1)
|
||||
return {
|
||||
"BaseName" : parts[0],
|
||||
"Component" : parts[1],
|
||||
}
|
||||
|
||||
func _find_property_type(property_name : String, property_list : Array) -> int:
|
||||
for node_property in property_list:
|
||||
if node_property["name"] == property_name:
|
||||
return node_property["type"]
|
||||
return -1
|
||||
|
||||
func _is_valid_indexed_component(base_type : int, component : String) -> bool:
|
||||
match base_type:
|
||||
TYPE_VECTOR2:
|
||||
return component in _VECTOR2_COMPONENTS
|
||||
TYPE_VECTOR3:
|
||||
return component in _VECTOR3_COMPONENTS
|
||||
TYPE_VECTOR4:
|
||||
return component in _VECTOR4_COMPONENTS
|
||||
TYPE_COLOR:
|
||||
return component in _COLOR_COMPONENTS
|
||||
return false
|
||||
|
||||
func _property_type_is_floating(property_type : int) -> bool:
|
||||
return (
|
||||
property_type == TYPE_INT
|
||||
or property_type == TYPE_FLOAT
|
||||
or property_type == TYPE_VECTOR2
|
||||
or property_type == TYPE_VECTOR3
|
||||
or property_type == TYPE_VECTOR4
|
||||
or property_type == TYPE_COLOR
|
||||
or property_type == TYPE_QUATERNION
|
||||
or property_type == TYPE_BASIS
|
||||
)
|
||||
|
||||
func _create_property_metadata(property_path : String, property_list : Array) -> Dictionary:
|
||||
var property_data : Dictionary = {
|
||||
"TargetValue" : null,
|
||||
"ReceivedValue" : null,
|
||||
"LastValue" : null,
|
||||
"LastSyncTime" : 0.0,
|
||||
"Type" : -1,
|
||||
"IsFloating" : false,
|
||||
"Exists" : false,
|
||||
"Indexed" : false,
|
||||
}
|
||||
|
||||
if !_is_indexed_property_path(property_path):
|
||||
var property_type : int = _find_property_type(property_path, property_list)
|
||||
if property_type == -1:
|
||||
return property_data
|
||||
|
||||
property_data["Exists"] = true
|
||||
property_data["Type"] = property_type
|
||||
property_data["IsFloating"] = _property_type_is_floating(property_type)
|
||||
return property_data
|
||||
|
||||
var parsed : Dictionary = _parse_indexed_property_path(property_path)
|
||||
var base_type : int = _find_property_type(parsed["BaseName"], property_list)
|
||||
if base_type == -1 or !_is_valid_indexed_component(base_type, parsed["Component"]):
|
||||
return property_data
|
||||
|
||||
property_data["Indexed"] = true
|
||||
property_data["Exists"] = true
|
||||
property_data["Type"] = TYPE_FLOAT
|
||||
property_data["IsFloating"] = true
|
||||
return property_data
|
||||
|
||||
func _get_sync_value(property_path : String):
|
||||
if _is_indexed_property_path(property_path):
|
||||
return node.get_indexed(property_path)
|
||||
return node.get(property_path)
|
||||
|
||||
func _set_sync_value(property_path : String, value) -> void:
|
||||
if _is_indexed_property_path(property_path):
|
||||
node.set_indexed(property_path, value)
|
||||
else:
|
||||
node.set(property_path, value)
|
||||
|
||||
func _rotation_base_name(property_name : String) -> String:
|
||||
if _is_indexed_property_path(property_name):
|
||||
return _parse_indexed_property_path(property_name)["BaseName"].to_lower()
|
||||
return property_name.to_lower()
|
||||
|
||||
func _is_angle_rotation_property(property_name : String, type : int) -> bool:
|
||||
var name : String = _rotation_base_name(property_name)
|
||||
if "degrees" in property_name.to_lower():
|
||||
return false
|
||||
if "velocity" in name or "speed" in name:
|
||||
return false
|
||||
match type:
|
||||
TYPE_FLOAT, TYPE_VECTOR2, TYPE_VECTOR3:
|
||||
return (
|
||||
name == "rotation"
|
||||
or name == "global_rotation"
|
||||
or name.ends_with("_rotation")
|
||||
or name.ends_with("rotation")
|
||||
)
|
||||
return false
|
||||
|
||||
func _lerp_rotation_value(current, target, weight : float, type : int):
|
||||
match type:
|
||||
TYPE_FLOAT:
|
||||
return lerp_angle(current, target, weight)
|
||||
TYPE_VECTOR2:
|
||||
return Vector2(
|
||||
lerp_angle(current.x, target.x, weight),
|
||||
lerp_angle(current.y, target.y, weight)
|
||||
)
|
||||
TYPE_VECTOR3:
|
||||
return Vector3(
|
||||
lerp_angle(current.x, target.x, weight),
|
||||
lerp_angle(current.y, target.y, weight),
|
||||
lerp_angle(current.z, target.z, weight)
|
||||
)
|
||||
return lerp(current, target, weight)
|
||||
|
||||
func _rotation_delta(last, target, type : int):
|
||||
match type:
|
||||
TYPE_FLOAT:
|
||||
return angle_difference(last, target)
|
||||
TYPE_VECTOR2:
|
||||
return Vector2(
|
||||
angle_difference(last.x, target.x),
|
||||
angle_difference(last.y, target.y)
|
||||
)
|
||||
TYPE_VECTOR3:
|
||||
return Vector3(
|
||||
angle_difference(last.x, target.x),
|
||||
angle_difference(last.y, target.y),
|
||||
angle_difference(last.z, target.z)
|
||||
)
|
||||
return target - last
|
||||
|
||||
func _extrapolate_rotation_value(target, delta, extrapolate_time : float, type : int):
|
||||
match type:
|
||||
TYPE_FLOAT:
|
||||
return target + delta * extrapolate_time
|
||||
TYPE_VECTOR2:
|
||||
return Vector2(
|
||||
target.x + delta.x * extrapolate_time,
|
||||
target.y + delta.y * extrapolate_time
|
||||
)
|
||||
TYPE_VECTOR3:
|
||||
return Vector3(
|
||||
target.x + delta.x * extrapolate_time,
|
||||
target.y + delta.y * extrapolate_time,
|
||||
target.z + delta.z * extrapolate_time
|
||||
)
|
||||
return target
|
||||
|
||||
func _interpolate(delta : float) -> void:
|
||||
for property_name in _property_lookup:
|
||||
var property_data : Dictionary = _property_lookup[property_name]
|
||||
if !property_data["IsFloating"]: continue
|
||||
|
||||
var current_value = _get_sync_value(property_name)
|
||||
var target_value = property_data.get("TargetValue", current_value)
|
||||
|
||||
if current_value == null || target_value == null: continue
|
||||
|
||||
var weight : float = delta * interpolation_speed
|
||||
var property_type : int = property_data["Type"]
|
||||
var lerped_value
|
||||
|
||||
if property_type == TYPE_BASIS:
|
||||
current_value = current_value.orthonormalized()
|
||||
target_value = target_value.orthonormalized()
|
||||
|
||||
var scale : Vector3 = node.scale
|
||||
|
||||
lerped_value = lerp(current_value, target_value, weight)
|
||||
_set_sync_value(property_name, lerped_value)
|
||||
|
||||
node.scale = scale
|
||||
elif _is_angle_rotation_property(property_name, property_type):
|
||||
lerped_value = _lerp_rotation_value(current_value, target_value, weight, property_type)
|
||||
_set_sync_value(property_name, lerped_value)
|
||||
else:
|
||||
lerped_value = lerp(current_value, target_value, weight)
|
||||
_set_sync_value(property_name, lerped_value)
|
||||
|
||||
value_changed.emit(property_name, lerped_value)
|
||||
|
||||
func _extrapolate(delta : float) -> void:
|
||||
for property_name in _property_lookup:
|
||||
var property_data : Dictionary = _property_lookup[property_name]
|
||||
if !property_data["IsFloating"]: continue
|
||||
|
||||
var last_value = property_data.get("LastValue")
|
||||
var target_value = property_data.get("ReceivedValue")
|
||||
|
||||
if last_value == null || target_value == null: continue
|
||||
var extrapolate_time : float = min(GDSync.get_multiplayer_time()-property_data["LastSyncTime"], max_extrapolation_time)
|
||||
var property_type : int = property_data["Type"]
|
||||
|
||||
if _is_angle_rotation_property(property_name, property_type):
|
||||
var angular_delta = _rotation_delta(last_value, target_value, property_type)
|
||||
property_data["TargetValue"] = _extrapolate_rotation_value(target_value, angular_delta, extrapolate_time, property_type)
|
||||
elif (
|
||||
property_type == TYPE_FLOAT
|
||||
or property_type == TYPE_VECTOR2
|
||||
or property_type == TYPE_VECTOR3
|
||||
or property_type == TYPE_VECTOR4
|
||||
):
|
||||
property_data["TargetValue"] = target_value + (target_value - last_value) * extrapolate_time
|
||||
|
||||
func _refresh_property_lookup() -> void:
|
||||
if node == null: return
|
||||
_property_lookup.clear()
|
||||
_property_paths = properties.duplicate()
|
||||
|
||||
var property_list : Array = node.get_property_list()
|
||||
if node.get_script() != null:
|
||||
var script : Script = node.get_script()
|
||||
if script.get_class() != "CSharpScript":
|
||||
property_list.append_array(script.get_script_property_list())
|
||||
elif Engine.is_editor_hint():
|
||||
property_list.append_array(_parse_csharp_properties(script))
|
||||
else:
|
||||
property_list.append_array(script.get_script_property_list())
|
||||
property_list.append_array(_parse_csharp_properties(script))
|
||||
|
||||
for property_name in properties:
|
||||
var property_data : Dictionary = _create_property_metadata(property_name, property_list)
|
||||
if !property_data["Exists"] and !Engine.is_editor_hint():
|
||||
property_data = _create_runtime_property_metadata(property_name)
|
||||
_property_lookup[property_name] = property_data
|
||||
|
||||
func _parse_csharp_properties(script : Script) -> Array[Dictionary]:
|
||||
var csharp_code : String = FileAccess.get_file_as_string(script.resource_path)
|
||||
var lines : PackedStringArray = csharp_code.split("\n")
|
||||
|
||||
var variables : Array[Dictionary] = []
|
||||
var inside_method : bool = false
|
||||
var brace_level : int = 0
|
||||
var method_regex : RegEx = RegEx.new()
|
||||
var var_regex : RegEx = RegEx.new()
|
||||
method_regex.compile(r"^(?:public|private|protected|internal|static|virtual|override|sealed|async|new|\s)*\s*\w+\s+\w+\s*\(.*\)\s*\{?$")
|
||||
var_regex.compile(r"^(?:public|private|protected|internal|static|const|readonly|\s)*\s*(\w+)\s+(\w+)\s*(=.*)?;")
|
||||
|
||||
var type_mapping : Dictionary = {
|
||||
"float": TYPE_FLOAT,
|
||||
"Vector2": TYPE_VECTOR2,
|
||||
"Vector3": TYPE_VECTOR3,
|
||||
"Vector4": TYPE_VECTOR4,
|
||||
"Color": TYPE_COLOR,
|
||||
"Quaternion": TYPE_QUATERNION,
|
||||
"Basis": TYPE_BASIS,
|
||||
}
|
||||
|
||||
for line in lines:
|
||||
line = line.strip_edges()
|
||||
if line == "" or line.begins_with("//"):
|
||||
continue
|
||||
brace_level += line.count("{") - line.count("}")
|
||||
if not inside_method:
|
||||
if method_regex.search(line):
|
||||
inside_method = true
|
||||
continue
|
||||
var var_match : RegExMatch = var_regex.search(line)
|
||||
if var_match:
|
||||
var type_name : String = var_match.get_string(1)
|
||||
var var_name : String = var_match.get_string(2)
|
||||
if type_name in type_mapping:
|
||||
variables.append({"name" : var_name, "type" : type_mapping[type_name]})
|
||||
else:
|
||||
if brace_level == 0:
|
||||
inside_method = false
|
||||
return variables
|
||||
|
||||
func _create_runtime_property_metadata(property_path : String) -> Dictionary:
|
||||
var property_data : Dictionary = _create_property_metadata(property_path, [])
|
||||
if _is_indexed_property_path(property_path):
|
||||
var parsed : Dictionary = _parse_indexed_property_path(property_path)
|
||||
if !(parsed["BaseName"] in node):
|
||||
return property_data
|
||||
var base_type : int = typeof(node.get(parsed["BaseName"]))
|
||||
if base_type == TYPE_NIL or !_is_valid_indexed_component(base_type, parsed["Component"]):
|
||||
return property_data
|
||||
property_data["Indexed"] = true
|
||||
property_data["Exists"] = true
|
||||
property_data["Type"] = TYPE_FLOAT
|
||||
property_data["IsFloating"] = true
|
||||
return property_data
|
||||
if !(property_path in node):
|
||||
return property_data
|
||||
var value = node.get(property_path)
|
||||
var property_type : int = typeof(value)
|
||||
if property_type == TYPE_NIL:
|
||||
return property_data
|
||||
property_data["Exists"] = true
|
||||
property_data["Type"] = property_type
|
||||
property_data["IsFloating"] = _property_type_is_floating(property_type)
|
||||
return property_data
|
||||
|
||||
func _clean_property_lookup() -> void:
|
||||
for property_name in _property_lookup:
|
||||
var property_data : Dictionary = _property_lookup[property_name]
|
||||
if !property_data["Exists"]: _property_lookup.erase(property_name)
|
||||
|
||||
func _get_configuration_warnings() -> PackedStringArray:
|
||||
var node : Node = get_node_or_null(node_path)
|
||||
if node == null:
|
||||
return ["No NodePath is specified."]
|
||||
|
||||
var warnings : PackedStringArray = []
|
||||
|
||||
_refresh_property_lookup()
|
||||
for property_name in _property_lookup:
|
||||
var property_data : Dictionary = _property_lookup[property_name]
|
||||
if !property_data["Exists"]:
|
||||
warnings.append("The selected Node does not have the property \""+property_name+"\"")
|
||||
|
||||
return warnings
|
||||
|
||||
func _refresh_property_list() -> void:
|
||||
notify_property_list_changed()
|
||||
|
||||
func _get_property_list() -> Array[Dictionary]:
|
||||
var properties : Array[Dictionary] = []
|
||||
|
||||
properties.append({
|
||||
"name" : "interpolation",
|
||||
"type" : TYPE_BOOL,
|
||||
"usage" : PROPERTY_USAGE_GROUP
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "interpolated",
|
||||
"type" : TYPE_BOOL,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "interpolation_speed",
|
||||
"type" : TYPE_FLOAT,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT if interpolated else PROPERTY_USAGE_NO_EDITOR
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "extrapolation",
|
||||
"type" : TYPE_BOOL,
|
||||
"usage" : PROPERTY_USAGE_GROUP if interpolated else PROPERTY_USAGE_NO_EDITOR
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "extrapolated",
|
||||
"type" : TYPE_BOOL,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT if interpolated else PROPERTY_USAGE_NO_EDITOR
|
||||
})
|
||||
|
||||
properties.append({
|
||||
"name" : "max_extrapolation_time",
|
||||
"type" : TYPE_FLOAT,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT if interpolated and extrapolated else PROPERTY_USAGE_NO_EDITOR
|
||||
})
|
||||
|
||||
return properties
|
||||
1
addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/PropertySynchronizer.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://fcoih1ax5dcs
|
||||
1
addons/GD-Sync/Scripts/Types/SyncZone.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/SyncZone.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b04bfa1lvmh3h
|
||||
197
addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd
Normal file
197
addons/GD-Sync/Scripts/Types/SynchronizedAnimatedSprite2D.gd
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAnimatedSprite.png")
|
||||
extends AnimatedSprite2D
|
||||
class_name SynchronizedAnimatedSprite2D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
func play_synced(name: StringName = &"", custom_speed: float = 1.0, from_end: bool = false) -> void:
|
||||
var send_remote_play : bool = !is_playing() || animation != name
|
||||
play(name, custom_speed, from_end)
|
||||
|
||||
if !GDSync.is_active(): return
|
||||
if !_should_broadcast: return
|
||||
if !send_remote_play: return
|
||||
|
||||
var use_name : bool = name.length() > 0
|
||||
var name_cached : bool = use_name and GDSync._session_controller.name_is_cached(name)
|
||||
var parameters : Array = []
|
||||
|
||||
var defaults_flipped : Array = [false, 1.0, null if name_cached else &""]
|
||||
var actual_values : Array = [
|
||||
from_end,
|
||||
custom_speed,
|
||||
GDSync._session_controller.get_name_index(name) if name_cached else name
|
||||
]
|
||||
|
||||
var include_all : bool = false
|
||||
for i in range(defaults_flipped.size()):
|
||||
var default = defaults_flipped[i]
|
||||
var actual = actual_values[i]
|
||||
if default != actual:
|
||||
include_all = true
|
||||
|
||||
if include_all:
|
||||
parameters.push_front(actual)
|
||||
|
||||
if name_cached:
|
||||
parameters.push_front(_play_remote_cached)
|
||||
GDSync.call_func_relevant.callv(parameters)
|
||||
else:
|
||||
if use_name:GDSync._request_processor.create_name_cache("", name)
|
||||
parameters.push_front(_play_remote)
|
||||
GDSync.call_func_relevant.callv(parameters)
|
||||
|
||||
func play_backwards_synced(name: StringName = &"") -> void:
|
||||
play_backwards(name)
|
||||
if !GDSync.is_active() or !_should_broadcast: return
|
||||
GDSync.call_func_relevant(_play_backwards_remote, name)
|
||||
|
||||
func set_frame_and_progress_synced(frame: int, progress: float) -> void:
|
||||
set_frame_and_progress(frame, progress)
|
||||
if !GDSync.is_active() or !_should_broadcast: return
|
||||
GDSync.call_func_relevant(_set_frame_and_progress_remote, frame, progress)
|
||||
|
||||
func stop_synced() -> void:
|
||||
stop()
|
||||
if !GDSync.is_active() or !_should_broadcast: return
|
||||
GDSync.call_func_relevant(_stop_remote)
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
var _last_flip_h : bool
|
||||
var _last_flip_v : bool
|
||||
var _last_speed_scale : float
|
||||
var _last_animation : StringName
|
||||
var _should_broadcast : bool = false
|
||||
var _last_owner : int = -1
|
||||
|
||||
func _ready() -> void:
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
GDSync.expose_func(_play_remote_cached)
|
||||
GDSync.expose_func(_play_remote)
|
||||
GDSync.expose_func(_play_backwards_remote)
|
||||
GDSync.expose_func(_set_frame_and_progress_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
GDSync.expose_func(_refresh_last_changes)
|
||||
|
||||
GDSync.expose_var(self, "flip_h")
|
||||
GDSync.expose_var(self, "flip_v")
|
||||
GDSync.expose_var(self, "speed_scale")
|
||||
|
||||
var timer : Timer = Timer.new()
|
||||
add_child(timer)
|
||||
timer.wait_time = 0.001
|
||||
timer.timeout.connect(_check_for_changes)
|
||||
timer.start()
|
||||
|
||||
_last_owner = GDSync.get_gdsync_owner(self)
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.client_joined.connect(_client_joined)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
|
||||
_refresh_last_changes()
|
||||
_update_sync_mode()
|
||||
|
||||
func _multiplayer_ready() -> void:
|
||||
_refresh_last_changes()
|
||||
_update_sync_mode()
|
||||
|
||||
func _check_for_changes() -> void:
|
||||
if !_has_changed():
|
||||
return
|
||||
if _should_broadcast:
|
||||
_refresh_last_changes()
|
||||
play_synced(animation)
|
||||
GDSync.sync_var_relevant(self, "flip_h")
|
||||
GDSync.sync_var_relevant(self, "flip_v")
|
||||
GDSync.sync_var_relevant(self, "speed_scale")
|
||||
GDSync.call_func_relevant(_refresh_last_changes)
|
||||
else:
|
||||
_refresh_last_changes()
|
||||
|
||||
func _refresh_last_changes() -> void:
|
||||
_last_flip_h = flip_h
|
||||
_last_flip_v = flip_v
|
||||
_last_speed_scale = speed_scale
|
||||
_last_animation = animation
|
||||
|
||||
func _has_changed() -> bool:
|
||||
return (
|
||||
_last_flip_h != flip_h or
|
||||
_last_flip_v != flip_v or
|
||||
_last_speed_scale != speed_scale or
|
||||
_last_animation != animation
|
||||
)
|
||||
|
||||
func _play_remote_cached(name_index = 0, custom_speed : float = 1.0, from_end : bool = false) -> void:
|
||||
if !GDSync._session_controller.has_name_from_index(name_index): return
|
||||
_play_remote(GDSync._session_controller.get_name_from_index(name_index), custom_speed, from_end)
|
||||
|
||||
func _play_remote(name : StringName = &"", custom_speed : float = 1.0, from_end : bool = false) -> void:
|
||||
play(name, custom_speed, from_end)
|
||||
|
||||
func _play_backwards_remote(name : StringName = &"") -> void:
|
||||
play_backwards(name)
|
||||
|
||||
func _set_frame_and_progress_remote(frame : int, progress : float) -> void:
|
||||
set_frame_and_progress(frame, progress)
|
||||
|
||||
func _stop_remote() -> void:
|
||||
stop()
|
||||
|
||||
func _owner_changed(owner) -> void:
|
||||
if owner >= 0:
|
||||
_last_owner = owner
|
||||
_update_sync_mode()
|
||||
|
||||
func _client_joined(_client_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !_should_broadcast:
|
||||
return
|
||||
GDSync.sync_var_on(client_id, self, "flip_h")
|
||||
GDSync.sync_var_on(client_id, self, "flip_v")
|
||||
GDSync.sync_var_on(client_id, self, "speed_scale")
|
||||
if is_playing():
|
||||
GDSync.call_func_on(client_id, _play_remote, animation, speed_scale, false)
|
||||
GDSync.call_func_on(client_id, _set_frame_and_progress_remote, frame, frame_progress)
|
||||
else:
|
||||
GDSync.call_func_on(client_id, _stop_remote)
|
||||
|
||||
func _host_changed(_is_host : bool, _new_host_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _update_sync_mode() -> void:
|
||||
if GDSync == null or !GDSync.is_active():
|
||||
return
|
||||
var is_host : bool = GDSync.is_host()
|
||||
var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
|
||||
_should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://dqpkvnosbpdvd
|
||||
197
addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd
Normal file
197
addons/GD-Sync/Scripts/Types/SynchronizedAnimationPlayer.gd
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAnimationPlayer.png")
|
||||
extends AnimationPlayer
|
||||
class_name SynchronizedAnimationPlayer
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## If enabled, GD-Sync will attempt to synchronize the playback of animations across clients.
|
||||
@export var sync_playback : bool = true
|
||||
|
||||
func play_synced(name: StringName = &"", custom_blend: float = -1, custom_speed: float = 1.0, from_end: bool = false) -> void:
|
||||
var send_remote_play : bool = !is_playing() || current_animation != name
|
||||
play(name, custom_blend, custom_speed, from_end)
|
||||
|
||||
_playing_backwards = from_end
|
||||
_custom_speed = custom_speed
|
||||
|
||||
if !GDSync.is_active(): return
|
||||
if !send_remote_play: return
|
||||
|
||||
var use_name : bool = name.length() > 0
|
||||
var name_cached : bool = use_name and GDSync._session_controller.name_is_cached(name)
|
||||
var parameters : Array = []
|
||||
|
||||
var defaults_flipped : Array = [false, 1.0, -1, null if name_cached else &""]
|
||||
var actual_values : Array = [
|
||||
from_end,
|
||||
custom_speed,
|
||||
custom_blend,
|
||||
GDSync._session_controller.get_name_index(name) if name_cached else name
|
||||
]
|
||||
|
||||
var include_all : bool = false
|
||||
for i in range(defaults_flipped.size()):
|
||||
var default = defaults_flipped[i]
|
||||
var actual = actual_values[i]
|
||||
if default != actual:
|
||||
include_all = true
|
||||
|
||||
if include_all:
|
||||
parameters.push_front(actual)
|
||||
|
||||
parameters.push_front(GDSync.get_multiplayer_time())
|
||||
|
||||
if name_cached:
|
||||
parameters.push_front(_play_remote_cached)
|
||||
GDSync.call_func_relevant.callv(parameters)
|
||||
else:
|
||||
if use_name:GDSync._request_processor.create_name_cache("", name)
|
||||
parameters.push_front(_play_remote)
|
||||
GDSync.call_func_relevant.callv(parameters)
|
||||
|
||||
func play_backwards_synced(name: StringName = &"", custom_blend: float = -1) -> void:
|
||||
self.play(name, custom_blend, -1.0, true)
|
||||
|
||||
func pause_synced() -> void:
|
||||
pause()
|
||||
if !GDSync.is_active(): return
|
||||
GDSync.call_func_relevant(_pause_remote)
|
||||
|
||||
func stop_synced(keep_state : bool = false) -> void:
|
||||
stop(keep_state)
|
||||
if !GDSync.is_active(): return
|
||||
GDSync.call_func_relevant(_stop_remote, keep_state)
|
||||
|
||||
func queue_synced(name : StringName) -> void:
|
||||
queue(name)
|
||||
if !GDSync.is_active(): return
|
||||
GDSync.call_func_relevant(_queue_remote, name)
|
||||
|
||||
func seek_synced(seconds : float, update : bool = false, update_only : bool = false) -> void:
|
||||
seek(seconds, update, update_only)
|
||||
if !GDSync.is_active(): return
|
||||
|
||||
var parameters : Array = []
|
||||
|
||||
var defaults_flipped : Array = [false, false]
|
||||
var actual_values : Array = [update_only, update]
|
||||
|
||||
var include_all : bool = false
|
||||
for i in range(defaults_flipped.size()):
|
||||
var default = defaults_flipped[i]
|
||||
var actual = actual_values[i]
|
||||
if default != actual:
|
||||
include_all = true
|
||||
|
||||
if include_all:
|
||||
parameters.push_front(actual)
|
||||
|
||||
parameters.push_front(seconds)
|
||||
parameters.push_front(GDSync.get_multiplayer_time())
|
||||
parameters.push_front(_seek_remote)
|
||||
GDSync.call_func_relevant.callv(parameters)
|
||||
|
||||
func advance_synced(delta : float) -> void:
|
||||
advance(delta)
|
||||
if !GDSync.is_active(): return
|
||||
GDSync.call_func_relevant(_advance_remote, delta)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
var _playing_backwards : bool = false
|
||||
var _custom_speed : float = 1.0
|
||||
|
||||
func _ready() -> void:
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
GDSync.expose_func(_play_remote)
|
||||
GDSync.expose_func(_play_remote_cached)
|
||||
GDSync.expose_func(_pause_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
GDSync.expose_func(_queue_remote)
|
||||
GDSync.expose_func(_seek_remote)
|
||||
GDSync.expose_func(_advance_remote)
|
||||
|
||||
GDSync.client_joined.connect(_client_joined)
|
||||
|
||||
func _client_joined(client_id : int) -> void:
|
||||
if GDSync._interest_manager.has_interest_object(self):
|
||||
return
|
||||
_send_state_to(client_id)
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
_send_state_to(client_id)
|
||||
|
||||
func _send_state_to(client_id : int) -> void:
|
||||
if is_playing():
|
||||
GDSync.call_func_on(client_id, _stop_remote)
|
||||
|
||||
GDSync.call_func_on(client_id, _play_remote,
|
||||
GDSync.get_multiplayer_time(),
|
||||
current_animation,
|
||||
-1,
|
||||
_custom_speed,
|
||||
_playing_backwards
|
||||
)
|
||||
|
||||
GDSync.call_func_on(client_id, _advance_remote, current_animation_position/_custom_speed)
|
||||
|
||||
func _play_remote_cached(start_time : float = 0.0, name_index = 0, custom_blend : float = -1, custom_speed : float = 1.0, from_end : bool = false) -> void:
|
||||
if !GDSync._session_controller.has_name_from_index(name_index): return
|
||||
_play_remote(start_time, GDSync._session_controller.get_name_from_index(name_index), custom_blend, custom_speed, from_end)
|
||||
|
||||
func _play_remote(start_time : float = 0.0, name : StringName = &"", custom_blend : float = -1, custom_speed : float = 1.0, from_end : bool = false) -> void:
|
||||
play(name, custom_blend, custom_speed, from_end)
|
||||
|
||||
if sync_playback:
|
||||
var time_passed : float = GDSync.get_multiplayer_time() - start_time
|
||||
if time_passed <= 0.5: advance(time_passed)
|
||||
|
||||
func _pause_remote() -> void:
|
||||
pause()
|
||||
|
||||
func _queue_remote(name : StringName) -> void:
|
||||
queue(name)
|
||||
|
||||
func _stop_remote(keep_state : bool = false) -> void:
|
||||
stop(keep_state)
|
||||
|
||||
func _seek_remote(start_time : float, seconds : float, update : bool = false, update_only : bool = false) -> void:
|
||||
seek(seconds, update, update_only)
|
||||
|
||||
if sync_playback:
|
||||
var time_passed : float = GDSync.get_multiplayer_time() - start_time
|
||||
if time_passed < 0.5: advance(time_passed)
|
||||
|
||||
func _advance_remote(delta : float) -> void:
|
||||
advance(delta)
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://cofugv2v6ssv5
|
||||
214
addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd
Normal file
214
addons/GD-Sync/Scripts/Types/SynchronizedAnimationTree.gd
Normal file
|
|
@ -0,0 +1,214 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAnimationTree.png")
|
||||
extends AnimationTree
|
||||
class_name SynchronizedAnimationTree
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
enum BROADCAST_MODE {
|
||||
## Broadcast when you are the host of this lobby.
|
||||
WHEN_HOST,
|
||||
## Broadcast when you are the not host of this lobby.
|
||||
WHEN_CLIENT,
|
||||
## Broadcast when you are the owner of this Node or any parent Node.
|
||||
WHEN_OWNER,
|
||||
## Broadcast on the last valid owner this Node had. If the last valid owner leaves or if no owner was ever assigned, it broadcasts on the host.
|
||||
WHEN_HOST_OR_LAST_VALID_OWNER,
|
||||
## Broadcast when you are the host of this lobby and this Node has no owner.
|
||||
## If it does have an owner, only the owner broadcasts.
|
||||
## [br]Useful for scenario's like picking up and holding objects, where you want the owner to broadcast
|
||||
## when the item is picked up. When it is dropped and the owner is removed, the lobby
|
||||
## host goes back to broadcasting it.
|
||||
WHEN_HOST_AND_NO_OWNER_OR_OWNER,
|
||||
## Always broadcast. Never recommended.
|
||||
ALWAYS,
|
||||
## Never broadcast.
|
||||
NEVER,
|
||||
}
|
||||
|
||||
static var _VARIABLE_INPUTS : PackedStringArray = [
|
||||
"/add_amount",
|
||||
"/blend_amount",
|
||||
"/blend_position"
|
||||
]
|
||||
|
||||
static var _INSTANT_INPUTS : PackedStringArray = [
|
||||
"/active",
|
||||
"/scale"
|
||||
]
|
||||
|
||||
## Decides when to broadcast animation changes to other clients.
|
||||
@export var broadcast: BROADCAST_MODE : set = _set_broadcast
|
||||
## How many times per second the animation tree should check for changes.
|
||||
@export var refresh_rate : int = 15
|
||||
|
||||
var _current_variable_inputs : Dictionary = {}
|
||||
var _current_instant_inputs : Dictionary = {}
|
||||
var _state_machines : Dictionary = {}
|
||||
var _state_machine_inputs : Dictionary = {}
|
||||
|
||||
var _cooldown : float = 0.0
|
||||
var _current_cooldown : float = 0.0
|
||||
var _should_broadcast : bool = false
|
||||
var last_owner : int = -1
|
||||
|
||||
var GDSync
|
||||
|
||||
func _ready() -> void:
|
||||
if Engine.is_editor_hint():
|
||||
set_process(false)
|
||||
return
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
_cooldown = 1.0/refresh_rate
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.expose_func(_travel_remote)
|
||||
GDSync.expose_func(set)
|
||||
|
||||
var property_list : Array = get_property_list()
|
||||
|
||||
for property in property_list:
|
||||
var name : String = property["name"]
|
||||
if "parameters/" in name:
|
||||
|
||||
for variable_input in _VARIABLE_INPUTS:
|
||||
if variable_input in name:
|
||||
_current_variable_inputs[name] = get(name)
|
||||
GDSync.expose_var(self, name)
|
||||
break
|
||||
|
||||
for instant_input in _INSTANT_INPUTS:
|
||||
if instant_input in name:
|
||||
_current_instant_inputs[name] = get(name)
|
||||
GDSync.expose_var(self, name)
|
||||
break
|
||||
|
||||
if "/playback" in name:
|
||||
var state_machine : AnimationNodeStateMachinePlayback = get(name)
|
||||
_state_machines[name] = state_machine
|
||||
_state_machine_inputs[state_machine] = state_machine.get_current_node()
|
||||
|
||||
_update_sync_mode()
|
||||
|
||||
if !_should_broadcast:
|
||||
_update_inputs(_current_variable_inputs, true)
|
||||
_update_inputs(_current_instant_inputs, true)
|
||||
_update_state_machines(true)
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if !_should_broadcast:
|
||||
return
|
||||
|
||||
_update_inputs(_current_instant_inputs)
|
||||
|
||||
_current_cooldown -= delta
|
||||
if _current_cooldown <= 0:
|
||||
_current_cooldown += _cooldown
|
||||
|
||||
_update_inputs(_current_variable_inputs)
|
||||
_update_state_machines()
|
||||
|
||||
func _update_inputs(inputs : Dictionary, forced : bool = false) -> void:
|
||||
for input_name in inputs:
|
||||
var old_value = inputs[input_name]
|
||||
var new_value = get(input_name)
|
||||
|
||||
if forced or old_value != new_value:
|
||||
inputs[input_name] = new_value
|
||||
|
||||
if "/active" in input_name:
|
||||
var request : String = input_name.replace("/active", "/request")
|
||||
GDSync.call_func_relevant(
|
||||
set,
|
||||
request,
|
||||
AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE if new_value else AnimationNodeOneShot.ONE_SHOT_REQUEST_ABORT
|
||||
)
|
||||
else:
|
||||
GDSync.sync_var_relevant(self, input_name)
|
||||
|
||||
func _update_state_machines(forced : bool = false) -> void:
|
||||
for state_machine_path in _state_machines:
|
||||
var state_machine : AnimationNodeStateMachinePlayback = _state_machines[state_machine_path]
|
||||
var old_node : String = _state_machine_inputs[state_machine]
|
||||
var new_node : String = state_machine.get_current_node()
|
||||
|
||||
if forced or old_node != new_node:
|
||||
_state_machine_inputs[state_machine] = new_node
|
||||
GDSync.call_func_relevant(_travel_remote, state_machine_path, new_node)
|
||||
|
||||
func _travel_remote(state_machine_path : String, node_name : String) -> void:
|
||||
var state_machine : AnimationNodeStateMachinePlayback = _state_machines[state_machine_path]
|
||||
state_machine.travel(node_name)
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !_should_broadcast:
|
||||
return
|
||||
for input_name in _current_variable_inputs:
|
||||
GDSync.sync_var_on(client_id, self, input_name)
|
||||
for input_name in _current_instant_inputs:
|
||||
if "/active" in input_name:
|
||||
var request : String = input_name.replace("/active", "/request")
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
set,
|
||||
request,
|
||||
AnimationNodeOneShot.ONE_SHOT_REQUEST_FIRE if get(input_name) else AnimationNodeOneShot.ONE_SHOT_REQUEST_ABORT
|
||||
)
|
||||
for state_machine_path in _state_machines:
|
||||
var state_machine : AnimationNodeStateMachinePlayback = _state_machines[state_machine_path]
|
||||
GDSync.call_func_on(client_id, _travel_remote, state_machine_path, state_machine.get_current_node())
|
||||
|
||||
func _host_changed(is_host : bool, new_host_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _owner_changed(owner) -> void:
|
||||
if owner >= 0: last_owner = owner
|
||||
_update_sync_mode()
|
||||
|
||||
func _set_broadcast(mode : int) -> void:
|
||||
broadcast = mode
|
||||
_update_sync_mode()
|
||||
|
||||
func _update_sync_mode() -> void:
|
||||
if Engine.is_editor_hint() || GDSync == null: return
|
||||
var is_host : bool = GDSync.is_host()
|
||||
var is_owner : bool = GDSync.is_gdsync_owner(self)
|
||||
match (broadcast):
|
||||
BROADCAST_MODE.WHEN_HOST:
|
||||
_should_broadcast = is_host
|
||||
BROADCAST_MODE.WHEN_CLIENT:
|
||||
_should_broadcast = !is_host
|
||||
BROADCAST_MODE.WHEN_OWNER:
|
||||
_should_broadcast = is_owner
|
||||
BROADCAST_MODE.WHEN_HOST_OR_LAST_VALID_OWNER:
|
||||
var valid_owner : bool = GDSync.lobby_get_all_clients().has(last_owner)
|
||||
_should_broadcast = (is_host and !valid_owner) || (valid_owner and last_owner == GDSync.get_client_id())
|
||||
BROADCAST_MODE.WHEN_HOST_AND_NO_OWNER_OR_OWNER:
|
||||
_should_broadcast = (is_host and GDSync.get_gdsync_owner(self) < 0) || is_owner
|
||||
BROADCAST_MODE.ALWAYS:
|
||||
_should_broadcast = true
|
||||
BROADCAST_MODE.NEVER:
|
||||
_should_broadcast = false
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://blnp51hc3v78q
|
||||
|
|
@ -0,0 +1,61 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png")
|
||||
extends AudioStreamPlayer
|
||||
class_name SynchronizedAudioStreamPlayer
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
func play_synced(from_position : float = 0.0) -> void:
|
||||
GDSync.sync_var_relevant(self, "volume_db")
|
||||
GDSync.sync_var_relevant(self, "pitch_scale")
|
||||
GDSync.call_func_all_relevant(_play_remote, from_position)
|
||||
|
||||
func stop_synced() -> void:
|
||||
GDSync.call_func_all_relevant(_stop_remote)
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
func _ready() -> void:
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
GDSync.expose_var(self, "volume_db")
|
||||
GDSync.expose_var(self, "pitch_scale")
|
||||
|
||||
GDSync.expose_func(_play_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
|
||||
func _play_remote(from_position : float) -> void:
|
||||
play(from_position)
|
||||
|
||||
func _stop_remote() -> void:
|
||||
stop()
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !playing:
|
||||
return
|
||||
GDSync.sync_var_on(client_id, self, "volume_db")
|
||||
GDSync.sync_var_on(client_id, self, "pitch_scale")
|
||||
GDSync.call_func_on(client_id, _play_remote, get_playback_position())
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://bqmvgr8uw1gt1
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png")
|
||||
extends AudioStreamPlayer2D
|
||||
class_name SynchronizedAudioStreamPlayer2D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
func play_synced(from_position : float = 0.0) -> void:
|
||||
GDSync.sync_var_relevant(self, "volume_db")
|
||||
GDSync.sync_var_relevant(self, "pitch_scale")
|
||||
GDSync.sync_var_relevant(self, "max_distance")
|
||||
GDSync.sync_var_relevant(self, "attenuation")
|
||||
GDSync.call_func_all_relevant(_play_remote, from_position)
|
||||
|
||||
func stop_synced() -> void:
|
||||
GDSync.call_func_all_relevant(_stop_remote)
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
func _ready() -> void:
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
GDSync.expose_var(self, "volume_db")
|
||||
GDSync.expose_var(self, "pitch_scale")
|
||||
GDSync.expose_var(self, "max_distance")
|
||||
GDSync.expose_var(self, "attenuation")
|
||||
|
||||
GDSync.expose_func(_play_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
|
||||
func _play_remote(from_position : float) -> void:
|
||||
play(from_position)
|
||||
|
||||
func _stop_remote() -> void:
|
||||
stop()
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !playing:
|
||||
return
|
||||
for property_name in ["volume_db", "pitch_scale", "max_distance", "attenuation"]:
|
||||
GDSync.sync_var_on(client_id, self, property_name)
|
||||
GDSync.call_func_on(client_id, _play_remote, get_playback_position())
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://bktq6dqr2x8j5
|
||||
|
|
@ -0,0 +1,69 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedAudioStreamPlayer.png")
|
||||
extends AudioStreamPlayer3D
|
||||
class_name SynchronizedAudioStreamPlayer3D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
func play_synced(from_position : float = 0.0) -> void:
|
||||
GDSync.sync_var_relevant(self, "volume_db")
|
||||
GDSync.sync_var_relevant(self, "unit_size")
|
||||
GDSync.sync_var_relevant(self, "max_db")
|
||||
GDSync.sync_var_relevant(self, "pitch_scale")
|
||||
GDSync.sync_var_relevant(self, "max_distance")
|
||||
GDSync.sync_var_relevant(self, "attenuation")
|
||||
GDSync.call_func_all_relevant(_play_remote, from_position)
|
||||
|
||||
func stop_synced() -> void:
|
||||
GDSync.call_func_all_relevant(_stop_remote)
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
func _ready() -> void:
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
GDSync.expose_var(self, "volume_db")
|
||||
GDSync.expose_var(self, "unit_size")
|
||||
GDSync.expose_var(self, "max_db")
|
||||
GDSync.expose_var(self, "pitch_scale")
|
||||
GDSync.expose_var(self, "max_distance")
|
||||
GDSync.expose_var(self, "attenuation")
|
||||
|
||||
GDSync.expose_func(_play_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
|
||||
func _play_remote(from_position : float) -> void:
|
||||
play(from_position)
|
||||
|
||||
func _stop_remote() -> void:
|
||||
stop()
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !playing:
|
||||
return
|
||||
for property_name in ["volume_db", "unit_size", "max_db", "pitch_scale", "max_distance", "attenuation"]:
|
||||
GDSync.sync_var_on(client_id, self, property_name)
|
||||
GDSync.call_func_on(client_id, _play_remote, get_playback_position())
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://ce0kf7sfcsjfw
|
||||
110
addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd
Normal file
110
addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles2D.gd
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png")
|
||||
extends GPUParticles2D
|
||||
class_name SynchronizedGPUParticles2D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## Restarts this particle system on all relevant clients with a shared random seed.
|
||||
## Useful for one-shot effects such as explosions, impacts, and bursts.
|
||||
func restart_synced() -> void:
|
||||
var particle_seed : int = _generate_seed()
|
||||
_sync_particle_properties()
|
||||
GDSync.call_func_all_relevant(_restart_remote, particle_seed)
|
||||
|
||||
## Starts emitting on all relevant clients with a shared random seed so the
|
||||
## particle look matches across clients.
|
||||
func emit_synced() -> void:
|
||||
var particle_seed : int = _generate_seed()
|
||||
_sync_particle_properties()
|
||||
GDSync.call_func_all_relevant(_emit_remote, particle_seed)
|
||||
|
||||
## Stops emitting on all relevant clients.
|
||||
func stop_synced() -> void:
|
||||
GDSync.call_func_all_relevant(_stop_remote)
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
const _SYNCED_PROPERTIES : PackedStringArray = [
|
||||
"amount",
|
||||
"lifetime",
|
||||
"one_shot",
|
||||
"preprocess",
|
||||
"speed_scale",
|
||||
"explosiveness",
|
||||
"randomness",
|
||||
"fixed_fps",
|
||||
"fract_delta",
|
||||
"interpolate",
|
||||
"local_coords",
|
||||
]
|
||||
|
||||
var GDSync
|
||||
var _last_seed : int = 0
|
||||
|
||||
func _ready() -> void:
|
||||
use_fixed_seed = true
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
for property_name in _SYNCED_PROPERTIES:
|
||||
GDSync.expose_var(self, property_name)
|
||||
|
||||
GDSync.expose_func(_restart_remote)
|
||||
GDSync.expose_func(_emit_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
|
||||
func _generate_seed() -> int:
|
||||
_last_seed = randi()
|
||||
return _last_seed
|
||||
|
||||
func _apply_seed(particle_seed : int) -> void:
|
||||
use_fixed_seed = true
|
||||
seed = particle_seed
|
||||
_last_seed = particle_seed
|
||||
|
||||
func _sync_particle_properties() -> void:
|
||||
for property_name in _SYNCED_PROPERTIES:
|
||||
GDSync.sync_var_relevant(self, property_name)
|
||||
|
||||
func _restart_remote(particle_seed : int) -> void:
|
||||
_apply_seed(particle_seed)
|
||||
restart(true)
|
||||
|
||||
func _emit_remote(particle_seed : int) -> void:
|
||||
_apply_seed(particle_seed)
|
||||
emitting = true
|
||||
restart(true)
|
||||
|
||||
func _stop_remote() -> void:
|
||||
emitting = false
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !emitting:
|
||||
return
|
||||
for property_name in _SYNCED_PROPERTIES:
|
||||
GDSync.sync_var_on(client_id, self, property_name)
|
||||
GDSync.call_func_on(client_id, _restart_remote, _last_seed)
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://cla81vxh3ep7b
|
||||
110
addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd
Normal file
110
addons/GD-Sync/Scripts/Types/SynchronizedGPUParticles3D.gd
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedGPUParticles.png")
|
||||
extends GPUParticles3D
|
||||
class_name SynchronizedGPUParticles3D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## Restarts this particle system on all relevant clients with a shared random seed.
|
||||
## Useful for one-shot effects such as explosions, impacts, and bursts.
|
||||
func restart_synced() -> void:
|
||||
var particle_seed : int = _generate_seed()
|
||||
_sync_particle_properties()
|
||||
GDSync.call_func_all_relevant(_restart_remote, particle_seed)
|
||||
|
||||
## Starts emitting on all relevant clients with a shared random seed so the
|
||||
## particle look matches across clients.
|
||||
func emit_synced() -> void:
|
||||
var particle_seed : int = _generate_seed()
|
||||
_sync_particle_properties()
|
||||
GDSync.call_func_all_relevant(_emit_remote, particle_seed)
|
||||
|
||||
## Stops emitting on all relevant clients.
|
||||
func stop_synced() -> void:
|
||||
GDSync.call_func_all_relevant(_stop_remote)
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
const _SYNCED_PROPERTIES : PackedStringArray = [
|
||||
"amount",
|
||||
"lifetime",
|
||||
"one_shot",
|
||||
"preprocess",
|
||||
"speed_scale",
|
||||
"explosiveness",
|
||||
"randomness",
|
||||
"fixed_fps",
|
||||
"fract_delta",
|
||||
"interpolate",
|
||||
"local_coords",
|
||||
]
|
||||
|
||||
var GDSync
|
||||
var _last_seed : int = 0
|
||||
|
||||
func _ready() -> void:
|
||||
use_fixed_seed = true
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
for property_name in _SYNCED_PROPERTIES:
|
||||
GDSync.expose_var(self, property_name)
|
||||
|
||||
GDSync.expose_func(_restart_remote)
|
||||
GDSync.expose_func(_emit_remote)
|
||||
GDSync.expose_func(_stop_remote)
|
||||
|
||||
func _generate_seed() -> int:
|
||||
_last_seed = randi()
|
||||
return _last_seed
|
||||
|
||||
func _apply_seed(particle_seed : int) -> void:
|
||||
use_fixed_seed = true
|
||||
seed = particle_seed
|
||||
_last_seed = particle_seed
|
||||
|
||||
func _sync_particle_properties() -> void:
|
||||
for property_name in _SYNCED_PROPERTIES:
|
||||
GDSync.sync_var_relevant(self, property_name)
|
||||
|
||||
func _restart_remote(particle_seed : int) -> void:
|
||||
_apply_seed(particle_seed)
|
||||
restart(true)
|
||||
|
||||
func _emit_remote(particle_seed : int) -> void:
|
||||
_apply_seed(particle_seed)
|
||||
emitting = true
|
||||
restart(true)
|
||||
|
||||
func _stop_remote() -> void:
|
||||
emitting = false
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !emitting:
|
||||
return
|
||||
for property_name in _SYNCED_PROPERTIES:
|
||||
GDSync.sync_var_on(client_id, self, property_name)
|
||||
GDSync.call_func_on(client_id, _restart_remote, _last_seed)
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://dhtpleux5en4e
|
||||
247
addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd
Normal file
247
addons/GD-Sync/Scripts/Types/SynchronizedRigidBody2D.gd
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png")
|
||||
extends RigidBody2D
|
||||
class_name SynchronizedRigidBody2D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## How many times per second the body should be synchronized.
|
||||
@export var refresh_rate : int = 30
|
||||
|
||||
func apply_central_impulse_synced(impulse : Vector2 = Vector2.ZERO) -> void:
|
||||
super.apply_central_impulse(impulse)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_central_force_synced(force : Vector2) -> void:
|
||||
super.apply_central_force(force)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_impulse_synced(impulse: Vector2, position: Vector2 = Vector2(0, 0)) -> void:
|
||||
super.apply_impulse(impulse, position)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_force_synced(force: Vector2, position: Vector2 = Vector2(0, 0)) -> void:
|
||||
super.apply_force(force, position)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_torque_synced(torque: float) -> void:
|
||||
super.apply_torque(torque)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_torque_impulse_synced(impulse: float) -> void:
|
||||
super.apply_torque_impulse(impulse)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
var _cooldown : float = 0.0
|
||||
var _current_cooldown : float = 0.0
|
||||
var _current_fixed_cooldown : float = 0.0
|
||||
var _should_broadcast : bool = false
|
||||
var _last_owner : int = -1
|
||||
|
||||
var _pending_sync : bool = true
|
||||
var _force_sync : bool = false
|
||||
var _pending_correction : bool = false
|
||||
|
||||
var _remote_position : Vector2
|
||||
var _remote_rotation : float
|
||||
var _remote_linear_velocity : Vector2
|
||||
var _remote_angular_velocity : float
|
||||
|
||||
var _disable_correction_counter : int = 0
|
||||
|
||||
var _last_sync_position : Vector2 = Vector2.ZERO
|
||||
var _last_sync_rotation : float = 0.0
|
||||
var _last_sync_linear_velocity : Vector2 = Vector2.ZERO
|
||||
var _last_sync_angular_velocity : float = 0.0
|
||||
|
||||
const _FIXED_COOLDOWN : float = 10.0
|
||||
const _SYNC_LINEAR_VELOCITY_THRESHOLD : float = 0.1
|
||||
const _SYNC_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
|
||||
const _SYNC_ROTATION_THRESHOLD : float = 0.01
|
||||
const _SYNC_POSITION_THRESHOLD : float = 0.01
|
||||
const _CORRECTION_ROTATION_THRESHOLD : float = 0.03
|
||||
const _CORRECTION_LINEAR_VELOCITY_THRESHOLD : float = 0.1
|
||||
const _CORRECTION_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
|
||||
const _CORRECTION_POSITION_THRESHOLD : float = 0.01
|
||||
|
||||
func _ready() -> void:
|
||||
if !Engine.is_editor_hint():
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
_cooldown = 1.0/refresh_rate
|
||||
_last_owner = GDSync.get_gdsync_owner(self)
|
||||
can_sleep = false
|
||||
|
||||
GDSync.expose_func(_sync_received)
|
||||
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.client_joined.connect(_client_joined)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
|
||||
_update_sync_mode()
|
||||
_current_fixed_cooldown = 2.0
|
||||
|
||||
func _physics_process(delta: float) -> void:
|
||||
if _should_broadcast:
|
||||
if _may_synchronize(delta):
|
||||
var current_rot : float = global_transform.get_rotation()
|
||||
var rot_diff : float = current_rot - _last_sync_rotation
|
||||
if (
|
||||
_force_sync or
|
||||
abs((global_transform.origin - _last_sync_position).length_squared()) > _SYNC_POSITION_THRESHOLD or
|
||||
abs((linear_velocity - _last_sync_linear_velocity).length_squared()) > _SYNC_LINEAR_VELOCITY_THRESHOLD or
|
||||
abs(angular_velocity - _last_sync_angular_velocity) > _SYNC_ANGULAR_VELOCITY_THRESHOLD or
|
||||
abs(rot_diff) > _SYNC_ROTATION_THRESHOLD
|
||||
):
|
||||
_last_sync_linear_velocity = linear_velocity
|
||||
_last_sync_angular_velocity = angular_velocity
|
||||
_last_sync_position = global_transform.origin
|
||||
_last_sync_rotation = current_rot
|
||||
_pending_sync = true
|
||||
_force_sync = false
|
||||
else:
|
||||
_remote_position += _remote_linear_velocity * delta
|
||||
_remote_rotation += _remote_angular_velocity * delta
|
||||
|
||||
func _may_synchronize(delta : float) -> bool:
|
||||
_current_cooldown -= delta
|
||||
if _current_cooldown <= 0:
|
||||
_current_cooldown += _cooldown
|
||||
return true
|
||||
|
||||
_current_fixed_cooldown -= delta
|
||||
if _current_fixed_cooldown <= 0.0:
|
||||
_current_fixed_cooldown += _FIXED_COOLDOWN
|
||||
_force_sync = true
|
||||
return true
|
||||
return false
|
||||
|
||||
func _integrate_forces(state: PhysicsDirectBodyState2D) -> void:
|
||||
if _should_broadcast:
|
||||
if _pending_correction:
|
||||
_pending_correction = false
|
||||
state.linear_velocity = _remote_linear_velocity
|
||||
state.angular_velocity = _remote_angular_velocity
|
||||
state.transform = Transform2D(_remote_rotation, _remote_position)
|
||||
|
||||
if _pending_sync:
|
||||
_pending_sync = false
|
||||
GDSync.call_func_relevant(
|
||||
_sync_received,
|
||||
GDSync.get_multiplayer_time(),
|
||||
state.linear_velocity,
|
||||
state.angular_velocity,
|
||||
state.transform.origin,
|
||||
state.transform.get_rotation()
|
||||
)
|
||||
_sync_received(GDSync.get_multiplayer_time(),
|
||||
state.linear_velocity,
|
||||
state.angular_velocity,
|
||||
state.transform.origin,
|
||||
state.transform.get_rotation())
|
||||
else:
|
||||
var rot_diff : float = state.transform.get_rotation() - _remote_rotation
|
||||
if (
|
||||
_disable_correction_counter == 0 and (
|
||||
abs((state.linear_velocity - _remote_linear_velocity).length_squared()) > _CORRECTION_LINEAR_VELOCITY_THRESHOLD or
|
||||
abs(state.angular_velocity - _remote_angular_velocity) > _CORRECTION_ANGULAR_VELOCITY_THRESHOLD or
|
||||
abs((state.transform.origin - _remote_position).length_squared()) > _CORRECTION_POSITION_THRESHOLD or
|
||||
abs(rot_diff) > _CORRECTION_ROTATION_THRESHOLD
|
||||
)):
|
||||
state.linear_velocity = _remote_linear_velocity
|
||||
state.angular_velocity = _remote_angular_velocity
|
||||
state.transform = Transform2D(
|
||||
lerp_angle(state.transform.get_rotation(), _remote_rotation, 0.3),
|
||||
lerp(state.transform.origin, _remote_position, 0.3))
|
||||
|
||||
func _sync_received(time : float, lv : Vector2, av : float, pos : Vector2, rotation : float) -> void:
|
||||
var delta : float = min(GDSync.get_multiplayer_time() - time, 0.3)
|
||||
_remote_linear_velocity = lv
|
||||
_remote_angular_velocity = av
|
||||
_remote_position = pos + _remote_linear_velocity * delta
|
||||
_remote_rotation = rotation + _remote_angular_velocity * delta
|
||||
_last_sync_linear_velocity = _remote_linear_velocity
|
||||
_last_sync_angular_velocity = _remote_angular_velocity
|
||||
_last_sync_position = pos
|
||||
_last_sync_rotation = rotation
|
||||
sleeping = false
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !_should_broadcast:
|
||||
return
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
_sync_received,
|
||||
GDSync.get_multiplayer_time(),
|
||||
linear_velocity,
|
||||
angular_velocity,
|
||||
global_position,
|
||||
global_rotation
|
||||
)
|
||||
|
||||
func _owner_changed(owner) -> void:
|
||||
if owner >= 0: _last_owner = owner
|
||||
_update_sync_mode()
|
||||
|
||||
func _client_joined(client_id : int) -> void:
|
||||
if _should_broadcast:
|
||||
_pending_sync = true
|
||||
|
||||
func _host_changed(is_host : bool, new_host_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _update_sync_mode() -> void:
|
||||
if Engine.is_editor_hint() || GDSync == null: return
|
||||
var is_host : bool = GDSync.is_host()
|
||||
var is_owner : bool = GDSync.is_gdsync_owner(self)
|
||||
var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
|
||||
_should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
|
||||
|
||||
func _get_configuration_warnings() -> PackedStringArray:
|
||||
var warnings : PackedStringArray = []
|
||||
|
||||
warnings.append("The SynchronizedRigidBody2D Node is experimental. Please report any issues on GitHub.")
|
||||
|
||||
return warnings
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://b78awbtrt2vik
|
||||
251
addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd
Normal file
251
addons/GD-Sync/Scripts/Types/SynchronizedRigidBody3D.gd
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/SynchronizedRigidBody3D.png")
|
||||
extends RigidBody3D
|
||||
class_name SynchronizedRigidBody3D
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## How many times per second the body should be synchronized.
|
||||
@export var refresh_rate : int = 30
|
||||
|
||||
func apply_central_impulse_synced(impulse : Vector3) -> void:
|
||||
super.apply_central_impulse(impulse)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_central_force_synced(force : Vector3) -> void:
|
||||
super.apply_central_force(force)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_impulse_synced(impulse: Vector3, position: Vector3 = Vector3(0, 0, 0)) -> void:
|
||||
super.apply_impulse(impulse, position)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_force_synced(force: Vector3, position: Vector3 = Vector3(0, 0, 0)) -> void:
|
||||
super.apply_force(force, position)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_torque_synced(torque: Vector3) -> void:
|
||||
super.apply_torque(torque)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
func apply_torque_impulse_synced(impulse: Vector3) -> void:
|
||||
super.apply_torque_impulse(impulse)
|
||||
await get_tree().physics_frame
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
GDSync.set_gdsync_owner(self, GDSync.get_client_id())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#Private functions ----------------------------------------------------------------------
|
||||
|
||||
var GDSync
|
||||
|
||||
var _cooldown : float = 0.0
|
||||
var _current_cooldown : float = 0.0
|
||||
var _current_fixed_cooldown : float = 0.0
|
||||
var _should_broadcast : bool = false
|
||||
var _last_owner : int = -1
|
||||
|
||||
var _pending_sync : bool = true
|
||||
var _force_sync : bool = false
|
||||
var _pending_correction : bool = false
|
||||
|
||||
var _remote_position : Vector3
|
||||
var _remote_euler : Vector3
|
||||
var _remote_linear_velocity : Vector3
|
||||
var _remote_angular_velocity : Vector3
|
||||
|
||||
var _disable_correction_counter : int = 0
|
||||
|
||||
var _last_sync_position : Vector3 = Vector3.ZERO
|
||||
var _last_sync_rotation : Vector3 = Vector3.UP
|
||||
var _last_sync_linear_velocity : Vector3 = Vector3.ZERO
|
||||
var _last_sync_angular_velocity : Vector3 = Vector3.ZERO
|
||||
|
||||
const _FIXED_COOLDOWN : float = 10.0
|
||||
const _SYNC_LINEAR_VELOCITY_THRESHOLD : float = 0.1
|
||||
const _SYNC_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
|
||||
const _SYNC_ROTATION_THRESHOLD : float = 0.01
|
||||
const _SYNC_POSITION_THRESHOLD : float = 0.01
|
||||
const _CORRECTION_ROTATION_THRESHOLD : float = 0.03
|
||||
const _CORRECTION_LINEAR_VELOCITY_THRESHOLD : float = 0.1
|
||||
const _CORRECTION_ANGULAR_VELOCITY_THRESHOLD : float = 0.05
|
||||
const _CORRECTION_POSITION_THRESHOLD : float = 0.01
|
||||
|
||||
func _ready() -> void:
|
||||
if !Engine.is_editor_hint():
|
||||
GDSync = get_node("/root/GDSync")
|
||||
|
||||
_cooldown = 1.0/refresh_rate
|
||||
_last_owner = GDSync.get_gdsync_owner(self)
|
||||
can_sleep = false
|
||||
|
||||
GDSync.expose_func(_sync_received)
|
||||
|
||||
GDSync.host_changed.connect(_host_changed)
|
||||
GDSync.client_joined.connect(_client_joined)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
|
||||
_update_sync_mode()
|
||||
_current_fixed_cooldown = 2.0
|
||||
|
||||
func _physics_process(delta: float) -> void:
|
||||
if _should_broadcast:
|
||||
if _may_synchronize(delta):
|
||||
var current_rot : Vector3 = global_transform.basis.get_euler()
|
||||
var rot_diff : Vector3 = current_rot-_last_sync_rotation
|
||||
if (
|
||||
_force_sync or
|
||||
abs((global_transform.origin-_last_sync_position).length_squared()) > _SYNC_POSITION_THRESHOLD or
|
||||
abs((linear_velocity-_last_sync_linear_velocity).length_squared()) > _SYNC_LINEAR_VELOCITY_THRESHOLD or
|
||||
abs((angular_velocity-_last_sync_angular_velocity).length_squared()) > _SYNC_ANGULAR_VELOCITY_THRESHOLD or
|
||||
abs(rot_diff.x) > _SYNC_ROTATION_THRESHOLD or
|
||||
abs(rot_diff.y) > _SYNC_ROTATION_THRESHOLD or
|
||||
abs(rot_diff.z) > _SYNC_ROTATION_THRESHOLD
|
||||
):
|
||||
_last_sync_linear_velocity = linear_velocity
|
||||
_last_sync_angular_velocity = angular_velocity
|
||||
_last_sync_position = global_transform.origin
|
||||
_last_sync_rotation = current_rot
|
||||
_pending_sync = true
|
||||
_force_sync = false
|
||||
|
||||
#_remote_position += _remote_linear_velocity * delta
|
||||
#_remote_euler += _remote_angular_velocity*delta
|
||||
|
||||
func _may_synchronize(delta : float) -> bool:
|
||||
_current_cooldown -= delta
|
||||
if _current_cooldown <= 0:
|
||||
_current_cooldown += _cooldown
|
||||
return true
|
||||
|
||||
_current_fixed_cooldown -= delta
|
||||
if _current_fixed_cooldown <= 0.0:
|
||||
_current_fixed_cooldown += _FIXED_COOLDOWN
|
||||
_force_sync = true
|
||||
return true
|
||||
return false
|
||||
|
||||
func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
|
||||
if _should_broadcast:
|
||||
if _pending_correction:
|
||||
_pending_correction = false
|
||||
state.linear_velocity = _remote_linear_velocity
|
||||
state.angular_velocity = _remote_angular_velocity
|
||||
state.transform.origin = _remote_position
|
||||
state.transform.basis = Basis(Quaternion.from_euler(_remote_euler))
|
||||
|
||||
if _pending_sync:
|
||||
_pending_sync = false
|
||||
GDSync.call_func_relevant(
|
||||
_sync_received,
|
||||
GDSync.get_multiplayer_time(),
|
||||
state.linear_velocity,
|
||||
state.angular_velocity,
|
||||
state.transform.origin,
|
||||
state.transform.basis.get_euler()
|
||||
)
|
||||
_sync_received(GDSync.get_multiplayer_time(),
|
||||
state.linear_velocity,
|
||||
state.angular_velocity,
|
||||
state.transform.origin,
|
||||
state.transform.basis.get_euler())
|
||||
else:
|
||||
var rot_diff : Vector3 = state.transform.basis.get_euler()-_remote_euler
|
||||
if (
|
||||
_disable_correction_counter == 0 and (
|
||||
abs((state.linear_velocity-_remote_linear_velocity).length_squared()) > _CORRECTION_LINEAR_VELOCITY_THRESHOLD or
|
||||
abs((state.angular_velocity-_remote_angular_velocity).length_squared()) > _CORRECTION_ANGULAR_VELOCITY_THRESHOLD or
|
||||
abs((state.transform.origin-_remote_position).length_squared()) > _CORRECTION_POSITION_THRESHOLD or
|
||||
abs(rot_diff.x) > _CORRECTION_ROTATION_THRESHOLD or
|
||||
abs(rot_diff.y) > _CORRECTION_ROTATION_THRESHOLD or
|
||||
abs(rot_diff.z) > _CORRECTION_ROTATION_THRESHOLD
|
||||
)):
|
||||
state.linear_velocity = _remote_linear_velocity
|
||||
state.angular_velocity = _remote_angular_velocity
|
||||
state.transform.origin = lerp(state.transform.origin, _remote_position, 0.3)
|
||||
state.transform.basis = state.transform.basis.slerp(Basis(Quaternion.from_euler(_remote_euler)), 0.3)
|
||||
|
||||
func _sync_received(time : float, lv : Vector3, av : Vector3, pos : Vector3, euler : Vector3) -> void:
|
||||
var delta : float = min(GDSync.get_multiplayer_time()-time, 0.3)
|
||||
_remote_linear_velocity = lv
|
||||
_remote_angular_velocity = av
|
||||
_remote_position = pos + _remote_linear_velocity*delta
|
||||
_remote_euler = euler + _remote_angular_velocity*delta
|
||||
_last_sync_linear_velocity = _remote_linear_velocity
|
||||
_last_sync_angular_velocity = _remote_angular_velocity
|
||||
_last_sync_position = pos
|
||||
_last_sync_rotation = euler
|
||||
sleeping = false
|
||||
|
||||
func _interest_object_client_entered(client_id : int) -> void:
|
||||
if !_should_broadcast:
|
||||
return
|
||||
GDSync.call_func_on(
|
||||
client_id,
|
||||
_sync_received,
|
||||
GDSync.get_multiplayer_time(),
|
||||
linear_velocity,
|
||||
angular_velocity,
|
||||
global_position,
|
||||
global_rotation
|
||||
)
|
||||
|
||||
func _owner_changed(owner) -> void:
|
||||
if owner >= 0: _last_owner = owner
|
||||
_update_sync_mode()
|
||||
|
||||
func _client_joined(client_id : int) -> void:
|
||||
if _should_broadcast:
|
||||
_pending_sync = true
|
||||
|
||||
func _host_changed(is_host : bool, new_host_id : int) -> void:
|
||||
_update_sync_mode()
|
||||
|
||||
func _update_sync_mode() -> void:
|
||||
if Engine.is_editor_hint() || GDSync == null: return
|
||||
var is_host : bool = GDSync.is_host()
|
||||
var is_owner : bool = GDSync.is_gdsync_owner(self)
|
||||
var valid_owner : bool = GDSync.lobby_get_all_clients().has(_last_owner)
|
||||
_should_broadcast = (is_host and !valid_owner) || (valid_owner and _last_owner == GDSync.get_client_id())
|
||||
|
||||
func _get_configuration_warnings() -> PackedStringArray:
|
||||
var warnings : PackedStringArray = []
|
||||
|
||||
warnings.append("The SynchronizedRigidBody3D Node is experimental. Please report any issues on GitHub.")
|
||||
|
||||
return warnings
|
||||
|
|
@ -0,0 +1 @@
|
|||
uid://doew6w5001xmd
|
||||
267
addons/GD-Sync/Scripts/Types/VoiceChat.gd
Normal file
267
addons/GD-Sync/Scripts/Types/VoiceChat.gd
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
@tool
|
||||
@icon("res://addons/GD-Sync/UI/Icons/VoiceChatIcon.png")
|
||||
extends Node
|
||||
class_name VoiceChat
|
||||
|
||||
#Copyright (c) 2023-present GD-Sync.
|
||||
#All rights reserved.
|
||||
#
|
||||
#Redistribution and use in source form, with or without modification,
|
||||
#are permitted provided that the following conditions are met:
|
||||
#
|
||||
#1. Redistributions of source code must retain the above copyright notice,
|
||||
# this list of conditions and the following disclaimer.
|
||||
#
|
||||
#2. Neither the name of GD-Sync nor the names of its contributors may be used
|
||||
# to endorse or promote products derived from this software without specific
|
||||
# prior written permission.
|
||||
#
|
||||
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
|
||||
#EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
|
||||
#OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
|
||||
#SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
|
||||
#INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
||||
#TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
||||
#BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
#CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
||||
#ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
|
||||
#SUCH DAMAGE.
|
||||
|
||||
## The minimum input volume at which the audio is broadcasted to other players.
|
||||
@export var input_volume_threshold : float = 0.01
|
||||
## The audio quality. Not recommended to go above Medium.
|
||||
@export_enum("Very High", "High", "Medium", "Low") var audio_quality : int = 2 :
|
||||
set(value):
|
||||
audio_quality = value
|
||||
update_configuration_warnings()
|
||||
|
||||
@export_group("Audio Bus")
|
||||
## Any extra effects you would like to be added to the record bus.
|
||||
@export var record_effects : Array[AudioEffect] = []
|
||||
|
||||
@export_group("Output")
|
||||
## Allows you to create 2D or 3D spatial audio, where players can only hear each other when close ingame.
|
||||
@export_enum("None", "2D", "3D") var spatial_mode : int :
|
||||
set(value):
|
||||
spatial_mode = value
|
||||
notify_property_list_changed()
|
||||
|
||||
var _bus_index : int = -1
|
||||
var _bus_name : String = "GDRecord"
|
||||
|
||||
var _microphone_stream : AudioStreamMicrophone
|
||||
var _record_effect : AudioEffectCapture
|
||||
|
||||
var _output_stream : AudioStreamGenerator
|
||||
var _output_stream_playback : AudioStreamGeneratorPlayback
|
||||
## The output player which will play received voice samples.
|
||||
var _output_player : Node : set = set_output_player
|
||||
|
||||
var _input_configured : bool = false
|
||||
var _output_configured : bool = false
|
||||
var _muted : bool = false
|
||||
|
||||
var GDSync
|
||||
|
||||
func set_input_device(device_name : String) -> void:
|
||||
AudioServer.input_device = device_name
|
||||
|
||||
func get_input_devices() -> PackedStringArray:
|
||||
return AudioServer.get_input_device_list()
|
||||
|
||||
func mute_microphone() -> void:
|
||||
_muted = true
|
||||
|
||||
func unmute_microphone() -> void:
|
||||
_muted = false
|
||||
|
||||
func _ready() -> void:
|
||||
if Engine.is_editor_hint():
|
||||
set_process(false)
|
||||
return
|
||||
|
||||
GDSync = get_node("/root/GDSync")
|
||||
GDSync.expose_func(_process_audio)
|
||||
GDSync.connect_gdsync_owner_changed(self, _owner_changed)
|
||||
|
||||
_configure_bus()
|
||||
|
||||
if _output_player == null:
|
||||
push_error("Output Node is null.")
|
||||
set_process(false)
|
||||
return
|
||||
|
||||
if GDSync.is_gdsync_owner(self):
|
||||
_configure_input()
|
||||
else:
|
||||
_configure_output()
|
||||
|
||||
func _owner_changed(owner_id : int) -> void:
|
||||
if GDSync.is_gdsync_owner(self):
|
||||
_configure_input()
|
||||
else:
|
||||
_configure_output()
|
||||
|
||||
func _process(delta: float) -> void:
|
||||
if !GDSync.is_gdsync_owner(self):
|
||||
return
|
||||
|
||||
if _input_configured and _record_effect.get_frames_available() > 0:
|
||||
if _muted:
|
||||
_record_effect.clear_buffer()
|
||||
return
|
||||
|
||||
var recording_data : PackedVector2Array = _record_effect.get_buffer(_record_effect.get_frames_available())
|
||||
var data : PackedFloat32Array = PackedFloat32Array()
|
||||
|
||||
var sr : float = AudioServer.get_mix_rate()
|
||||
match(audio_quality):
|
||||
0:
|
||||
_sample_raw(recording_data, data)
|
||||
1:
|
||||
_downsample_half(recording_data, data)
|
||||
sr /= 2.0
|
||||
2:
|
||||
_downsample_quarter(recording_data, data)
|
||||
sr /= 4.0
|
||||
3:
|
||||
_downsample_eighth(recording_data, data)
|
||||
sr /= 8.0
|
||||
|
||||
var max_amp : float = 0.0
|
||||
for i in range(data.size()):
|
||||
max_amp = max(abs(data[i]), max_amp)
|
||||
|
||||
if max_amp > input_volume_threshold:
|
||||
GDSync.call_func_relevant_unreliable(_process_audio, data, sr)
|
||||
|
||||
func _process_audio(audio : PackedFloat32Array, mixrate : float) -> void:
|
||||
if _output_stream.mix_rate != mixrate: _output_stream.mix_rate = mixrate
|
||||
for i in range(min(_output_stream_playback.get_frames_available(), audio.size())):
|
||||
var d : float = audio[i]
|
||||
_output_stream_playback.push_frame(Vector2(d, d))
|
||||
|
||||
func _sample_raw(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
|
||||
var frames : int = recording_data.size()
|
||||
data.resize(frames)
|
||||
for i in range(frames):
|
||||
data[i] = (recording_data[i].x + recording_data[i].y) / 2
|
||||
return data
|
||||
|
||||
func _downsample_half(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
|
||||
var frames : int = recording_data.size()
|
||||
var half_frames : int = frames / 2
|
||||
data.resize(half_frames)
|
||||
for i in range(half_frames):
|
||||
var v1 : float = (recording_data[i * 2].x + recording_data[i * 2].y) / 2
|
||||
var v2 : float = (recording_data[i * 2 + 1].x + recording_data[i * 2 + 1].y) / 2
|
||||
data[i] = (v1 + v2) / 2
|
||||
return data
|
||||
|
||||
func _downsample_quarter(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
|
||||
var frames : int = recording_data.size()
|
||||
var quarter_frames : int = frames / 4
|
||||
data.resize(quarter_frames)
|
||||
for i in range(quarter_frames):
|
||||
var v0 : float = (recording_data[i * 4].x + recording_data[i * 4].y) / 2
|
||||
var v1 : float = (recording_data[i * 4 + 1].x + recording_data[i * 4 + 1].y) / 2
|
||||
var v2 : float = (recording_data[i * 4 + 2].x + recording_data[i * 4 + 2].y) / 2
|
||||
var v3 : float = (recording_data[i * 4 + 3].x + recording_data[i * 4 + 3].y) / 2
|
||||
data[i] = (v0 + v1 + v2 + v3) / 4
|
||||
return data
|
||||
|
||||
func _downsample_eighth(recording_data: PackedVector2Array, data : PackedFloat32Array) -> PackedFloat32Array:
|
||||
var frames : int = recording_data.size()
|
||||
var eighth_frames : int = frames / 8
|
||||
data.resize(eighth_frames)
|
||||
for i in range(eighth_frames):
|
||||
var sum : float = 0.0
|
||||
for j in range(8):
|
||||
sum += (recording_data[i * 8 + j].x + recording_data[i * 8 + j].y) / 2
|
||||
data[i] = sum / 8
|
||||
return data
|
||||
|
||||
func _configure_bus() -> void:
|
||||
for i in range(AudioServer.bus_count):
|
||||
if AudioServer.get_bus_name(i) == _bus_name:
|
||||
_record_effect = AudioServer.get_bus_effect(i, AudioServer.get_bus_effect_count(i)-1)
|
||||
_bus_index = i
|
||||
|
||||
if _bus_index >= 0:
|
||||
return
|
||||
|
||||
_bus_index = AudioServer.bus_count
|
||||
AudioServer.add_bus(_bus_index)
|
||||
AudioServer.set_bus_name(_bus_index, _bus_name)
|
||||
AudioServer.set_bus_mute(_bus_index, true)
|
||||
|
||||
for effect in record_effects:
|
||||
AudioServer.add_bus_effect(_bus_index, effect)
|
||||
|
||||
_record_effect = AudioEffectCapture.new()
|
||||
AudioServer.add_bus_effect(_bus_index, _record_effect)
|
||||
|
||||
func _configure_input() -> void:
|
||||
if _input_configured:
|
||||
return
|
||||
_input_configured = true
|
||||
|
||||
_microphone_stream = AudioStreamMicrophone.new()
|
||||
|
||||
var microphone_player : AudioStreamPlayer = AudioStreamPlayer.new()
|
||||
microphone_player.name = "MicIn"
|
||||
add_child(microphone_player)
|
||||
microphone_player.bus = _bus_name
|
||||
microphone_player.stream = _microphone_stream
|
||||
microphone_player.play()
|
||||
|
||||
func _configure_output() -> void:
|
||||
if _output_configured:
|
||||
return
|
||||
_output_configured = true
|
||||
|
||||
_output_stream = AudioStreamGenerator.new()
|
||||
_output_stream.buffer_length = 0.1
|
||||
_output_player.stream = _output_stream
|
||||
_output_player.play()
|
||||
|
||||
_output_stream_playback = _output_player.get_stream_playback()
|
||||
|
||||
func set_output_player(p : Node) -> void:
|
||||
_output_player = p
|
||||
update_configuration_warnings()
|
||||
|
||||
func _get_property_list() -> Array[Dictionary]:
|
||||
var properties : Array[Dictionary] = []
|
||||
|
||||
var type : String = ""
|
||||
match(spatial_mode):
|
||||
0:
|
||||
type = "AudioStreamPlayer"
|
||||
1:
|
||||
type = "AudioStreamPlayer2D"
|
||||
2:
|
||||
type = "AudioStreamPlayer3D"
|
||||
|
||||
properties.append({
|
||||
"name" : "_output_player",
|
||||
"type" : TYPE_OBJECT,
|
||||
"hint" : PROPERTY_HINT_NODE_TYPE,
|
||||
"hint_string" : type,
|
||||
"usage" : PROPERTY_USAGE_DEFAULT
|
||||
})
|
||||
|
||||
return properties
|
||||
|
||||
func _get_configuration_warnings() -> PackedStringArray:
|
||||
var warnings : PackedStringArray = []
|
||||
|
||||
warnings.append("The VoiceChat Node is experimental. Please report any issues on GitHub.")
|
||||
|
||||
if _output_player == null:
|
||||
warnings.append("No output AudioStreamPlayer assigned.")
|
||||
|
||||
if audio_quality < 2:
|
||||
warnings.append("Higher audio quality will use up significantly more data.")
|
||||
|
||||
return warnings
|
||||
1
addons/GD-Sync/Scripts/Types/VoiceChat.gd.uid
Normal file
1
addons/GD-Sync/Scripts/Types/VoiceChat.gd.uid
Normal file
|
|
@ -0,0 +1 @@
|
|||
uid://b53bpow4wicbi
|
||||
Loading…
Add table
Add a link
Reference in a new issue