91 lines
2.4 KiB
GDScript
91 lines
2.4 KiB
GDScript
extends Node
|
|
|
|
"""
|
|
This module sets up WebRTC peer connections.
|
|
"""
|
|
|
|
var multiplayer_url = "ws://localhost:8888"
|
|
var webrtc_ice_servers = [
|
|
{ "urls": ["stun:stun.l.google.com:19302"] }
|
|
]
|
|
|
|
const SignallerClient = preload("signaller_client.gd")
|
|
|
|
onready var mp = WebRTCMultiplayer.new()
|
|
onready var signaller = SignallerClient.new()
|
|
|
|
func _ready():
|
|
# connect("connected", self, "connected")
|
|
# connect("disconnected", self, "disconnected")
|
|
|
|
# connect("offer_received", self, "offer_received")
|
|
# connect("answer_received", self, "answer_received")
|
|
# connect("candidate_received", self, "candidate_received")
|
|
|
|
# connect("lobby_joined", self, "lobby_joined")
|
|
# connect("lobby_sealed", self, "lobby_sealed")
|
|
# connect("peer_connected", self, "peer_connected")
|
|
# connect("peer_disconnected", self, "peer_disconnected")
|
|
add_child(signaller)
|
|
|
|
func close():
|
|
mp.close()
|
|
signaller.close()
|
|
|
|
func connect_to_signaller():
|
|
close()
|
|
signaller.connect_to_websocket_signaller(multiplayer_url)
|
|
|
|
func _create_peer(id):
|
|
var peer: WebRTCPeerConnection = WebRTCPeerConnection.new()
|
|
peer.initialize({"iceServers": webrtc_ice_servers})
|
|
peer.connect("session_description_created", self, "_offer_created", [id])
|
|
peer.connect("ice_candidate_created", self, "_new_ice_candidate", [id])
|
|
mp.add_peer(peer, id)
|
|
if id > mp.get_unique_id():
|
|
# TODO: peer.create_offer()
|
|
pass
|
|
return peer
|
|
|
|
func _new_ice_candidate(mid_name, index_name, sdp_name, id):
|
|
print("New ICE Candidate: ", mid_name, index_name, sdp_name, id)
|
|
# TODO: send_candidate(id, mid_name, index_name, sdp_name)
|
|
|
|
func _offer_created(type, data, id):
|
|
if not mp.has_peer(id):
|
|
return
|
|
print("created", type)
|
|
mp.get_peer(id).connection.set_local_description(type, data)
|
|
if type == "offer":
|
|
# TODO: send_offer(id, data)
|
|
pass
|
|
else:
|
|
# TODO: send_answer(id, data)
|
|
pass
|
|
|
|
func connected(id):
|
|
print("Connected %d" % id)
|
|
mp.initialize(id, true)
|
|
|
|
func peer_connected(id):
|
|
print("Peer connected %d" % id)
|
|
_create_peer(id)
|
|
|
|
func peer_disconnected(id):
|
|
if mp.has_peer(id):
|
|
mp.remove_peer(id)
|
|
|
|
func offer_received(id, offer):
|
|
print("Got offer: %d" % id)
|
|
if mp.has_peer(id):
|
|
mp.get_peer(id).connection.set_remote_description("offer", offer)
|
|
|
|
func answer_received(id, answer):
|
|
print("Got answer: %d" % id)
|
|
if mp.has_peer(id):
|
|
mp.get_peer(id).connection.set_remote_description("answer", answer)
|
|
|
|
func candidate_received(id, mid, index, sdp):
|
|
if mp.has_peer(id):
|
|
mp.get_peer(id).connection.add_ice_candidate(mid, index, sdp)
|