edbeeching HF staff commited on
Commit
b1bb420
1 Parent(s): 689f721

Upload folder using huggingface_hub

Browse files
AIController3D.gd ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends AIController3D
2
+
3
+
4
+ func _physics_process(_delta):
5
+ n_steps += 1
6
+ if n_steps >= reset_after:
7
+ done = true
8
+ needs_reset = true
9
+
10
+ if needs_reset:
11
+ _player.game_over()
12
+
13
+
14
+ func get_obs():
15
+ var goal_distance = 0.0
16
+ var goal_position = Vector3.ZERO
17
+ if _player.next == 0:
18
+ goal_distance = _player.position.distance_to(_player.first_jump_pad.position)
19
+ goal_position = _player.first_jump_pad.global_position
20
+
21
+ if _player.next == 1:
22
+ goal_distance = _player.position.distance_to(_player.second_jump_pad.position)
23
+ goal_position = _player.second_jump_pad.global_position
24
+
25
+
26
+ var goal_vector = _player.to_local(goal_position).normalized()
27
+
28
+ goal_distance = clamp(goal_distance, 0.0, 20.0)
29
+ var obs = []
30
+ obs.append_array(
31
+ [
32
+ _player.move_vec.x / _player.MOVE_SPEED,
33
+ _player.move_vec.y / _player.MAX_FALL_SPEED,
34
+ _player.move_vec.z / _player.MOVE_SPEED
35
+ ]
36
+ )
37
+ obs.append_array([goal_distance / 20.0, goal_vector.x, goal_vector.y, goal_vector.z])
38
+ obs.append(_player.grounded)
39
+ obs.append_array(_player.raycast_sensor.get_observation())
40
+
41
+ return {
42
+ "obs": obs,
43
+ }
44
+
45
+
46
+ func set_action(action):
47
+ _player.move_action = action["move"][0]
48
+ _player.turn_action = action["turn"][0]
49
+ _player.jump_action = action["jump"][0] > 0
50
+
51
+
52
+ func get_action_space():
53
+ return {
54
+ "jump": {"size": 1, "action_type": "continuous"},
55
+ "move": {"size": 1, "action_type": "continuous"},
56
+ "turn": {"size": 1, "action_type": "continuous"}
57
+ }
58
+
59
+
60
+ func get_reward():
61
+ var current_reward = reward
62
+ reward = 0 # reset the reward to zero checked every decision step
63
+ return current_reward
JumperHard.csproj CHANGED
@@ -1,4 +1,4 @@
1
- <Project Sdk="Godot.NET.Sdk/4.1.1">
2
  <PropertyGroup>
3
  <TargetFramework>net6.0</TargetFramework>
4
  <EnableDynamicLoading>true</EnableDynamicLoading>
 
1
+ <Project Sdk="Godot.NET.Sdk/4.2.1">
2
  <PropertyGroup>
3
  <TargetFramework>net6.0</TargetFramework>
4
  <EnableDynamicLoading>true</EnableDynamicLoading>
JumperHard.csproj.old CHANGED
@@ -1,4 +1,4 @@
1
- <Project Sdk="Godot.NET.Sdk/4.0.2">
2
  <PropertyGroup>
3
  <TargetFramework>net6.0</TargetFramework>
4
  <EnableDynamicLoading>true</EnableDynamicLoading>
 
1
+ <Project Sdk="Godot.NET.Sdk/4.1.3">
2
  <PropertyGroup>
3
  <TargetFramework>net6.0</TargetFramework>
4
  <EnableDynamicLoading>true</EnableDynamicLoading>
Player.gd CHANGED
@@ -5,7 +5,6 @@ const JUMP_FORCE = 30
5
  const GRAVITY = 0.98
6
  const MAX_FALL_SPEED = 30
7
  const TURN_SENS = 2.0
8
- const MAX_STEPS = 20000
9
 
10
  @onready var cam = $Camera3D
11
  var move_vec = Vector3()
@@ -17,198 +16,130 @@ var needs_reset = false
17
  @onready var first_jump_pad = $"../Pads/FirstPad"
18
  @onready var second_jump_pad = $"../Pads/SecondPad"
19
  @onready var robot = $Robot
 
20
 
21
  var next = 1
22
- var done = false
23
  var just_reached_end = false
24
  var just_reached_next = false
25
  var just_fell_off = false
26
  var best_goal_distance := 10000.0
27
  var grounded := false
28
- var _heuristic := "player"
29
  var move_action := 0.0
30
  var turn_action := 0.0
31
  var jump_action := false
32
- var n_steps = 0
33
- var _goal_vec = null
34
- var reward = 0.0
35
 
36
  func _ready():
 
37
  raycast_sensor.activate()
38
- reset()
39
 
40
- #func _process(_delta):
41
- # if _goal_vec != null:
42
- # DebugDraw.draw_line_3d(position, position + (_goal_vec*10), Color(1, 1, 0))
43
 
44
  func _physics_process(_delta):
45
-
46
- #reward = 0.0
47
- n_steps +=1
48
- if n_steps >= MAX_STEPS:
49
- done = true
50
- needs_reset = true
51
-
52
- if needs_reset:
53
- needs_reset = false
54
- reset()
55
- return
56
-
57
-
58
- move_vec *= 0
59
  move_vec = get_move_vec()
60
- #move_vec = move_vec.normalized()
61
  move_vec = move_vec.rotated(Vector3(0, 1, 0), rotation.y)
62
  move_vec *= MOVE_SPEED
63
  move_vec.y = y_velo
64
  set_velocity(move_vec)
65
  set_up_direction(Vector3(0, 1, 0))
66
  move_and_slide()
67
-
68
  # turning
69
-
70
  var turn_vec = get_turn_vec()
71
- rotation.y += deg_to_rad(turn_vec*TURN_SENS)
72
-
73
  grounded = is_on_floor()
74
 
75
  y_velo -= GRAVITY
76
- var just_jumped = false
77
  if grounded and get_jump_action():
78
  robot.set_animation("jump")
79
- just_jumped = true
80
  y_velo = JUMP_FORCE
81
  grounded = false
82
  if grounded and y_velo <= 0:
83
  y_velo = -0.1
84
  if y_velo < -MAX_FALL_SPEED:
85
  y_velo = -MAX_FALL_SPEED
86
-
87
- if y_velo < 0 and !grounded :
88
  robot.set_animation("falling")
89
-
90
  var horizontal_speed = Vector2(move_vec.x, move_vec.z)
91
  if horizontal_speed.length() < 0.1 and grounded:
92
  robot.set_animation("idle")
93
  elif horizontal_speed.length() < 1.0 and grounded:
94
- robot.set_animation("walk")
95
  elif horizontal_speed.length() >= 1.0 and grounded:
96
  robot.set_animation("run")
