-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathDataChannelTransmitter.gd
85 lines (66 loc) · 2.5 KB
/
DataChannelTransmitter.gd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
class_name DataChannelTransmitter
extends Node
signal update_requested(transmission_resource:TransmissionResource)
signal success
signal failed
signal denied
signal try_again(receiver:AreaReceiver2D)
@export var enabled:bool = true
## If transmission errors with state TRY_AGAIN, try sending next physics frame
@export var try_next_frame:bool = true
## Data that will be transmitted
@export var transmission_resource:TransmissionResource
## Node that creates transmission connection
@export var area_transmitter:AreaTransmitter2D
func set_enabled(value:bool)->void:
enabled = value
func _ready()->void:
area_transmitter.area_entered.connect(_on_area_entered)
func _on_area_entered(area:Area2D)->void:
if !(area is AreaReceiver2D):
return
send(area)
func send(receiver:AreaReceiver2D)->void:
if !enabled:
return
assert(transmission_resource != null)
var _transmission_resource:TransmissionResource = transmission_resource.duplicate()
_transmission_resource.update_requested.connect(_on_update_requested.bind(_transmission_resource))
if _transmission_resource.send_transmission(receiver):
on_success()
return
if _transmission_resource.state == TransmissionResource.ErrorType.FAILED:
on_failed()
return
if _transmission_resource.state == TransmissionResource.ErrorType.DENIED:
on_denied()
return
if _transmission_resource.state == TransmissionResource.ErrorType.TRY_AGAIN:
# If this is called from next frame the calling signal connection is stil active.
# By deffering a function call, the signal connection wont be active.
on_try_again.call_deferred(receiver)
return
## Call transmission next physics frame
func on_try_again(receiver:AreaReceiver2D)->void:
try_again.emit(receiver)
if try_next_frame:
on_try_next_frame(receiver)
func on_try_next_frame(receiver:AreaReceiver2D)->void:
if !get_tree().physics_frame.is_connected(test_receiver):
get_tree().physics_frame.connect(test_receiver.bind(receiver), CONNECT_ONE_SHOT)
func test_receiver(receiver:AreaReceiver2D)->void:
var overlapping_areas:Array[Area2D] = area_transmitter.get_overlapping_areas()
if overlapping_areas.has(receiver):
send(receiver)
## Give notification to other nodes
func on_success()->void:
success.emit()
## Give notification to other nodes
func on_failed()->void:
failed.emit()
## Give notification to other nodes
func on_denied()->void:
denied.emit()
## Resource requests a need to be updated
func _on_update_requested(transmission_resource:TransmissionResource)->void:
update_requested.emit(transmission_resource)