Datasets:
Upload folder using huggingface_hub
Browse files- AIController2D.gd +47 -0
- BallChase.csproj +10 -0
- BallChase.onnx +3 -0
- BallChase.sln +25 -0
- BallChase.tscn +177 -0
- BatchEnvs.tscn +61 -0
- Camera2D.gd +31 -0
- Player.gd +151 -0
- README.md +25 -0
- addons/godot_rl_agents/controller/ai_controller_2d.gd +113 -0
- addons/godot_rl_agents/controller/ai_controller_3d.gd +114 -0
- addons/godot_rl_agents/godot_rl_agents.gd +16 -0
- addons/godot_rl_agents/icon.png +3 -0
- addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +103 -0
- addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
- addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
- addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml +29 -0
- addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd +27 -0
- addons/godot_rl_agents/plugin.cfg +7 -0
- addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn +48 -0
- addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd +235 -0
- addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd +25 -0
- addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd +118 -0
- addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn +7 -0
- addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn +6 -0
- addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd +258 -0
- addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd +25 -0
- addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd +21 -0
- addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn +41 -0
- addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd +185 -0
- addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn +27 -0
- addons/godot_rl_agents/sync.gd +540 -0
- cherry.png +3 -0
- default_env.tres +7 -0
- icon.png +3 -0
- light_mask.png +3 -0
- lollipopGreen.png +3 -0
- project.godot +102 -0
AIController2D.gd
ADDED
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends AIController2D
|
2 |
+
|
3 |
+
|
4 |
+
func _ready():
|
5 |
+
reset()
|
6 |
+
|
7 |
+
|
8 |
+
func _physics_process(_delta):
|
9 |
+
n_steps += 1
|
10 |
+
if n_steps > reset_after:
|
11 |
+
needs_reset = true
|
12 |
+
done = true
|
13 |
+
|
14 |
+
if needs_reset:
|
15 |
+
needs_reset = false
|
16 |
+
reset()
|
17 |
+
|
18 |
+
|
19 |
+
func get_reward():
|
20 |
+
return reward
|
21 |
+
|
22 |
+
|
23 |
+
func get_obs():
|
24 |
+
var relative = to_local(_player.get_fruit_position())
|
25 |
+
var distance = relative.length() / 1500.0
|
26 |
+
relative = relative.normalized()
|
27 |
+
var result := []
|
28 |
+
result.append(((position.x / _player.WIDTH) - 0.5) * 2)
|
29 |
+
result.append(((position.y / _player.HEIGHT) - 0.5) * 2)
|
30 |
+
result.append(relative.x)
|
31 |
+
result.append(relative.y)
|
32 |
+
result.append(distance)
|
33 |
+
var raycast_obs = _player.raycast_sensor.get_observation()
|
34 |
+
result.append_array(raycast_obs)
|
35 |
+
|
36 |
+
return {
|
37 |
+
"obs": result,
|
38 |
+
}
|
39 |
+
|
40 |
+
|
41 |
+
func set_action(action):
|
42 |
+
_player._action.x = action["move"][0]
|
43 |
+
_player._action.y = action["move"][1]
|
44 |
+
|
45 |
+
|
46 |
+
func get_action_space():
|
47 |
+
return {"move": {"size": 2, "action_type": "continuous"}}
|
BallChase.csproj
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<Project Sdk="Godot.NET.Sdk/4.0.3">
|
2 |
+
<PropertyGroup>
|
3 |
+
<TargetFramework>net6.0</TargetFramework>
|
4 |
+
<EnableDynamicLoading>true</EnableDynamicLoading>
|
5 |
+
<RootNamespace>GodotRLAgents</RootNamespace>
|
6 |
+
</PropertyGroup>
|
7 |
+
<ItemGroup>
|
8 |
+
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.15.1" />
|
9 |
+
</ItemGroup>
|
10 |
+
</Project>
|
BallChase.onnx
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:9396d2bfad557df48afb8f57318acc9e9801ca9161e3e6bcb8c6a2194f773217
|
3 |
+
size 24525
|
BallChase.sln
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
Microsoft Visual Studio Solution File, Format Version 12.00
|
3 |
+
# Visual Studio Version 17
|
4 |
+
VisualStudioVersion = 17.5.33530.505
|
5 |
+
MinimumVisualStudioVersion = 10.0.40219.1
|
6 |
+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Godot RL Agents", "Godot RL Agents.csproj", "{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}"
|
7 |
+
EndProject
|
8 |
+
Global
|
9 |
+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
10 |
+
Debug|Any CPU = Debug|Any CPU
|
11 |
+
ExportDebug|Any CPU = ExportDebug|Any CPU
|
12 |
+
ExportRelease|Any CPU = ExportRelease|Any CPU
|
13 |
+
EndGlobalSection
|
14 |
+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
15 |
+
{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
16 |
+
{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
17 |
+
{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
|
18 |
+
{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
|
19 |
+
{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
|
20 |
+
{055E8CBC-A3EC-41A8-BC53-EC3010682AE4}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
|
21 |
+
EndGlobalSection
|
22 |
+
GlobalSection(SolutionProperties) = preSolution
|
23 |
+
HideSolutionNode = FALSE
|
24 |
+
EndGlobalSection
|
25 |
+
EndGlobal
|
BallChase.tscn
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=14 format=3 uid="uid://bj8j0v5unredq"]
|
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_2d/RaycastSensor2D.gd" id="2"]
|
5 |
+
[ext_resource type="Texture2D" uid="uid://3wc0oii4d560" path="res://cherry.png" id="3_25acu"]
|
6 |
+
[ext_resource type="Texture2D" uid="uid://cje1ar3xnl01x" path="res://lollipopGreen.png" id="3_ty2qt"]
|
7 |
+
[ext_resource type="Script" path="res://AIController2D.gd" id="4_hrp2t"]
|
8 |
+
|
9 |
+
[sub_resource type="CircleShape2D" id="1"]
|
10 |
+
radius = 30.0
|
11 |
+
|
12 |
+
[sub_resource type="CircleShape2D" id="3"]
|
13 |
+
radius = 30.0
|
14 |
+
|
15 |
+
[sub_resource type="RectangleShape2D" id="4"]
|
16 |
+
size = Vector2(20, 720)
|
17 |
+
|
18 |
+
[sub_resource type="RectangleShape2D" id="5"]
|
19 |
+
size = Vector2(20, 720)
|
20 |
+
|
21 |
+
[sub_resource type="RectangleShape2D" id="6"]
|
22 |
+
size = Vector2(1240, 20)
|
23 |
+
|
24 |
+
[sub_resource type="RectangleShape2D" id="7"]
|
25 |
+
size = Vector2(1240, 20)
|
26 |
+
|
27 |
+
[sub_resource type="RectangleShape2D" id="8"]
|
28 |
+
size = Vector2(58.338, 286.306)
|
29 |
+
|
30 |
+
[sub_resource type="Environment" id="9"]
|
31 |
+
background_mode = 4
|
32 |
+
tonemap_mode = 3
|
33 |
+
glow_levels/1 = 1.0
|
34 |
+
glow_levels/2 = 1.0
|
35 |
+
glow_levels/3 = 0.0
|
36 |
+
glow_levels/4 = 1.0
|
37 |
+
glow_levels/5 = 0.0
|
38 |
+
glow_intensity = 0.1
|
39 |
+
glow_strength = 1.17
|
40 |
+
glow_bloom = 0.09
|
41 |
+
glow_blend_mode = 0
|
42 |
+
|
43 |
+
[node name="BallChase" type="Node2D"]
|
44 |
+
|
45 |
+
[node name="Player" type="CharacterBody2D" parent="."]
|
46 |
+
position = Vector2(281.728, 162.943)
|
47 |
+
script = ExtResource("1")
|
48 |
+
|
49 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Player"]
|
50 |
+
shape = SubResource("1")
|
51 |
+
|
52 |
+
[node name="RaycastSensor2D" type="Node2D" parent="Player"]
|
53 |
+
script = ExtResource("2")
|
54 |
+
collide_with_areas = true
|
55 |
+
|
56 |
+
[node name="Sprite2D" type="Sprite2D" parent="Player"]
|
57 |
+
scale = Vector2(0.9, 0.9)
|
58 |
+
texture = ExtResource("3_ty2qt")
|
59 |
+
|
60 |
+
[node name="AIController2D" type="Node2D" parent="Player" groups=["AGENT"]]
|
61 |
+
script = ExtResource("4_hrp2t")
|
62 |
+
reset_after = 20000
|
63 |
+
|
64 |
+
[node name="Fruit" type="Area2D" parent="."]
|
65 |
+
position = Vector2(1095.01, 578.224)
|
66 |
+
collision_layer = 2
|
67 |
+
collision_mask = 3
|
68 |
+
|
69 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Fruit"]
|
70 |
+
shape = SubResource("3")
|
71 |
+
|
72 |
+
[node name="Sprite2D" type="Sprite2D" parent="Fruit"]
|
73 |
+
position = Vector2(3.98999, -14.224)
|
74 |
+
scale = Vector2(1.2, 1.2)
|
75 |
+
texture = ExtResource("3_25acu")
|
76 |
+
|
77 |
+
[node name="Walls" type="Node2D" parent="."]
|
78 |
+
|
79 |
+
[node name="LeftWall" type="Area2D" parent="Walls"]
|
80 |
+
position = Vector2(10, 360)
|
81 |
+
|
82 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Walls/LeftWall"]
|
83 |
+
shape = SubResource("4")
|
84 |
+
|
85 |
+
[node name="ColorRect" type="ColorRect" parent="Walls/LeftWall"]
|
86 |
+
offset_left = -10.0
|
87 |
+
offset_top = -360.0
|
88 |
+
offset_right = 10.0
|
89 |
+
offset_bottom = 360.0
|
90 |
+
color = Color(0.27451, 0.529412, 0.560784, 1)
|
91 |
+
|
92 |
+
[node name="RightWall" type="Area2D" parent="Walls"]
|
93 |
+
position = Vector2(1270, 360)
|
94 |
+
|
95 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Walls/RightWall"]
|
96 |
+
shape = SubResource("5")
|
97 |
+
|
98 |
+
[node name="ColorRect" type="ColorRect" parent="Walls/RightWall"]
|
99 |
+
offset_left = -10.0
|
100 |
+
offset_top = -360.0
|
101 |
+
offset_right = 10.0
|
102 |
+
offset_bottom = 360.0
|
103 |
+
color = Color(0.27451, 0.529412, 0.560784, 1)
|
104 |
+
|
105 |
+
[node name="TopWall" type="Area2D" parent="Walls"]
|
106 |
+
position = Vector2(640, 10)
|
107 |
+
|
108 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Walls/TopWall"]
|
109 |
+
shape = SubResource("6")
|
110 |
+
|
111 |
+
[node name="ColorRect" type="ColorRect" parent="Walls/TopWall"]
|
112 |
+
offset_left = -620.0
|
113 |
+
offset_top = -10.0
|
114 |
+
offset_right = 620.0
|
115 |
+
offset_bottom = 10.0
|
116 |
+
color = Color(0.27451, 0.529412, 0.560784, 1)
|
117 |
+
|
118 |
+
[node name="BottomWall" type="Area2D" parent="Walls"]
|
119 |
+
position = Vector2(640, 710)
|
120 |
+
|
121 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Walls/BottomWall"]
|
122 |
+
shape = SubResource("7")
|
123 |
+
|
124 |
+
[node name="ColorRect" type="ColorRect" parent="Walls/BottomWall"]
|
125 |
+
offset_left = -620.0
|
126 |
+
offset_top = -10.0
|
127 |
+
offset_right = 620.0
|
128 |
+
offset_bottom = 10.0
|
129 |
+
color = Color(0.27451, 0.529412, 0.560784, 1)
|
130 |
+
|
131 |
+
[node name="Obstacle4" type="Area2D" parent="Walls"]
|
132 |
+
position = Vector2(896, 328)
|
133 |
+
|
134 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Walls/Obstacle4"]
|
135 |
+
shape = SubResource("8")
|
136 |
+
|
137 |
+
[node name="ColorRect" type="ColorRect" parent="Walls/Obstacle4"]
|
138 |
+
offset_left = -35.0
|
139 |
+
offset_top = -143.0
|
140 |
+
offset_right = 29.0
|
141 |
+
offset_bottom = 153.0
|
142 |
+
color = Color(0.27451, 0.529412, 0.560784, 1)
|
143 |
+
|
144 |
+
[node name="Obstacle5" type="Area2D" parent="Walls"]
|
145 |
+
position = Vector2(360, 328)
|
146 |
+
|
147 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="Walls/Obstacle5"]
|
148 |
+
shape = SubResource("8")
|
149 |
+
|
150 |
+
[node name="ColorRect" type="ColorRect" parent="Walls/Obstacle5"]
|
151 |
+
offset_left = -35.0
|
152 |
+
offset_top = -143.0
|
153 |
+
offset_right = 29.0
|
154 |
+
offset_bottom = 153.0
|
155 |
+
color = Color(0.27451, 0.529412, 0.560784, 1)
|
156 |
+
|
157 |
+
[node name="BackGround" type="CanvasLayer" parent="."]
|
158 |
+
layer = -2
|
159 |
+
|
160 |
+
[node name="ColorRect" type="ColorRect" parent="BackGround"]
|
161 |
+
anchors_preset = -1
|
162 |
+
anchor_right = 5.954
|
163 |
+
anchor_bottom = 5.885
|
164 |
+
offset_right = 15506.9
|
165 |
+
offset_bottom = 7480.8
|
166 |
+
color = Color(0.2, 0.172549, 0.313726, 1)
|
167 |
+
|
168 |
+
[node name="WorldEnvironment" type="WorldEnvironment" parent="."]
|
169 |
+
environment = SubResource("9")
|
170 |
+
|
171 |
+
[connection signal="body_entered" from="Fruit" to="Player" method="_on_Fruit_body_entered"]
|
172 |
+
[connection signal="body_entered" from="Walls/LeftWall" to="Player" method="_on_LeftWall_body_entered"]
|
173 |
+
[connection signal="body_entered" from="Walls/RightWall" to="Player" method="_on_RightWall_body_entered"]
|
174 |
+
[connection signal="body_entered" from="Walls/TopWall" to="Player" method="_on_TopWall_body_entered"]
|
175 |
+
[connection signal="body_entered" from="Walls/BottomWall" to="Player" method="_on_BottomWall_body_entered"]
|
176 |
+
[connection signal="body_entered" from="Walls/Obstacle4" to="Player" method="_on_BottomWall_body_entered"]
|
177 |
+
[connection signal="body_entered" from="Walls/Obstacle5" to="Player" method="_on_BottomWall_body_entered"]
|
BatchEnvs.tscn
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=4 format=3 uid="uid://b6wx3tp61htno"]
|
2 |
+
|
3 |
+
[ext_resource type="PackedScene" uid="uid://bj8j0v5unredq" path="res://BallChase.tscn" id="1"]
|
4 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2"]
|
5 |
+
[ext_resource type="Script" path="res://Camera2D.gd" id="3"]
|
6 |
+
|
7 |
+
[node name="BatchEnvs" type="Node"]
|
8 |
+
|
9 |
+
[node name="BallChase" parent="." instance=ExtResource("1")]
|
10 |
+
|
11 |
+
[node name="BallChase2" parent="." instance=ExtResource("1")]
|
12 |
+
position = Vector2(1305.28, 0)
|
13 |
+
|
14 |
+
[node name="BallChase3" parent="." instance=ExtResource("1")]
|
15 |
+
position = Vector2(2610.56, 0)
|
16 |
+
|
17 |
+
[node name="BallChase4" parent="." instance=ExtResource("1")]
|
18 |
+
position = Vector2(0, 755.953)
|
19 |
+
|
20 |
+
[node name="BallChase5" parent="." instance=ExtResource("1")]
|
21 |
+
position = Vector2(1305.28, 755.953)
|
22 |
+
|
23 |
+
[node name="BallChase6" parent="." instance=ExtResource("1")]
|
24 |
+
position = Vector2(2615.6, 755.953)
|
25 |
+
|
26 |
+
[node name="BallChase7" parent="." instance=ExtResource("1")]
|
27 |
+
position = Vector2(-6.73053, 1499.22)
|
28 |
+
|
29 |
+
[node name="BallChase8" parent="." instance=ExtResource("1")]
|
30 |
+
position = Vector2(1313.05, 1497.38)
|
31 |
+
|
32 |
+
[node name="BallChase9" parent="." instance=ExtResource("1")]
|
33 |
+
position = Vector2(2622.25, 1501.73)
|
34 |
+
|
35 |
+
[node name="BallChase10" parent="." instance=ExtResource("1")]
|
36 |
+
position = Vector2(1.70138, 2248.41)
|
37 |
+
|
38 |
+
[node name="BallChase11" parent="." instance=ExtResource("1")]
|
39 |
+
position = Vector2(1311.82, 2240.65)
|
40 |
+
|
41 |
+
[node name="BallChase12" parent="." instance=ExtResource("1")]
|
42 |
+
position = Vector2(2623.68, 2247.05)
|
43 |
+
|
44 |
+
[node name="BallChase13" parent="." instance=ExtResource("1")]
|
45 |
+
position = Vector2(3915.78, 0)
|
46 |
+
|
47 |
+
[node name="BallChase14" parent="." instance=ExtResource("1")]
|
48 |
+
position = Vector2(3922.71, 751.447)
|
49 |
+
|
50 |
+
[node name="BallChase15" parent="." instance=ExtResource("1")]
|
51 |
+
position = Vector2(3924.84, 1505.68)
|
52 |
+
|
53 |
+
[node name="BallChase16" parent="." instance=ExtResource("1")]
|
54 |
+
position = Vector2(3922.87, 2243.04)
|
55 |
+
|
56 |
+
[node name="Camera2D" type="Camera2D" parent="."]
|
57 |
+
offset = Vector2(640, 360)
|
58 |
+
script = ExtResource("3")
|
59 |
+
|
60 |
+
[node name="Sync" type="Node" parent="."]
|
61 |
+
script = ExtResource("2")
|
Camera2D.gd
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Camera2D
|
2 |
+
|
3 |
+
const MOVE_SPEED = 1000
|
4 |
+
const MIN_ZOOM = 0.1
|
5 |
+
const MAX_ZOOM = 1
|
6 |
+
const ZOOM_FACTOR = 1.2
|
7 |
+
|
8 |
+
func _process(delta):
|
9 |
+
if Input.is_action_pressed("reset_camera"):
|
10 |
+
global_position = Vector2.ZERO
|
11 |
+
if Input.is_action_pressed("left_arrow"):
|
12 |
+
global_position += Vector2.LEFT * delta * MOVE_SPEED
|
13 |
+
elif Input.is_action_pressed("right_arrow"):
|
14 |
+
global_position += Vector2.RIGHT * delta * MOVE_SPEED
|
15 |
+
if Input.is_action_pressed("up_arrow"):
|
16 |
+
global_position += Vector2.UP * delta * MOVE_SPEED
|
17 |
+
elif Input.is_action_pressed("down_arrow"):
|
18 |
+
global_position += Vector2.DOWN * delta * MOVE_SPEED
|
19 |
+
|
20 |
+
global_position.x = max(0, global_position.x)
|
21 |
+
global_position.y = max(0, global_position.y)
|
22 |
+
|
23 |
+
|
24 |
+
func _input(event : InputEvent) -> void:
|
25 |
+
if event is InputEventMouseButton:
|
26 |
+
if event.is_action_pressed("zoom_in"):
|
27 |
+
print("zoom_in")
|
28 |
+
if event.is_action_pressed("zoom_out"):
|
29 |
+
zoom /= ZOOM_FACTOR
|
30 |
+
zoom.x = clamp(zoom.x, MIN_ZOOM, MAX_ZOOM)
|
31 |
+
zoom.y = clamp(zoom.y, MIN_ZOOM, MAX_ZOOM)
|
Player.gd
ADDED
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends CharacterBody2D
|
2 |
+
|
3 |
+
const pad = 100
|
4 |
+
const WIDTH = 1280
|
5 |
+
const HEIGHT = 720
|
6 |
+
const MAX_FRUIT = 10
|
7 |
+
var _bounds := Rect2(pad, pad, WIDTH - 2 * pad, HEIGHT - 2 * pad)
|
8 |
+
|
9 |
+
@export var speed := 500
|
10 |
+
@export var friction = 0.18
|
11 |
+
var _velocity := Vector2.ZERO
|
12 |
+
var _action = Vector2.ZERO
|
13 |
+
@onready var fruit = $"../Fruit"
|
14 |
+
@onready var raycast_sensor = $"RaycastSensor2D"
|
15 |
+
@onready var walls := $"../Walls"
|
16 |
+
@onready var colision_shape := $"CollisionShape2D"
|
17 |
+
@onready var ai_controller := $AIController2D
|
18 |
+
var fruit_just_entered = false
|
19 |
+
var just_hit_wall = false
|
20 |
+
var best_fruit_distance = 10000.0
|
21 |
+
var fruit_count = 0
|
22 |
+
|
23 |
+
|
24 |
+
func _ready():
|
25 |
+
ai_controller.init(self)
|
26 |
+
raycast_sensor.activate()
|
27 |
+
|
28 |
+
|
29 |
+
func _physics_process(_delta):
|
30 |
+
var direction = get_direction()
|
31 |
+
if direction.length() > 1.0:
|
32 |
+
direction = direction.normalized()
|
33 |
+
# Using the follow steering behavior.
|
34 |
+
var target_velocity = direction * speed
|
35 |
+
_velocity += (target_velocity - _velocity) * friction
|
36 |
+
set_velocity(_velocity)
|
37 |
+
move_and_slide()
|
38 |
+
_velocity = velocity
|
39 |
+
|
40 |
+
update_reward()
|
41 |
+
|
42 |
+
if Input.is_action_just_pressed("r_key"):
|
43 |
+
game_over()
|
44 |
+
|
45 |
+
|
46 |
+
func game_over():
|
47 |
+
fruit_just_entered = false
|
48 |
+
just_hit_wall = false
|
49 |
+
fruit_count = 0
|
50 |
+
_velocity = Vector2.ZERO
|
51 |
+
_action = Vector2.ZERO
|
52 |
+
position = _calculate_new_position()
|
53 |
+
spawn_fruit()
|
54 |
+
best_fruit_distance = position.distance_to(fruit.position)
|
55 |
+
ai_controller.reset()
|
56 |
+
|
57 |
+
|
58 |
+
func _calculate_new_position(current_position: Vector2 = Vector2.ZERO) -> Vector2:
|
59 |
+
var new_position := Vector2.ZERO
|
60 |
+
new_position.x = randf_range(_bounds.position.x, _bounds.end.x)
|
61 |
+
new_position.y = randf_range(_bounds.position.y, _bounds.end.y)
|
62 |
+
|
63 |
+
if (current_position - new_position).length() < 4.0 * colision_shape.shape.get_radius():
|
64 |
+
return _calculate_new_position(current_position)
|
65 |
+
|
66 |
+
var radius = colision_shape.shape.get_radius()
|
67 |
+
var rect = Rect2(new_position - Vector2(radius, radius), Vector2(radius * 2, radius * 2))
|
68 |
+
for wall in walls.get_children():
|
69 |
+
#wall = wall as Area2D
|
70 |
+
var cr = wall.get_node("ColorRect")
|
71 |
+
var rect2 = Rect2(cr.get_position() + wall.position, cr.get_size())
|
72 |
+
if rect.intersects(rect2):
|
73 |
+
return _calculate_new_position()
|
74 |
+
|
75 |
+
return new_position
|
76 |
+
|
77 |
+
|
78 |
+
func get_direction():
|
79 |
+
if ai_controller.done:
|
80 |
+
_velocity = Vector2.ZERO
|
81 |
+
return Vector2.ZERO
|
82 |
+
|
83 |
+
if ai_controller.heuristic == "model":
|
84 |
+
return _action
|
85 |
+
|
86 |
+
var direction := Vector2(
|
87 |
+
Input.get_action_strength("move_right") - Input.get_action_strength("move_left"),
|
88 |
+
Input.get_action_strength("move_down") - Input.get_action_strength("move_up")
|
89 |
+
)
|
90 |
+
|
91 |
+
return direction
|
92 |
+
|
93 |
+
|
94 |
+
func get_fruit_position():
|
95 |
+
return $"../Fruit".global_position
|
96 |
+
|
97 |
+
|
98 |
+
func update_reward():
|
99 |
+
ai_controller.reward -= 0.01 # step penalty
|
100 |
+
ai_controller.reward += shaping_reward()
|
101 |
+
|
102 |
+
|
103 |
+
func shaping_reward():
|
104 |
+
var s_reward = 0.0
|
105 |
+
var fruit_distance = position.distance_to(fruit.position)
|
106 |
+
|
107 |
+
if fruit_distance < best_fruit_distance:
|
108 |
+
s_reward += best_fruit_distance - fruit_distance
|
109 |
+
best_fruit_distance = fruit_distance
|
110 |
+
|
111 |
+
s_reward /= 100.0
|
112 |
+
return s_reward
|
113 |
+
|
114 |
+
|
115 |
+
func spawn_fruit():
|
116 |
+
fruit.position = _calculate_new_position(position)
|
117 |
+
best_fruit_distance = position.distance_to(fruit.position)
|
118 |
+
|
119 |
+
|
120 |
+
func fruit_collected():
|
121 |
+
fruit_just_entered = true
|
122 |
+
ai_controller.reward += 10.0
|
123 |
+
fruit_count += 1
|
124 |
+
spawn_fruit()
|
125 |
+
|
126 |
+
|
127 |
+
func wall_hit():
|
128 |
+
ai_controller.done = true
|
129 |
+
ai_controller.reward -= 10.0
|
130 |
+
just_hit_wall = true
|
131 |
+
game_over()
|
132 |
+
|
133 |
+
|
134 |
+
func _on_Fruit_body_entered(_body):
|
135 |
+
fruit_collected()
|
136 |
+
|
137 |
+
|
138 |
+
func _on_LeftWall_body_entered(_body):
|
139 |
+
wall_hit()
|
140 |
+
|
141 |
+
|
142 |
+
func _on_RightWall_body_entered(_body):
|
143 |
+
wall_hit()
|
144 |
+
|
145 |
+
|
146 |
+
func _on_TopWall_body_entered(_body):
|
147 |
+
wall_hit()
|
148 |
+
|
149 |
+
|
150 |
+
func _on_BottomWall_body_entered(_body):
|
151 |
+
wall_hit()
|
README.md
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
library_name: godot-rl
|
3 |
+
tags:
|
4 |
+
- deep-reinforcement-learning
|
5 |
+
- reinforcement-learning
|
6 |
+
- godot-rl
|
7 |
+
- environments
|
8 |
+
- video-games
|
9 |
+
---
|
10 |
+
|
11 |
+
A RL environment called BallChase for the Godot Game Engine.
|
12 |
+
|
13 |
+
This environment was created with: https://github.com/edbeeching/godot_rl_agents
|
14 |
+
|
15 |
+
|
16 |
+
## Downloading the environment
|
17 |
+
|
18 |
+
After installing Godot RL Agents, download the environment with:
|
19 |
+
|
20 |
+
```
|
21 |
+
gdrl.env_from_hub -r jtatman/godot_rl_BallChase
|
22 |
+
```
|
23 |
+
|
24 |
+
|
25 |
+
|
addons/godot_rl_agents/controller/ai_controller_2d.gd
ADDED
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node2D
|
2 |
+
class_name AIController2D
|
3 |
+
|
4 |
+
enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
|
5 |
+
@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
|
6 |
+
@export var onnx_model_path := ""
|
7 |
+
@export var reset_after := 1000
|
8 |
+
|
9 |
+
@export_group("Record expert demos mode options")
|
10 |
+
## Path where the demos will be saved. The file can later be used for imitation learning.
|
11 |
+
@export var expert_demo_save_path: String
|
12 |
+
## The action that erases the last recorded episode from the currently recorded data.
|
13 |
+
@export var remove_last_episode_key: InputEvent
|
14 |
+
## Action will be repeated for n frames. Will introduce control lag if larger than 1.
|
15 |
+
## Can be used to ensure that action_repeat on inference and training matches
|
16 |
+
## the recorded demonstrations.
|
17 |
+
@export var action_repeat: int = 1
|
18 |
+
|
19 |
+
var onnx_model: ONNXModel
|
20 |
+
|
21 |
+
var heuristic := "human"
|
22 |
+
var done := false
|
23 |
+
var reward := 0.0
|
24 |
+
var n_steps := 0
|
25 |
+
var needs_reset := false
|
26 |
+
|
27 |
+
var _player: Node2D
|
28 |
+
|
29 |
+
|
30 |
+
func _ready():
|
31 |
+
add_to_group("AGENT")
|
32 |
+
|
33 |
+
|
34 |
+
func init(player: Node2D):
|
35 |
+
_player = player
|
36 |
+
|
37 |
+
|
38 |
+
#-- Methods that need implementing using the "extend script" option in Godot --#
|
39 |
+
func get_obs() -> Dictionary:
|
40 |
+
assert(false, "the get_obs method is not implemented when extending from ai_controller")
|
41 |
+
return {"obs": []}
|
42 |
+
|
43 |
+
|
44 |
+
func get_reward() -> float:
|
45 |
+
assert(false, "the get_reward method is not implemented when extending from ai_controller")
|
46 |
+
return 0.0
|
47 |
+
|
48 |
+
|
49 |
+
func get_action_space() -> Dictionary:
|
50 |
+
assert(
|
51 |
+
false,
|
52 |
+
"the get get_action_space method is not implemented when extending from ai_controller"
|
53 |
+
)
|
54 |
+
return {
|
55 |
+
"example_actions_continous": {"size": 2, "action_type": "continuous"},
|
56 |
+
"example_actions_discrete": {"size": 2, "action_type": "discrete"},
|
57 |
+
}
|
58 |
+
|
59 |
+
|
60 |
+
func set_action(action) -> void:
|
61 |
+
assert(false, "the get set_action method is not implemented when extending from ai_controller")
|
62 |
+
|
63 |
+
|
64 |
+
#-----------------------------------------------------------------------------#
|
65 |
+
|
66 |
+
|
67 |
+
#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
|
68 |
+
# Only needed if you are recording expert demos with this AIController
|
69 |
+
func get_action() -> Array:
|
70 |
+
assert(false, "the get set_action method is not implemented in extended AIController but demo_recorder is used")
|
71 |
+
return []
|
72 |
+
|
73 |
+
# -----------------------------------------------------------------------------#
|
74 |
+
|
75 |
+
func _physics_process(delta):
|
76 |
+
n_steps += 1
|
77 |
+
if n_steps > reset_after:
|
78 |
+
needs_reset = true
|
79 |
+
|
80 |
+
|
81 |
+
func get_obs_space():
|
82 |
+
# may need overriding if the obs space is complex
|
83 |
+
var obs = get_obs()
|
84 |
+
return {
|
85 |
+
"obs": {"size": [len(obs["obs"])], "space": "box"},
|
86 |
+
}
|
87 |
+
|
88 |
+
|
89 |
+
func reset():
|
90 |
+
n_steps = 0
|
91 |
+
needs_reset = false
|
92 |
+
|
93 |
+
|
94 |
+
func reset_if_done():
|
95 |
+
if done:
|
96 |
+
reset()
|
97 |
+
|
98 |
+
|
99 |
+
func set_heuristic(h):
|
100 |
+
# sets the heuristic from "human" or "model" nothing to change here
|
101 |
+
heuristic = h
|
102 |
+
|
103 |
+
|
104 |
+
func get_done():
|
105 |
+
return done
|
106 |
+
|
107 |
+
|
108 |
+
func set_done_false():
|
109 |
+
done = false
|
110 |
+
|
111 |
+
|
112 |
+
func zero_reward():
|
113 |
+
reward = 0.0
|
addons/godot_rl_agents/controller/ai_controller_3d.gd
ADDED
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name AIController3D
|
3 |
+
|
4 |
+
enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
|
5 |
+
@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
|
6 |
+
@export var onnx_model_path := ""
|
7 |
+
@export var reset_after := 1000
|
8 |
+
|
9 |
+
@export_group("Record expert demos mode options")
|
10 |
+
## Path where the demos will be saved. The file can later be used for imitation learning.
|
11 |
+
@export var expert_demo_save_path: String
|
12 |
+
## The action that erases the last recorded episode from the currently recorded data.
|
13 |
+
@export var remove_last_episode_key: InputEvent
|
14 |
+
## Action will be repeated for n frames. Will introduce control lag if larger than 1.
|
15 |
+
## Can be used to ensure that action_repeat on inference and training matches
|
16 |
+
## the recorded demonstrations.
|
17 |
+
@export var action_repeat: int = 1
|
18 |
+
|
19 |
+
var onnx_model: ONNXModel
|
20 |
+
|
21 |
+
var heuristic := "human"
|
22 |
+
var done := false
|
23 |
+
var reward := 0.0
|
24 |
+
var n_steps := 0
|
25 |
+
var needs_reset := false
|
26 |
+
|
27 |
+
var _player: Node3D
|
28 |
+
|
29 |
+
|
30 |
+
func _ready():
|
31 |
+
add_to_group("AGENT")
|
32 |
+
|
33 |
+
|
34 |
+
func init(player: Node3D):
|
35 |
+
_player = player
|
36 |
+
|
37 |
+
|
38 |
+
#-- Methods that need implementing using the "extend script" option in Godot --#
|
39 |
+
func get_obs() -> Dictionary:
|
40 |
+
assert(false, "the get_obs method is not implemented when extending from ai_controller")
|
41 |
+
return {"obs": []}
|
42 |
+
|
43 |
+
|
44 |
+
func get_reward() -> float:
|
45 |
+
assert(false, "the get_reward method is not implemented when extending from ai_controller")
|
46 |
+
return 0.0
|
47 |
+
|
48 |
+
|
49 |
+
func get_action_space() -> Dictionary:
|
50 |
+
assert(
|
51 |
+
false,
|
52 |
+
"the get get_action_space method is not implemented when extending from ai_controller"
|
53 |
+
)
|
54 |
+
return {
|
55 |
+
"example_actions_continous": {"size": 2, "action_type": "continuous"},
|
56 |
+
"example_actions_discrete": {"size": 2, "action_type": "discrete"},
|
57 |
+
}
|
58 |
+
|
59 |
+
|
60 |
+
func set_action(action) -> void:
|
61 |
+
assert(false, "the get set_action method is not implemented when extending from ai_controller")
|
62 |
+
|
63 |
+
|
64 |
+
#-----------------------------------------------------------------------------#
|
65 |
+
|
66 |
+
|
67 |
+
#-- Methods that sometimes need implementing using the "extend script" option in Godot --#
|
68 |
+
# Only needed if you are recording expert demos with this AIController
|
69 |
+
func get_action() -> Array:
|
70 |
+
assert(false, "the get set_action method is not implemented in extended AIController but demo_recorder is used")
|
71 |
+
return []
|
72 |
+
|
73 |
+
# -----------------------------------------------------------------------------#
|
74 |
+
|
75 |
+
|
76 |
+
func _physics_process(delta):
|
77 |
+
n_steps += 1
|
78 |
+
if n_steps > reset_after:
|
79 |
+
needs_reset = true
|
80 |
+
|
81 |
+
|
82 |
+
func get_obs_space():
|
83 |
+
# may need overriding if the obs space is complex
|
84 |
+
var obs = get_obs()
|
85 |
+
return {
|
86 |
+
"obs": {"size": [len(obs["obs"])], "space": "box"},
|
87 |
+
}
|
88 |
+
|
89 |
+
|
90 |
+
func reset():
|
91 |
+
n_steps = 0
|
92 |
+
needs_reset = false
|
93 |
+
|
94 |
+
|
95 |
+
func reset_if_done():
|
96 |
+
if done:
|
97 |
+
reset()
|
98 |
+
|
99 |
+
|
100 |
+
func set_heuristic(h):
|
101 |
+
# sets the heuristic from "human" or "model" nothing to change here
|
102 |
+
heuristic = h
|
103 |
+
|
104 |
+
|
105 |
+
func get_done():
|
106 |
+
return done
|
107 |
+
|
108 |
+
|
109 |
+
func set_done_false():
|
110 |
+
done = false
|
111 |
+
|
112 |
+
|
113 |
+
func zero_reward():
|
114 |
+
reward = 0.0
|
addons/godot_rl_agents/godot_rl_agents.gd
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends EditorPlugin
|
3 |
+
|
4 |
+
|
5 |
+
func _enter_tree():
|
6 |
+
# Initialization of the plugin goes here.
|
7 |
+
# Add the new type with a name, a parent type, a script and an icon.
|
8 |
+
add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png"))
|
9 |
+
#add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png"))
|
10 |
+
|
11 |
+
|
12 |
+
func _exit_tree():
|
13 |
+
# Clean-up of the plugin goes here.
|
14 |
+
# Always remember to remove it from the engine when deactivated.
|
15 |
+
remove_custom_type("Sync")
|
16 |
+
#remove_custom_type("RaycastSensor2D2")
|
addons/godot_rl_agents/icon.png
ADDED
Git LFS Details
|
addons/godot_rl_agents/onnx/csharp/ONNXInference.cs
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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/csharp/docs/ONNXInference.xml
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<docs>
|
2 |
+
<members name="ONNXInference">
|
3 |
+
<ONNXInference>
|
4 |
+
<summary>
|
5 |
+
The main <c>ONNXInference</c> Class that handles the inference process.
|
6 |
+
</summary>
|
7 |
+
</ONNXInference>
|
8 |
+
<Initialize>
|
9 |
+
<summary>
|
10 |
+
Starts the inference process.
|
11 |
+
</summary>
|
12 |
+
<param name="Path">Path to the ONNX model, expects a path inside resources.</param>
|
13 |
+
<param name="BatchSize">How many observations will the model recieve.</param>
|
14 |
+
</Initialize>
|
15 |
+
<Run>
|
16 |
+
<summary>
|
17 |
+
Runs the given input through the model and returns the output.
|
18 |
+
</summary>
|
19 |
+
<param name="obs">Dictionary containing all observations.</param>
|
20 |
+
<param name="state_ins">How many different agents are creating these observations.</param>
|
21 |
+
<returns>A Dictionary of arrays, containing instructions based on the observations.</returns>
|
22 |
+
</Run>
|
23 |
+
<Load>
|
24 |
+
<summary>
|
25 |
+
Loads the given model into the inference process, using the best Execution provider available.
|
26 |
+
</summary>
|
27 |
+
<param name="Path">Path to the ONNX model, expects a path inside resources.</param>
|
28 |
+
<returns>InferenceSession ready to run.</returns>
|
29 |
+
</Load>
|
30 |
+
</members>
|
31 |
+
</docs>
|
addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<docs>
|
2 |
+
<members name="SessionConfigurator">
|
3 |
+
<SessionConfigurator>
|
4 |
+
<summary>
|
5 |
+
The main <c>SessionConfigurator</c> Class that handles the execution options and providers for the inference process.
|
6 |
+
</summary>
|
7 |
+
</SessionConfigurator>
|
8 |
+
<GetSessionOptions>
|
9 |
+
<summary>
|
10 |
+
Creates a SessionOptions with all available execution providers.
|
11 |
+
</summary>
|
12 |
+
<returns>SessionOptions with all available execution providers.</returns>
|
13 |
+
</GetSessionOptions>
|
14 |
+
<SystemCheck>
|
15 |
+
<summary>
|
16 |
+
Appends any execution provider available in the current system.
|
17 |
+
</summary>
|
18 |
+
<remarks>
|
19 |
+
This function is mainly verbose for tracking implementation progress of different compute APIs.
|
20 |
+
</remarks>
|
21 |
+
</SystemCheck>
|
22 |
+
<ComputeCheck>
|
23 |
+
<summary>
|
24 |
+
Checks for available GPUs.
|
25 |
+
</summary>
|
26 |
+
<returns>An integer identifier for each compute platform.</returns>
|
27 |
+
</ComputeCheck>
|
28 |
+
</members>
|
29 |
+
</docs>
|
addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Resource
|
2 |
+
class_name ONNXModel
|
3 |
+
var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
|
4 |
+
|
5 |
+
var inferencer = null
|
6 |
+
|
7 |
+
|
8 |
+
# Must provide the path to the model and the batch size
|
9 |
+
func _init(model_path, batch_size):
|
10 |
+
inferencer = inferencer_script.new()
|
11 |
+
inferencer.Initialize(model_path, batch_size)
|
12 |
+
|
13 |
+
|
14 |
+
# This function is the one that will be called from the game,
|
15 |
+
# requires the observation as an array and the state_ins as an int
|
16 |
+
# returns an Array containing the action the model takes.
|
17 |
+
func run_inference(obs: Array, state_ins: int) -> Dictionary:
|
18 |
+
if inferencer == null:
|
19 |
+
printerr("Inferencer not initialized")
|
20 |
+
return {}
|
21 |
+
return inferencer.RunInference(obs, state_ins)
|
22 |
+
|
23 |
+
|
24 |
+
func _notification(what):
|
25 |
+
if what == NOTIFICATION_PREDELETE:
|
26 |
+
inferencer.FreeDisposables()
|
27 |
+
inferencer.free()
|
addons/godot_rl_agents/plugin.cfg
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[plugin]
|
2 |
+
|
3 |
+
name="GodotRLAgents"
|
4 |
+
description="Custom nodes for the godot rl agents toolkit "
|
5 |
+
author="Edward Beeching"
|
6 |
+
version="0.1"
|
7 |
+
script="godot_rl_agents.gd"
|
addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
7 |
+
|
8 |
+
|
9 |
+
|
10 |
+
func _physics_process(delta: float) -> void:
|
11 |
+
print(\"step start\")
|
12 |
+
|
13 |
+
"
|
14 |
+
|
15 |
+
[sub_resource type="GDScript" id="1"]
|
16 |
+
script/source = "extends RayCast2D
|
17 |
+
|
18 |
+
var steps = 1
|
19 |
+
|
20 |
+
func _physics_process(delta: float) -> void:
|
21 |
+
print(\"processing raycast\")
|
22 |
+
steps += 1
|
23 |
+
if steps % 2:
|
24 |
+
force_raycast_update()
|
25 |
+
|
26 |
+
print(is_colliding())
|
27 |
+
"
|
28 |
+
|
29 |
+
[sub_resource type="CircleShape2D" id="3"]
|
30 |
+
|
31 |
+
[node name="ExampleRaycastSensor2D" type="Node2D"]
|
32 |
+
script = SubResource("2")
|
33 |
+
|
34 |
+
[node name="ExampleAgent" type="Node2D" parent="."]
|
35 |
+
position = Vector2(573, 314)
|
36 |
+
rotation = 0.286234
|
37 |
+
|
38 |
+
[node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"]
|
39 |
+
script = ExtResource("1")
|
40 |
+
|
41 |
+
[node name="TestRayCast2D" type="RayCast2D" parent="."]
|
42 |
+
script = SubResource("1")
|
43 |
+
|
44 |
+
[node name="StaticBody2D" type="StaticBody2D" parent="."]
|
45 |
+
position = Vector2(1, 52)
|
46 |
+
|
47 |
+
[node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"]
|
48 |
+
shape = SubResource("3")
|
addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd
ADDED
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor2D
|
3 |
+
class_name GridSensor2D
|
4 |
+
|
5 |
+
@export var debug_view := false:
|
6 |
+
get:
|
7 |
+
return debug_view
|
8 |
+
set(value):
|
9 |
+
debug_view = value
|
10 |
+
_update()
|
11 |
+
|
12 |
+
@export_flags_2d_physics var detection_mask := 0:
|
13 |
+
get:
|
14 |
+
return detection_mask
|
15 |
+
set(value):
|
16 |
+
detection_mask = value
|
17 |
+
_update()
|
18 |
+
|
19 |
+
@export var collide_with_areas := false:
|
20 |
+
get:
|
21 |
+
return collide_with_areas
|
22 |
+
set(value):
|
23 |
+
collide_with_areas = value
|
24 |
+
_update()
|
25 |
+
|
26 |
+
@export var collide_with_bodies := true:
|
27 |
+
get:
|
28 |
+
return collide_with_bodies
|
29 |
+
set(value):
|
30 |
+
collide_with_bodies = value
|
31 |
+
_update()
|
32 |
+
|
33 |
+
@export_range(1, 200, 0.1) var cell_width := 20.0:
|
34 |
+
get:
|
35 |
+
return cell_width
|
36 |
+
set(value):
|
37 |
+
cell_width = value
|
38 |
+
_update()
|
39 |
+
|
40 |
+
@export_range(1, 200, 0.1) var cell_height := 20.0:
|
41 |
+
get:
|
42 |
+
return cell_height
|
43 |
+
set(value):
|
44 |
+
cell_height = value
|
45 |
+
_update()
|
46 |
+
|
47 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
|
48 |
+
get:
|
49 |
+
return grid_size_x
|
50 |
+
set(value):
|
51 |
+
grid_size_x = value
|
52 |
+
_update()
|
53 |
+
|
54 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
|
55 |
+
get:
|
56 |
+
return grid_size_y
|
57 |
+
set(value):
|
58 |
+
grid_size_y = value
|
59 |
+
_update()
|
60 |
+
|
61 |
+
var _obs_buffer: PackedFloat64Array
|
62 |
+
var _rectangle_shape: RectangleShape2D
|
63 |
+
var _collision_mapping: Dictionary
|
64 |
+
var _n_layers_per_cell: int
|
65 |
+
|
66 |
+
var _highlighted_cell_color: Color
|
67 |
+
var _standard_cell_color: Color
|
68 |
+
|
69 |
+
|
70 |
+
func get_observation():
|
71 |
+
return _obs_buffer
|
72 |
+
|
73 |
+
|
74 |
+
func _update():
|
75 |
+
if Engine.is_editor_hint():
|
76 |
+
if is_node_ready():
|
77 |
+
_spawn_nodes()
|
78 |
+
|
79 |
+
|
80 |
+
func _ready() -> void:
|
81 |
+
_set_colors()
|
82 |
+
|
83 |
+
if Engine.is_editor_hint():
|
84 |
+
if get_child_count() == 0:
|
85 |
+
_spawn_nodes()
|
86 |
+
else:
|
87 |
+
_spawn_nodes()
|
88 |
+
|
89 |
+
|
90 |
+
func _set_colors() -> void:
|
91 |
+
_standard_cell_color = Color(100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
|
92 |
+
_highlighted_cell_color = Color(255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
|
93 |
+
|
94 |
+
|
95 |
+
func _get_collision_mapping() -> Dictionary:
|
96 |
+
# defines which layer is mapped to which cell obs index
|
97 |
+
var total_bits = 0
|
98 |
+
var collision_mapping = {}
|
99 |
+
for i in 32:
|
100 |
+
var bit_mask = 2 ** i
|
101 |
+
if (detection_mask & bit_mask) > 0:
|
102 |
+
collision_mapping[i] = total_bits
|
103 |
+
total_bits += 1
|
104 |
+
|
105 |
+
return collision_mapping
|
106 |
+
|
107 |
+
|
108 |
+
func _spawn_nodes():
|
109 |
+
for cell in get_children():
|
110 |
+
cell.name = "_%s" % cell.name # Otherwise naming below will fail
|
111 |
+
cell.queue_free()
|
112 |
+
|
113 |
+
_collision_mapping = _get_collision_mapping()
|
114 |
+
#prints("collision_mapping", _collision_mapping, len(_collision_mapping))
|
115 |
+
# allocate memory for the observations
|
116 |
+
_n_layers_per_cell = len(_collision_mapping)
|
117 |
+
_obs_buffer = PackedFloat64Array()
|
118 |
+
_obs_buffer.resize(grid_size_x * grid_size_y * _n_layers_per_cell)
|
119 |
+
_obs_buffer.fill(0)
|
120 |
+
#prints(len(_obs_buffer), _obs_buffer )
|
121 |
+
|
122 |
+
_rectangle_shape = RectangleShape2D.new()
|
123 |
+
_rectangle_shape.set_size(Vector2(cell_width, cell_height))
|
124 |
+
|
125 |
+
var shift := Vector2(
|
126 |
+
-(grid_size_x / 2) * cell_width,
|
127 |
+
-(grid_size_y / 2) * cell_height,
|
128 |
+
)
|
129 |
+
|
130 |
+
for i in grid_size_x:
|
131 |
+
for j in grid_size_y:
|
132 |
+
var cell_position = Vector2(i * cell_width, j * cell_height) + shift
|
133 |
+
_create_cell(i, j, cell_position)
|
134 |
+
|
135 |
+
|
136 |
+
func _create_cell(i: int, j: int, position: Vector2):
|
137 |
+
var cell := Area2D.new()
|
138 |
+
cell.position = position
|
139 |
+
cell.name = "GridCell %s %s" % [i, j]
|
140 |
+
cell.modulate = _standard_cell_color
|
141 |
+
|
142 |
+
if collide_with_areas:
|
143 |
+
cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
|
144 |
+
cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
|
145 |
+
|
146 |
+
if collide_with_bodies:
|
147 |
+
cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
|
148 |
+
cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
|
149 |
+
|
150 |
+
cell.collision_layer = 0
|
151 |
+
cell.collision_mask = detection_mask
|
152 |
+
cell.monitorable = true
|
153 |
+
add_child(cell)
|
154 |
+
cell.set_owner(get_tree().edited_scene_root)
|
155 |
+
|
156 |
+
var col_shape := CollisionShape2D.new()
|
157 |
+
col_shape.shape = _rectangle_shape
|
158 |
+
col_shape.name = "CollisionShape2D"
|
159 |
+
cell.add_child(col_shape)
|
160 |
+
col_shape.set_owner(get_tree().edited_scene_root)
|
161 |
+
|
162 |
+
if debug_view:
|
163 |
+
var quad = MeshInstance2D.new()
|
164 |
+
quad.name = "MeshInstance2D"
|
165 |
+
var quad_mesh = QuadMesh.new()
|
166 |
+
|
167 |
+
quad_mesh.set_size(Vector2(cell_width, cell_height))
|
168 |
+
|
169 |
+
quad.mesh = quad_mesh
|
170 |
+
cell.add_child(quad)
|
171 |
+
quad.set_owner(get_tree().edited_scene_root)
|
172 |
+
|
173 |
+
|
174 |
+
func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
|
175 |
+
for key in _collision_mapping:
|
176 |
+
var bit_mask = 2 ** key
|
177 |
+
if (collision_layer & bit_mask) > 0:
|
178 |
+
var collison_map_index = _collision_mapping[key]
|
179 |
+
|
180 |
+
var obs_index = (
|
181 |
+
(cell_i * grid_size_x * _n_layers_per_cell)
|
182 |
+
+ (cell_j * _n_layers_per_cell)
|
183 |
+
+ collison_map_index
|
184 |
+
)
|
185 |
+
#prints(obs_index, cell_i, cell_j)
|
186 |
+
if entered:
|
187 |
+
_obs_buffer[obs_index] += 1
|
188 |
+
else:
|
189 |
+
_obs_buffer[obs_index] -= 1
|
190 |
+
|
191 |
+
|
192 |
+
func _toggle_cell(cell_i: int, cell_j: int):
|
193 |
+
var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
|
194 |
+
|
195 |
+
if cell == null:
|
196 |
+
print("cell not found, returning")
|
197 |
+
|
198 |
+
var n_hits = 0
|
199 |
+
var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
|
200 |
+
for i in _n_layers_per_cell:
|
201 |
+
n_hits += _obs_buffer[start_index + i]
|
202 |
+
|
203 |
+
if n_hits > 0:
|
204 |
+
cell.modulate = _highlighted_cell_color
|
205 |
+
else:
|
206 |
+
cell.modulate = _standard_cell_color
|
207 |
+
|
208 |
+
|
209 |
+
func _on_cell_area_entered(area: Area2D, cell_i: int, cell_j: int):
|
210 |
+
#prints("_on_cell_area_entered", cell_i, cell_j)
|
211 |
+
_update_obs(cell_i, cell_j, area.collision_layer, true)
|
212 |
+
if debug_view:
|
213 |
+
_toggle_cell(cell_i, cell_j)
|
214 |
+
#print(_obs_buffer)
|
215 |
+
|
216 |
+
|
217 |
+
func _on_cell_area_exited(area: Area2D, cell_i: int, cell_j: int):
|
218 |
+
#prints("_on_cell_area_exited", cell_i, cell_j)
|
219 |
+
_update_obs(cell_i, cell_j, area.collision_layer, false)
|
220 |
+
if debug_view:
|
221 |
+
_toggle_cell(cell_i, cell_j)
|
222 |
+
|
223 |
+
|
224 |
+
func _on_cell_body_entered(body: Node2D, cell_i: int, cell_j: int):
|
225 |
+
#prints("_on_cell_body_entered", cell_i, cell_j)
|
226 |
+
_update_obs(cell_i, cell_j, body.collision_layer, true)
|
227 |
+
if debug_view:
|
228 |
+
_toggle_cell(cell_i, cell_j)
|
229 |
+
|
230 |
+
|
231 |
+
func _on_cell_body_exited(body: Node2D, cell_i: int, cell_j: int):
|
232 |
+
#prints("_on_cell_body_exited", cell_i, cell_j)
|
233 |
+
_update_obs(cell_i, cell_j, body.collision_layer, false)
|
234 |
+
if debug_view:
|
235 |
+
_toggle_cell(cell_i, cell_j)
|
addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node2D
|
2 |
+
class_name ISensor2D
|
3 |
+
|
4 |
+
var _obs: Array = []
|
5 |
+
var _active := false
|
6 |
+
|
7 |
+
|
8 |
+
func get_observation():
|
9 |
+
pass
|
10 |
+
|
11 |
+
|
12 |
+
func activate():
|
13 |
+
_active = true
|
14 |
+
|
15 |
+
|
16 |
+
func deactivate():
|
17 |
+
_active = false
|
18 |
+
|
19 |
+
|
20 |
+
func _update_observation():
|
21 |
+
pass
|
22 |
+
|
23 |
+
|
24 |
+
func reset():
|
25 |
+
pass
|
addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd
ADDED
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor2D
|
3 |
+
class_name RaycastSensor2D
|
4 |
+
|
5 |
+
@export_flags_2d_physics var collision_mask := 1:
|
6 |
+
get:
|
7 |
+
return collision_mask
|
8 |
+
set(value):
|
9 |
+
collision_mask = value
|
10 |
+
_update()
|
11 |
+
|
12 |
+
@export var collide_with_areas := false:
|
13 |
+
get:
|
14 |
+
return collide_with_areas
|
15 |
+
set(value):
|
16 |
+
collide_with_areas = value
|
17 |
+
_update()
|
18 |
+
|
19 |
+
@export var collide_with_bodies := true:
|
20 |
+
get:
|
21 |
+
return collide_with_bodies
|
22 |
+
set(value):
|
23 |
+
collide_with_bodies = value
|
24 |
+
_update()
|
25 |
+
|
26 |
+
@export var n_rays := 16.0:
|
27 |
+
get:
|
28 |
+
return n_rays
|
29 |
+
set(value):
|
30 |
+
n_rays = value
|
31 |
+
_update()
|
32 |
+
|
33 |
+
@export_range(5, 3000, 5.0) var ray_length := 200:
|
34 |
+
get:
|
35 |
+
return ray_length
|
36 |
+
set(value):
|
37 |
+
ray_length = value
|
38 |
+
_update()
|
39 |
+
@export_range(5, 360, 5.0) var cone_width := 360.0:
|
40 |
+
get:
|
41 |
+
return cone_width
|
42 |
+
set(value):
|
43 |
+
cone_width = value
|
44 |
+
_update()
|
45 |
+
|
46 |
+
@export var debug_draw := true:
|
47 |
+
get:
|
48 |
+
return debug_draw
|
49 |
+
set(value):
|
50 |
+
debug_draw = value
|
51 |
+
_update()
|
52 |
+
|
53 |
+
var _angles = []
|
54 |
+
var rays := []
|
55 |
+
|
56 |
+
|
57 |
+
func _update():
|
58 |
+
if Engine.is_editor_hint():
|
59 |
+
if debug_draw:
|
60 |
+
_spawn_nodes()
|
61 |
+
else:
|
62 |
+
for ray in get_children():
|
63 |
+
if ray is RayCast2D:
|
64 |
+
remove_child(ray)
|
65 |
+
|
66 |
+
|
67 |
+
func _ready() -> void:
|
68 |
+
_spawn_nodes()
|
69 |
+
|
70 |
+
|
71 |
+
func _spawn_nodes():
|
72 |
+
for ray in rays:
|
73 |
+
ray.queue_free()
|
74 |
+
rays = []
|
75 |
+
|
76 |
+
_angles = []
|
77 |
+
var step = cone_width / (n_rays)
|
78 |
+
var start = step / 2 - cone_width / 2
|
79 |
+
|
80 |
+
for i in n_rays:
|
81 |
+
var angle = start + i * step
|
82 |
+
var ray = RayCast2D.new()
|
83 |
+
ray.set_target_position(
|
84 |
+
Vector2(ray_length * cos(deg_to_rad(angle)), ray_length * sin(deg_to_rad(angle)))
|
85 |
+
)
|
86 |
+
ray.set_name("node_" + str(i))
|
87 |
+
ray.enabled = false
|
88 |
+
ray.collide_with_areas = collide_with_areas
|
89 |
+
ray.collide_with_bodies = collide_with_bodies
|
90 |
+
ray.collision_mask = collision_mask
|
91 |
+
add_child(ray)
|
92 |
+
rays.append(ray)
|
93 |
+
|
94 |
+
_angles.append(start + i * step)
|
95 |
+
|
96 |
+
|
97 |
+
func get_observation() -> Array:
|
98 |
+
return self.calculate_raycasts()
|
99 |
+
|
100 |
+
|
101 |
+
func calculate_raycasts() -> Array:
|
102 |
+
var result = []
|
103 |
+
for ray in rays:
|
104 |
+
ray.enabled = true
|
105 |
+
ray.force_raycast_update()
|
106 |
+
var distance = _get_raycast_distance(ray)
|
107 |
+
result.append(distance)
|
108 |
+
ray.enabled = false
|
109 |
+
return result
|
110 |
+
|
111 |
+
|
112 |
+
func _get_raycast_distance(ray: RayCast2D) -> float:
|
113 |
+
if !ray.is_colliding():
|
114 |
+
return 0.0
|
115 |
+
|
116 |
+
var distance = (global_position - ray.get_collision_point()).length()
|
117 |
+
distance = clamp(distance, 0.0, ray_length)
|
118 |
+
return (ray_length - distance) / ray_length
|
addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
|
4 |
+
|
5 |
+
[node name="RaycastSensor2D" type="Node2D"]
|
6 |
+
script = ExtResource("1")
|
7 |
+
n_rays = 17.0
|
addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene format=3 uid="uid://biu787qh4woik"]
|
2 |
+
|
3 |
+
[node name="ExampleRaycastSensor3D" type="Node3D"]
|
4 |
+
|
5 |
+
[node name="Camera3D" type="Camera3D" parent="."]
|
6 |
+
transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146)
|
addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd
ADDED
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor3D
|
3 |
+
class_name GridSensor3D
|
4 |
+
|
5 |
+
@export var debug_view := false:
|
6 |
+
get:
|
7 |
+
return debug_view
|
8 |
+
set(value):
|
9 |
+
debug_view = value
|
10 |
+
_update()
|
11 |
+
|
12 |
+
@export_flags_3d_physics var detection_mask := 0:
|
13 |
+
get:
|
14 |
+
return detection_mask
|
15 |
+
set(value):
|
16 |
+
detection_mask = value
|
17 |
+
_update()
|
18 |
+
|
19 |
+
@export var collide_with_areas := false:
|
20 |
+
get:
|
21 |
+
return collide_with_areas
|
22 |
+
set(value):
|
23 |
+
collide_with_areas = value
|
24 |
+
_update()
|
25 |
+
|
26 |
+
@export var collide_with_bodies := false:
|
27 |
+
# NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
|
28 |
+
get:
|
29 |
+
return collide_with_bodies
|
30 |
+
set(value):
|
31 |
+
collide_with_bodies = value
|
32 |
+
_update()
|
33 |
+
|
34 |
+
@export_range(0.1, 2, 0.1) var cell_width := 1.0:
|
35 |
+
get:
|
36 |
+
return cell_width
|
37 |
+
set(value):
|
38 |
+
cell_width = value
|
39 |
+
_update()
|
40 |
+
|
41 |
+
@export_range(0.1, 2, 0.1) var cell_height := 1.0:
|
42 |
+
get:
|
43 |
+
return cell_height
|
44 |
+
set(value):
|
45 |
+
cell_height = value
|
46 |
+
_update()
|
47 |
+
|
48 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
|
49 |
+
get:
|
50 |
+
return grid_size_x
|
51 |
+
set(value):
|
52 |
+
grid_size_x = value
|
53 |
+
_update()
|
54 |
+
|
55 |
+
@export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
|
56 |
+
get:
|
57 |
+
return grid_size_z
|
58 |
+
set(value):
|
59 |
+
grid_size_z = value
|
60 |
+
_update()
|
61 |
+
|
62 |
+
var _obs_buffer: PackedFloat64Array
|
63 |
+
var _box_shape: BoxShape3D
|
64 |
+
var _collision_mapping: Dictionary
|
65 |
+
var _n_layers_per_cell: int
|
66 |
+
|
67 |
+
var _highlighted_box_material: StandardMaterial3D
|
68 |
+
var _standard_box_material: StandardMaterial3D
|
69 |
+
|
70 |
+
|
71 |
+
func get_observation():
|
72 |
+
return _obs_buffer
|
73 |
+
|
74 |
+
|
75 |
+
func reset():
|
76 |
+
_obs_buffer.fill(0)
|
77 |
+
|
78 |
+
|
79 |
+
func _update():
|
80 |
+
if Engine.is_editor_hint():
|
81 |
+
if is_node_ready():
|
82 |
+
_spawn_nodes()
|
83 |
+
|
84 |
+
|
85 |
+
func _ready() -> void:
|
86 |
+
_make_materials()
|
87 |
+
|
88 |
+
if Engine.is_editor_hint():
|
89 |
+
if get_child_count() == 0:
|
90 |
+
_spawn_nodes()
|
91 |
+
else:
|
92 |
+
_spawn_nodes()
|
93 |
+
|
94 |
+
|
95 |
+
func _make_materials() -> void:
|
96 |
+
if _highlighted_box_material != null and _standard_box_material != null:
|
97 |
+
return
|
98 |
+
|
99 |
+
_standard_box_material = StandardMaterial3D.new()
|
100 |
+
_standard_box_material.set_transparency(1) # ALPHA
|
101 |
+
_standard_box_material.albedo_color = Color(
|
102 |
+
100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
|
103 |
+
)
|
104 |
+
|
105 |
+
_highlighted_box_material = StandardMaterial3D.new()
|
106 |
+
_highlighted_box_material.set_transparency(1) # ALPHA
|
107 |
+
_highlighted_box_material.albedo_color = Color(
|
108 |
+
255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
|
109 |
+
)
|
110 |
+
|
111 |
+
|
112 |
+
func _get_collision_mapping() -> Dictionary:
|
113 |
+
# defines which layer is mapped to which cell obs index
|
114 |
+
var total_bits = 0
|
115 |
+
var collision_mapping = {}
|
116 |
+
for i in 32:
|
117 |
+
var bit_mask = 2 ** i
|
118 |
+
if (detection_mask & bit_mask) > 0:
|
119 |
+
collision_mapping[i] = total_bits
|
120 |
+
total_bits += 1
|
121 |
+
|
122 |
+
return collision_mapping
|
123 |
+
|
124 |
+
|
125 |
+
func _spawn_nodes():
|
126 |
+
for cell in get_children():
|
127 |
+
cell.name = "_%s" % cell.name # Otherwise naming below will fail
|
128 |
+
cell.queue_free()
|
129 |
+
|
130 |
+
_collision_mapping = _get_collision_mapping()
|
131 |
+
#prints("collision_mapping", _collision_mapping, len(_collision_mapping))
|
132 |
+
# allocate memory for the observations
|
133 |
+
_n_layers_per_cell = len(_collision_mapping)
|
134 |
+
_obs_buffer = PackedFloat64Array()
|
135 |
+
_obs_buffer.resize(grid_size_x * grid_size_z * _n_layers_per_cell)
|
136 |
+
_obs_buffer.fill(0)
|
137 |
+
#prints(len(_obs_buffer), _obs_buffer )
|
138 |
+
|
139 |
+
_box_shape = BoxShape3D.new()
|
140 |
+
_box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
|
141 |
+
|
142 |
+
var shift := Vector3(
|
143 |
+
-(grid_size_x / 2) * cell_width,
|
144 |
+
0,
|
145 |
+
-(grid_size_z / 2) * cell_width,
|
146 |
+
)
|
147 |
+
|
148 |
+
for i in grid_size_x:
|
149 |
+
for j in grid_size_z:
|
150 |
+
var cell_position = Vector3(i * cell_width, 0.0, j * cell_width) + shift
|
151 |
+
_create_cell(i, j, cell_position)
|
152 |
+
|
153 |
+
|
154 |
+
func _create_cell(i: int, j: int, position: Vector3):
|
155 |
+
var cell := Area3D.new()
|
156 |
+
cell.position = position
|
157 |
+
cell.name = "GridCell %s %s" % [i, j]
|
158 |
+
|
159 |
+
if collide_with_areas:
|
160 |
+
cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
|
161 |
+
cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
|
162 |
+
|
163 |
+
if collide_with_bodies:
|
164 |
+
cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
|
165 |
+
cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
|
166 |
+
|
167 |
+
# cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
|
168 |
+
# cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
|
169 |
+
|
170 |
+
cell.collision_layer = 0
|
171 |
+
cell.collision_mask = detection_mask
|
172 |
+
cell.monitorable = true
|
173 |
+
cell.input_ray_pickable = false
|
174 |
+
add_child(cell)
|
175 |
+
cell.set_owner(get_tree().edited_scene_root)
|
176 |
+
|
177 |
+
var col_shape := CollisionShape3D.new()
|
178 |
+
col_shape.shape = _box_shape
|
179 |
+
col_shape.name = "CollisionShape3D"
|
180 |
+
cell.add_child(col_shape)
|
181 |
+
col_shape.set_owner(get_tree().edited_scene_root)
|
182 |
+
|
183 |
+
if debug_view:
|
184 |
+
var box = MeshInstance3D.new()
|
185 |
+
box.name = "MeshInstance3D"
|
186 |
+
var box_mesh = BoxMesh.new()
|
187 |
+
|
188 |
+
box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
|
189 |
+
box_mesh.material = _standard_box_material
|
190 |
+
|
191 |
+
box.mesh = box_mesh
|
192 |
+
cell.add_child(box)
|
193 |
+
box.set_owner(get_tree().edited_scene_root)
|
194 |
+
|
195 |
+
|
196 |
+
func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
|
197 |
+
for key in _collision_mapping:
|
198 |
+
var bit_mask = 2 ** key
|
199 |
+
if (collision_layer & bit_mask) > 0:
|
200 |
+
var collison_map_index = _collision_mapping[key]
|
201 |
+
|
202 |
+
var obs_index = (
|
203 |
+
(cell_i * grid_size_x * _n_layers_per_cell)
|
204 |
+
+ (cell_j * _n_layers_per_cell)
|
205 |
+
+ collison_map_index
|
206 |
+
)
|
207 |
+
#prints(obs_index, cell_i, cell_j)
|
208 |
+
if entered:
|
209 |
+
_obs_buffer[obs_index] += 1
|
210 |
+
else:
|
211 |
+
_obs_buffer[obs_index] -= 1
|
212 |
+
|
213 |
+
|
214 |
+
func _toggle_cell(cell_i: int, cell_j: int):
|
215 |
+
var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
|
216 |
+
|
217 |
+
if cell == null:
|
218 |
+
print("cell not found, returning")
|
219 |
+
|
220 |
+
var n_hits = 0
|
221 |
+
var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
|
222 |
+
for i in _n_layers_per_cell:
|
223 |
+
n_hits += _obs_buffer[start_index + i]
|
224 |
+
|
225 |
+
var cell_mesh = cell.get_node_or_null("MeshInstance3D")
|
226 |
+
if n_hits > 0:
|
227 |
+
cell_mesh.mesh.material = _highlighted_box_material
|
228 |
+
else:
|
229 |
+
cell_mesh.mesh.material = _standard_box_material
|
230 |
+
|
231 |
+
|
232 |
+
func _on_cell_area_entered(area: Area3D, cell_i: int, cell_j: int):
|
233 |
+
#prints("_on_cell_area_entered", cell_i, cell_j)
|
234 |
+
_update_obs(cell_i, cell_j, area.collision_layer, true)
|
235 |
+
if debug_view:
|
236 |
+
_toggle_cell(cell_i, cell_j)
|
237 |
+
#print(_obs_buffer)
|
238 |
+
|
239 |
+
|
240 |
+
func _on_cell_area_exited(area: Area3D, cell_i: int, cell_j: int):
|
241 |
+
#prints("_on_cell_area_exited", cell_i, cell_j)
|
242 |
+
_update_obs(cell_i, cell_j, area.collision_layer, false)
|
243 |
+
if debug_view:
|
244 |
+
_toggle_cell(cell_i, cell_j)
|
245 |
+
|
246 |
+
|
247 |
+
func _on_cell_body_entered(body: Node3D, cell_i: int, cell_j: int):
|
248 |
+
#prints("_on_cell_body_entered", cell_i, cell_j)
|
249 |
+
_update_obs(cell_i, cell_j, body.collision_layer, true)
|
250 |
+
if debug_view:
|
251 |
+
_toggle_cell(cell_i, cell_j)
|
252 |
+
|
253 |
+
|
254 |
+
func _on_cell_body_exited(body: Node3D, cell_i: int, cell_j: int):
|
255 |
+
#prints("_on_cell_body_exited", cell_i, cell_j)
|
256 |
+
_update_obs(cell_i, cell_j, body.collision_layer, false)
|
257 |
+
if debug_view:
|
258 |
+
_toggle_cell(cell_i, cell_j)
|
addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name ISensor3D
|
3 |
+
|
4 |
+
var _obs: Array = []
|
5 |
+
var _active := false
|
6 |
+
|
7 |
+
|
8 |
+
func get_observation():
|
9 |
+
pass
|
10 |
+
|
11 |
+
|
12 |
+
func activate():
|
13 |
+
_active = true
|
14 |
+
|
15 |
+
|
16 |
+
func deactivate():
|
17 |
+
_active = false
|
18 |
+
|
19 |
+
|
20 |
+
func _update_observation():
|
21 |
+
pass
|
22 |
+
|
23 |
+
|
24 |
+
func reset():
|
25 |
+
pass
|
addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node3D
|
2 |
+
class_name RGBCameraSensor3D
|
3 |
+
var camera_pixels = null
|
4 |
+
|
5 |
+
@onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D
|
6 |
+
@onready var sub_viewport := $SubViewport as SubViewport
|
7 |
+
|
8 |
+
|
9 |
+
func get_camera_pixel_encoding():
|
10 |
+
return camera_texture.get_texture().get_image().get_data().hex_encode()
|
11 |
+
|
12 |
+
|
13 |
+
func get_camera_shape() -> Array:
|
14 |
+
assert(
|
15 |
+
sub_viewport.size.x >= 36 and sub_viewport.size.y >= 36,
|
16 |
+
"SubViewport size must be 36x36 or larger."
|
17 |
+
)
|
18 |
+
if sub_viewport.transparent_bg:
|
19 |
+
return [4, sub_viewport.size.y, sub_viewport.size.x]
|
20 |
+
else:
|
21 |
+
return [3, sub_viewport.size.y, sub_viewport.size.x]
|
addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"]
|
4 |
+
|
5 |
+
[sub_resource type="ViewportTexture" id="1"]
|
6 |
+
viewport_path = NodePath("SubViewport")
|
7 |
+
|
8 |
+
[node name="RGBCameraSensor3D" type="Node3D"]
|
9 |
+
script = ExtResource("1")
|
10 |
+
|
11 |
+
[node name="RemoteTransform3D" type="RemoteTransform3D" parent="."]
|
12 |
+
remote_path = NodePath("../SubViewport/Camera3D")
|
13 |
+
|
14 |
+
[node name="SubViewport" type="SubViewport" parent="."]
|
15 |
+
size = Vector2i(32, 32)
|
16 |
+
render_target_update_mode = 3
|
17 |
+
|
18 |
+
[node name="Camera3D" type="Camera3D" parent="SubViewport"]
|
19 |
+
near = 0.5
|
20 |
+
|
21 |
+
[node name="Control" type="Control" parent="."]
|
22 |
+
layout_mode = 3
|
23 |
+
anchors_preset = 15
|
24 |
+
anchor_right = 1.0
|
25 |
+
anchor_bottom = 1.0
|
26 |
+
grow_horizontal = 2
|
27 |
+
grow_vertical = 2
|
28 |
+
|
29 |
+
[node name="TextureRect" type="ColorRect" parent="Control"]
|
30 |
+
layout_mode = 0
|
31 |
+
offset_left = 1096.0
|
32 |
+
offset_top = 534.0
|
33 |
+
offset_right = 1114.0
|
34 |
+
offset_bottom = 552.0
|
35 |
+
scale = Vector2(10, 10)
|
36 |
+
color = Color(0.00784314, 0.00784314, 0.00784314, 1)
|
37 |
+
|
38 |
+
[node name="CameraTexture" type="Sprite2D" parent="Control/TextureRect"]
|
39 |
+
texture = SubResource("1")
|
40 |
+
offset = Vector2(9, 9)
|
41 |
+
flip_v = true
|
addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd
ADDED
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
@tool
|
2 |
+
extends ISensor3D
|
3 |
+
class_name RayCastSensor3D
|
4 |
+
@export_flags_3d_physics var collision_mask = 1:
|
5 |
+
get:
|
6 |
+
return collision_mask
|
7 |
+
set(value):
|
8 |
+
collision_mask = value
|
9 |
+
_update()
|
10 |
+
@export_flags_3d_physics var boolean_class_mask = 1:
|
11 |
+
get:
|
12 |
+
return boolean_class_mask
|
13 |
+
set(value):
|
14 |
+
boolean_class_mask = value
|
15 |
+
_update()
|
16 |
+
|
17 |
+
@export var n_rays_width := 6.0:
|
18 |
+
get:
|
19 |
+
return n_rays_width
|
20 |
+
set(value):
|
21 |
+
n_rays_width = value
|
22 |
+
_update()
|
23 |
+
|
24 |
+
@export var n_rays_height := 6.0:
|
25 |
+
get:
|
26 |
+
return n_rays_height
|
27 |
+
set(value):
|
28 |
+
n_rays_height = value
|
29 |
+
_update()
|
30 |
+
|
31 |
+
@export var ray_length := 10.0:
|
32 |
+
get:
|
33 |
+
return ray_length
|
34 |
+
set(value):
|
35 |
+
ray_length = value
|
36 |
+
_update()
|
37 |
+
|
38 |
+
@export var cone_width := 60.0:
|
39 |
+
get:
|
40 |
+
return cone_width
|
41 |
+
set(value):
|
42 |
+
cone_width = value
|
43 |
+
_update()
|
44 |
+
|
45 |
+
@export var cone_height := 60.0:
|
46 |
+
get:
|
47 |
+
return cone_height
|
48 |
+
set(value):
|
49 |
+
cone_height = value
|
50 |
+
_update()
|
51 |
+
|
52 |
+
@export var collide_with_areas := false:
|
53 |
+
get:
|
54 |
+
return collide_with_areas
|
55 |
+
set(value):
|
56 |
+
collide_with_areas = value
|
57 |
+
_update()
|
58 |
+
|
59 |
+
@export var collide_with_bodies := true:
|
60 |
+
get:
|
61 |
+
return collide_with_bodies
|
62 |
+
set(value):
|
63 |
+
collide_with_bodies = value
|
64 |
+
_update()
|
65 |
+
|
66 |
+
@export var class_sensor := false
|
67 |
+
|
68 |
+
var rays := []
|
69 |
+
var geo = null
|
70 |
+
|
71 |
+
|
72 |
+
func _update():
|
73 |
+
if Engine.is_editor_hint():
|
74 |
+
if is_node_ready():
|
75 |
+
_spawn_nodes()
|
76 |
+
|
77 |
+
|
78 |
+
func _ready() -> void:
|
79 |
+
if Engine.is_editor_hint():
|
80 |
+
if get_child_count() == 0:
|
81 |
+
_spawn_nodes()
|
82 |
+
else:
|
83 |
+
_spawn_nodes()
|
84 |
+
|
85 |
+
|
86 |
+
func _spawn_nodes():
|
87 |
+
print("spawning nodes")
|
88 |
+
for ray in get_children():
|
89 |
+
ray.queue_free()
|
90 |
+
if geo:
|
91 |
+
geo.clear()
|
92 |
+
#$Lines.remove_points()
|
93 |
+
rays = []
|
94 |
+
|
95 |
+
var horizontal_step = cone_width / (n_rays_width)
|
96 |
+
var vertical_step = cone_height / (n_rays_height)
|
97 |
+
|
98 |
+
var horizontal_start = horizontal_step / 2 - cone_width / 2
|
99 |
+
var vertical_start = vertical_step / 2 - cone_height / 2
|
100 |
+
|
101 |
+
var points = []
|
102 |
+
|
103 |
+
for i in n_rays_width:
|
104 |
+
for j in n_rays_height:
|
105 |
+
var angle_w = horizontal_start + i * horizontal_step
|
106 |
+
var angle_h = vertical_start + j * vertical_step
|
107 |
+
#angle_h = 0.0
|
108 |
+
var ray = RayCast3D.new()
|
109 |
+
var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
|
110 |
+
ray.set_target_position(cast_to)
|
111 |
+
|
112 |
+
points.append(cast_to)
|
113 |
+
|
114 |
+
ray.set_name("node_" + str(i) + " " + str(j))
|
115 |
+
ray.enabled = true
|
116 |
+
ray.collide_with_bodies = collide_with_bodies
|
117 |
+
ray.collide_with_areas = collide_with_areas
|
118 |
+
ray.collision_mask = collision_mask
|
119 |
+
add_child(ray)
|
120 |
+
ray.set_owner(get_tree().edited_scene_root)
|
121 |
+
rays.append(ray)
|
122 |
+
ray.force_raycast_update()
|
123 |
+
|
124 |
+
|
125 |
+
# if Engine.editor_hint:
|
126 |
+
# _create_debug_lines(points)
|
127 |
+
|
128 |
+
|
129 |
+
func _create_debug_lines(points):
|
130 |
+
if not geo:
|
131 |
+
geo = ImmediateMesh.new()
|
132 |
+
add_child(geo)
|
133 |
+
|
134 |
+
geo.clear()
|
135 |
+
geo.begin(Mesh.PRIMITIVE_LINES)
|
136 |
+
for point in points:
|
137 |
+
geo.set_color(Color.AQUA)
|
138 |
+
geo.add_vertex(Vector3.ZERO)
|
139 |
+
geo.add_vertex(point)
|
140 |
+
geo.end()
|
141 |
+
|
142 |
+
|
143 |
+
func display():
|
144 |
+
if geo:
|
145 |
+
geo.display()
|
146 |
+
|
147 |
+
|
148 |
+
func to_spherical_coords(r, inc, azimuth) -> Vector3:
|
149 |
+
return Vector3(
|
150 |
+
r * sin(deg_to_rad(inc)) * cos(deg_to_rad(azimuth)),
|
151 |
+
r * sin(deg_to_rad(azimuth)),
|
152 |
+
r * cos(deg_to_rad(inc)) * cos(deg_to_rad(azimuth))
|
153 |
+
)
|
154 |
+
|
155 |
+
|
156 |
+
func get_observation() -> Array:
|
157 |
+
return self.calculate_raycasts()
|
158 |
+
|
159 |
+
|
160 |
+
func calculate_raycasts() -> Array:
|
161 |
+
var result = []
|
162 |
+
for ray in rays:
|
163 |
+
ray.set_enabled(true)
|
164 |
+
ray.force_raycast_update()
|
165 |
+
var distance = _get_raycast_distance(ray)
|
166 |
+
|
167 |
+
result.append(distance)
|
168 |
+
if class_sensor:
|
169 |
+
var hit_class: float = 0
|
170 |
+
if ray.get_collider():
|
171 |
+
var hit_collision_layer = ray.get_collider().collision_layer
|
172 |
+
hit_collision_layer = hit_collision_layer & collision_mask
|
173 |
+
hit_class = (hit_collision_layer & boolean_class_mask) > 0
|
174 |
+
result.append(float(hit_class))
|
175 |
+
ray.set_enabled(false)
|
176 |
+
return result
|
177 |
+
|
178 |
+
|
179 |
+
func _get_raycast_distance(ray: RayCast3D) -> float:
|
180 |
+
if !ray.is_colliding():
|
181 |
+
return 0.0
|
182 |
+
|
183 |
+
var distance = (global_transform.origin - ray.get_collision_point()).length()
|
184 |
+
distance = clamp(distance, 0.0, ray_length)
|
185 |
+
return (ray_length - distance) / ray_length
|
addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"]
|
2 |
+
|
3 |
+
[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"]
|
4 |
+
|
5 |
+
[node name="RaycastSensor3D" type="Node3D"]
|
6 |
+
script = ExtResource("1")
|
7 |
+
n_rays_width = 4.0
|
8 |
+
n_rays_height = 2.0
|
9 |
+
ray_length = 11.0
|
10 |
+
|
11 |
+
[node name="node_1 0" type="RayCast3D" parent="."]
|
12 |
+
target_position = Vector3(-1.38686, -2.84701, 10.5343)
|
13 |
+
|
14 |
+
[node name="node_1 1" type="RayCast3D" parent="."]
|
15 |
+
target_position = Vector3(-1.38686, 2.84701, 10.5343)
|
16 |
+
|
17 |
+
[node name="node_2 0" type="RayCast3D" parent="."]
|
18 |
+
target_position = Vector3(1.38686, -2.84701, 10.5343)
|
19 |
+
|
20 |
+
[node name="node_2 1" type="RayCast3D" parent="."]
|
21 |
+
target_position = Vector3(1.38686, 2.84701, 10.5343)
|
22 |
+
|
23 |
+
[node name="node_3 0" type="RayCast3D" parent="."]
|
24 |
+
target_position = Vector3(4.06608, -2.84701, 9.81639)
|
25 |
+
|
26 |
+
[node name="node_3 1" type="RayCast3D" parent="."]
|
27 |
+
target_position = Vector3(4.06608, 2.84701, 9.81639)
|
addons/godot_rl_agents/sync.gd
ADDED
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
extends Node
|
2 |
+
|
3 |
+
# --fixed-fps 2000 --disable-render-loop
|
4 |
+
|
5 |
+
enum ControlModes { HUMAN, TRAINING, ONNX_INFERENCE }
|
6 |
+
@export var control_mode: ControlModes = ControlModes.TRAINING
|
7 |
+
@export_range(1, 10, 1, "or_greater") var action_repeat := 8
|
8 |
+
@export_range(0, 10, 0.1, "or_greater") var speed_up := 1.0
|
9 |
+
@export var onnx_model_path := ""
|
10 |
+
|
11 |
+
# Onnx model stored for each requested path
|
12 |
+
var onnx_models: Dictionary
|
13 |
+
|
14 |
+
@onready var start_time = Time.get_ticks_msec()
|
15 |
+
|
16 |
+
const MAJOR_VERSION := "0"
|
17 |
+
const MINOR_VERSION := "7"
|
18 |
+
const DEFAULT_PORT := "11008"
|
19 |
+
const DEFAULT_SEED := "1"
|
20 |
+
var stream: StreamPeerTCP = null
|
21 |
+
var connected = false
|
22 |
+
var message_center
|
23 |
+
var should_connect = true
|
24 |
+
|
25 |
+
var all_agents: Array
|
26 |
+
var agents_training: Array
|
27 |
+
var agents_inference: Array
|
28 |
+
var agents_heuristic: Array
|
29 |
+
|
30 |
+
## For recording expert demos
|
31 |
+
var agent_demo_record: Node
|
32 |
+
## Stores recorded trajectories
|
33 |
+
var demo_trajectories: Array
|
34 |
+
## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
|
35 |
+
var current_demo_trajectory: Array
|
36 |
+
|
37 |
+
var need_to_send_obs = false
|
38 |
+
var args = null
|
39 |
+
var initialized = false
|
40 |
+
var just_reset = false
|
41 |
+
var onnx_model = null
|
42 |
+
var n_action_steps = 0
|
43 |
+
|
44 |
+
var _action_space: Dictionary
|
45 |
+
var _action_space_inference: Array[Dictionary] = []
|
46 |
+
var _obs_space: Dictionary
|
47 |
+
|
48 |
+
|
49 |
+
# Called when the node enters the scene tree for the first time.
|
50 |
+
func _ready():
|
51 |
+
await get_tree().root.ready
|
52 |
+
get_tree().set_pause(true)
|
53 |
+
_initialize()
|
54 |
+
await get_tree().create_timer(1.0).timeout
|
55 |
+
get_tree().set_pause(false)
|
56 |
+
|
57 |
+
|
58 |
+
func _initialize():
|
59 |
+
_get_agents()
|
60 |
+
args = _get_args()
|
61 |
+
Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
|
62 |
+
Engine.time_scale = _get_speedup() * 1.0
|
63 |
+
prints(
|
64 |
+
"physics ticks",
|
65 |
+
Engine.physics_ticks_per_second,
|
66 |
+
Engine.time_scale,
|
67 |
+
_get_speedup(),
|
68 |
+
speed_up
|
69 |
+
)
|
70 |
+
|
71 |
+
_set_heuristic("human", all_agents)
|
72 |
+
|
73 |
+
_initialize_training_agents()
|
74 |
+
_initialize_inference_agents()
|
75 |
+
_initialize_demo_recording()
|
76 |
+
|
77 |
+
_set_seed()
|
78 |
+
_set_action_repeat()
|
79 |
+
initialized = true
|
80 |
+
|
81 |
+
|
82 |
+
func _initialize_training_agents():
|
83 |
+
if agents_training.size() > 0:
|
84 |
+
_obs_space = agents_training[0].get_obs_space()
|
85 |
+
_action_space = agents_training[0].get_action_space()
|
86 |
+
connected = connect_to_server()
|
87 |
+
if connected:
|
88 |
+
_set_heuristic("model", agents_training)
|
89 |
+
_handshake()
|
90 |
+
_send_env_info()
|
91 |
+
else:
|
92 |
+
push_warning(
|
93 |
+
"Couldn't connect to Python server, using human controls instead. ",
|
94 |
+
"Did you start the training server using e.g. `gdrl` from the console?"
|
95 |
+
)
|
96 |
+
|
97 |
+
|
98 |
+
func _initialize_inference_agents():
|
99 |
+
if agents_inference.size() > 0:
|
100 |
+
if control_mode == ControlModes.ONNX_INFERENCE:
|
101 |
+
assert(
|
102 |
+
FileAccess.file_exists(onnx_model_path),
|
103 |
+
"Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
|
104 |
+
)
|
105 |
+
onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
|
106 |
+
|
107 |
+
for agent in agents_inference:
|
108 |
+
_action_space_inference.append(agent.get_action_space())
|
109 |
+
|
110 |
+
var agent_onnx_model: ONNXModel
|
111 |
+
if agent.onnx_model_path.is_empty():
|
112 |
+
assert(
|
113 |
+
onnx_models.has(onnx_model_path),
|
114 |
+
(
|
115 |
+
"Node %s has no onnx model path set " % agent.get_path()
|
116 |
+
+ "and sync node's control mode is not set to OnnxInference. "
|
117 |
+
+ "Either add the path to the AIController, "
|
118 |
+
+ "or if you want to use the path set on sync node instead, "
|
119 |
+
+ "set control mode to OnnxInference."
|
120 |
+
)
|
121 |
+
)
|
122 |
+
prints(
|
123 |
+
"Info: AIController %s" % agent.get_path(),
|
124 |
+
"has no onnx model path set.",
|
125 |
+
"Using path set on the sync node instead."
|
126 |
+
)
|
127 |
+
agent_onnx_model = onnx_models[onnx_model_path]
|
128 |
+
else:
|
129 |
+
if not onnx_models.has(agent.onnx_model_path):
|
130 |
+
assert(
|
131 |
+
FileAccess.file_exists(agent.onnx_model_path),
|
132 |
+
(
|
133 |
+
"Onnx Model Path set on %s node does not exist: %s"
|
134 |
+
% [agent.get_path(), agent.onnx_model_path]
|
135 |
+
)
|
136 |
+
)
|
137 |
+
onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
|
138 |
+
agent_onnx_model = onnx_models[agent.onnx_model_path]
|
139 |
+
|
140 |
+
agent.onnx_model = agent_onnx_model
|
141 |
+
_set_heuristic("model", agents_inference)
|
142 |
+
|
143 |
+
|
144 |
+
func _initialize_demo_recording():
|
145 |
+
if agent_demo_record:
|
146 |
+
InputMap.add_action("RemoveLastDemoEpisode")
|
147 |
+
InputMap.action_add_event(
|
148 |
+
"RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
|
149 |
+
)
|
150 |
+
current_demo_trajectory.resize(2)
|
151 |
+
current_demo_trajectory[0] = []
|
152 |
+
current_demo_trajectory[1] = []
|
153 |
+
agent_demo_record.heuristic = "demo_record"
|
154 |
+
|
155 |
+
|
156 |
+
func _physics_process(_delta):
|
157 |
+
# two modes, human control, agent control
|
158 |
+
# pause tree, send obs, get actions, set actions, unpause tree
|
159 |
+
|
160 |
+
_demo_record_process()
|
161 |
+
|
162 |
+
if n_action_steps % action_repeat != 0:
|
163 |
+
n_action_steps += 1
|
164 |
+
return
|
165 |
+
|
166 |
+
n_action_steps += 1
|
167 |
+
|
168 |
+
_training_process()
|
169 |
+
_inference_process()
|
170 |
+
_heuristic_process()
|
171 |
+
|
172 |
+
|
173 |
+
func _training_process():
|
174 |
+
if connected:
|
175 |
+
get_tree().set_pause(true)
|
176 |
+
|
177 |
+
if just_reset:
|
178 |
+
just_reset = false
|
179 |
+
var obs = _get_obs_from_agents(agents_training)
|
180 |
+
|
181 |
+
var reply = {"type": "reset", "obs": obs}
|
182 |
+
_send_dict_as_json_message(reply)
|
183 |
+
# this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
|
184 |
+
get_tree().set_pause(false)
|
185 |
+
return
|
186 |
+
|
187 |
+
if need_to_send_obs:
|
188 |
+
need_to_send_obs = false
|
189 |
+
var reward = _get_reward_from_agents()
|
190 |
+
var done = _get_done_from_agents()
|
191 |
+
#_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
|
192 |
+
|
193 |
+
var obs = _get_obs_from_agents(agents_training)
|
194 |
+
|
195 |
+
var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
|
196 |
+
_send_dict_as_json_message(reply)
|
197 |
+
|
198 |
+
var handled = handle_message()
|
199 |
+
|
200 |
+
|
201 |
+
func _inference_process():
|
202 |
+
if agents_inference.size() > 0:
|
203 |
+
var obs: Array = _get_obs_from_agents(agents_inference)
|
204 |
+
var actions = []
|
205 |
+
|
206 |
+
for agent_id in range(0, agents_inference.size()):
|
207 |
+
var action = agents_inference[agent_id].onnx_model.run_inference(
|
208 |
+
obs[agent_id]["obs"], 1.0
|
209 |
+
)
|
210 |
+
action["output"] = clamp_array(action["output"], -1.0, 1.0)
|
211 |
+
var action_dict = _extract_action_dict(
|
212 |
+
action["output"], _action_space_inference[agent_id]
|
213 |
+
)
|
214 |
+
actions.append(action_dict)
|
215 |
+
|
216 |
+
_set_agent_actions(actions, agents_inference)
|
217 |
+
_reset_agents_if_done(agents_inference)
|
218 |
+
get_tree().set_pause(false)
|
219 |
+
|
220 |
+
|
221 |
+
func _demo_record_process():
|
222 |
+
if not agent_demo_record:
|
223 |
+
return
|
224 |
+
|
225 |
+
if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
|
226 |
+
print("[Sync script][Demo recorder] Removing last recorded episode.")
|
227 |
+
demo_trajectories.remove_at(demo_trajectories.size() - 1)
|
228 |
+
print("Remaining episode count: %d" % demo_trajectories.size())
|
229 |
+
|
230 |
+
if n_action_steps % agent_demo_record.action_repeat != 0:
|
231 |
+
return
|
232 |
+
|
233 |
+
var obs_dict: Dictionary = agent_demo_record.get_obs()
|
234 |
+
|
235 |
+
# Get the current obs from the agent
|
236 |
+
assert(
|
237 |
+
obs_dict.has("obs"),
|
238 |
+
"Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
|
239 |
+
)
|
240 |
+
current_demo_trajectory[0].append(obs_dict.obs)
|
241 |
+
|
242 |
+
# Get the action applied for the current obs from the agent
|
243 |
+
agent_demo_record.set_action()
|
244 |
+
var acts = agent_demo_record.get_action()
|
245 |
+
|
246 |
+
var terminal = agent_demo_record.get_done()
|
247 |
+
# Record actions only for non-terminal states
|
248 |
+
if terminal:
|
249 |
+
agent_demo_record.set_done_false()
|
250 |
+
else:
|
251 |
+
current_demo_trajectory[1].append(acts)
|
252 |
+
|
253 |
+
if terminal:
|
254 |
+
#current_demo_trajectory[2].append(true)
|
255 |
+
demo_trajectories.append(current_demo_trajectory.duplicate(true))
|
256 |
+
print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
|
257 |
+
current_demo_trajectory[0].clear()
|
258 |
+
current_demo_trajectory[1].clear()
|
259 |
+
|
260 |
+
|
261 |
+
func _heuristic_process():
|
262 |
+
for agent in agents_heuristic:
|
263 |
+
_reset_agents_if_done(agents_heuristic)
|
264 |
+
|
265 |
+
|
266 |
+
func _extract_action_dict(action_array: Array, action_space: Dictionary):
|
267 |
+
var index = 0
|
268 |
+
var result = {}
|
269 |
+
for key in action_space.keys():
|
270 |
+
var size = action_space[key]["size"]
|
271 |
+
if action_space[key]["action_type"] == "discrete":
|
272 |
+
result[key] = round(action_array[index])
|
273 |
+
else:
|
274 |
+
result[key] = action_array.slice(index, index + size)
|
275 |
+
index += size
|
276 |
+
|
277 |
+
return result
|
278 |
+
|
279 |
+
|
280 |
+
## For AIControllers that inherit mode from sync, sets the correct mode.
|
281 |
+
func _set_agent_mode(agent: Node):
|
282 |
+
var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
|
283 |
+
|
284 |
+
if agent_inherits_mode:
|
285 |
+
match control_mode:
|
286 |
+
ControlModes.HUMAN:
|
287 |
+
agent.control_mode = agent.ControlModes.HUMAN
|
288 |
+
ControlModes.TRAINING:
|
289 |
+
agent.control_mode = agent.ControlModes.TRAINING
|
290 |
+
ControlModes.ONNX_INFERENCE:
|
291 |
+
agent.control_mode = agent.ControlModes.ONNX_INFERENCE
|
292 |
+
|
293 |
+
|
294 |
+
func _get_agents():
|
295 |
+
all_agents = get_tree().get_nodes_in_group("AGENT")
|
296 |
+
for agent in all_agents:
|
297 |
+
_set_agent_mode(agent)
|
298 |
+
|
299 |
+
if agent.control_mode == agent.ControlModes.TRAINING:
|
300 |
+
agents_training.append(agent)
|
301 |
+
elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
|
302 |
+
agents_inference.append(agent)
|
303 |
+
elif agent.control_mode == agent.ControlModes.HUMAN:
|
304 |
+
agents_heuristic.append(agent)
|
305 |
+
elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
|
306 |
+
assert(
|
307 |
+
not agent_demo_record,
|
308 |
+
"Currently only a single AIController can be used for recording expert demos."
|
309 |
+
)
|
310 |
+
agent_demo_record = agent
|
311 |
+
|
312 |
+
|
313 |
+
func _set_heuristic(heuristic, agents: Array):
|
314 |
+
for agent in agents:
|
315 |
+
agent.set_heuristic(heuristic)
|
316 |
+
|
317 |
+
|
318 |
+
func _handshake():
|
319 |
+
print("performing handshake")
|
320 |
+
|
321 |
+
var json_dict = _get_dict_json_message()
|
322 |
+
assert(json_dict["type"] == "handshake")
|
323 |
+
var major_version = json_dict["major_version"]
|
324 |
+
var minor_version = json_dict["minor_version"]
|
325 |
+
if major_version != MAJOR_VERSION:
|
326 |
+
print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
|
327 |
+
if minor_version != MINOR_VERSION:
|
328 |
+
print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
|
329 |
+
|
330 |
+
print("handshake complete")
|
331 |
+
|
332 |
+
|
333 |
+
func _get_dict_json_message():
|
334 |
+
# returns a dictionary from of the most recent message
|
335 |
+
# this is not waiting
|
336 |
+
while stream.get_available_bytes() == 0:
|
337 |
+
stream.poll()
|
338 |
+
if stream.get_status() != 2:
|
339 |
+
print("server disconnected status, closing")
|
340 |
+
get_tree().quit()
|
341 |
+
return null
|
342 |
+
|
343 |
+
OS.delay_usec(10)
|
344 |
+
|
345 |
+
var message = stream.get_string()
|
346 |
+
var json_data = JSON.parse_string(message)
|
347 |
+
|
348 |
+
return json_data
|
349 |
+
|
350 |
+
|
351 |
+
func _send_dict_as_json_message(dict):
|
352 |
+
stream.put_string(JSON.stringify(dict, "", false))
|
353 |
+
|
354 |
+
|
355 |
+
func _send_env_info():
|
356 |
+
var json_dict = _get_dict_json_message()
|
357 |
+
assert(json_dict["type"] == "env_info")
|
358 |
+
|
359 |
+
var message = {
|
360 |
+
"type": "env_info",
|
361 |
+
"observation_space": _obs_space,
|
362 |
+
"action_space": _action_space,
|
363 |
+
"n_agents": len(agents_training)
|
364 |
+
}
|
365 |
+
_send_dict_as_json_message(message)
|
366 |
+
|
367 |
+
|
368 |
+
func connect_to_server():
|
369 |
+
print("Waiting for one second to allow server to start")
|
370 |
+
OS.delay_msec(1000)
|
371 |
+
print("trying to connect to server")
|
372 |
+
stream = StreamPeerTCP.new()
|
373 |
+
|
374 |
+
# "localhost" was not working on windows VM, had to use the IP
|
375 |
+
var ip = "127.0.0.1"
|
376 |
+
var port = _get_port()
|
377 |
+
var connect = stream.connect_to_host(ip, port)
|
378 |
+
stream.set_no_delay(true) # TODO check if this improves performance or not
|
379 |
+
stream.poll()
|
380 |
+
# Fetch the status until it is either connected (2) or failed to connect (3)
|
381 |
+
while stream.get_status() < 2:
|
382 |
+
stream.poll()
|
383 |
+
return stream.get_status() == 2
|
384 |
+
|
385 |
+
|
386 |
+
func _get_args():
|
387 |
+
print("getting command line arguments")
|
388 |
+
var arguments = {}
|
389 |
+
for argument in OS.get_cmdline_args():
|
390 |
+
print(argument)
|
391 |
+
if argument.find("=") > -1:
|
392 |
+
var key_value = argument.split("=")
|
393 |
+
arguments[key_value[0].lstrip("--")] = key_value[1]
|
394 |
+
else:
|
395 |
+
# Options without an argument will be present in the dictionary,
|
396 |
+
# with the value set to an empty string.
|
397 |
+
arguments[argument.lstrip("--")] = ""
|
398 |
+
|
399 |
+
return arguments
|
400 |
+
|
401 |
+
|
402 |
+
func _get_speedup():
|
403 |
+
print(args)
|
404 |
+
return args.get("speedup", str(speed_up)).to_float()
|
405 |
+
|
406 |
+
|
407 |
+
func _get_port():
|
408 |
+
return args.get("port", DEFAULT_PORT).to_int()
|
409 |
+
|
410 |
+
|
411 |
+
func _set_seed():
|
412 |
+
var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
|
413 |
+
seed(_seed)
|
414 |
+
|
415 |
+
|
416 |
+
func _set_action_repeat():
|
417 |
+
action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
|
418 |
+
|
419 |
+
|
420 |
+
func disconnect_from_server():
|
421 |
+
stream.disconnect_from_host()
|
422 |
+
|
423 |
+
|
424 |
+
func handle_message() -> bool:
|
425 |
+
# get json message: reset, step, close
|
426 |
+
var message = _get_dict_json_message()
|
427 |
+
if message["type"] == "close":
|
428 |
+
print("received close message, closing game")
|
429 |
+
get_tree().quit()
|
430 |
+
get_tree().set_pause(false)
|
431 |
+
return true
|
432 |
+
|
433 |
+
if message["type"] == "reset":
|
434 |
+
print("resetting all agents")
|
435 |
+
_reset_agents()
|
436 |
+
just_reset = true
|
437 |
+
get_tree().set_pause(false)
|
438 |
+
#print("resetting forcing draw")
|
439 |
+
# RenderingServer.force_draw()
|
440 |
+
# var obs = _get_obs_from_agents()
|
441 |
+
# print("obs ", obs)
|
442 |
+
# var reply = {
|
443 |
+
# "type": "reset",
|
444 |
+
# "obs": obs
|
445 |
+
# }
|
446 |
+
# _send_dict_as_json_message(reply)
|
447 |
+
return true
|
448 |
+
|
449 |
+
if message["type"] == "call":
|
450 |
+
var method = message["method"]
|
451 |
+
var returns = _call_method_on_agents(method)
|
452 |
+
var reply = {"type": "call", "returns": returns}
|
453 |
+
print("calling method from Python")
|
454 |
+
_send_dict_as_json_message(reply)
|
455 |
+
return handle_message()
|
456 |
+
|
457 |
+
if message["type"] == "action":
|
458 |
+
var action = message["action"]
|
459 |
+
_set_agent_actions(action, agents_training)
|
460 |
+
need_to_send_obs = true
|
461 |
+
get_tree().set_pause(false)
|
462 |
+
return true
|
463 |
+
|
464 |
+
print("message was not handled")
|
465 |
+
return false
|
466 |
+
|
467 |
+
|
468 |
+
func _call_method_on_agents(method):
|
469 |
+
var returns = []
|
470 |
+
for agent in all_agents:
|
471 |
+
returns.append(agent.call(method))
|
472 |
+
|
473 |
+
return returns
|
474 |
+
|
475 |
+
|
476 |
+
func _reset_agents_if_done(agents = all_agents):
|
477 |
+
for agent in agents:
|
478 |
+
if agent.get_done():
|
479 |
+
agent.set_done_false()
|
480 |
+
|
481 |
+
|
482 |
+
func _reset_agents(agents = all_agents):
|
483 |
+
for agent in agents:
|
484 |
+
agent.needs_reset = true
|
485 |
+
#agent.reset()
|
486 |
+
|
487 |
+
|
488 |
+
func _get_obs_from_agents(agents: Array = all_agents):
|
489 |
+
var obs = []
|
490 |
+
for agent in agents:
|
491 |
+
obs.append(agent.get_obs())
|
492 |
+
return obs
|
493 |
+
|
494 |
+
|
495 |
+
func _get_reward_from_agents(agents: Array = agents_training):
|
496 |
+
var rewards = []
|
497 |
+
for agent in agents:
|
498 |
+
rewards.append(agent.get_reward())
|
499 |
+
agent.zero_reward()
|
500 |
+
return rewards
|
501 |
+
|
502 |
+
|
503 |
+
func _get_done_from_agents(agents: Array = agents_training):
|
504 |
+
var dones = []
|
505 |
+
for agent in agents:
|
506 |
+
var done = agent.get_done()
|
507 |
+
if done:
|
508 |
+
agent.set_done_false()
|
509 |
+
dones.append(done)
|
510 |
+
return dones
|
511 |
+
|
512 |
+
|
513 |
+
func _set_agent_actions(actions, agents: Array = all_agents):
|
514 |
+
for i in range(len(actions)):
|
515 |
+
agents[i].set_action(actions[i])
|
516 |
+
|
517 |
+
|
518 |
+
func clamp_array(arr: Array, min: float, max: float):
|
519 |
+
var output: Array = []
|
520 |
+
for a in arr:
|
521 |
+
output.append(clamp(a, min, max))
|
522 |
+
return output
|
523 |
+
|
524 |
+
|
525 |
+
## Save recorded export demos on window exit (Close window instead of "Stop" button in Godot Editor)
|
526 |
+
func _notification(what):
|
527 |
+
if not agent_demo_record:
|
528 |
+
return
|
529 |
+
|
530 |
+
if what == NOTIFICATION_PREDELETE:
|
531 |
+
var json_string = JSON.stringify(demo_trajectories, "", false)
|
532 |
+
var file = FileAccess.open(agent_demo_record.expert_demo_save_path, FileAccess.WRITE)
|
533 |
+
|
534 |
+
if not file:
|
535 |
+
var error: Error = FileAccess.get_open_error()
|
536 |
+
assert(not error, "There was an error opening the file: %d" % error)
|
537 |
+
|
538 |
+
file.store_line(json_string)
|
539 |
+
var error = file.get_error()
|
540 |
+
assert(not error, "There was an error after trying to write to the file: %d" % error)
|
cherry.png
ADDED
Git LFS Details
|
default_env.tres
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[gd_resource type="Environment" load_steps=2 format=2]
|
2 |
+
|
3 |
+
[sub_resource type="Sky" id=1]
|
4 |
+
|
5 |
+
[resource]
|
6 |
+
background_mode = 2
|
7 |
+
background_sky = SubResource( 1 )
|
icon.png
ADDED
Git LFS Details
|
light_mask.png
ADDED
Git LFS Details
|
lollipopGreen.png
ADDED
Git LFS Details
|
project.godot
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
; Engine configuration file.
|
2 |
+
; It's best edited using the editor UI and not directly,
|
3 |
+
; since the parameters that go here are not all obvious.
|
4 |
+
;
|
5 |
+
; Format:
|
6 |
+
; [section] ; section goes between []
|
7 |
+
; param=value ; assign values to parameters
|
8 |
+
|
9 |
+
config_version=5
|
10 |
+
|
11 |
+
[application]
|
12 |
+
|
13 |
+
config/name="BallChase"
|
14 |
+
run/main_scene="res://BatchEnvs.tscn"
|
15 |
+
config/features=PackedStringArray("4.1", "C#")
|
16 |
+
config/icon="res://icon.png"
|
17 |
+
|
18 |
+
[display]
|
19 |
+
|
20 |
+
window/stretch/mode="2d"
|
21 |
+
window/size/width=1280
|
22 |
+
window/size/height=720
|
23 |
+
|
24 |
+
[dotnet]
|
25 |
+
|
26 |
+
project/assembly_name="BallChase"
|
27 |
+
|
28 |
+
[editor_plugins]
|
29 |
+
|
30 |
+
enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
|
31 |
+
|
32 |
+
[input]
|
33 |
+
|
34 |
+
move_left={
|
35 |
+
"deadzone": 0.5,
|
36 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":0,"echo":false,"script":null)
|
37 |
+
]
|
38 |
+
}
|
39 |
+
move_right={
|
40 |
+
"deadzone": 0.5,
|
41 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":0,"echo":false,"script":null)
|
42 |
+
]
|
43 |
+
}
|
44 |
+
move_up={
|
45 |
+
"deadzone": 0.5,
|
46 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":0,"echo":false,"script":null)
|
47 |
+
]
|
48 |
+
}
|
49 |
+
move_down={
|
50 |
+
"deadzone": 0.5,
|
51 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":0,"echo":false,"script":null)
|
52 |
+
]
|
53 |
+
}
|
54 |
+
left_arrow={
|
55 |
+
"deadzone": 0.5,
|
56 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194319,"key_label":0,"unicode":0,"echo":false,"script":null)
|
57 |
+
]
|
58 |
+
}
|
59 |
+
right_arrow={
|
60 |
+
"deadzone": 0.5,
|
61 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194321,"key_label":0,"unicode":0,"echo":false,"script":null)
|
62 |
+
]
|
63 |
+
}
|
64 |
+
up_arrow={
|
65 |
+
"deadzone": 0.5,
|
66 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194320,"key_label":0,"unicode":0,"echo":false,"script":null)
|
67 |
+
]
|
68 |
+
}
|
69 |
+
down_arrow={
|
70 |
+
"deadzone": 0.5,
|
71 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194322,"key_label":0,"unicode":0,"echo":false,"script":null)
|
72 |
+
]
|
73 |
+
}
|
74 |
+
r_key={
|
75 |
+
"deadzone": 0.5,
|
76 |
+
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":82,"key_label":0,"unicode":0,"echo":false,"script":null)
|
77 |
+
]
|
78 |
+
}
|
79 |
+
zoom_out={
|
80 |
+
"deadzone": 0.5,
|
81 |
+
"events": [Object(InputEventMouseButton,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"button_mask":0,"position":Vector2(0, 0),"global_position":Vector2(0, 0),"factor":1.0,"button_index":5,"canceled":false,"pressed":false,"double_click":false,"script":null)
|
82 |
+
]
|
83 |
+
}
|
84 |
+
zoom_in={
|
85 |
+
"deadzone": 0.5,
|
86 |
+
"events": [Object(InputEventMouseButton,"resource_local_to_scene":false,"resource_name":"","device":0,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"button_mask":0,"position":Vector2(0, 0),"global_position":Vector2(0, 0),"factor":1.0,"button_index":4,"canceled":false,"pressed":false,"double_click":false,"script":null)
|
87 |
+
]
|
88 |
+
}
|
89 |
+
reset_camera={
|
90 |
+
"deadzone": 0.5,
|
91 |
+
"events": [Object(InputEventMouseButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"button_mask":0,"position":Vector2(0, 0),"global_position":Vector2(0, 0),"factor":1.0,"button_index":3,"canceled":false,"pressed":false,"double_click":false,"script":null)
|
92 |
+
]
|
93 |
+
}
|
94 |
+
|
95 |
+
[physics]
|
96 |
+
|
97 |
+
common/enable_pause_aware_picking=true
|
98 |
+
|
99 |
+
[rendering]
|
100 |
+
|
101 |
+
quality/filters/msaa=2
|
102 |
+
environment/default_environment="res://default_env.tres"
|