97
-
98
  update_reward()
99
-
100
  if Input.is_action_just_pressed("r_key"):
101
- reset()
102
-
103
 
104
  func get_move_vec() -> Vector3:
105
- if done:
106
- move_vec = Vector3.ZERO
107
- return move_vec
108
-
109
- if _heuristic == "model":
110
- return Vector3(
111
- 0,
112
- 0,
113
- clamp(move_action, -1.0, 0.5)
114
- )
115
-
116
- var move_vec := Vector3(
117
  0,
118
  0,
119
- clamp(Input.get_action_strength("move_backwards") - Input.get_action_strength("move_forwards"),-1.0, 0.5)
120
-
 
 
 
 
 
 
121
  )
122
- return move_vec
123
 
124
  func get_turn_vec() -> float:
125
- if _heuristic == "model":
126
  return turn_action
127
- var rotation_amount = Input.get_action_strength("turn_left") - Input.get_action_strength("turn_right")
 
 
128
 
129
  return rotation_amount
130
-
 
131
  func get_jump_action() -> bool:
132
- if done:
133
  jump_action = false
134
  return jump_action
135
-
136
- if _heuristic == "model":
137
- return jump_action
138
-
139
  return Input.is_action_just_pressed("jump")
140
-
141
- func reset():
142
- needs_reset = false
143
  next = 1
144
- n_steps = 0
145
  first_jump_pad.position = Vector3.ZERO
146
- second_jump_pad.position = Vector3(0,0,-12)
147
  just_reached_end = false
148
  just_fell_off = false
149
  jump_action = false
150
 
151
- set_position(Vector3(0,5,0))
152
- rotation.y = deg_to_rad(randf_range(-180,180))
153
  y_velo = 0.1
154
  reset_best_goal_distance()
155
-
156
- func set_action(action):
157
- move_action = action["move"][0]
158
- turn_action = action["turn"][0]
159
- jump_action = action["jump"] == 1
160
-
161
- func reset_if_done():
162
- if done:
163
- reset()
164
-
165
- func get_obs():
166
- var goal_distance = 0.0
167
- var goal_vector = Vector3.ZERO
168
- if next == 0:
169
- goal_distance = position.distance_to(first_jump_pad.position)
170
- goal_vector = (first_jump_pad.position - position).normalized()
171
-
172
- if next == 1:
173
- goal_distance = position.distance_to(second_jump_pad.position)
174
- goal_vector = (second_jump_pad.position - position).normalized()
175
-
176
- goal_vector = goal_vector.rotated(Vector3.UP, -rotation.y)
177
-
178
- goal_distance = clamp(goal_distance, 0.0, 20.0)
179
- var obs = []
180
- obs.append_array([move_vec.x/MOVE_SPEED,
181
- move_vec.y/MAX_FALL_SPEED,
182
- move_vec.z/MOVE_SPEED])
183
- obs.append_array([goal_distance/20.0,
184
- goal_vector.x,
185
- goal_vector.y,
186
- goal_vector.z])
187
- obs.append(grounded)
188
- obs.append_array(raycast_sensor.get_observation())
189
-
190
- return {
191
- "obs": obs,
192
- }
193
-
194
- func get_obs_space():
195
- # typs of obs space: box, discrete, repeated
196
- return {
197
- "obs": {
198
- "size": [len(get_obs()["obs"])],
199
- "space": "box"
200
- }
201
- }
202
-
203
  func update_reward():
204
- reward -= 0.01 # step penalty
205
- reward += shaping_reward()
206
-
207
- func get_reward():
208
- var current_reward = reward
209
- reward = 0 # reset the reward to zero checked every decision step
210
- return current_reward
211
-
212
  func shaping_reward():
213
  var s_reward = 0.0
214
  var goal_distance = 0
@@ -220,75 +151,46 @@ func shaping_reward():
220
  if goal_distance < best_goal_distance:
221
  s_reward += best_goal_distance - goal_distance
222
  best_goal_distance = goal_distance
223
-
224
  s_reward /= 1.0
225
- return s_reward
 
226
 
227
  func reset_best_goal_distance():
228
  if next == 0:
229
  best_goal_distance = position.distance_to(first_jump_pad.position)
230
  if next == 1:
231
- best_goal_distance = position.distance_to(second_jump_pad.position)
232
-
233
- func set_heuristic(heuristic):
234
- self._heuristic = heuristic
235
-
236
- func get_obs_size():
237
- return len(get_obs())
238
-
239
- func zero_reward():
240
- reward = 0
241
-
242
- func get_action_space():
243
- return {
244
- "move" : {
245
- "size": 1,
246
- "action_type": "continuous"
247
- },
248
- "turn" : {
249
- "size": 1,
250
- "action_type": "continuous"
251
- },
252
- "jump": {
253
- "size": 2,
254
- "action_type": "discrete"
255
- }
256
- }
257
-
258
- func get_done():
259
- return done
260
-
261
- func set_done_false():
262
- done = false
263
-
264
- func calculate_translation(other_pad_translation : Vector3) -> Vector3:
265
  var new_translation := Vector3.ZERO
266
- var distance = randf_range(12,16)
267
- var angle = randf_range(-180,180)
268
- new_translation.z = other_pad_translation.z + sin(deg_to_rad(angle))*distance
269
- new_translation.x = other_pad_translation.x + cos(deg_to_rad(angle))*distance
270
-
271
  return new_translation
272
 
273
 
274
- func _on_First_Pad_Trigger_body_entered(body):
275
  if next != 0:
276
  return
277
- reward += 100.0
278
  next = 1
279
  reset_best_goal_distance()
280
  second_jump_pad.position = calculate_translation(first_jump_pad.position)
281
 
282
- func _on_Second_Trigger_body_entered(body):
 
283
  if next != 1:
284
  return
285
- reward += 100.0
286
  next = 0
287
  reset_best_goal_distance()
288
  first_jump_pad.position = calculate_translation(second_jump_pad.position)
289
-
290
 
291
 
292
- func _on_ResetTriggerBox_body_entered(body):
293
- done = true
294
- reset()
 
5
  const GRAVITY = 0.98
6
  const MAX_FALL_SPEED = 30
7
  const TURN_SENS = 2.0
 
8
 
9
  @onready var cam = $Camera3D
10
  var move_vec = Vector3()
 
16
  @onready var first_jump_pad = $"../Pads/FirstPad"
17
  @onready var second_jump_pad = $"../Pads/SecondPad"
18
  @onready var robot = $Robot
19
+ @onready var ai_controller = $AIController3D
20
 
21
  var next = 1
 
22
  var just_reached_end = false
23
  var just_reached_next = false
24
  var just_fell_off = false
25
  var best_goal_distance := 10000.0
26
  var grounded := false
 
27
  var move_action := 0.0
28
  var turn_action := 0.0
