jtatman commited on
Commit
35ae6ce
1 Parent(s): 65c3952

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -58
  2. .gitignore +3 -0
  3. MultiAgentTestEnv.csproj +10 -0
  4. MultiAgentTestEnv.sln +19 -0
  5. README.md +25 -0
  6. addons/godot_rl_agents/controller/ai_controller_2d.gd +119 -0
  7. addons/godot_rl_agents/controller/ai_controller_3d.gd +120 -0
  8. addons/godot_rl_agents/godot_rl_agents.gd +16 -0
  9. addons/godot_rl_agents/icon.png +3 -0
  10. addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +109 -0
  11. addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
  12. addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
  13. addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml +29 -0
  14. addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd +51 -0
  15. addons/godot_rl_agents/plugin.cfg +7 -0
  16. addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn +48 -0
  17. addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd +235 -0
  18. addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd +25 -0
  19. addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd +118 -0
  20. addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn +7 -0
  21. addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn +6 -0
  22. addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd +258 -0
  23. addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd +25 -0
  24. addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd +21 -0
  25. addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn +41 -0
  26. addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd +185 -0
  27. addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn +27 -0
  28. addons/godot_rl_agents/sync.gd +579 -0
  29. assets/flying_platform.glb +0 -0
  30. assets/platform.glb +0 -0
  31. assets/robot.glb +0 -0
  32. icon.svg +1 -0
  33. license.md +5 -0
  34. onnx/platform_onnx/model.onnx +3 -0
  35. onnx/player_onnx/model.onnx +3 -0
  36. project.godot +61 -0
  37. readme.md +78 -0
  38. scenes/game_scene/game_scene.tscn +61 -0
  39. scenes/game_scene/game_scene_manager.gd +36 -0
  40. scenes/game_scene/game_scene_onnx_inference.tscn +25 -0
  41. scenes/goal/goal.gd +23 -0
  42. scenes/goal/goal.tscn +28 -0
  43. scenes/platform/platform.gd +16 -0
  44. scenes/platform/platform.tscn +25 -0
  45. scenes/platform/platform_ai_controller.gd +71 -0
  46. scenes/player/player.gd +50 -0
  47. scenes/player/player.tscn +145 -0
  48. scenes/player/player_ai_controller.gd +100 -0
  49. scenes/testing_scene/testing_scene.tscn +35 -0
  50. scenes/training_scene/training_manager.gd +36 -0
.gitattributes CHANGED
@@ -1,58 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.lz4 filter=lfs diff=lfs merge=lfs -text
12
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
- *.model filter=lfs diff=lfs merge=lfs -text
14
- *.msgpack filter=lfs diff=lfs merge=lfs -text
15
- *.npy filter=lfs diff=lfs merge=lfs -text
16
- *.npz filter=lfs diff=lfs merge=lfs -text
17
- *.onnx filter=lfs diff=lfs merge=lfs -text
18
- *.ot filter=lfs diff=lfs merge=lfs -text
19
- *.parquet filter=lfs diff=lfs merge=lfs -text
20
- *.pb filter=lfs diff=lfs merge=lfs -text
21
- *.pickle filter=lfs diff=lfs merge=lfs -text
22
- *.pkl filter=lfs diff=lfs merge=lfs -text
23
- *.pt filter=lfs diff=lfs merge=lfs -text
24
- *.pth filter=lfs diff=lfs merge=lfs -text
25
- *.rar filter=lfs diff=lfs merge=lfs -text
26
- *.safetensors filter=lfs diff=lfs merge=lfs -text
27
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
- *.tar.* filter=lfs diff=lfs merge=lfs -text
29
- *.tar filter=lfs diff=lfs merge=lfs -text
30
- *.tflite filter=lfs diff=lfs merge=lfs -text
31
- *.tgz filter=lfs diff=lfs merge=lfs -text
32
- *.wasm filter=lfs diff=lfs merge=lfs -text
33
- *.xz filter=lfs diff=lfs merge=lfs -text
34
- *.zip filter=lfs diff=lfs merge=lfs -text
35
- *.zst filter=lfs diff=lfs merge=lfs -text
36
- *tfevents* filter=lfs diff=lfs merge=lfs -text
37
- # Audio files - uncompressed
38
- *.pcm filter=lfs diff=lfs merge=lfs -text
39
- *.sam filter=lfs diff=lfs merge=lfs -text
40
- *.raw filter=lfs diff=lfs merge=lfs -text
41
- # Audio files - compressed
42
- *.aac filter=lfs diff=lfs merge=lfs -text
43
- *.flac filter=lfs diff=lfs merge=lfs -text
44
- *.mp3 filter=lfs diff=lfs merge=lfs -text
45
- *.ogg filter=lfs diff=lfs merge=lfs -text
46
- *.wav filter=lfs diff=lfs merge=lfs -text
47
- # Image files - uncompressed
48
- *.bmp filter=lfs diff=lfs merge=lfs -text
49
- *.gif filter=lfs diff=lfs merge=lfs -text
50
- *.png filter=lfs diff=lfs merge=lfs -text
51
- *.tiff filter=lfs diff=lfs merge=lfs -text
52
- # Image files - compressed
53
- *.jpg filter=lfs diff=lfs merge=lfs -text
54
- *.jpeg filter=lfs diff=lfs merge=lfs -text
55
- *.webp filter=lfs diff=lfs merge=lfs -text
56
- # Video files - compressed
57
- *.mp4 filter=lfs diff=lfs merge=lfs -text
58
- *.webm filter=lfs diff=lfs merge=lfs -text
 
