godot-webrtc-mplayer-testing/scripts/global/signalled_webrtc_multiplayer.gd

347 lines
11 KiB
GDScript3
Raw Permalink Normal View History

2021-12-10 12:31:48 -06:00
extends Node
const DISPLAY_NAME_FILE = "user://display_name.txt"
const DEFAULT_DISPLAY_NAME = "UnnamedPlayer"
const DEFAULT_SIGNALLER_URL = "ws://localhost:8888"
# const DEFAULT_SIGNALLER_URL = "wss://webrtc-signaller.deno.dev:443"
2021-12-21 17:13:02 -06:00
var default_ice_servers: Array[Dictionary] = [
2021-12-11 00:08:28 -06:00
# first element in this array is for STUN
{ "urls": ["stun:localhost:3478", "stun:stun.l.google.com:19302"] },
2021-12-10 12:31:48 -06:00
# { "urls": ["stun:stun.l.google.com:19302"] }, # just google
2021-12-11 00:08:28 -06:00
# { "urls": ["stun:localhost:3478"] }, # just localhost
# {} # TURN servers
2021-12-10 12:31:48 -06:00
]
signal lobby_data(lobbies)
2021-12-11 00:08:28 -06:00
signal lobby_begin_join(uuid)
2021-12-10 12:31:48 -06:00
signal lobby_joined(lobby_and_peer)
2021-12-11 00:08:28 -06:00
signal lobby_left(uuid)
signal lobby_delete(uuid)
2021-12-10 12:31:48 -06:00
signal peer_data(peers)
2021-12-11 00:08:28 -06:00
signal peer_created(peer)
2021-12-10 12:31:48 -06:00
signal peer_left(id)
signal peer_init(id)
2021-12-10 12:31:48 -06:00
signal candidate_received(cand)
signal offer_received(data)
signal answer_received(data)
# webrtc
signal webrtc_peer_connected(id)
signal webrtc_peer_disconnected(id)
signal webrtc_connection_succeeded()
# websocket
2021-12-21 17:13:02 -06:00
signal signaller_connected()
signal signaller_connection_failure()
signal signaller_disconnected()
2021-12-10 12:31:48 -06:00
2021-12-21 17:13:02 -06:00
@onready var webrtc = null
@onready var websocket = WebSocketClient.new()
2021-12-10 12:31:48 -06:00
2021-12-21 17:13:02 -06:00
var _display_name = DEFAULT_DISPLAY_NAME
@onready var display_name: String:
get: return _display_name
set(value):
_display_name = value
_send("update_display_name:%s" % value)
@onready var current_lobby = null
@onready var lobbies = {}
@onready var peers = {}
2021-12-10 12:31:48 -06:00
2021-12-21 17:13:02 -06:00
@onready var signaller_url = DEFAULT_SIGNALLER_URL
2021-12-10 12:31:48 -06:00
func _init():
pass
func _ready():
display_name = _load_display_name()
2021-12-21 17:13:02 -06:00
websocket.connection_established.connect(_signaller_connected)
websocket.data_received.connect(_signaller_data)
websocket.server_close_request.connect(_signaller_close_request)
websocket.connection_closed.connect(_signaller_closed)
websocket.connection_error.connect(_signaller_error)
websocket.connection_failed.connect(_signaller_error)
2021-12-10 12:31:48 -06:00
2021-12-11 00:08:28 -06:00
func is_signaller_connected():
return websocket.get_connection_status() in [
websocket.CONNECTION_CONNECTED,
websocket.CONNECTION_CONNECTED,
]
func is_in_lobby(): return current_lobby != null
2021-12-10 12:31:48 -06:00
func connect_to_signaller(url = signaller_url):
2021-12-11 00:08:28 -06:00
if url == signaller_url and is_signaller_connected(): return
2021-12-10 12:31:48 -06:00
signaller_url = url
close()
print("Attempting to connect to WebSocket signalling server at %s" % signaller_url)
var result = websocket.connect_to_url(signaller_url)
if result != OK:
print("Failed to connect to WebSocket signalling server at %s: %s" % [signaller_url, result])
2021-12-15 16:14:36 -06:00
func singleplayer():
close()
2021-12-21 17:13:02 -06:00
webrtc = WebRTCMultiplayerPeer.new()
2021-12-15 16:14:36 -06:00
webrtc.initialize(1, false)
2021-12-21 17:13:02 -06:00
get_tree().multiplayer = webrtc
2021-12-17 17:10:56 -06:00
peers[1] = {
connected = false,
ready = false,
name = display_name,
}
2021-12-15 16:14:36 -06:00
2021-12-10 12:31:48 -06:00
func close():
2021-12-11 00:08:28 -06:00
if webrtc != null: webrtc.close()
2021-12-10 12:31:48 -06:00
websocket.disconnect_from_host()
2021-12-21 17:13:02 -06:00
get_tree().multiplayer = null
2021-12-10 12:31:48 -06:00
func request_lobby_list():
return _send("request_lobby_list")
func join_lobby(id: String):
2021-12-11 00:08:28 -06:00
emit_signal("lobby_begin_join", id)
call_deferred("_send", "lobby_join:%s" % id)
func leave_lobby():
return _send("lobby_leave")
2021-12-10 12:31:48 -06:00
func get_lobby_name():
2021-12-11 00:08:28 -06:00
return current_lobby.name if current_lobby.has("name") else null
2021-12-10 12:31:48 -06:00
func create_lobby():
2021-12-11 00:08:28 -06:00
_send("lobby_create")
2021-12-10 12:31:48 -06:00
2021-12-11 00:08:28 -06:00
func is_host(): return is_signaller_connected() and is_in_lobby() and get_tree().get_network_unique_id() == 1
2021-12-10 12:31:48 -06:00
func set_lobby_name(s: String):
if is_host(): _send_json({"name": s}, "update_lobby")
func lock_lobby():
if is_host(): _send_json({"locked": true}, "update_lobby")
func set_lobby_max_players(n: int):
if is_host(): _send_json({"maxPlayers": n}, "update_lobby")
func request_peer_list(): _send("request_peer_list")
func send_candidate(id, mid, index, sdp) -> int:
return _send_json({"id": id, "mid": mid, "index": index, "sdp": sdp}, "candidate")
func send_offer(id, offer) -> int:
return _send_json({"id": id, "offer": offer }, "offer")
func send_answer(id, answer) -> int:
return _send_json({"id": id, "answer": answer }, "answer")
func _webrtc_peer_connected(id):
2021-12-15 16:14:36 -06:00
peers[id].connected = true
2021-12-10 12:31:48 -06:00
emit_signal("webrtc_peer_connected", id)
func _webrtc_peer_disconnected(id):
2021-12-15 16:14:36 -06:00
peers[id].connected = false
2021-12-10 12:31:48 -06:00
emit_signal("webrtc_peer_disconnected", id)
func _webrtc_connection_succeeded():
emit_signal("webrtc_connection_succeeded")
func _signaller_error(err):
print("WebSocket error: %s" % err)
emit_signal("signaller_connection_failure")
_signaller_closed(err)
func _signaller_closed(code):
print("WebSocket closed: %s: " % code)
emit_signal("signaller_disconnected")
func _signaller_close_request(code: int, reason: String):
print("Received WebSocket close request from signalling server - Code: %s, Reason: %s" % [code, reason])
# TODO: does this fire _closed?
func _signaller_connected(protocol = ""):
print("Signaller connected via WebSocket using protocol %s" % protocol)
websocket.get_peer(1).set_write_mode(WebSocketPeer.WRITE_MODE_TEXT)
emit_signal("signaller_connected")
_send_json({name = display_name}, "init")
func _process(_delta: float):
2021-12-17 17:10:56 -06:00
if webrtc:
webrtc.poll()
2021-12-21 16:40:58 -06:00
# while webrtc.get_available_packet_count() > 0:
# print("WebRTC Packet: %s" % webrtc.get_packet().get_string_from_utf8())
2021-12-10 12:31:48 -06:00
var status: int = websocket.get_connection_status()
2021-12-11 00:08:28 -06:00
if status in [WebSocketClient.CONNECTION_CONNECTED, WebSocketClient.CONNECTION_CONNECTING]:
2021-12-10 12:31:48 -06:00
websocket.poll()
2021-12-17 17:10:56 -06:00
func _input(event):
if event is InputEventKey:
2021-12-21 16:40:58 -06:00
if event.pressed and event.scancode == KEY_D and event.alt:
2021-12-17 17:10:56 -06:00
print("## DEBUG NET INFO")
for p in get_tree().get_network_connected_peers():
var d = webrtc.get_peer(p)
print("get_peer(%s): %s" % [p, d])
for c in d.channels:
print("Channel: %s" % c)
if c:
print("Label: %s, Protocol: %s, Negotiated: %s" % [c.get_label(), c.get_protocol(), "true" if c.is_negotiated() else "false"])
else:
print("Channel is null?")
2021-12-10 12:31:48 -06:00
func _signaller_data():
var msg: String = websocket.get_peer(1).get_packet().get_string_from_utf8()
if msg.begins_with("json:"):
2021-12-21 17:13:02 -06:00
var data = JSON.new().parse(msg.substr(5))
2021-12-10 12:31:48 -06:00
if data.error == OK:
_process_signaller_message(data.result)
2021-12-21 17:13:02 -06:00
var _result = websocket.get_peer(1).put_packet("".to_utf8_buffer())
2021-12-10 12:31:48 -06:00
else:
var d = msg.split(":", false, 2)
_process_signaller_message({type = d[0], data = d[1]})
2021-12-11 00:08:28 -06:00
func _init_webrtc_peer(data):
2021-12-21 17:13:02 -06:00
webrtc = WebRTCMultiplayerPeer.new()
2021-12-11 00:08:28 -06:00
webrtc.connect("connection_succeeded", self, "_webrtc_connection_succeeded")
webrtc.connect("peer_connected", self, "_webrtc_peer_connected")
webrtc.connect("peer_disconnected", self, "_webrtc_peer_disconnected")
webrtc.initialize(int(data), true)
get_tree().network_peer = webrtc
func _deinit_webrtc_peer():
webrtc.close()
get_tree().network_peer = null
webrtc = null
2021-12-10 12:31:48 -06:00
func _process_signaller_message(data: Dictionary):
match data["type"]:
# "init":
2021-12-11 00:08:28 -06:00
"init_peer": _init_webrtc_peer(data.data)
2021-12-10 12:31:48 -06:00
"lobby_data": emit_signal("lobby_data", data.data)
2021-12-11 00:08:28 -06:00
"lobby_delete": emit_signal("lobby_delete", data.uuid)
"lobby_joined": _lobby_joined(data)
"lobby_left": _lobby_left(data.uuid)
"peer_data": _signaller_peer_data([data] if data.has("id") else data.data)
2021-12-21 16:40:58 -06:00
"peer_left": _signaller_peer_left(int(data.id))
2021-12-11 00:08:28 -06:00
"candidate": _webrtc_candidate_received(data)
"offer": _webrtc_offer_received(data)
"answer": _webrtc_answer_received(data)
2021-12-10 12:31:48 -06:00
"ping": _send("pong")
_: print("Unhandled Message - Data: %s" % JSON.print(data))
2021-12-11 00:08:28 -06:00
func _lobby_joined(lobby_data):
current_lobby = lobby_data
2021-12-17 17:10:56 -06:00
peers[int(lobby_data.id)] = {
connected = true,
ready = int(lobby_data.id) == 1,
name = display_name,
id = int(lobby_data.id),
}
2021-12-11 00:08:28 -06:00
print("Lobby Joined: %s" % lobby_data)
emit_signal("lobby_joined", lobby_data)
func _lobby_left(uuid):
current_lobby = null
2021-12-17 17:10:56 -06:00
peers.erase(get_tree().get_network_unique_id())
2021-12-11 00:08:28 -06:00
print("Lobby Left: %s" % uuid)
emit_signal("lobby_left", uuid)
_deinit_webrtc_peer()
2021-12-17 17:10:56 -06:00
func _create_peer(data: Dictionary):
2021-12-11 00:08:28 -06:00
var id = data.id
2021-12-17 17:10:56 -06:00
if id == webrtc.get_unique_id(): return
2021-12-11 00:08:28 -06:00
var peer: WebRTCPeerConnection = WebRTCPeerConnection.new()
2021-12-17 17:10:56 -06:00
print("Creating WebRTC Peer: %s" % [data])
2021-12-21 17:13:02 -06:00
peer.session_description_created.connect(_webrtc_offer_created, id)
peer.ice_candidate_created.connect(_new_ice_candidate, id)
peer.initialize({"iceServers": default_ice_servers})
2021-12-11 00:08:28 -06:00
webrtc.add_peer(peer, int(id))
# this guarantees only one peer sends the offer and that offers are never
# sent to ourselves?
if int(id) > webrtc.get_unique_id(): peer.create_offer()
2021-12-15 16:14:36 -06:00
peers[int(id)] = {
connected = false,
2021-12-21 16:40:58 -06:00
ready = data.ready if data.has("ready") else false,
2021-12-17 17:10:56 -06:00
name = data.name if data.has(name) else DEFAULT_DISPLAY_NAME,
2021-12-15 16:14:36 -06:00
}
2021-12-11 00:08:28 -06:00
emit_signal("peer_created", data)
2021-12-15 16:14:36 -06:00
func _delete_peer(id):
if webrtc.has_peer(id): webrtc.remove_peer(id)
if peers.has(id): peers.erase(id)
2021-12-21 16:40:58 -06:00
emit_signal("peer_left", id)
2021-12-15 16:14:36 -06:00
2021-12-11 00:08:28 -06:00
func _webrtc_offer_created(type, data, id):
print("WebRTC %s created for peer %s" % [type, id])
if not webrtc.has_peer(int(id)): return
print("WebRTC local description set for peer %s" % id)
webrtc.get_peer(id).connection.set_local_description(type, data)
print("--> Local Description: %s" % JSON.print(data))
if type == "offer": send_offer(id, data)
else: send_answer(id, data)
func _new_ice_candidate(mid, index, sdp, id):
print("New ICE candidate for peer %s" % id)
send_candidate(id, mid, index, sdp)
2021-12-15 16:14:36 -06:00
func _signaller_peer_left(id):
_delete_peer(id)
2021-12-11 00:08:28 -06:00
func _signaller_peer_data(peers):
for peer in peers:
if peer.has("id") and not webrtc.has_peer(int(peer.id)):
_create_peer(peer)
emit_signal("peer_data", peers)
func _webrtc_offer_received(data):
if webrtc.has_peer(int(data.id)):
print("Setting offer remote description for peer %s" % data.id)
print("--> Offer: %s" % JSON.print(data.offer))
webrtc.get_peer(data.id).connection.set_remote_description("offer", data.offer)
else:
print("Received an offer for a peer with ID %s that hasn't been added" % data.id)
func _webrtc_answer_received(data):
if webrtc.has_peer(data.id):
print("Setting answer remote description for peer %s" % data.id)
print("--> Answer: %s" % JSON.print(data.answer))
webrtc.get_peer(data.id).connection.set_remote_description("answer", data.answer)
func _webrtc_candidate_received(data):
if webrtc.has_peer(data.id):
print("Adding ice candidate for peer %s" % data.id)
2021-12-15 16:14:36 -06:00
print("--> Candidate: %s" % JSON.print(data))
2021-12-11 00:08:28 -06:00
webrtc.get_peer(data.id).connection.add_ice_candidate(data.mid, data.index, data.sdp)
else:
print("Received candidate for non-existant peer %s" % data.id)
2021-12-10 12:31:48 -06:00
func _load_display_name():
var _display_name = DEFAULT_DISPLAY_NAME
var display_name_file = File.new()
if display_name_file.open(DISPLAY_NAME_FILE, File.READ) == OK:
_display_name = display_name_file.get_as_text()
else:
print("Failed to open %s for reading display_name, creating default" % DISPLAY_NAME_FILE)
_store_display_name()
display_name_file.close()
return _display_name
func _store_display_name():
var display_name_file = File.new()
if display_name_file.open(DISPLAY_NAME_FILE, File.WRITE) == OK:
display_name_file.store_string(display_name)
else:
print("Failed to open %s for writing display_name" % DISPLAY_NAME_FILE)
display_name_file.close()
func _send(s: String):
2021-12-21 17:13:02 -06:00
return websocket.get_peer(1).put_packet(s.to_utf8_buffer())
2021-12-10 12:31:48 -06:00
func _send_json(data: Dictionary, type=null):
if type != null: data["type"] = type
_send("json:%s" % JSON.print(data))