29
  var jump_action := false
30
+
 
 
31
 
32
  func _ready():
33
+ ai_controller.init(self)
34
  raycast_sensor.activate()
35
+ game_over()
36
 
 
 
 
37
 
38
  func _physics_process(_delta):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  move_vec = get_move_vec()
 
40
  move_vec = move_vec.rotated(Vector3(0, 1, 0), rotation.y)
41
  move_vec *= MOVE_SPEED
42
  move_vec.y = y_velo
43
  set_velocity(move_vec)
44
  set_up_direction(Vector3(0, 1, 0))
45
  move_and_slide()
46
+
47
  # turning
48
+
49
  var turn_vec = get_turn_vec()
50
+ rotation.y += deg_to_rad(turn_vec * TURN_SENS)
51
+
52
  grounded = is_on_floor()
53
 
54
  y_velo -= GRAVITY
 
55
  if grounded and get_jump_action():
56
  robot.set_animation("jump")
 
57
  y_velo = JUMP_FORCE
58
  grounded = false
59
  if grounded and y_velo <= 0:
60
  y_velo = -0.1
61
  if y_velo < -MAX_FALL_SPEED:
62
  y_velo = -MAX_FALL_SPEED
63
+
64
+ if y_velo < 0 and !grounded:
65
  robot.set_animation("falling")
66
+
67
  var horizontal_speed = Vector2(move_vec.x, move_vec.z)
68
  if horizontal_speed.length() < 0.1 and grounded:
69
  robot.set_animation("idle")
70
  elif horizontal_speed.length() < 1.0 and grounded:
71
+ robot.set_animation("walk")
72
  elif horizontal_speed.length() >= 1.0 and grounded:
73
  robot.set_animation("run")
74
+
75
  update_reward()
76
+
77
  if Input.is_action_just_pressed("r_key"):
78
+ game_over()
79
+
80
 
81
  func get_move_vec() -> Vector3:
82
+ if ai_controller.done:
83
+ return Vector3.ZERO
84
+
85
+ if ai_controller.heuristic == "model":
86
+ return Vector3(0, 0, clamp(move_action, -1.0, 0.5))
87
+
88
+ return Vector3(
 
 
 
 
 
89
  0,
90
  0,
91
+ clamp(
92
+ (
93
+ Input.get_action_strength("move_backwards")
94
+ - Input.get_action_strength("move_forwards")
95
+ ),
96
+ -1.0,
97
+ 0.5
98
+ )
99
  )
100
+
101
 
102
  func get_turn_vec() -> float:
103
+ if ai_controller.heuristic == "model":
104
  return turn_action
105
+ var rotation_amount = (
106
+ Input.get_action_strength("turn_left") - Input.get_action_strength("turn_right")
107
+ )
108
 
109
  return rotation_amount
110
+
111
+
112
  func get_jump_action() -> bool:
113
+ if ai_controller.done:
114
  jump_action = false
115
  return jump_action
116
+
117
+ if ai_controller.heuristic == "model":
118
+ return jump_action
119
+
120
  return Input.is_action_just_pressed("jump")
121
+
122
+
123
+ func game_over():
124
  next = 1
 
125
  first_jump_pad.position = Vector3.ZERO
126
+ second_jump_pad.position = Vector3(0, 0, -12)
127
  just_reached_end = false
128
  just_fell_off = false
129
  jump_action = false
130
 
131
+ set_position(Vector3(0, 5, 0))
132
+ rotation.y = deg_to_rad(randf_range(-180, 180))
133
  y_velo = 0.1
134
  reset_best_goal_distance()
135
+ ai_controller.reset()
136
+
137
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
138
  func update_reward():
139
+ ai_controller.reward -= 0.01 # step penalty
140
+ ai_controller.reward += shaping_reward()
141
+
142
+
 
 
 
 
143
  func shaping_reward():
144
  var s_reward = 0.0
145
  var goal_distance = 0
 
151
  if goal_distance < best_goal_distance:
152
  s_reward += best_goal_distance - goal_distance
153
  best_goal_distance = goal_distance
154
+
155
  s_reward /= 1.0
156
+ return s_reward
157
+
158
 
159
  func reset_best_goal_distance():
160
  if next == 0:
161
  best_goal_distance = position.distance_to(first_jump_pad.position)
162
  if next == 1:
163
+ best_goal_distance = position.distance_to(second_jump_pad.position)
164
+
165
+
166
+ func calculate_translation(other_pad_translation: Vector3) -> Vector3:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  var new_translation := Vector3.ZERO
168
+ var distance = randf_range(12, 16)
169
+ var angle = randf_range(-180, 180)
170
+ new_translation.z = other_pad_translation.z + sin(deg_to_rad(angle)) * distance
171
+ new_translation.x = other_pad_translation.x + cos(deg_to_rad(angle)) * distance
172
+
173
  return new_translation
174
 
175
 
176
+ func _on_First_Pad_Trigger_body_entered(_body):
177
  if next != 0:
178
  return
179
+ ai_controller.reward += 100.0
180
  next = 1
181
  reset_best_goal_distance()
182
  second_jump_pad.position = calculate_translation(first_jump_pad.position)
183
 
184
+
185
+ func _on_Second_Trigger_body_entered(_body):
186
  if next != 1:
187
  return
188
+ ai_controller.reward += 100.0
189
  next = 0
190
  reset_best_goal_distance()
191
  first_jump_pad.position = calculate_translation(second_jump_pad.position)
 
192
 
193
 
194
+ func _on_ResetTriggerBox_body_entered(_body):
195
+ ai_controller.done = true
196
+ game_over()
Player.tscn CHANGED
@@ -1,8 +1,9 @@
1
- [gd_scene load_steps=8 format=3 uid="uid://btjelqxpc6evr"]
2
 
3
  [ext_resource type="Script" path="res://Player.gd" id="1"]