1
+ # Normalize EOL for all files that Git considers text files.
2
+ * text=auto eol=lf
3
+ addons/godot_rl_agents/icon.png filter=lfs diff=lfs merge=lfs -text
4
+ onnx/platform_onnx/model.onnx filter=lfs diff=lfs merge=lfs -text
5
+ onnx/player_onnx/model.onnx filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Godot 4+ specific ignores
2
+ .godot/
3
+ android/
MultiAgentTestEnv.csproj ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Godot.NET.Sdk/4.3.0-dev.5">
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.16.3" />
9
+ </ItemGroup>
10
+ </Project>
MultiAgentTestEnv.sln ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Microsoft Visual Studio Solution File, Format Version 12.00
2
+ # Visual Studio 2012
3
+ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RobotEnv", "RobotEnv.csproj", "{C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}"
4
+ EndProject
5
+ Global
6
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
7
+ Debug|Any CPU = Debug|Any CPU
8
+ ExportDebug|Any CPU = ExportDebug|Any CPU
9
+ ExportRelease|Any CPU = ExportRelease|Any CPU
10
+ EndGlobalSection
11
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
12
+ {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13
+ {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.Debug|Any CPU.Build.0 = Debug|Any CPU
14
+ {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
15
+ {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
16
+ {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
17
+ {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
18
+ EndGlobalSection
19
+ EndGlobal
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 MultiAgentSimple 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_MultiAgentSimple
22
+ ```
23
+
24
+
25
+
addons/godot_rl_agents/controller/ai_controller_2d.gd ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ @export_group("Multi-policy mode options")
20
+ ## Allows you to set certain agents to use different policies.
21
+ ## Changing has no effect with default SB3 training. Works with Rllib example.
22
+ ## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md
23
+ @export var policy_name: String = "shared_policy"
24
+
25
+ var onnx_model: ONNXModel
26
+
27
+ var heuristic := "human"
28
+ var done := false
29
+ var reward := 0.0
30
+ var n_steps := 0
31
+ var needs_reset := false
32
+
33
+ var _player: Node2D
34
+
35
+
36
+ func _ready():
37
+ add_to_group("AGENT")
38
+
39
+
40
+ func init(player: Node2D):
41
+ _player = player
42
+
43
+
44
+ #-- Methods that need implementing using the "extend script" option in Godot --#
45
+ func get_obs() -> Dictionary:
46
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
47
+ return {"obs": []}
48
+
49
+
50
+ func get_reward() -> float:
51
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
52
+ return 0.0
53
+
54
+
55
+ func get_action_space() -> Dictionary:
56
+ assert(
57
+ false,
58
+ "the get get_action_space method is not implemented when extending from ai_controller"
59
+ )
60
+ return {
61
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
62
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
63
+ }
64
+
65
+
66
+ func set_action(action) -> void:
67
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
68
+
69
+
70
+ #-----------------------------------------------------------------------------#
71
+
72
+
73
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
74
+ # Only needed if you are recording expert demos with this AIController
75
+ func get_action() -> Array:
76
+ assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used")
77
+ return []
78
+
79
+ # -----------------------------------------------------------------------------#
80
+
81
+ func _physics_process(delta):
82
+ n_steps += 1
83
+ if n_steps > reset_after:
84
+ needs_reset = true
85
+
86
+
87
+ func get_obs_space():
88
+ # may need overriding if the obs space is complex
89
+ var obs = get_obs()
90
+ return {
91
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
92
+ }
93
+
94
+
95
+ func reset():
96
+ n_steps = 0
97
+ needs_reset = false
98
+
99
+
100
+ func reset_if_done():
101
+ if done:
102
+ reset()
103
+
104
+
105
+ func set_heuristic(h):
106
+ # sets the heuristic from "human" or "model" nothing to change here
107
+ heuristic = h
108
+
109
+
110
+ func get_done():
111
+ return done
112
+
113
+
114
+ func set_done_false():
115
+ done = false
116
+
117
+
118
+ func zero_reward():
119
+ reward = 0.0
addons/godot_rl_agents/controller/ai_controller_3d.gd ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ @export_group("Multi-policy mode options")
20
+ ## Allows you to set certain agents to use different policies.
21
+ ## Changing has no effect with default SB3 training. Works with Rllib example.
22
+ ## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md
23
+ @export var policy_name: String = "shared_policy"
24
+
25
+ var onnx_model: ONNXModel
26
+
27
+ var heuristic := "human"
28
+ var done := false
29
+ var reward := 0.0
30
+ var n_steps := 0
31
+ var needs_reset := false
32
+
33
+ var _player: Node3D
34
+
35
+
36
+ func _ready():
37
+ add_to_group("AGENT")
38
+
39
+
40
+ func init(player: Node3D):
41
+ _player = player
42
+
43
+
44
+ #-- Methods that need implementing using the "extend script" option in Godot --#
45
+ func get_obs() -> Dictionary:
46
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
47
+ return {"obs": []}
48
+
49
+
50
+ func get_reward() -> float:
51
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
52
+ return 0.0
53
+
54
+
55
+ func get_action_space() -> Dictionary:
56
+ assert(
57
+ false,
58
+ "the get_action_space method is not implemented when extending from ai_controller"
59
+ )
60
+ return {
61
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
62
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
63
+ }
64
+
65
+
66
+ func set_action(action) -> void:
67
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
68
+
69
+
70
+ #-----------------------------------------------------------------------------#
71
+
72
+
73
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
74
+ # Only needed if you are recording expert demos with this AIController
75
+ func get_action() -> Array:
76
+ assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used")
77
+ return []
78
+
79
+ # -----------------------------------------------------------------------------#
80
+
81
+
82
+ func _physics_process(delta):
83
+ n_steps += 1
84
+ if n_steps > reset_after:
85
+ needs_reset = true
86
+
87
+
88
+ func get_obs_space():
89
+ # may need overriding if the obs space is complex
90
+ var obs = get_obs()
91
+ return {
92
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
93
+ }
94
+
95
+
96
+ func reset():
97
+ n_steps = 0
98
+ needs_reset = false
99
+
100
+
101
+ func reset_if_done():
102
+ if done:
103
+ reset()
104
+
105
+
106
+ func set_heuristic(h):
107
+ # sets the heuristic from "human" or "model" nothing to change here
108
+ heuristic = h
109
+
110
+
111
+ func get_done():
112
+ return done
113
+
114
+
115
+ func set_done_false():
116
+ done = false
117
+
118
+
119
+ func zero_reward():
120
+ 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

  • SHA256: e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
  • Pointer size: 128 Bytes
  • Size of remote file: 198 Bytes
addons/godot_rl_agents/onnx/csharp/ONNXInference.cs ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ /// <summary>
23
+ /// init function
24
+ /// </summary>
25
+ /// <param name="Path"></param>
26
+ /// <param name="BatchSize"></param>
27
+ /// <returns>Returns the output size of the model</returns>
28
+ public int Initialize(string Path, int BatchSize)
29
+ {
30
+ modelPath = Path;
31
+ batchSize = BatchSize;
32
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
33
+ session = LoadModel(modelPath);
34
+ return session.OutputMetadata["output"].Dimensions[1];
35
+ }
36
+
37
+
38
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
39
+ public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
40
+ {
41
+ //Current model: Any (Godot Rl Agents)
42
+ //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
43
+
44
+ //Fill the input tensors
45
+ // create span from inputSize
46
+ var span = new float[obs.Count]; //There's probably a better way to do this
47
+ for (int i = 0; i < obs.Count; i++)
48
+ {
49
+ span[i] = obs[i];
50
+ }
51
+
52
+ IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
53
+ {
54
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
55
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
56
+ };
57
+ IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
58
+
59
+ IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
60
+ //We do not use "using" here so we get a better exception explaination later
61
+ try
62
+ {
63
+ results = session.Run(inputs, outputNames);
64
+ }
65
+ catch (OnnxRuntimeException e)
66
+ {
67
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
68
+ GD.Print("Error at inference: ", e);
69
+ return null;
70
+ }
71
+ //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
72
+ Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
73
+ DisposableNamedOnnxValue output1 = results.First();
74
+ DisposableNamedOnnxValue output2 = results.Last();
75
+ Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
76
+ Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
77
+
78
+ foreach (float f in output1.AsEnumerable<float>())
79
+ {
80
+ output1Array.Add(f);
81
+ }
82
+
83
+ foreach (float f in output2.AsEnumerable<float>())
84
+ {
85
+ output2Array.Add(f);
86
+ }
87
+
88
+ output.Add(output1.Name, output1Array);
89
+ output.Add(output2.Name, output2Array);
90
+
91
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
92
+ results.Dispose();
93
+ return output;
94
+ }
95
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
96
+ public InferenceSession LoadModel(string Path)
97
+ {
98
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
99
+ byte[] model = file.GetBuffer((int)file.GetLength());
100
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
101
+ return new InferenceSession(model, SessionOpt); //Load the model
102
+ }
103
+ public void FreeDisposables()
104
+ {
105
+ session.Dispose();
106
+ SessionOpt.Dispose();
107
+ }
108
+ }
109
+ }
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,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## How many action values the model outputs
8
+ var action_output_size: int
9
+
10
+ ## Used to differentiate models
11
+ ## that only output continuous action mean (e.g. sb3, cleanrl export)
12
+ ## versus models that output mean and logstd (e.g. rllib export)
13
+ var action_means_only: bool
14
+
15
+ ## Whether action_means_value has been set already for this model
16
+ var action_means_only_set: bool
17
+
18
+ # Must provide the path to the model and the batch size
19
+ func _init(model_path, batch_size):
20
+ inferencer = inferencer_script.new()
21
+ action_output_size = inferencer.Initialize(model_path, batch_size)
22
+
23
+ # This function is the one that will be called from the game,
24
+ # requires the observation as an array and the state_ins as an int
25
+ # returns an Array containing the action the model takes.
26
+ func run_inference(obs: Array, state_ins: int) -> Dictionary:
27
+ if inferencer == null:
28
+ printerr("Inferencer not initialized")
29
+ return {}
30
+ return inferencer.RunInference(obs, state_ins)
31
+
32
+
33
+ func _notification(what):
34
+ if what == NOTIFICATION_PREDELETE:
35
+ inferencer.FreeDisposables()
36
+ inferencer.free()
37
+
38
+ # Check whether agent uses a continuous actions model with only action means or not
39
+ func set_action_means_only(agent_action_space):
40
+ action_means_only_set = true
41
+ var continuous_only: bool = true
42
+ var continuous_actions: int
43
+ for action in agent_action_space:
44
+ if not agent_action_space[action]["action_type"] == "continuous":
45
+ continuous_only = false
46
+ break
47
+ else:
48
+ continuous_actions += agent_action_space[action]["size"]
49
+ if continuous_only:
50
+ if continuous_actions == action_output_size:
51
+ action_means_only = true
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,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## Policy name of each agent, for use with multi-policy multi-agent RL cases
28
+ var agents_training_policy_names: Array[String] = ["shared_policy"]
29
+ var agents_inference: Array
30
+ var agents_heuristic: Array
31
+
32
+ ## For recording expert demos
33
+ var agent_demo_record: Node
34
+ ## File path for writing recorded trajectories
35
+ var expert_demo_save_path: String
36
+ ## Stores recorded trajectories
37
+ var demo_trajectories: Array
38
+ ## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
39
+ var current_demo_trajectory: Array
40
+
41
+ var need_to_send_obs = false
42
+ var args = null
43
+ var initialized = false
44
+ var just_reset = false
45
+ var onnx_model = null
46
+ var n_action_steps = 0
47
+
48
+ var _action_space_training: Array[Dictionary] = []
49
+ var _action_space_inference: Array[Dictionary] = []
50
+ var _obs_space_training: Array[Dictionary] = []
51
+
52
+ # Called when the node enters the scene tree for the first time.
53
+ func _ready():
54
+ await get_tree().root.ready
55
+ get_tree().set_pause(true)
56
+ _initialize()
57
+ await get_tree().create_timer(1.0).timeout
58
+ get_tree().set_pause(false)
59
+
60
+
61
+ func _initialize():
62
+ _get_agents()
63
+ args = _get_args()
64
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
65
+ Engine.time_scale = _get_speedup() * 1.0
66
+ prints(
67
+ "physics ticks",
68
+ Engine.physics_ticks_per_second,
69
+ Engine.time_scale,
70
+ _get_speedup(),
71
+ speed_up
72
+ )
73
+
74
+ _set_heuristic("human", all_agents)
75
+
76
+ _initialize_training_agents()
77
+ _initialize_inference_agents()
78
+ _initialize_demo_recording()
79
+
80
+ _set_seed()
81
+ _set_action_repeat()
82
+ initialized = true
83
+
84
+
85
+ func _initialize_training_agents():
86
+ if agents_training.size() > 0:
87
+ _obs_space_training.resize(agents_training.size())
88
+ _action_space_training.resize(agents_training.size())
89
+ for agent_idx in range(0, agents_training.size()):
90
+ _obs_space_training[agent_idx] = agents_training[agent_idx].get_obs_space()
91
+ _action_space_training[agent_idx] = agents_training[agent_idx].get_action_space()
92
+ connected = connect_to_server()
93
+ if connected:
94
+ _set_heuristic("model", agents_training)
95
+ _handshake()
96
+ _send_env_info()
97
+ else:
98
+ push_warning(
99
+ "Couldn't connect to Python server, using human controls instead. ",
100
+ "Did you start the training server using e.g. `gdrl` from the console?"
101
+ )
102
+
103
+
104
+ func _initialize_inference_agents():
105
+ if agents_inference.size() > 0:
106
+ if control_mode == ControlModes.ONNX_INFERENCE:
107
+ assert(
108
+ FileAccess.file_exists(onnx_model_path),
109
+ "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
110
+ )
111
+ onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
112
+
113
+ for agent in agents_inference:
114
+ var action_space = agent.get_action_space()
115
+ _action_space_inference.append(action_space)
116
+
117
+ var agent_onnx_model: ONNXModel
118
+ if agent.onnx_model_path.is_empty():
119
+ assert(
120
+ onnx_models.has(onnx_model_path),
121
+ (
122
+ "Node %s has no onnx model path set " % agent.get_path()
123
+ + "and sync node's control mode is not set to OnnxInference. "
124
+ + "Either add the path to the AIController, "
125
+ + "or if you want to use the path set on sync node instead, "
126
+ + "set control mode to OnnxInference."
127
+ )
128
+ )
129
+ prints(
130
+ "Info: AIController %s" % agent.get_path(),
131
+ "has no onnx model path set.",
132
+ "Using path set on the sync node instead."
133
+ )
134
+ agent_onnx_model = onnx_models[onnx_model_path]
135
+ else:
136
+ if not onnx_models.has(agent.onnx_model_path):
137
+ assert(
138
+ FileAccess.file_exists(agent.onnx_model_path),
139
+ (
140
+ "Onnx Model Path set on %s node does not exist: %s"
141
+ % [agent.get_path(), agent.onnx_model_path]
142
+ )
143
+ )
144
+ onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
145
+ agent_onnx_model = onnx_models[agent.onnx_model_path]
146
+
147
+ agent.onnx_model = agent_onnx_model
148
+ if not agent_onnx_model.action_means_only_set:
149
+ agent_onnx_model.set_action_means_only(action_space)
150
+
151
+ _set_heuristic("model", agents_inference)
152
+
153
+
154
+ func _initialize_demo_recording():
155
+ if agent_demo_record:
156
+ expert_demo_save_path = agent_demo_record.expert_demo_save_path
157
+ assert(
158
+ not expert_demo_save_path.is_empty(),
159
+ "Expert demo save path set in %s is empty." % agent_demo_record.get_path()
160
+ )
161
+
162
+ InputMap.add_action("RemoveLastDemoEpisode")
163
+ InputMap.action_add_event(
164
+ "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
165
+ )
166
+ current_demo_trajectory.resize(2)
167
+ current_demo_trajectory[0] = []
168
+ current_demo_trajectory[1] = []
169
+ agent_demo_record.heuristic = "demo_record"
170
+
171
+
172
+ func _physics_process(_delta):
173
+ # two modes, human control, agent control
174
+ # pause tree, send obs, get actions, set actions, unpause tree
175
+
176
+ _demo_record_process()
177
+
178
+ if n_action_steps % action_repeat != 0:
179
+ n_action_steps += 1
180
+ return
181
+
182
+ n_action_steps += 1
183
+
184
+ _training_process()
185
+ _inference_process()
186
+ _heuristic_process()
187
+
188
+
189
+ func _training_process():
190
+ if connected:
191
+ get_tree().set_pause(true)
192
+
193
+ if just_reset:
194
+ just_reset = false
195
+ var obs = _get_obs_from_agents(agents_training)
196
+
197
+ var reply = {"type": "reset", "obs": obs}
198
+ _send_dict_as_json_message(reply)
199
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
200
+ get_tree().set_pause(false)
201
+ return
202
+
203
+ if need_to_send_obs:
204
+ need_to_send_obs = false
205
+ var reward = _get_reward_from_agents()
206
+ var done = _get_done_from_agents()
207
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
208
+
209
+ var obs = _get_obs_from_agents(agents_training)
210
+
211
+ var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
212
+ _send_dict_as_json_message(reply)
213
+
214
+ var handled = handle_message()
215
+
216
+
217
+ func _inference_process():
218
+ if agents_inference.size() > 0:
219
+ var obs: Array = _get_obs_from_agents(agents_inference)
220
+ var actions = []
221
+
222
+ for agent_id in range(0, agents_inference.size()):
223
+ var model: ONNXModel = agents_inference[agent_id].onnx_model
224
+ var action = model.run_inference(
225
+ obs[agent_id]["obs"], 1.0
226
+ )
227
+ var action_dict = _extract_action_dict(
228
+ action["output"], _action_space_inference[agent_id], model.action_means_only
229
+ )
230
+ actions.append(action_dict)
231
+
232
+ _set_agent_actions(actions, agents_inference)
233
+ _reset_agents_if_done(agents_inference)
234
+ get_tree().set_pause(false)
235
+
236
+
237
+ func _demo_record_process():
238
+ if not agent_demo_record:
239
+ return
240
+
241
+ if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
242
+ print("[Sync script][Demo recorder] Removing last recorded episode.")
243
+ demo_trajectories.remove_at(demo_trajectories.size() - 1)
244
+ print("Remaining episode count: %d" % demo_trajectories.size())
245
+
246
+ if n_action_steps % agent_demo_record.action_repeat != 0:
247
+ return
248
+
249
+ var obs_dict: Dictionary = agent_demo_record.get_obs()
250
+
251
+ # Get the current obs from the agent
252
+ assert(
253
+ obs_dict.has("obs"),
254
+ "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
255
+ )
256
+ current_demo_trajectory[0].append(obs_dict.obs)
257
+
258
+ # Get the action applied for the current obs from the agent
259
+ agent_demo_record.set_action()
260
+ var acts = agent_demo_record.get_action()
261
+
262
+ var terminal = agent_demo_record.get_done()
263
+ # Record actions only for non-terminal states
264
+ if terminal:
265
+ agent_demo_record.set_done_false()
266
+ else:
267
+ current_demo_trajectory[1].append(acts)
268
+
269
+ if terminal:
270
+ #current_demo_trajectory[2].append(true)
271
+ demo_trajectories.append(current_demo_trajectory.duplicate(true))
272
+ print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
273
+ current_demo_trajectory[0].clear()
274
+ current_demo_trajectory[1].clear()
275
+
276
+
277
+ func _heuristic_process():
278
+ for agent in agents_heuristic:
279
+ _reset_agents_if_done(agents_heuristic)
280
+
281
+
282
+ func _extract_action_dict(action_array: Array, action_space: Dictionary, action_means_only: bool):
283
+ var index = 0
284
+ var result = {}
285
+ for key in action_space.keys():
286
+ var size = action_space[key]["size"]
287
+ var action_type = action_space[key]["action_type"]
288
+ if action_type == "discrete":
289
+ var largest_logit: float # Value of the largest logit for this action in the actions array
290
+ var largest_logit_idx: int # Index of the largest logit for this action in the actions array
291
+ for logit_idx in range(0, size):
292
+ var logit_value = action_array[index + logit_idx]
293
+ if logit_value > largest_logit:
294
+ largest_logit = logit_value
295
+ largest_logit_idx = logit_idx
296
+ result[key] = largest_logit_idx # Index of the largest logit is the discrete action value
297
+ index += size
298
+ elif action_type == "continuous":
299
+ # For continous actions, we only take the action mean values
300
+ result[key] = clamp_array(action_array.slice(index, index + size), -1.0, 1.0)
301
+ if action_means_only:
302
+ index += size # model only outputs action means, so we move index by size
303
+ else:
304
+ index += size * 2 # model outputs logstd after action mean, we skip the logstd part
305
+
306
+ else:
307
+ assert(false, 'Only "discrete" and "continuous" action types supported. Found: %s action type set.' % action_type)
308
+
309
+
310
+ return result
311
+
312
+
313
+ ## For AIControllers that inherit mode from sync, sets the correct mode.
314
+ func _set_agent_mode(agent: Node):
315
+ var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
316
+
317
+ if agent_inherits_mode:
318
+ match control_mode:
319
+ ControlModes.HUMAN:
320
+ agent.control_mode = agent.ControlModes.HUMAN
321
+ ControlModes.TRAINING:
322
+ agent.control_mode = agent.ControlModes.TRAINING
323
+ ControlModes.ONNX_INFERENCE:
324
+ agent.control_mode = agent.ControlModes.ONNX_INFERENCE
325
+
326
+
327
+ func _get_agents():
328
+ all_agents = get_tree().get_nodes_in_group("AGENT")
329
+ for agent in all_agents:
330
+ _set_agent_mode(agent)
331
+
332
+ if agent.control_mode == agent.ControlModes.TRAINING:
333
+ agents_training.append(agent)
334
+ elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
335
+ agents_inference.append(agent)
336
+ elif agent.control_mode == agent.ControlModes.HUMAN:
337
+ agents_heuristic.append(agent)
338
+ elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
339
+ assert(
340
+ not agent_demo_record,
341
+ "Currently only a single AIController can be used for recording expert demos."
342
+ )
343
+ agent_demo_record = agent
344
+
345
+ var training_agent_count = agents_training.size()
346
+ agents_training_policy_names.resize(training_agent_count)
347
+ for i in range(0, training_agent_count):
348
+ agents_training_policy_names[i] = agents_training[i].policy_name
349
+
350
+
351
+ func _set_heuristic(heuristic, agents: Array):
352
+ for agent in agents:
353
+ agent.set_heuristic(heuristic)
354
+
355
+
356
+ func _handshake():
357
+ print("performing handshake")
358
+
359
+ var json_dict = _get_dict_json_message()
360
+ assert(json_dict["type"] == "handshake")
361
+ var major_version = json_dict["major_version"]
362
+ var minor_version = json_dict["minor_version"]
363
+ if major_version != MAJOR_VERSION:
364
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
365
+ if minor_version != MINOR_VERSION:
366
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
367
+
368
+ print("handshake complete")
369
+
370
+
371
+ func _get_dict_json_message():
372
+ # returns a dictionary from of the most recent message
373
+ # this is not waiting
374
+ while stream.get_available_bytes() == 0:
375
+ stream.poll()
376
+ if stream.get_status() != 2:
377
+ print("server disconnected status, closing")
378
+ get_tree().quit()
379
+ return null
380
+
381
+ OS.delay_usec(10)
382
+
383
+ var message = stream.get_string()
384
+ var json_data = JSON.parse_string(message)
385
+
386
+ return json_data
387
+
388
+
389
+ func _send_dict_as_json_message(dict):
390
+ stream.put_string(JSON.stringify(dict, "", false))
391
+
392
+
393
+ func _send_env_info():
394
+ var json_dict = _get_dict_json_message()
395
+ assert(json_dict["type"] == "env_info")
396
+
397
+ var message = {
398
+ "type": "env_info",
399
+ "observation_space": _obs_space_training,
400
+ "action_space": _action_space_training,
401
+ "n_agents": len(agents_training),
402
+ "agent_policy_names": agents_training_policy_names
403
+ }
404
+ _send_dict_as_json_message(message)
405
+
406
+
407
+ func connect_to_server():
408
+ print("Waiting for one second to allow server to start")
409
+ OS.delay_msec(1000)
410
+ print("trying to connect to server")
411
+ stream = StreamPeerTCP.new()
412
+
413
+ # "localhost" was not working on windows VM, had to use the IP
414
+ var ip = "127.0.0.1"
415
+ var port = _get_port()
416
+ var connect = stream.connect_to_host(ip, port)
417
+ stream.set_no_delay(true) # TODO check if this improves performance or not
418
+ stream.poll()
419
+ # Fetch the status until it is either connected (2) or failed to connect (3)
420
+ while stream.get_status() < 2:
421
+ stream.poll()
422
+ return stream.get_status() == 2
423
+
424
+
425
+ func _get_args():
426
+ print("getting command line arguments")
427
+ var arguments = {}
428
+ for argument in OS.get_cmdline_args():
429
+ print(argument)
430
+ if argument.find("=") > -1:
431
+ var key_value = argument.split("=")
432
+ arguments[key_value[0].lstrip("--")] = key_value[1]
433
+ else:
434
+ # Options without an argument will be present in the dictionary,
435
+ # with the value set to an empty string.
436
+ arguments[argument.lstrip("--")] = ""
437
+
438
+ return arguments
439
+
440
+
441
+ func _get_speedup():
442
+ print(args)
443
+ return args.get("speedup", str(speed_up)).to_float()
444
+
445
+
446
+ func _get_port():
447
+ return args.get("port", DEFAULT_PORT).to_int()
448
+
449
+
450
+ func _set_seed():
451
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
452
+ seed(_seed)
453
+
454
+
455
+ func _set_action_repeat():
456
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
457
+
458
+
459
+ func disconnect_from_server():
460
+ stream.disconnect_from_host()
461
+
462
+
463
+ func handle_message() -> bool:
464
+ # get json message: reset, step, close
465
+ var message = _get_dict_json_message()
466
+ if message["type"] == "close":
467
+ print("received close message, closing game")
468
+ get_tree().quit()
469
+ get_tree().set_pause(false)
470
+ return true
471
+
472
+ if message["type"] == "reset":
473
+ print("resetting all agents")
474
+ _reset_agents()
475
+ just_reset = true
476
+ get_tree().set_pause(false)
477
+ #print("resetting forcing draw")
478
+ # RenderingServer.force_draw()
479
+ # var obs = _get_obs_from_agents()
480
+ # print("obs ", obs)
481
+ # var reply = {
482
+ # "type": "reset",
483
+ # "obs": obs
484
+ # }
485
+ # _send_dict_as_json_message(reply)
486
+ return true
487
+
488
+ if message["type"] == "call":
489
+ var method = message["method"]
490
+ var returns = _call_method_on_agents(method)
491
+ var reply = {"type": "call", "returns": returns}
492
+ print("calling method from Python")
493
+ _send_dict_as_json_message(reply)
494
+ return handle_message()
495
+
496
+ if message["type"] == "action":
497
+ var action = message["action"]
498
+ _set_agent_actions(action, agents_training)
499
+ need_to_send_obs = true
500
+ get_tree().set_pause(false)
501
+ return true
502
+
503
+ print("message was not handled")
504
+ return false
505
+
506
+
507
+ func _call_method_on_agents(method):
508
+ var returns = []
509
+ for agent in all_agents:
510
+ returns.append(agent.call(method))
511
+
512
+ return returns
513
+
514
+
515
+ func _reset_agents_if_done(agents = all_agents):
516
+ for agent in agents:
517
+ if agent.get_done():
518
+ agent.set_done_false()
519
+
520
+
521
+ func _reset_agents(agents = all_agents):
522
+ for agent in agents:
523
+ agent.needs_reset = true
524
+ #agent.reset()
525
+
526
+
527
+ func _get_obs_from_agents(agents: Array = all_agents):
528
+ var obs = []
529
+ for agent in agents:
530
+ obs.append(agent.get_obs())
531
+ return obs
532
+
533
+
534
+ func _get_reward_from_agents(agents: Array = agents_training):
535
+ var rewards = []
536
+ for agent in agents:
537
+ rewards.append(agent.get_reward())
538
+ agent.zero_reward()
539
+ return rewards
540
+
541
+
542
+ func _get_done_from_agents(agents: Array = agents_training):
543
+ var dones = []
544
+ for agent in agents:
545
+ var done = agent.get_done()
546
+ if done:
547
+ agent.set_done_false()
548
+ dones.append(done)
549
+ return dones
550
+
551
+
552
+ func _set_agent_actions(actions, agents: Array = all_agents):
553
+ for i in range(len(actions)):
554
+ agents[i].set_action(actions[i])
555
+
556
+
557
+ func clamp_array(arr: Array, min: float, max: float):
558
+ var output: Array = []
559
+ for a in arr:
560
+ output.append(clamp(a, min, max))
561
+ return output
562
+
563
+
564
+ ## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
565
+ func _notification(what):
566
+ if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
567
+ return
568
+
569
+ if what == NOTIFICATION_PREDELETE:
570
+ var json_string = JSON.stringify(demo_trajectories, "", false)
571
+ var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
572
+
573
+ if not file:
574
+ var error: Error = FileAccess.get_open_error()
575
+ assert(not error, "There was an error opening the file: %d" % error)
576
+
577
+ file.store_line(json_string)
578
+ var error = file.get_error()
579
+ assert(not error, "There was an error after trying to write to the file: %d" % error)
assets/flying_platform.glb ADDED
Binary file (38 kB). View file
 
assets/platform.glb ADDED
Binary file (4.41 kB). View file
 
assets/robot.glb ADDED
Binary file (86 kB). View file
 
icon.svg ADDED
license.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ MultiAgent Simple environment made by https://github.com/Ivan-267.
2
+
3
+ The following license is only for the graphical assets in the folder "assets", including .glb format files:
4
+ Author: Ivan Dodic (https://github.com/Ivan-267),
5
+ License: https://creativecommons.org/licenses/by/4.0/
onnx/platform_onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dd705240611b375bf5de8ffbe43adb56ee600685b87120be350513a01bfbb2f
3
+ size 22676
onnx/player_onnx/model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cf3db421d81e88303f449ef57f04408cf652d2cef2b191ea10a25d3d33ad3857
3
+ size 32412
project.godot ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="MultiAgentSimple"
14
+ run/main_scene="res://scenes/training_scene/training_scene.tscn"
15
+ config/features=PackedStringArray("4.3", "C#", "Forward Plus")
16
+ config/icon="res://icon.svg"
17
+
18
+ [dotnet]
19
+
20
+ project/assembly_name="MultiAgentTestEnv"
21
+
22
+ [editor_plugins]
23
+
24
+ enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
25
+
26
+ [global_group]
27
+
28
+ resetable=""
29
+
30
+ [input]
31
+
32
+ platform_left={
33
+ "deadzone": 0.5,
34
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"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,"location":0,"echo":false,"script":null)
35
+ ]
36
+ }
37
+ platform_right={
38
+ "deadzone": 0.5,
39
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"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,"location":0,"echo":false,"script":null)
40
+ ]
41
+ }
42
+ robot_left={
43
+ "deadzone": 0.5,
44
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"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":97,"location":0,"echo":false,"script":null)
45
+ ]
46
+ }
47
+ robot_right={
48
+ "deadzone": 0.5,
49
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"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":100,"location":0,"echo":false,"script":null)
50
+ ]
51
+ }
52
+ robot_forward={
53
+ "deadzone": 0.5,
54
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"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":119,"location":0,"echo":false,"script":null)
55
+ ]
56
+ }
57
+ robot_back={
58
+ "deadzone": 0.5,
59
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"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":115,"location":0,"echo":false,"script":null)
60
+ ]
61
+ }
readme.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MultiAgent Simple Environment
2
+
3
+ https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/0ce8e667-124d-4c99-8136-e139b4a5aaca
4
+
5
+ ## Goal:
6
+
7
+ The robot agent needs to reach the goal (marked by a transparent green square) as many times as possible during the episode. It needs to work together with the platform agent to be able to reach static platforms. Goal position switches to the other static platform after being reached.
8
+
9
+ ### Rewards:
10
+
11
+ All agents (AIController pairs for each batch) receive the same rewards, including:
12
+
13
+ - A negative reward for the robot falling,
14
+ - A positive reward for reaching the goal position,
15
+ - A reward every step based on the change in distance between the robot and the goal (positive for approaching, negative for moving away from).
16
+
17
+ ## Episode end condition:
18
+
19
+ Episodes have a fixed length and end at the same time for all agents.
20
+
21
+ ## Agents:
22
+
23
+ ### Robot:
24
+
25
+ ![robot](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/a046de7d-3714-4593-9fc4-9d9dd8e3054e)
26
+
27
+
28
+ Policy name: `player`
29
+
30
+ ### Actions:
31
+
32
+ Robot has continuous actions for movement in 2 axes.
33
+
34
+ ```python
35
+ func get_action_space() -> Dictionary:
36
+ return {
37
+ "movement": {"size": 2, "action_type": "continuous"},
38
+ }
39
+ ```
40
+
41
+ ### Observations:
42
+
43
+ Robot has a Raycast sensor for observations, and has additional observations including the relative positions of the goal and platform agent, as well as its own and the platform agent’s velocities.
44
+
45
+ ### Platform:
46
+
47
+ ![Platform](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/238aacd4-dcec-4c27-9f0c-f8f409289704)
48
+
49
+ Policy name: `platform`
50
+
51
+ ### Actions:
52
+
53
+ Platform has a single continuous action for movement.
54
+
55
+ ```python
56
+ func get_action_space() -> Dictionary:
57
+ return {
58
+ "movement": {"size": 1, "action_type": "continuous"},
59
+ }
60
+ ```
61
+
62
+ ### Observations:
63
+
64
+ Platform’s observations include the relative positions of the goal and robot agent, as well as its own and the robot agent’s velocities.
65
+
66
+ ### Onnx inference:
67
+
68
+ To run the included trained model, open `res://scenes/testing_scene/testing_scene.tscn` in Godot Editor and press F6.
69
+
70
+ If you want to change the paths to run your own onnx file in a different folder, you can adjust them in `res://scenes/game_scene/game_scene_onnx_inference.tscn` > `PlayerAIController` and `PlatformAIController` inspector properties.
71
+
72
+ ### Training:
73
+
74
+ Training this scene is currently only supported using the [Rllib example](https://github.com/edbeeching/godot_rl_agents/blob/main/examples/rllib_example.py) (`env_is_multiagent` should be set to `true` in the config file, and you can adjust the stopping criteria and other settings as needed).
75
+
76
+ Here are some stats from the session that was used to get the trained onnx model (for testing a single worker / env instance was used and the training time was likely longer than required). Steps are env steps, since there are multiple agents using each policy in the env, there are many more total agent steps than env steps:
77
+
78
+ ![Training stats](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/6b7005aa-ddc4-4f7e-bc7e-4a0d0d1b4c28)
scenes/game_scene/game_scene.tscn ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=8 format=3 uid="uid://tpt7yljsu6ei"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/game_scene/game_scene_manager.gd" id="1_7f2j4"]
4
+ [ext_resource type="PackedScene" uid="uid://byg2il8fbav13" path="res://assets/platform.glb" id="2_1mict"]
5
+ [ext_resource type="PackedScene" uid="uid://bpgscnt6a3c2" path="res://scenes/player/player.tscn" id="3_hmuow"]
6
+ [ext_resource type="PackedScene" uid="uid://u16gxctwsq88" path="res://scenes/platform/platform.tscn" id="4_imy8y"]
7
+ [ext_resource type="PackedScene" uid="uid://duqqne2b1we3x" path="res://scenes/goal/goal.tscn" id="5_j8srg"]
8
+
9
+ [sub_resource type="BoxShape3D" id="BoxShape3D_ajlrv"]
10
+ size = Vector3(4, 1, 4)
11
+
12
+ [sub_resource type="BoxShape3D" id="BoxShape3D_3o3mb"]
13
+ size = Vector3(4, 1, 4)
14
+
15
+ [node name="GameScene" type="Node3D" node_paths=PackedStringArray("AIControllers", "player_goal_spawn_positions")]
16
+ script = ExtResource("1_7f2j4")
17
+ AIControllers = [NodePath("PlayerAIController"), NodePath("PlatformAIController")]
18
+ player_goal_spawn_positions = [NodePath("platform"), NodePath("platform2")]
19
+
20
+ [node name="platform" type="StaticBody3D" parent="."]
21
+
22
+ [node name="platform" parent="platform" instance=ExtResource("2_1mict")]
23
+ transform = Transform3D(2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)
24
+
25
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="platform"]
26
+ shape = SubResource("BoxShape3D_ajlrv")
27
+
28
+ [node name="platform2" type="StaticBody3D" parent="."]
29
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 18, 0, 0)
30
+
31
+ [node name="platform" parent="platform2" instance=ExtResource("2_1mict")]
32
+ transform = Transform3D(2, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0)
33
+
34
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="platform2"]
35
+ shape = SubResource("BoxShape3D_3o3mb")
36
+
37
+ [node name="Goal" parent="." node_paths=PackedStringArray("game_manager", "player_ai_controller") instance=ExtResource("5_j8srg")]
38
+ collision_mask = 2
39
+ monitorable = false
40
+ game_manager = NodePath("..")
41
+ player_ai_controller = NodePath("../PlayerAIController")
42
+
43
+ [node name="PlayerAIController" parent="." node_paths=PackedStringArray("game_manager", "platform_ai_controller", "goal") instance=ExtResource("3_hmuow")]
44
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.6, 0)
45
+ game_manager = NodePath("..")
46
+ platform_ai_controller = NodePath("../PlatformAIController")
47
+ goal = NodePath("../Goal")
48
+ onnx_model_path = ""
49
+
50
+ [node name="PlatformAIController" parent="." node_paths=PackedStringArray("game_manager", "goal", "player_ai_controller") instance=ExtResource("4_imy8y")]
51
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 8.3, 0.362, 0)
52
+ game_manager = NodePath("..")
53
+ goal = NodePath("../Goal")
54
+ player_ai_controller = NodePath("../PlayerAIController")
55
+ onnx_model_path = ""
56
+
57
+ [node name="Camera3D" type="Camera3D" parent="."]
58
+ transform = Transform3D(0.999701, -0.00611733, 0.023654, 0, 0.968148, 0.25038, -0.0244322, -0.250305, 0.967859, 9.475, 6.297, 10.476)
59
+ fov = 64.9
60
+
61
+ [connection signal="body_entered" from="Goal" to="PlayerAIController" method="_on_goal_body_entered"]
scenes/game_scene/game_scene_manager.gd ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name GameSceneManager
3
+
4
+ @export var AIControllers: Array[Node]
5
+
6
+ ## Used by the player and goal to calculate new positions
7
+ @export var player_goal_spawn_positions: Array[Node3D]
8
+
9
+ var resetables: Array
10
+ var steps := 0
11
+ var max_steps := 100
12
+
13
+ ## Value set by training manager
14
+ var training_manager: TrainingManager
15
+
16
+
17
+ func _ready():
18
+ for node in find_children("*"):
19
+ if node.is_in_group("resetable"):
20
+ resetables.append(node)
21
+
22
+
23
+ func reset_game(reward = 0, done = false):
24
+ for agent in AIControllers:
25
+ agent.reward += reward
26
+ if done:
27
+ agent.done = true
28
+ agent.reset()
29
+
30
+ for resetable in resetables:
31
+ resetable.reset()
32
+
33
+
34
+ func set_agents_rewards(reward = 0):
35
+ for agent in AIControllers:
36
+ agent.reward += reward
scenes/game_scene/game_scene_onnx_inference.tscn ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=2 format=3 uid="uid://xomproo2eyut"]
2
+
3
+ [ext_resource type="PackedScene" uid="uid://tpt7yljsu6ei" path="res://scenes/game_scene/game_scene.tscn" id="1_eys64"]
4
+
5
+ [node name="GameScene" node_paths=PackedStringArray("AIControllers", "player_goal_spawn_positions") instance=ExtResource("1_eys64")]
6
+ AIControllers = [NodePath("PlayerAIController"), NodePath("PlatformAIController")]
7
+ player_goal_spawn_positions = [NodePath("platform"), NodePath("platform2")]
8
+
9
+ [node name="Goal" parent="." index="2" node_paths=PackedStringArray("game_manager", "player_ai_controller")]
10
+ game_manager = NodePath("..")
11
+ player_ai_controller = NodePath("../PlayerAIController")
12
+
13
+ [node name="PlayerAIController" parent="." index="3" node_paths=PackedStringArray("game_manager", "platform_ai_controller", "goal")]
14
+ game_manager = NodePath("..")
15
+ platform_ai_controller = NodePath("../PlatformAIController")
16
+ goal = NodePath("../Goal")
17
+ control_mode = 3
18
+ onnx_model_path = "onnx\\player_onnx\\model.onnx"
19
+
20
+ [node name="PlatformAIController" parent="." index="4" node_paths=PackedStringArray("game_manager", "goal", "player_ai_controller")]
21
+ game_manager = NodePath("..")
22
+ goal = NodePath("../Goal")
23
+ player_ai_controller = NodePath("../PlayerAIController")
24
+ control_mode = 3
25
+ onnx_model_path = "onnx\\platform_onnx\\model.onnx"
scenes/goal/goal.gd ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Area3D
2
+ class_name Goal
3
+
4
+ @onready var initial_position = global_position
5
+ @export var game_manager: GameSceneManager
6
+ @export var player_ai_controller: PlayerAIController
7
+
8
+ ## Nodes that this goal will spawn on (it will reset to the platform that has the largest distance from the player)
9
+ @onready var spawn_positions := game_manager.player_goal_spawn_positions
10
+
11
+
12
+ func reset():
13
+ await get_tree().physics_frame # Wait a physics frame before moving to avoid detecting player on reset
14
+ var farthest_distance: float = 0.0
15
+ var farthest_node: Node3D
16
+ for node in spawn_positions:
17
+ var distance = node.global_position.distance_squared_to(
18
+ player_ai_controller.player.global_position
19
+ )
20
+ if distance > farthest_distance:
21
+ farthest_distance = distance
22
+ farthest_node = node
23
+ global_position = farthest_node.global_position + Vector3.UP * 1.5
scenes/goal/goal.tscn ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=5 format=3 uid="uid://duqqne2b1we3x"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/goal/goal.gd" id="1_k3tuu"]
4
+
5
+ [sub_resource type="BoxShape3D" id="BoxShape3D_n45yr"]
6
+ size = Vector3(1, 2, 1)
7
+
8
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_hko7p"]
9
+ transparency = 1
10
+ albedo_color = Color(0, 1, 0, 0.282353)
11
+
12
+ [sub_resource type="BoxMesh" id="BoxMesh_myqp0"]
13
+ material = SubResource("StandardMaterial3D_hko7p")
14
+ size = Vector3(1, 2, 1)
15
+
16
+ [node name="Goal" type="Area3D" node_paths=PackedStringArray("game_manager", "player") groups=["resetable"]]
17
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 18, 1.5, 0)
18
+ collision_layer = 0
19
+ script = ExtResource("1_k3tuu")
20
+ game_manager = NodePath("")
21
+ player = NodePath("")
22
+
23
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="."]
24
+ shape = SubResource("BoxShape3D_n45yr")
25
+
26
+ [node name="MeshInstance3D" type="MeshInstance3D" parent="."]
27
+ mesh = SubResource("BoxMesh_myqp0")
28
+ skeleton = NodePath("../..")
scenes/platform/platform.gd ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends CharacterBody3D
2
+ class_name Platform
3
+
4
+ @export var speed := 8.0
5
+ # Visual rotation speed of the propeller
6
+ @export var propeller_rotation_speed := 1.0
7
+
8
+ @onready var propeller = $flying_platform/flying_platform/Torus/propeller
9
+
10
+ var requested_movement: float
11
+
12
+
13
+ func _physics_process(delta: float) -> void:
14
+ velocity = Vector3.RIGHT * requested_movement * speed
15
+ move_and_slide()
16
+ propeller.rotate_object_local(Vector3.UP, propeller_rotation_speed * speed)
scenes/platform/platform.tscn ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=5 format=3 uid="uid://u16gxctwsq88"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/platform/platform_ai_controller.gd" id="1_u84vt"]
4
+ [ext_resource type="Script" path="res://scenes/platform/platform.gd" id="2_6qscy"]
5
+ [ext_resource type="PackedScene" uid="uid://b8k5wlite2uag" path="res://assets/flying_platform.glb" id="3_pn8gp"]
6
+
7
+ [sub_resource type="BoxShape3D" id="BoxShape3D_xu28c"]
8
+ size = Vector3(3.8, 0.5, 3)
9
+
10
+ [node name="PlatformAIController" type="Node3D"]
11
+ script = ExtResource("1_u84vt")
12
+ policy_name = "platform"
13
+
14
+ [node name="Platform" type="CharacterBody3D" parent="."]
15
+ collision_mask = 3
16
+ axis_lock_linear_y = true
17
+ motion_mode = 1
18
+ wall_min_slide_angle = 0.0523599
19
+ script = ExtResource("2_6qscy")
20
+
21
+ [node name="flying_platform" parent="Platform" instance=ExtResource("3_pn8gp")]
22
+
23
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="Platform"]
24
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.110486, 0)
25
+ shape = SubResource("BoxShape3D_xu28c")
scenes/platform/platform_ai_controller.gd ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends AIController3D
2
+ class_name PlatformAIController
3
+
4
+ @export var game_manager: GameSceneManager
5
+ @export var goal: Goal
6
+ @export var player_ai_controller: PlayerAIController
7
+
8
+ @onready var platform: Platform = $Platform
9
+ @onready var initial_position = position
10
+
11
+
12
+ func get_obs() -> Dictionary:
13
+ var obs: Array
14
+ var goal_relative = (platform.to_local(goal.global_position) / 20.0).limit_length(1.0)
15
+ var player_relative = (
16
+ (platform.to_local(player_ai_controller.player.global_position) / 10.0).limit_length(1.0)
17
+ )
18
+
19
+ var platform_velocity = platform.velocity.limit_length(platform.speed) / platform.speed
20
+ var player_speed = player_ai_controller.player.speed
21
+ var player_velocity = player_ai_controller.player.velocity.limit_length(player_speed) / player_speed
22
+ obs.append_array(
23
+ [
24
+ goal_relative.x,
25
+ goal_relative.y,
26
+ goal_relative.z,
27
+ player_relative.x,
28
+ player_relative.y,
29
+ player_relative.z,
30
+ platform_velocity.x,
31
+ platform_velocity.y,
32
+ platform_velocity.z,
33
+ player_velocity.x,
34
+ player_velocity.y,
35
+ player_velocity.z
36
+ ]
37
+ )
38
+ return {"obs": obs}
39
+
40
+
41
+ func get_reward() -> float:
42
+ return reward
43
+
44
+
45
+ func get_action_space() -> Dictionary:
46
+ return {
47
+ "movement": {"size": 1, "action_type": "continuous"},
48
+ }
49
+
50
+
51
+ func _physics_process(delta: float) -> void:
52
+ super._physics_process(delta)
53
+ if heuristic == "human":
54
+ set_action()
55
+
56
+
57
+ func set_action(action = null) -> void:
58
+ if action == null:
59
+ platform.requested_movement = (
60
+ Input.get_action_strength("platform_right") - Input.get_action_strength("platform_left")
61
+ )
62
+ return
63
+
64
+ platform.requested_movement = clamp(action.movement[0], -1.0, 1.0)
65
+
66
+
67
+ func reset():
68
+ super.reset()
69
+ position = position
70
+ platform.position = Vector3.ZERO
71
+ platform.velocity = Vector3.ZERO
scenes/player/player.gd ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends CharacterBody3D
2
+ class_name Player
3
+
4
+ @export var speed = 3.0
5
+ @export var gravity_strength = 10.0
6
+ @export var visual_rotation_update_speed = 8.0
7
+ @export var wheels: Array[Node3D]
8
+
9
+ var requested_movement: Vector2
10
+ var requested_jump: bool
11
+
12
+ @onready var robot_visual = $robot
13
+
14
+ ## Value set by AIController
15
+ var game_manager: GameSceneManager
16
+ var last_movement_direction: Vector3
17
+
18
+
19
+ func _physics_process(delta: float) -> void:
20
+ if global_position.y < -5:
21
+ game_manager.reset_game(-5, false)
22
+
23
+ if not is_on_floor():
24
+ velocity += Vector3.DOWN * gravity_strength * delta
25
+
26
+ velocity.x = requested_movement.x * speed
27
+ velocity.z = requested_movement.y * speed
28
+
29
+ if velocity:
30
+ last_movement_direction = Vector3(requested_movement.x, 0, requested_movement.y)
31
+
32
+ _update_visual_rotation(delta)
33
+ _update_wheels_rotation(delta)
34
+ move_and_slide()
35
+
36
+
37
+ func _update_visual_rotation(delta):
38
+ var direction: Vector3 = last_movement_direction
39
+
40
+ if direction:
41
+ var target_basis := Basis.looking_at(direction)
42
+ robot_visual.global_basis = robot_visual.global_basis.orthonormalized().slerp(
43
+ target_basis, delta * visual_rotation_update_speed
44
+ )
45
+
46
+
47
+ func _update_wheels_rotation(delta):
48
+ var movement := Vector2(requested_movement.x, requested_movement.y).length()
49
+ for wheel in wheels:
50
+ wheel.rotate_object_local(Vector3.LEFT, movement * speed * delta * 2.0)
scenes/player/player.tscn ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=6 format=3 uid="uid://bpgscnt6a3c2"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/player/player_ai_controller.gd" id="1_chk3m"]
4
+ [ext_resource type="Script" path="res://scenes/player/player.gd" id="2_fh5nj"]
5
+ [ext_resource type="PackedScene" uid="uid://doqudr33pr7we" path="res://assets/robot.glb" id="3_lvsyl"]
6
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="4_bgl3b"]
7
+
8
+ [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_uiics"]
9
+ radius = 0.67
10
+ height = 1.981
11
+
12
+ [node name="PlayerAIController" type="Node3D"]
13
+ script = ExtResource("1_chk3m")
14
+ policy_name = "player"
15
+
16
+ [node name="Player" type="CharacterBody3D" parent="." node_paths=PackedStringArray("wheels")]
17
+ collision_layer = 2
18
+ collision_mask = 3
19
+ script = ExtResource("2_fh5nj")
20
+ speed = 5.0
21
+ visual_rotation_update_speed = 5.0
22
+ wheels = [NodePath("robot/Wheel_001"), NodePath("robot/Wheel")]
23
+
24
+ [node name="robot" parent="Player" instance=ExtResource("3_lvsyl")]
25
+ transform = Transform3D(-4.37114e-08, 0, -1, 0, 1, 0, 1, 0, -4.37114e-08, 0, -0.608908, 0)
26
+
27
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="Player"]
28
+ shape = SubResource("CapsuleShape3D_uiics")
29
+
30
+ [node name="RayCastSensor3D" type="Node3D" parent="Player"]
31
+ transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 1, 0)
32
+ script = ExtResource("4_bgl3b")
33
+ ray_length = 8.0
34
+ cone_width = 160.0
35
+ cone_height = 160.0
36
+
37
+ [node name="@RayCast3D@69341" type="RayCast3D" parent="Player/RayCastSensor3D"]
38
+ target_position = Vector3(-2.90949, -7.34573, 1.25503)
39
+
40
+ [node name="@RayCast3D@69342" type="RayCast3D" parent="Player/RayCastSensor3D"]
41
+ target_position = Vector3(-5.62715, -5.1423, 2.42732)
42
+
43
+ [node name="@RayCast3D@69343" type="RayCast3D" parent="Player/RayCastSensor3D"]
44
+ target_position = Vector3(-7.14772, -1.84493, 3.08323)
45
+
46
+ [node name="@RayCast3D@69344" type="RayCast3D" parent="Player/RayCastSensor3D"]
47
+ target_position = Vector3(-7.14772, 1.84493, 3.08323)
48
+
49
+ [node name="@RayCast3D@69345" type="RayCast3D" parent="Player/RayCastSensor3D"]
50
+ target_position = Vector3(-5.62715, 5.1423, 2.42732)
51
+
52
+ [node name="@RayCast3D@69346" type="RayCast3D" parent="Player/RayCastSensor3D"]
53
+ target_position = Vector3(-2.90949, 7.34573, 1.25503)
54
+
55
+ [node name="@RayCast3D@69347" type="RayCast3D" parent="Player/RayCastSensor3D"]
56
+ target_position = Vector3(-2.03676, -7.34573, 2.42732)
57
+
58
+ [node name="@RayCast3D@69348" type="RayCast3D" parent="Player/RayCastSensor3D"]
59
+ target_position = Vector3(-3.93923, -5.1423, 4.69459)
60
+
61
+ [node name="@RayCast3D@69349" type="RayCast3D" parent="Player/RayCastSensor3D"]
62
+ target_position = Vector3(-5.00369, -1.84493, 5.96316)
63
+
64
+ [node name="@RayCast3D@69350" type="RayCast3D" parent="Player/RayCastSensor3D"]
65
+ target_position = Vector3(-5.00369, 1.84493, 5.96316)
66
+
67
+ [node name="@RayCast3D@69351" type="RayCast3D" parent="Player/RayCastSensor3D"]
68
+ target_position = Vector3(-3.93923, 5.1423, 4.69459)
69
+
70
+ [node name="@RayCast3D@69352" type="RayCast3D" parent="Player/RayCastSensor3D"]
71
+ target_position = Vector3(-2.03676, 7.34573, 2.42732)
72
+
73
+ [node name="@RayCast3D@69353" type="RayCast3D" parent="Player/RayCastSensor3D"]
74
+ target_position = Vector3(-0.730738, -7.34573, 3.08323)
75
+
76
+ [node name="@RayCast3D@69354" type="RayCast3D" parent="Player/RayCastSensor3D"]
77
+ target_position = Vector3(-1.4133, -5.1423, 5.96316)
78
+
79
+ [node name="@RayCast3D@69355" type="RayCast3D" parent="Player/RayCastSensor3D"]
80
+ target_position = Vector3(-1.7952, -1.84493, 7.57453)
81
+
82
+ [node name="@RayCast3D@69356" type="RayCast3D" parent="Player/RayCastSensor3D"]
83
+ target_position = Vector3(-1.7952, 1.84493, 7.57453)
84
+
85
+ [node name="@RayCast3D@69357" type="RayCast3D" parent="Player/RayCastSensor3D"]
86
+ target_position = Vector3(-1.4133, 5.1423, 5.96316)
87
+
88
+ [node name="@RayCast3D@69358" type="RayCast3D" parent="Player/RayCastSensor3D"]
89
+ target_position = Vector3(-0.730738, 7.34573, 3.08323)
90
+
91
+ [node name="node_3 0" type="RayCast3D" parent="Player/RayCastSensor3D"]
92
+ target_position = Vector3(0.730738, -7.34573, 3.08323)
93
+
94
+ [node name="node_3 1" type="RayCast3D" parent="Player/RayCastSensor3D"]
95
+ target_position = Vector3(1.4133, -5.1423, 5.96316)
96
+
97
+ [node name="node_3 2" type="RayCast3D" parent="Player/RayCastSensor3D"]
98
+ target_position = Vector3(1.7952, -1.84493, 7.57453)
99
+
100
+ [node name="@RayCast3D@69359" type="RayCast3D" parent="Player/RayCastSensor3D"]
101
+ target_position = Vector3(1.7952, 1.84493, 7.57453)
102
+
103
+ [node name="@RayCast3D@69360" type="RayCast3D" parent="Player/RayCastSensor3D"]
104
+ target_position = Vector3(1.4133, 5.1423, 5.96316)
105
+
106
+ [node name="@RayCast3D@69361" type="RayCast3D" parent="Player/RayCastSensor3D"]
107
+ target_position = Vector3(0.730738, 7.34573, 3.08323)
108
+
109
+ [node name="node_4 0" type="RayCast3D" parent="Player/RayCastSensor3D"]
110
+ target_position = Vector3(2.03676, -7.34573, 2.42732)
111
+
112
+ [node name="node_4 1" type="RayCast3D" parent="Player/RayCastSensor3D"]
113
+ target_position = Vector3(3.93923, -5.1423, 4.69459)
114
+
115
+ [node name="node_4 2" type="RayCast3D" parent="Player/RayCastSensor3D"]
116
+ target_position = Vector3(5.00369, -1.84493, 5.96316)
117
+
118
+ [node name="@RayCast3D@69362" type="RayCast3D" parent="Player/RayCastSensor3D"]
119
+ target_position = Vector3(5.00369, 1.84493, 5.96316)
120
+
121
+ [node name="@RayCast3D@69363" type="RayCast3D" parent="Player/RayCastSensor3D"]
122
+ target_position = Vector3(3.93923, 5.1423, 4.69459)
123
+
124
+ [node name="@RayCast3D@69364" type="RayCast3D" parent="Player/RayCastSensor3D"]
125
+ target_position = Vector3(2.03676, 7.34573, 2.42732)
126
+
127
+ [node name="node_5 0" type="RayCast3D" parent="Player/RayCastSensor3D"]
128
+ target_position = Vector3(2.90949, -7.34573, 1.25503)
129
+
130
+ [node name="node_5 1" type="RayCast3D" parent="Player/RayCastSensor3D"]
131
+ target_position = Vector3(5.62715, -5.1423, 2.42732)
132
+
133
+ [node name="node_5 2" type="RayCast3D" parent="Player/RayCastSensor3D"]
134
+ target_position = Vector3(7.14772, -1.84493, 3.08323)
135
+
136
+ [node name="@RayCast3D@69365" type="RayCast3D" parent="Player/RayCastSensor3D"]
137
+ target_position = Vector3(7.14772, 1.84493, 3.08323)
138
+
139
+ [node name="@RayCast3D@69366" type="RayCast3D" parent="Player/RayCastSensor3D"]
140
+ target_position = Vector3(5.62715, 5.1423, 2.42732)
141
+
142
+ [node name="@RayCast3D@69367" type="RayCast3D" parent="Player/RayCastSensor3D"]
143
+ target_position = Vector3(2.90949, 7.34573, 1.25503)
144
+
145
+ [editable path="Player/robot"]
scenes/player/player_ai_controller.gd ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends AIController3D
2
+ class_name PlayerAIController
3
+
4
+ @export var game_manager: GameSceneManager
5
+ @export var platform_ai_controller: PlatformAIController
6
+ @export var goal: Goal
7
+
8
+ @onready var player: Player = $Player
9
+ @onready var raycast_sensor = $Player/RayCastSensor3D
10
+ @onready var spawn_positions = game_manager.player_goal_spawn_positions
11
+
12
+ var previous_distance_to_goal
13
+
14
+
15
+ func _ready():
16
+ super._ready()
17
+ player.game_manager = game_manager
18
+
19
+
20
+ func get_obs() -> Dictionary:
21
+ var obs: Array
22
+ obs.append_array(raycast_sensor.get_observation())
23
+ var platform: Platform = platform_ai_controller.platform
24
+ var platform_relative = (player.to_local(platform.global_position) / 10.0).limit_length(1.0)
25
+ var goal_relative = (player.to_local(goal.global_position) / 20.0).limit_length(1.0)
26
+
27
+ var player_velocity = player.velocity.limit_length(player.speed) / player.speed
28
+ var platform_velocity = platform.velocity.limit_length(platform.speed) / platform.speed
29
+
30
+ obs.append_array(
31
+ [
32
+ goal_relative.x,
33
+ goal_relative.y,
34
+ goal_relative.z,
35
+ platform_relative.x,
36
+ platform_relative.y,
37
+ platform_relative.z,
38
+ player_velocity.x,
39
+ player_velocity.y,
40
+ player_velocity.z,
41
+ platform_velocity.x,
42
+ platform_velocity.y,
43
+ platform_velocity.z
44
+ ]
45
+ )
46
+
47
+ return {"obs": obs}
48
+
49
+
50
+ func get_reward() -> float:
51
+ var distance_to_goal = player.global_position.distance_to(goal.global_position)
52
+
53
+ if not previous_distance_to_goal:
54
+ previous_distance_to_goal = distance_to_goal
55
+
56
+ #if distance_to_goal < previous_distance_to_goal:
57
+ game_manager.set_agents_rewards(previous_distance_to_goal - distance_to_goal)
58
+ previous_distance_to_goal = distance_to_goal
59
+
60
+ return reward
61
+
62
+
63
+ func reset():
64
+ super.reset()
65
+ previous_distance_to_goal = null
66
+
67
+ global_position = spawn_positions.pick_random().global_position + Vector3.UP * 1.5
68
+ player.position = Vector3.ZERO
69
+ player.velocity = Vector3.ZERO
70
+
71
+
72
+ func get_action_space() -> Dictionary:
73
+ return {
74
+ "movement": {"size": 2, "action_type": "continuous"},
75
+ }
76
+
77
+
78
+ func _physics_process(delta: float) -> void:
79
+ super._physics_process(delta)
80
+ if heuristic == "human":
81
+ set_action()
82
+
83
+
84
+ func set_action(action = null) -> void:
85
+ if action == null:
86
+ player.requested_movement = Input.get_vector(
87
+ "robot_left", "robot_right", "robot_forward", "robot_back"
88
+ )
89
+ return
90
+
91
+ player.requested_movement = Vector2(
92
+ clamp(action.movement[0], -1.0, 1.0), clamp(action.movement[1], -1.0, 1.0)
93
+ )
94
+
95
+
96
+ func _on_goal_body_entered(body: Node3D) -> void:
97
+ if body is Player:
98
+ goal.reset()
99
+ game_manager.set_agents_rewards(5)
100
+ previous_distance_to_goal = null
scenes/testing_scene/testing_scene.tscn ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=7 format=3 uid="uid://n5fft12lumgd"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/training_scene/training_manager.gd" id="1_1k23j"]
4
+ [ext_resource type="PackedScene" uid="uid://xomproo2eyut" path="res://scenes/game_scene/game_scene_onnx_inference.tscn" id="2_u86wc"]
5
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="3_p180x"]
6
+
7
+ [sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_riw1h"]
8
+ sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
9
+ ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
10
+
11
+ [sub_resource type="Sky" id="Sky_qx0n5"]
12
+ sky_material = SubResource("ProceduralSkyMaterial_riw1h")
13
+
14
+ [sub_resource type="Environment" id="Environment_b3cgd"]
15
+ background_mode = 2
16
+ sky = SubResource("Sky_qx0n5")
17
+ tonemap_mode = 2
18
+ glow_enabled = true
19
+
20
+ [node name="TestingScene" type="Node3D"]
21
+ script = ExtResource("1_1k23j")
22
+ reset_after_steps = 1800
23
+ game_scene_to_instantiate = ExtResource("2_u86wc")
24
+ scene_count = 3
25
+ offset_between_scenes = Vector3(0, 0, -20)
26
+
27
+ [node name="Sync" type="Node" parent="."]
28
+ script = ExtResource("3_p180x")
29
+
30
+ [node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
31
+ transform = Transform3D(-0.866023, -0.433016, 0.250001, 0, 0.499998, 0.866027, -0.500003, 0.749999, -0.43301, 0, 0, 0)
32
+ shadow_enabled = true
33
+
34
+ [node name="WorldEnvironment" type="WorldEnvironment" parent="."]
35
+ environment = SubResource("Environment_b3cgd")
scenes/training_scene/training_manager.gd ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name TrainingManager
3
+
4
+ ## Manages multiple GameScenes.
5
+
6
+ ## Resets all game scenes at this many steps and ends episode
7
+ @export var reset_after_steps := 300
8
+
9
+ @export var game_scene_to_instantiate: PackedScene
10
+ @export var scene_count: int = 8
11
+ @export var offset_between_scenes: Vector3
12
+
13
+ # Physics steps since game started
14
+ var _steps := 0
15
+
16
+ var _game_scenes: Array[GameSceneManager]
17
+
18
+
19
+ func _ready():
20
+ var current_position = offset_between_scenes
21
+ for i in range(0, scene_count):
22
+ var new_instance = game_scene_to_instantiate.instantiate() as GameSceneManager
23
+ add_child(new_instance, true)
24
+ new_instance.training_manager = self
25
+ new_instance.global_position += current_position
26
+ current_position += offset_between_scenes
27
+ new_instance.reset_game(0, false) # Reset game initially to randomize positions
28
+ _game_scenes.append(new_instance)
29
+
30
+
31
+ func _physics_process(delta: float) -> void:
32
+ _steps += 1
33
+ if _steps > reset_after_steps:
34
+ for game_scene in _game_scenes:
35
+ game_scene.reset_game(0, true)
36
+ _steps = 0