4
  [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3"]
5
  [ext_resource type="PackedScene" uid="uid://dmvrtwu4ml51r" path="res://robot2.tscn" id="3_pt6ta"]
 
6
 
7
  [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_k5nui"]
8
 
@@ -20,7 +21,7 @@ ambient_light_energy = 0.79
20
  tonemap_mode = 3
21
  glow_intensity = 0.65
22
 
23
- [node name="Player" type="CharacterBody3D" groups=["AGENT"]]
24
  transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0)
25
  script = ExtResource("1")
26
 
@@ -478,3 +479,7 @@ target_position = Vector3(6.14364, 6.92623, 11.8018)
478
 
479
  [node name="Robot" parent="." instance=ExtResource("3_pt6ta")]
480
  transform = Transform3D(-1.5, 0, -2.26494e-07, 0, 1.5, 0, 2.26494e-07, 0, -1.5, 0, -0.951698, 0)
 
 
 
 
 
1
+ [gd_scene load_steps=9 format=3 uid="uid://btjelqxpc6evr"]
2
 
3
  [ext_resource type="Script" path="res://Player.gd" id="1"]
4
  [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3"]
5
  [ext_resource type="PackedScene" uid="uid://dmvrtwu4ml51r" path="res://robot2.tscn" id="3_pt6ta"]
6
+ [ext_resource type="Script" path="res://AIController3D.gd" id="4_grup7"]
7
 
8
  [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_k5nui"]
9
 
 
21
  tonemap_mode = 3
22
  glow_intensity = 0.65
23
 
24
+ [node name="Player" type="CharacterBody3D"]
25
  transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0)
26
  script = ExtResource("1")
27
 
 
479
 
480
  [node name="Robot" parent="." instance=ExtResource("3_pt6ta")]
481
  transform = Transform3D(-1.5, 0, -2.26494e-07, 0, 1.5, 0, 2.26494e-07, 0, -1.5, 0, -0.951698, 0)
482
+
483
+ [node name="AIController3D" type="Node3D" parent="."]
484
+ script = ExtResource("4_grup7")
485
+ reset_after = 20000
Robot.gd CHANGED
@@ -1,16 +1,8 @@
1
  extends Node3D
2
 
3
 
4
- # Declare member variables here. Examples:
5
- # var a = 2
6
- # var b = "text"
7
-
8
  @onready var player = $AnimationPlayer
9
 
10
- # Called when the node enters the scene tree for the first time.
11
- func _ready():
12
- pass # Replace with function body.
13
-
14
  func set_animation(anim):
15
  if player.current_animation == anim:
16
  return
 
1
  extends Node3D
2
 
3
 
 
 
 
 
4
  @onready var player = $AnimationPlayer
5
 
 
 
 
 
6
  func set_animation(anim):
7
  if player.current_animation == anim:
8
  return
addons/godot_rl_agents/controller/ai_controller_2d.gd CHANGED
@@ -1,8 +1,82 @@
1
- extends AIController
2
  class_name AIController2D
3
 
4
- # ------------------ Godot RL Agents Logic ------------------------------------#
 
 
 
 
 
 
 
5
  var _player: Node2D
6
 
 
 
 
7
  func init(player: Node2D):
8
  _player = player
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
  class_name AIController2D
3
 
4
+ @export var reset_after := 1000
5
+
6
+ var heuristic := "human"
7
+ var done := false
8
+ var reward := 0.0
9
+ var n_steps := 0
10
+ var needs_reset := false
11
+
12
  var _player: Node2D
13
 
14
+ func _ready():
15
+ add_to_group("AGENT")
16
+
17
  func init(player: Node2D):
18
  _player = player
19
+
20
+ #-- Methods that need implementing using the "extend script" option in Godot --#
21
+ func get_obs() -> Dictionary:
22
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
23
+ return {"obs":[]}
24
+
25
+ func get_reward() -> float:
26
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
27
+ return 0.0
28
+
29
+ func get_action_space() -> Dictionary:
30
+ assert(false, "the get get_action_space method is not implemented when extending from ai_controller")
31
+ return {
32
+ "example_actions_continous" : {
33
+ "size": 2,
34
+ "action_type": "continuous"
35
+ },
36
+ "example_actions_discrete" : {
37
+ "size": 2,
38
+ "action_type": "discrete"
39
+ },
40
+ }
41
+
42
+ func set_action(action) -> void:
43
+ assert(false, "the get set_action method is not implemented when extending from ai_controller")
44
+ # -----------------------------------------------------------------------------#
45
+
46
+ func _physics_process(delta):
47
+ n_steps += 1
48
+ if n_steps > reset_after:
49
+ needs_reset = true
50
+
51
+ func get_obs_space():
52
+ # may need overriding if the obs space is complex
53
+ var obs = get_obs()
54
+ return {
55
+ "obs": {
56
+ "size": [len(obs["obs"])],
57
+ "space": "box"
58
+ },
59
+ }
60
+
61
+ func reset():
62
+ n_steps = 0
63
+ needs_reset = false
64
+
65
+ func reset_if_done():
66
+ if done:
67
+ reset()
68
+
69
+ func set_heuristic(h):
70
+ # sets the heuristic from "human" or "model" nothing to change here
71
+ heuristic = h
72
+
73
+ func get_done():
74
+ return done
75
+
76
+ func set_done_false():
77
+ done = false
78
+
79
+ func zero_reward():
80
+ reward = 0.0
81
+
82
+
addons/godot_rl_agents/controller/ai_controller_3d.gd CHANGED
@@ -1,8 +1,80 @@
1
- extends AIController
2
  class_name AIController3D
3
 
4
- # ------------------ Godot RL Agents Logic ------------------------------------#
 
 
 
 
 
 
 
5
  var _player: Node3D
6
 
 
 
 
7
  func init(player: Node3D):
8
  _player = player
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
  class_name AIController3D
3
 
4
+ @export var reset_after := 1000
5
+
6
+ var heuristic := "human"
7
+ var done := false
8
+ var reward := 0.0
9
+ var n_steps := 0
10
+ var needs_reset := false
11
+
12
  var _player: Node3D
13
 
14
+ func _ready():
15
+ add_to_group("AGENT")
16
+
17
  func init(player: Node3D):
18
  _player = player
19
+
20
+ #-- Methods that need implementing using the "extend script" option in Godot --#
21
+ func get_obs() -> Dictionary:
22
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
23
+ return {"obs":[]}
24
+
25
+ func get_reward() -> float:
26
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
27
+ return 0.0
28
+
29
+ func get_action_space() -> Dictionary:
30
+ assert(false, "the get get_action_space method is not implemented when extending from ai_controller")
31
+ return {
32
+ "example_actions_continous" : {
33
+ "size": 2,
34
+ "action_type": "continuous"
35
+ },
36
+ "example_actions_discrete" : {
37
+ "size": 2,
38
+ "action_type": "discrete"
39
+ },
40
+ }
41
+
42
+ func set_action(action) -> void:
43
+ assert(false, "the get set_action method is not implemented when extending from ai_controller")
44
+ # -----------------------------------------------------------------------------#
45
+
46
+ func _physics_process(delta):
47
+ n_steps += 1
48
+ if n_steps > reset_after:
49
+ needs_reset = true
50
+
51
+ func get_obs_space():
52
+ # may need overriding if the obs space is complex
53
+ var obs = get_obs()
54
+ return {
55
+ "obs": {
56
+ "size": [len(obs["obs"])],
57
+ "space": "box"
58
+ },
59
+ }
60
+
61
+ func reset():
62
+ n_steps = 0
63
+ needs_reset = false
64
+
65
+ func reset_if_done():
66
+ if done:
67
+ reset()
68
+
69
+ func set_heuristic(h):
70
+ # sets the heuristic from "human" or "model" nothing to change here
71
+ heuristic = h
72
+
73
+ func get_done():
74
+ return done
75
+
76
+ func set_done_false():
77
+ done = false
78
+
79
+ func zero_reward():
80
+ reward = 0.0
addons/godot_rl_agents/icon.png.import CHANGED
@@ -2,7 +2,7 @@
2
 
3
  importer="texture"
4
  type="CompressedTexture2D"
5
- uid="uid://bxj7outrsyldm"
6
  path="res://.godot/imported/icon.png-45a871b53434e556222f5901d598ab34.ctex"
7
  metadata={
8
  "vram_texture": false
 
2
 
3
  importer="texture"
4
  type="CompressedTexture2D"
5
+ uid="uid://btyhe25nk3d13"
6
  path="res://.godot/imported/icon.png-45a871b53434e556222f5901d598ab34.ctex"
7
  metadata={
8
  "vram_texture": false
addons/godot_rl_agents/onnx/csharp/ONNXInference.cs CHANGED
@@ -1,93 +1,103 @@
1
  using Godot;
2
- using System.Collections.Generic;
3
- using System.Linq;
4
  using Microsoft.ML.OnnxRuntime;
5
  using Microsoft.ML.OnnxRuntime.Tensors;
 
 
6
 
7
- namespace GodotONNX{
8
- /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
9
- public partial class ONNXInference : Node
10
  {
11
-
12
- private InferenceSession session;
13
- /// <summary>
14
- /// Path to the ONNX model. Use Initialize to change it.
15
- /// </summary>
16
- private string modelPath;
17
- private int batchSize;
18
 
19
- private SessionOptions SessionOpt;
 
 
 
 
 
20
 
21
- //init function
22
- /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Initialize/*'/>
23
- public void Initialize(string Path, int BatchSize)
24
- {
25
- modelPath = Path;
26
- batchSize = BatchSize;
27
- SessionConfigurator.SystemCheck();
28
- SessionOpt = SessionConfigurator.GetSessionOptions();
29
- session = LoadModel(modelPath);
30
 
31
- }
32
- /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
33
- public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
34
- {
35
- //Current model: Any (Godot Rl Agents)
36
- //Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
37
-
38
- //Fill the input tensors
39
- // create span from inputSize
40
- var span = new float[obs.Count]; //There's probably a better way to do this
41
- for (int i = 0; i < obs.Count; i++)
42
  {
43
- span[i] = obs[i];
 
 
 
 
44
  }
45
-
46
- IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  {
48
  NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
49
  NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
50
- };
51
- IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
52
 
53
- IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
54
-
55
- try{
56
- results = session.Run(inputs, outputNames);
57
- }
58
- catch (OnnxRuntimeException e) {
59
- //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
60
- GD.Print("Error at inference: ", e);
61
- return null;
62
- }
63
- //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
64
- Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
65
- DisposableNamedOnnxValue output1 = results.First();
66
- DisposableNamedOnnxValue output2 = results.Last();
67
- Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
68
- Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
 
 
69
 
70
- foreach (float f in output1.AsEnumerable<float>()) {
71
- output1Array.Add(f);
72
- }
 
73
 
74
- foreach (float f in output2.AsEnumerable<float>()) {
75
- output2Array.Add(f);
76
- }
 
77
 
78
- output.Add(output1.Name, output1Array);
79
- output.Add(output2.Name, output2Array);
80
-
81
- //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
82
- return output;
83
- }
84
- /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
85
- public InferenceSession LoadModel(string Path)
86
- {
87
- Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
88
- byte[] model = file.GetBuffer((int)file.GetLength());
89
- file.Close();
90
- return new InferenceSession(model, SessionOpt); //Load the model
91
- }
 
 
 
 
 
 
92
  }
93
- }
 
1
  using Godot;
 
 
2
  using Microsoft.ML.OnnxRuntime;
3
  using Microsoft.ML.OnnxRuntime.Tensors;
4
+ using System.Collections.Generic;
5
+ using System.Linq;
6
 
7
+ namespace GodotONNX
 
 
8
  {
9
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
10
+ public partial class ONNXInference : GodotObject
11
+ {
 
 
 
 
12
 
13
+ private InferenceSession session;
14
+ /// <summary>
15
+ /// Path to the ONNX model. Use Initialize to change it.
16
+ /// </summary>
17
+ private string modelPath;
18
+ private int batchSize;
19
 
20
+ private SessionOptions SessionOpt;
 
 
 
 
 
 
 
 
21
 
22
+ //init function
23
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Initialize/*'/>
24
+ public void Initialize(string Path, int BatchSize)
 
 
 
 
 
 
 
 
25
  {
26
+ modelPath = Path;
27
+ batchSize = BatchSize;
28
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
29
+ session = LoadModel(modelPath);
30
+
31
  }
32
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
33
+ public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
34
+ {
35
+ //Current model: Any (Godot Rl Agents)
36
+ //Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
37
+
38
+ //Fill the input tensors
39
+ // create span from inputSize
40
+ var span = new float[obs.Count]; //There's probably a better way to do this
41
+ for (int i = 0; i < obs.Count; i++)
42
+ {
43
+ span[i] = obs[i];
44
+ }
45
+
46
+ IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
47
  {
48
  NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
49
  NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
50
+ };
51
+ IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
52
 
53
+ IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
54
+ //We do not use "using" here so we get a better exception explaination later
55
+ try
56
+ {
57
+ results = session.Run(inputs, outputNames);
58
+ }
59
+ catch (OnnxRuntimeException e)
60
+ {
61
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
62
+ GD.Print("Error at inference: ", e);
63
+ return null;
64
+ }
65
+ //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
66
+ Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
67
+ DisposableNamedOnnxValue output1 = results.First();
68
+ DisposableNamedOnnxValue output2 = results.Last();
69
+ Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
70
+ Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
71
 
72
+ foreach (float f in output1.AsEnumerable<float>())
73
+ {
74
+ output1Array.Add(f);
75
+ }
76
 
77
+ foreach (float f in output2.AsEnumerable<float>())
78
+ {
79
+ output2Array.Add(f);
80
+ }
81
 
82
+ output.Add(output1.Name, output1Array);
83
+ output.Add(output2.Name, output2Array);
84
+
85
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
86
+ results.Dispose();
87
+ return output;
88
+ }
89
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
90
+ public InferenceSession LoadModel(string Path)
91
+ {
92
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
93
+ byte[] model = file.GetBuffer((int)file.GetLength());
94
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
95
+ return new InferenceSession(model, SessionOpt); //Load the model
96
+ }
97
+ public void FreeDisposables()
98
+ {
99
+ session.Dispose();
100
+ SessionOpt.Dispose();
101
+ }
102
  }
103
+ }
addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs CHANGED
@@ -1,106 +1,131 @@
1
  using Godot;
2
  using Microsoft.ML.OnnxRuntime;
3
 
4
- namespace GodotONNX{
5
- /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SessionConfigurator/*'/>
6
-
7
- public static class SessionConfigurator {
8
-
9
- private static SessionOptions options = new SessionOptions();
10
-
11
- /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/GetSessionOptions/*'/>
12
- public static SessionOptions GetSessionOptions() {
13
- options = new SessionOptions();
14
- options.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
15
- // see warnings
16
- SystemCheck();
17
- return options;
18
- }
19
- /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SystemCheck/*'/>
20
 
21
- static public void SystemCheck()
22
  {
23
- //Most code for this function is verbose only, the only reason it exists is to track
24
- //implementation progress of the different compute APIs.
25
-
26
- //December 2022: CUDA is not working.
27
-
28
- string OSName = OS.GetName(); //Get OS Name
29
- int ComputeAPIID = ComputeCheck(); //Get Compute API
30
- //TODO: Get CPU architecture
31
-
32
- //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
33
- //Windows can use OpenVINO (C#) on x64
34
- //TODO: try TensorRT instead of CUDA
35
- //TODO: Use OpenVINO for Intel Graphics
36
-
37
- string [] ComputeNames = {"CUDA", "DirectML/ROCm", "DirectML", "CoreML", "CPU"};
38
- //match OS and Compute API
39
- options.AppendExecutionProvider_CPU(0); // Always use CPU
40
- GD.Print("OS: " + OSName, " | Compute API: " + ComputeNames[ComputeAPIID]);
41
-
42
- switch (OSName)
43
  {
44
- case "Windows": //Can use CUDA, DirectML
45
- if (ComputeAPIID == 0)
46
- {
47
- //CUDA
48
- //options.AppendExecutionProvider_CUDA(0);
49
- options.AppendExecutionProvider_DML(0);
50
- }
51
- else if (ComputeAPIID == 1)
52
- {
53
- //DirectML
54
- options.AppendExecutionProvider_DML(0);
55
- }
56
- break;
57
- case "X11": //Can use CUDA, ROCm
58
- if (ComputeAPIID == 0)
59
- {
60
- //CUDA
61
- //options.AppendExecutionProvider_CUDA(0);
62
- }
63
- if (ComputeAPIID == 1)
64
- {
65
- //ROCm, only works on x86
66
- //Research indicates that this has to be compiled as a GDNative plugin
67
- GD.Print("ROCm not supported yet, using CPU.");
68
- options.AppendExecutionProvider_CPU(0);
69
- }
70
-
71
- break;
72
- case "OSX": //Can use CoreML
73
- if (ComputeAPIID == 0) { //CoreML
74
- //TODO: Needs testing
75
- options.AppendExecutionProvider_CoreML(0);
76
- //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
77
- }
78
- break;
79
- default:
80
- GD.Print("OS not Supported.");
81
- break;
82
  }
83
- }
84
- /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/ComputeCheck/*'/>
85
 
86
- public static int ComputeCheck()
87
- {
88
- string adapterName = Godot.RenderingServer.GetVideoAdapterName();
89
- //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
90
- adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
91
- //TODO: GPU vendors for MacOS, what do they even use these days?
92
- if (adapterName.Contains("INTEL")) {
93
- //Return 2, should use DirectML only
94
- return 2;}
95
- if (adapterName.Contains("AMD")) {
96
- //Return 1, should use DirectML, check later for ROCm
97
- return 1;}
98
- if (adapterName.Contains("NVIDIA")){
99
- //Return 0, should use CUDA
100
- return 0;}
101
-
102
- GD.Print("Graphics Card not recognized."); //Return -1, should use CPU
103
- return -1;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  }
 
 
 
105
  }
106
- }
 
 
1
  using Godot;
2
  using Microsoft.ML.OnnxRuntime;
3
 
4
+ namespace GodotONNX
5
+ {
6
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SessionConfigurator/*'/>
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ public static class SessionConfigurator
9
  {
10
+ public enum ComputeName
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  {
12
+ CUDA,
13
+ ROCm,
14
+ DirectML,
15
+ CoreML,
16
+ CPU
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  }
 
 
18
 
19
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/GetSessionOptions/*'/>
20
+ public static SessionOptions MakeConfiguredSessionOptions()
21
+ {
22
+ SessionOptions sessionOptions = new();
23
+ SetOptions(sessionOptions);
24
+ return sessionOptions;
25
+ }
26
+
27
+ private static void SetOptions(SessionOptions sessionOptions)
28
+ {
29
+ sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
30
+ ApplySystemSpecificOptions(sessionOptions);
31
+ }
32
+
33
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SystemCheck/*'/>
34
+ static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
35
+ {
36
+ //Most code for this function is verbose only, the only reason it exists is to track
37
+ //implementation progress of the different compute APIs.
38
+
39
+ //December 2022: CUDA is not working.
40
+
41
+ string OSName = OS.GetName(); //Get OS Name
42
+
43
+ //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
44
+ // //TODO: Get CPU architecture
45
+
46
+ //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
47
+ //Windows can use OpenVINO (C#) on x64
48
+ //TODO: try TensorRT instead of CUDA
49
+ //TODO: Use OpenVINO for Intel Graphics
50
+
51
+ // Temporarily using CPU on all platforms to avoid errors detected with DML
52
+ ComputeName ComputeAPI = ComputeName.CPU;
53
+
54
+ //match OS and Compute API
55
+ GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
56
+
57
+ // CPU is set by default without appending necessary
58
+ // sessionOptions.AppendExecutionProvider_CPU(0);
59
+
60
+ /*
61
+ switch (OSName)
62
+ {
63
+ case "Windows": //Can use CUDA, DirectML
64
+ if (ComputeAPI is ComputeName.CUDA)
65
+ {
66
+ //CUDA
67
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
68
+ //sessionOptions.AppendExecutionProvider_DML(0);
69
+ }
70
+ else if (ComputeAPI is ComputeName.DirectML)
71
+ {
72
+ //DirectML
73
+ //sessionOptions.AppendExecutionProvider_DML(0);
74
+ }
75
+ break;
76
+ case "X11": //Can use CUDA, ROCm
77
+ if (ComputeAPI is ComputeName.CUDA)
78
+ {
79
+ //CUDA
80
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
81
+ }
82
+ if (ComputeAPI is ComputeName.ROCm)
83
+ {
84
+ //ROCm, only works on x86
85
+ //Research indicates that this has to be compiled as a GDNative plugin
86
+ //GD.Print("ROCm not supported yet, using CPU.");
87
+ //sessionOptions.AppendExecutionProvider_CPU(0);
88
+ }
89
+ break;
90
+ case "macOS": //Can use CoreML
91
+ if (ComputeAPI is ComputeName.CoreML)
92
+ { //CoreML
93
+ //TODO: Needs testing
94
+ //sessionOptions.AppendExecutionProvider_CoreML(0);
95
+ //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
96
+ }
97
+ break;
98
+ default:
99
+ GD.Print("OS not Supported.");
100
+ break;
101
+ }
102
+ */
103
+ }
104
+
105
+
106
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/ComputeCheck/*'/>
107
+ public static ComputeName ComputeCheck()
108
+ {
109
+ string adapterName = Godot.RenderingServer.GetVideoAdapterName();
110
+ //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
111
+ adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
112
+ //TODO: GPU vendors for MacOS, what do they even use these days?
113
+
114
+ if (adapterName.Contains("INTEL"))
115
+ {
116
+ return ComputeName.DirectML;
117
+ }
118
+ if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
119
+ {
120
+ return ComputeName.DirectML;
121
+ }
122
+ if (adapterName.Contains("NVIDIA"))
123
+ {
124
+ return ComputeName.CUDA;
125
  }
126
+
127
+ GD.Print("Graphics Card not recognized."); //Should use CPU
128
+ return ComputeName.CPU;
129
  }
130
+ }
131
+ }
addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd CHANGED
@@ -1,4 +1,4 @@
1
- extends Node
2
  class_name ONNXModel
3
  var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
4
 
@@ -17,3 +17,8 @@ func run_inference(obs : Array, state_ins : int) -> Dictionary:
17
  printerr("Inferencer not initialized")
18
  return {}
19
  return inferencer.RunInference(obs, state_ins)
 
 
 
 
 
 
1
+ extends Resource
2
  class_name ONNXModel
3
  var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
4
 
 
17
  printerr("Inferencer not initialized")
18
  return {}
19
  return inferencer.RunInference(obs, state_ins)
20
+
21
+ func _notification(what):
22
+ if what == NOTIFICATION_PREDELETE:
23
+ inferencer.FreeDisposables()
24
+ inferencer.free()
addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn CHANGED
@@ -1,6 +1,6 @@
1
  [gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
2
 
3
- [ext_resource type="Script" path="res://sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
4
 
5
  [sub_resource type="GDScript" id="2"]
6
  script/source = "extends Node2D
 
1
  [gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
2
 
3
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
4
 
5
  [sub_resource type="GDScript" id="2"]
6
  script/source = "extends Node2D
addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd CHANGED
@@ -61,11 +61,15 @@ var geo = null
61
 
62
  func _update():
63
  if Engine.is_editor_hint():
64
- _spawn_nodes()
65
-
66
 
67
  func _ready() -> void:
68
- _spawn_nodes()
 
 
 
 
69
 
70
  func _spawn_nodes():
71
  print("spawning nodes")
 
61
 
62
  func _update():
63
  if Engine.is_editor_hint():
64
+ if is_node_ready():
65
+ _spawn_nodes()
66
 
67
  func _ready() -> void:
68
+ if Engine.is_editor_hint():
69
+ if get_child_count() == 0:
70
+ _spawn_nodes()
71
+ else:
72
+ _spawn_nodes()
73
 
74
  func _spawn_nodes():
75
  print("spawning nodes")
addons/godot_rl_agents/sync.gd CHANGED
@@ -1,7 +1,7 @@
1
  extends Node
2
  # --fixed-fps 2000 --disable-render-loop
3
- @export var action_repeat := 8
4
- @export var speed_up = 1
5
  @export var onnx_model_path := ""
6
 
7
  @onready var start_time = Time.get_ticks_msec()
@@ -10,7 +10,6 @@ const MAJOR_VERSION := "0"
10
  const MINOR_VERSION := "3"
11
  const DEFAULT_PORT := "11008"
12
  const DEFAULT_SEED := "1"
13
- const DEFAULT_ACTION_REPEAT := "8"
14
  var stream : StreamPeerTCP = null
15
  var connected = false
16
  var message_center
@@ -44,17 +43,20 @@ func _initialize():
44
  Engine.time_scale = _get_speedup() * 1.0
45
  prints("physics ticks", Engine.physics_ticks_per_second, Engine.time_scale, _get_speedup(), speed_up)
46
 
47
-
48
- connected = connect_to_server()
49
- if connected:
50
- _set_heuristic("model")
51
- _handshake()
52
- _send_env_info()
53
- elif onnx_model_path != "":
54
  onnx_model = ONNXModel.new(onnx_model_path, 1)
55
  _set_heuristic("model")
56
- else:
57
- _set_heuristic("human")
 
 
 
 
 
 
58
 
59
  _set_seed()
60
  _set_action_repeat()
@@ -232,7 +234,7 @@ func _set_seed():
232
  seed(_seed)
233
 
234
  func _set_action_repeat():
235
- action_repeat = args.get("action_repeat", DEFAULT_ACTION_REPEAT).to_int()
236
 
237
  func disconnect_from_server():
238
  stream.disconnect_from_host()
 
1
  extends Node
2
  # --fixed-fps 2000 --disable-render-loop
3
+ @export_range(1, 10, 1, "or_greater") var action_repeat := 8
4
+ @export_range(1, 10, 1, "or_greater") var speed_up = 1
5
  @export var onnx_model_path := ""
6
 
7
  @onready var start_time = Time.get_ticks_msec()
 
10
  const MINOR_VERSION := "3"
11
  const DEFAULT_PORT := "11008"
12
  const DEFAULT_SEED := "1"
 
13
  var stream : StreamPeerTCP = null
14
  var connected = false
15
  var message_center
 
43
  Engine.time_scale = _get_speedup() * 1.0
44
  prints("physics ticks", Engine.physics_ticks_per_second, Engine.time_scale, _get_speedup(), speed_up)
45
 
46
+ # Run inference if onnx model path is set, otherwise wait for server connection
47
+ var run_onnx_model_inference : bool = onnx_model_path != ""
48
+ if run_onnx_model_inference:
49
+ assert(FileAccess.file_exists(onnx_model_path), "Onnx Model Path set on Sync node does not exist: " + onnx_model_path)
 
 
 
50
  onnx_model = ONNXModel.new(onnx_model_path, 1)
51
  _set_heuristic("model")
52
+ else:
53
+ connected = connect_to_server()
54
+ if connected:
55
+ _set_heuristic("model")
56
+ _handshake()
57
+ _send_env_info()
58
+ else:
59
+ _set_heuristic("human")
60
 
61
  _set_seed()
62
  _set_action_repeat()
 
234
  seed(_seed)
235
 
236
  func _set_action_repeat():
237
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
238
 
239
  func disconnect_from_server():
240
  stream.disconnect_from_host()
bin/JumperHard.console.exe CHANGED
Binary files a/bin/JumperHard.console.exe and b/bin/JumperHard.console.exe differ
 
bin/JumperHard.exe CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2de407f42a3db0dece9ff075b69219a30493b90c67f0a14bc450b414fba39125
3
- size 71425536
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:910d1661cf406eb788be65369b4784b8bde02dd16e327fac690b501d08e9e886
3
+ size 69051392
bin/JumperHard.pck CHANGED
Binary files a/bin/JumperHard.pck and b/bin/JumperHard.pck differ
 
bin/JumperHard.x86_64 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:843a1e5f8df1e6b2fe57ff86ca637436c7e1216f8409f2b079090c373548e86f
3
- size 72784744
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb6fa01639dd98489aac3e0dd5f9ecf0691b25b37a717f7380b1350d91ed23a4
3
+ size 61637496
export_presets.cfg CHANGED
@@ -8,18 +8,17 @@ custom_features=""
8
  export_filter="all_resources"
9
  include_filter=""
10
  exclude_filter=""
11
- export_path=""
12
  encryption_include_filters=""
13
  encryption_exclude_filters=""
14
  encrypt_pck=false
15
  encrypt_directory=false
16
- script_encryption_key=""
17
 
18
  [preset.0.options]
19
 
20
  custom_template/debug=""
21
  custom_template/release=""
22
- debug/export_console_script=1
23
  binary_format/embed_pck=false
24
  texture_format/bptc=true
25
  texture_format/s3tc=true
@@ -38,6 +37,10 @@ unzip -o -q \"{temp_dir}/{archive_name}\" -d \"{temp_dir}\"
38
  ssh_remote_deploy/cleanup_script="#!/usr/bin/env bash
39
  kill $(pgrep -x -f \"{temp_dir}/{exe_name} {cmd_args}\")
40
  rm -rf \"{temp_dir}\""
 
 
 
 
41
 
42
  [preset.1]
43
 
@@ -54,13 +57,12 @@ encryption_include_filters=""
54
  encryption_exclude_filters=""
55
  encrypt_pck=false
56
  encrypt_directory=false
57
- script_encryption_key=""
58
 
59
  [preset.1.options]
60
 
61
  custom_template/debug=""
62
  custom_template/release=""
63
- debug/export_console_script=1
64
  binary_format/embed_pck=false
65
  texture_format/bptc=true
66
  texture_format/s3tc=true
@@ -68,9 +70,6 @@ texture_format/etc=false
68
  texture_format/etc2=false
69
  binary_format/architecture="x86_64"
70
  codesign/enable=false
71
- codesign/identity_type=0
72
- codesign/identity=""
73
- codesign/password=""
74
  codesign/timestamp=true
75
  codesign/timestamp_server_url=""
76
  codesign/digest_algorithm=1
@@ -87,6 +86,7 @@ application/product_name=""
87
  application/file_description=""
88
  application/copyright=""
89
  application/trademarks=""
 
90
  ssh_remote_deploy/enabled=false
91
  ssh_remote_deploy/host="user@host_ip"
92
  ssh_remote_deploy/port="22"
@@ -104,3 +104,7 @@ Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorActi
104
  ssh_remote_deploy/cleanup_script="Stop-ScheduledTask -TaskName godot_remote_debug -ErrorAction:SilentlyContinue
105
  Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorAction:SilentlyContinue
106
  Remove-Item -Recurse -Force '{temp_dir}'"
 
 
 
 
 
8
  export_filter="all_resources"
9
  include_filter=""
10
  exclude_filter=""
11
+ export_path="../../../godot_rl_agents/examples/jh/JumperHard.x86_64"
12
  encryption_include_filters=""
13
  encryption_exclude_filters=""
14
  encrypt_pck=false
15
  encrypt_directory=false
 
16
 
17
  [preset.0.options]
18
 
19
  custom_template/debug=""
20
  custom_template/release=""
21
+ debug/export_console_wrapper=1
22
  binary_format/embed_pck=false
23
  texture_format/bptc=true
24
  texture_format/s3tc=true
 
37
  ssh_remote_deploy/cleanup_script="#!/usr/bin/env bash
38
  kill $(pgrep -x -f \"{temp_dir}/{exe_name} {cmd_args}\")
39
  rm -rf \"{temp_dir}\""
40
+ dotnet/include_scripts_content=false
41
+ dotnet/include_debug_symbols=true
42
+ dotnet/embed_build_outputs=false
43
+ debug/export_console_script=1
44
 
45
  [preset.1]
46
 
 
57
  encryption_exclude_filters=""
58
  encrypt_pck=false
59
  encrypt_directory=false
 
60
 
61
  [preset.1.options]
62
 
63
  custom_template/debug=""
64
  custom_template/release=""
65
+ debug/export_console_wrapper=1
66
  binary_format/embed_pck=false
67
  texture_format/bptc=true
68
  texture_format/s3tc=true
 
70
  texture_format/etc2=false
71
  binary_format/architecture="x86_64"
72
  codesign/enable=false
 
 
 
73
  codesign/timestamp=true
74
  codesign/timestamp_server_url=""
75
  codesign/digest_algorithm=1
 
86
  application/file_description=""
87
  application/copyright=""
88
  application/trademarks=""
89
+ application/export_angle=0
90
  ssh_remote_deploy/enabled=false
91
  ssh_remote_deploy/host="user@host_ip"
92
  ssh_remote_deploy/port="22"
 
104
  ssh_remote_deploy/cleanup_script="Stop-ScheduledTask -TaskName godot_remote_debug -ErrorAction:SilentlyContinue
105
  Unregister-ScheduledTask -TaskName godot_remote_debug -Confirm:$false -ErrorAction:SilentlyContinue
106
  Remove-Item -Recurse -Force '{temp_dir}'"
107
+ dotnet/include_scripts_content=false
108
+ dotnet/include_debug_symbols=true
109
+ dotnet/embed_build_outputs=false
110
+ debug/export_console_script=1
project.godot CHANGED
@@ -12,7 +12,7 @@ config_version=5
12
 
13
  config/name="JumperHard"
14
  run/main_scene="res://BatchEnvs.tscn"
15
- config/features=PackedStringArray("4.0", "C#")
16
  config/icon="res://icon.png"
17
 
18
  [dotnet]
@@ -21,7 +21,7 @@ project/assembly_name="JumperHard"
21
 
22
  [editor_plugins]
23
 
24
- enabled=PackedStringArray()
25
 
26
  [input]
27
 
 
12
 
13
  config/name="JumperHard"
14
  run/main_scene="res://BatchEnvs.tscn"
15
+ config/features=PackedStringArray("4.1", "C#")
16
  config/icon="res://icon.png"
17
 
18
  [dotnet]
 
21
 
22
  [editor_plugins]
23
 
24
+ enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
25
 
26
  [input]
27