jtatman commited on
Commit
2952f21
1 Parent(s): 1db0140

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. README.md +25 -0
  2. SimpleReachGoal/CSharp/.gitattributes +2 -0
  3. SimpleReachGoal/CSharp/.gitignore +3 -0
  4. SimpleReachGoal/CSharp/SimpleReachGoal.csproj +11 -0
  5. SimpleReachGoal/CSharp/SimpleReachGoal.onnx +3 -0
  6. SimpleReachGoal/CSharp/SimpleReachGoal.sln +19 -0
  7. SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_2d.gd +118 -0
  8. SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_3d.gd +117 -0
  9. SimpleReachGoal/CSharp/addons/godot_rl_agents/godot_rl_agents.gd +16 -0
  10. SimpleReachGoal/CSharp/addons/godot_rl_agents/icon.png +3 -0
  11. SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +103 -0
  12. SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
  13. SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
  14. SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml +29 -0
  15. SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd +27 -0
  16. SimpleReachGoal/CSharp/addons/godot_rl_agents/plugin.cfg +7 -0
  17. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn +48 -0
  18. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd +235 -0
  19. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd +25 -0
  20. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd +118 -0
  21. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn +7 -0
  22. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn +6 -0
  23. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd +258 -0
  24. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd +25 -0
  25. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd +21 -0
  26. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn +41 -0
  27. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd +185 -0
  28. SimpleReachGoal/CSharp/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn +27 -0
  29. SimpleReachGoal/CSharp/addons/godot_rl_agents/sync.gd +548 -0
  30. SimpleReachGoal/CSharp/icon.svg +1 -0
  31. SimpleReachGoal/CSharp/project.godot +24 -0
  32. SimpleReachGoal/CSharp/scenes/game_scene/AreaPositionRandomizer.cs +31 -0
  33. SimpleReachGoal/CSharp/scenes/game_scene/GameSceneManager.cs +24 -0
  34. SimpleReachGoal/CSharp/scenes/game_scene/game_scene.tscn +190 -0
  35. SimpleReachGoal/CSharp/scenes/player/Player.cs +92 -0
  36. SimpleReachGoal/CSharp/scenes/player/player.tscn +497 -0
  37. SimpleReachGoal/CSharp/scenes/player/player_ai_controller.gd +48 -0
  38. SimpleReachGoal/CSharp/scenes/training_scene/training_scene.tscn +83 -0
  39. SimpleReachGoal/CSharpAll/.gitattributes +2 -0
  40. SimpleReachGoal/CSharpAll/.gitignore +3 -0
  41. SimpleReachGoal/CSharpAll/SimpleReachGoal.csproj +11 -0
  42. SimpleReachGoal/CSharpAll/SimpleReachGoal.onnx +3 -0
  43. SimpleReachGoal/CSharpAll/SimpleReachGoal.sln +19 -0
  44. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_2d.gd +118 -0
  45. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_3d.gd +117 -0
  46. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/godot_rl_agents.gd +16 -0
  47. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/icon.png +3 -0
  48. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +103 -0
  49. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
  50. SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
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 TestExamples 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_TestExamples
22
+ ```
23
+
24
+
25
+
SimpleReachGoal/CSharp/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Normalize EOL for all files that Git considers text files.
2
+ * text=auto eol=lf
SimpleReachGoal/CSharp/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Godot 4+ specific ignores
2
+ .godot/
3
+ android/
SimpleReachGoal/CSharp/SimpleReachGoal.csproj ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Godot.NET.Sdk/4.3.0-dev.5">
2
+ <PropertyGroup>
3
+ <TargetFramework>net6.0</TargetFramework>
4
+ <TargetFramework Condition=" '$(GodotTargetPlatform)' == 'android' ">net7.0</TargetFramework>
5
+ <TargetFramework Condition=" '$(GodotTargetPlatform)' == 'ios' ">net8.0</TargetFramework>
6
+ <EnableDynamicLoading>true</EnableDynamicLoading>
7
+ </PropertyGroup>
8
+ <ItemGroup>
9
+ <PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.15.1" />
10
+ </ItemGroup>
11
+ </Project>
SimpleReachGoal/CSharp/SimpleReachGoal.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80cdcca6356a62cf997e3f18777c799ca930b53236f4fb2e911edec5c6c78838
3
+ size 40656
SimpleReachGoal/CSharp/SimpleReachGoal.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}") = "SimpleReachGoal", "SimpleReachGoal.csproj", "{8B1C40FD-E462-48E5-B273-A0E360A0580B}"
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
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.Build.0 = Debug|Any CPU
14
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
15
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
16
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
17
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
18
+ EndGlobalSection
19
+ EndGlobal
SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_2d.gd ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+ class_name AIController2D
3
+
4
+ enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
5
+ @export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
6
+ @export var onnx_model_path := ""
7
+ @export var reset_after := 1000
8
+
9
+ @export_group("Record expert demos mode options")
10
+ ## Path where the demos will be saved. The file can later be used for imitation learning.
11
+ @export var expert_demo_save_path: String
12
+ ## The action that erases the last recorded episode from the currently recorded data.
13
+ @export var remove_last_episode_key: InputEvent
14
+ ## Action will be repeated for n frames. Will introduce control lag if larger than 1.
15
+ ## Can be used to ensure that action_repeat on inference and training matches
16
+ ## the recorded demonstrations.
17
+ @export var action_repeat: int = 1
18
+
19
+ var onnx_model: ONNXModel
20
+
21
+ var heuristic := "human"
22
+ var done := false
23
+ var reward := 0.0
24
+ var n_steps := 0
25
+ var needs_reset := false
26
+
27
+ var _player: Node2D
28
+
29
+
30
+ func _ready():
31
+ add_to_group("AGENT")
32
+
33
+
34
+ func init(player: Node2D):
35
+ _player = player
36
+
37
+
38
+ #-- Methods that need implementing using the "extend script" option in Godot --#
39
+ func get_obs() -> Dictionary:
40
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
41
+ return {"obs": []}
42
+
43
+
44
+ func get_reward() -> float:
45
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
46
+ return 0.0
47
+
48
+
49
+ func get_action_space() -> Dictionary:
50
+ assert(
51
+ false,
52
+ "the get get_action_space method is not implemented when extending from ai_controller"
53
+ )
54
+ return {
55
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
56
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
57
+ }
58
+
59
+
60
+ func set_action(action) -> void:
61
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
62
+
63
+
64
+ #-----------------------------------------------------------------------------#
65
+
66
+
67
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
68
+ # Only needed if you are recording expert demos with this AIController
69
+ func get_action() -> Array:
70
+ assert(
71
+ false,
72
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
73
+ )
74
+ return []
75
+
76
+
77
+ # -----------------------------------------------------------------------------#
78
+
79
+
80
+ func _physics_process(delta):
81
+ n_steps += 1
82
+ if n_steps > reset_after:
83
+ needs_reset = true
84
+
85
+
86
+ func get_obs_space():
87
+ # may need overriding if the obs space is complex
88
+ var obs = get_obs()
89
+ return {
90
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
91
+ }
92
+
93
+
94
+ func reset():
95
+ n_steps = 0
96
+ needs_reset = false
97
+
98
+
99
+ func reset_if_done():
100
+ if done:
101
+ reset()
102
+
103
+
104
+ func set_heuristic(h):
105
+ # sets the heuristic from "human" or "model" nothing to change here
106
+ heuristic = h
107
+
108
+
109
+ func get_done():
110
+ return done
111
+
112
+
113
+ func set_done_false():
114
+ done = false
115
+
116
+
117
+ func zero_reward():
118
+ reward = 0.0
SimpleReachGoal/CSharp/addons/godot_rl_agents/controller/ai_controller_3d.gd ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name AIController3D
3
+
4
+ enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
5
+ @export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
6
+ @export var onnx_model_path := ""
7
+ @export var reset_after := 1000
8
+
9
+ @export_group("Record expert demos mode options")
10
+ ## Path where the demos will be saved. The file can later be used for imitation learning.
11
+ @export var expert_demo_save_path: String
12
+ ## The action that erases the last recorded episode from the currently recorded data.
13
+ @export var remove_last_episode_key: InputEvent
14
+ ## Action will be repeated for n frames. Will introduce control lag if larger than 1.
15
+ ## Can be used to ensure that action_repeat on inference and training matches
16
+ ## the recorded demonstrations.
17
+ @export var action_repeat: int = 1
18
+
19
+ var onnx_model: ONNXModel
20
+
21
+ var heuristic := "human"
22
+ var done := false
23
+ var reward := 0.0
24
+ var n_steps := 0
25
+ var needs_reset := false
26
+
27
+ var _player: Node3D
28
+
29
+
30
+ func _ready():
31
+ add_to_group("AGENT")
32
+
33
+
34
+ func init(player: Node3D):
35
+ _player = player
36
+
37
+
38
+ #-- Methods that need implementing using the "extend script" option in Godot --#
39
+ func get_obs() -> Dictionary:
40
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
41
+ return {"obs": []}
42
+
43
+
44
+ func get_reward() -> float:
45
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
46
+ return 0.0
47
+
48
+
49
+ func get_action_space() -> Dictionary:
50
+ assert(
51
+ false, "the get_action_space method is not implemented when extending from ai_controller"
52
+ )
53
+ return {
54
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
55
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
56
+ }
57
+
58
+
59
+ func set_action(action) -> void:
60
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
61
+
62
+
63
+ #-----------------------------------------------------------------------------#
64
+
65
+
66
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
67
+ # Only needed if you are recording expert demos with this AIController
68
+ func get_action() -> Array:
69
+ assert(
70
+ false,
71
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
72
+ )
73
+ return []
74
+
75
+
76
+ # -----------------------------------------------------------------------------#
77
+
78
+
79
+ func _physics_process(delta):
80
+ n_steps += 1
81
+ if n_steps > reset_after:
82
+ needs_reset = true
83
+
84
+
85
+ func get_obs_space():
86
+ # may need overriding if the obs space is complex
87
+ var obs = get_obs()
88
+ return {
89
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
90
+ }
91
+
92
+
93
+ func reset():
94
+ n_steps = 0
95
+ needs_reset = false
96
+
97
+
98
+ func reset_if_done():
99
+ if done:
100
+ reset()
101
+
102
+
103
+ func set_heuristic(h):
104
+ # sets the heuristic from "human" or "model" nothing to change here
105
+ heuristic = h
106
+
107
+
108
+ func get_done():
109
+ return done
110
+
111
+
112
+ func set_done_false():
113
+ done = false
114
+
115
+
116
+ func zero_reward():
117
+ reward = 0.0
SimpleReachGoal/CSharp/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")
SimpleReachGoal/CSharp/addons/godot_rl_agents/icon.png ADDED

Git LFS Details

  • SHA256: e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
  • Pointer size: 128 Bytes
  • Size of remote file: 198 Bytes
SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using Microsoft.ML.OnnxRuntime;
3
+ using Microsoft.ML.OnnxRuntime.Tensors;
4
+ using System.Collections.Generic;
5
+ using System.Linq;
6
+
7
+ namespace GodotONNX
8
+ {
9
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
10
+ public partial class ONNXInference : GodotObject
11
+ {
12
+
13
+ private InferenceSession session;
14
+ /// <summary>
15
+ /// Path to the ONNX model. Use Initialize to change it.
16
+ /// </summary>
17
+ private string modelPath;
18
+ private int batchSize;
19
+
20
+ private SessionOptions SessionOpt;
21
+
22
+ //init function
23
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Initialize/*'/>
24
+ public void Initialize(string Path, int BatchSize)
25
+ {
26
+ modelPath = Path;
27
+ batchSize = BatchSize;
28
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
29
+ session = LoadModel(modelPath);
30
+
31
+ }
32
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
33
+ public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
34
+ {
35
+ //Current model: Any (Godot Rl Agents)
36
+ //Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
37
+
38
+ //Fill the input tensors
39
+ // create span from inputSize
40
+ var span = new float[obs.Count]; //There's probably a better way to do this
41
+ for (int i = 0; i < obs.Count; i++)
42
+ {
43
+ span[i] = obs[i];
44
+ }
45
+
46
+ IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
47
+ {
48
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
49
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
50
+ };
51
+ IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
52
+
53
+ IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
54
+ //We do not use "using" here so we get a better exception explaination later
55
+ try
56
+ {
57
+ results = session.Run(inputs, outputNames);
58
+ }
59
+ catch (OnnxRuntimeException e)
60
+ {
61
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
62
+ GD.Print("Error at inference: ", e);
63
+ return null;
64
+ }
65
+ //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
66
+ Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
67
+ DisposableNamedOnnxValue output1 = results.First();
68
+ DisposableNamedOnnxValue output2 = results.Last();
69
+ Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
70
+ Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
71
+
72
+ foreach (float f in output1.AsEnumerable<float>())
73
+ {
74
+ output1Array.Add(f);
75
+ }
76
+
77
+ foreach (float f in output2.AsEnumerable<float>())
78
+ {
79
+ output2Array.Add(f);
80
+ }
81
+
82
+ output.Add(output1.Name, output1Array);
83
+ output.Add(output2.Name, output2Array);
84
+
85
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
86
+ results.Dispose();
87
+ return output;
88
+ }
89
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
90
+ public InferenceSession LoadModel(string Path)
91
+ {
92
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
93
+ byte[] model = file.GetBuffer((int)file.GetLength());
94
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
95
+ return new InferenceSession(model, SessionOpt); //Load the model
96
+ }
97
+ public void FreeDisposables()
98
+ {
99
+ session.Dispose();
100
+ SessionOpt.Dispose();
101
+ }
102
+ }
103
+ }
SimpleReachGoal/CSharp/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
+ }
SimpleReachGoal/CSharp/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>
SimpleReachGoal/CSharp/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>
SimpleReachGoal/CSharp/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Resource
2
+ class_name ONNXModel
3
+ var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
4
+
5
+ var inferencer = null
6
+
7
+
8
+ # Must provide the path to the model and the batch size
9
+ func _init(model_path, batch_size):
10
+ inferencer = inferencer_script.new()
11
+ inferencer.Initialize(model_path, batch_size)
12
+
13
+
14
+ # This function is the one that will be called from the game,
15
+ # requires the observation as an array and the state_ins as an int
16
+ # returns an Array containing the action the model takes.
17
+ func run_inference(obs: Array, state_ins: int) -> Dictionary:
18
+ if inferencer == null:
19
+ printerr("Inferencer not initialized")
20
+ return {}
21
+ return inferencer.RunInference(obs, state_ins)
22
+
23
+
24
+ func _notification(what):
25
+ if what == NOTIFICATION_PREDELETE:
26
+ inferencer.FreeDisposables()
27
+ inferencer.free()
SimpleReachGoal/CSharp/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"
SimpleReachGoal/CSharp/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")
SimpleReachGoal/CSharp/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)
SimpleReachGoal/CSharp/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
SimpleReachGoal/CSharp/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
SimpleReachGoal/CSharp/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
SimpleReachGoal/CSharp/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)
SimpleReachGoal/CSharp/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)
SimpleReachGoal/CSharp/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
SimpleReachGoal/CSharp/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]
SimpleReachGoal/CSharp/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
SimpleReachGoal/CSharp/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
SimpleReachGoal/CSharp/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)
SimpleReachGoal/CSharp/addons/godot_rl_agents/sync.gd ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node
2
+
3
+ # --fixed-fps 2000 --disable-render-loop
4
+
5
+ enum ControlModes { HUMAN, TRAINING, ONNX_INFERENCE }
6
+ @export var control_mode: ControlModes = ControlModes.TRAINING
7
+ @export_range(1, 10, 1, "or_greater") var action_repeat := 8
8
+ @export_range(0, 10, 0.1, "or_greater") var speed_up := 1.0
9
+ @export var onnx_model_path := ""
10
+
11
+ # Onnx model stored for each requested path
12
+ var onnx_models: Dictionary
13
+
14
+ @onready var start_time = Time.get_ticks_msec()
15
+
16
+ const MAJOR_VERSION := "0"
17
+ const MINOR_VERSION := "7"
18
+ const DEFAULT_PORT := "11008"
19
+ const DEFAULT_SEED := "1"
20
+ var stream: StreamPeerTCP = null
21
+ var connected = false
22
+ var message_center
23
+ var should_connect = true
24
+
25
+ var all_agents: Array
26
+ var agents_training: Array
27
+ var agents_inference: Array
28
+ var agents_heuristic: Array
29
+
30
+ ## For recording expert demos
31
+ var agent_demo_record: Node
32
+ ## File path for writing recorded trajectories
33
+ var expert_demo_save_path: String
34
+ ## Stores recorded trajectories
35
+ var demo_trajectories: Array
36
+ ## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
37
+ var current_demo_trajectory: Array
38
+
39
+ var need_to_send_obs = false
40
+ var args = null
41
+ var initialized = false
42
+ var just_reset = false
43
+ var onnx_model = null
44
+ var n_action_steps = 0
45
+
46
+ var _action_space: Dictionary
47
+ var _action_space_inference: Array[Dictionary] = []
48
+ var _obs_space: Dictionary
49
+
50
+
51
+ # Called when the node enters the scene tree for the first time.
52
+ func _ready():
53
+ await get_tree().root.ready
54
+ get_tree().set_pause(true)
55
+ _initialize()
56
+ await get_tree().create_timer(1.0).timeout
57
+ get_tree().set_pause(false)
58
+
59
+
60
+ func _initialize():
61
+ _get_agents()
62
+ args = _get_args()
63
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
64
+ Engine.time_scale = _get_speedup() * 1.0
65
+ prints(
66
+ "physics ticks",
67
+ Engine.physics_ticks_per_second,
68
+ Engine.time_scale,
69
+ _get_speedup(),
70
+ speed_up
71
+ )
72
+
73
+ _set_heuristic("human", all_agents)
74
+
75
+ _initialize_training_agents()
76
+ _initialize_inference_agents()
77
+ _initialize_demo_recording()
78
+
79
+ _set_seed()
80
+ _set_action_repeat()
81
+ initialized = true
82
+
83
+
84
+ func _initialize_training_agents():
85
+ if agents_training.size() > 0:
86
+ _obs_space = agents_training[0].get_obs_space()
87
+ _action_space = agents_training[0].get_action_space()
88
+ connected = connect_to_server()
89
+ if connected:
90
+ _set_heuristic("model", agents_training)
91
+ _handshake()
92
+ _send_env_info()
93
+ else:
94
+ push_warning(
95
+ "Couldn't connect to Python server, using human controls instead. ",
96
+ "Did you start the training server using e.g. `gdrl` from the console?"
97
+ )
98
+
99
+
100
+ func _initialize_inference_agents():
101
+ if agents_inference.size() > 0:
102
+ if control_mode == ControlModes.ONNX_INFERENCE:
103
+ assert(
104
+ FileAccess.file_exists(onnx_model_path),
105
+ "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
106
+ )
107
+ onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
108
+
109
+ for agent in agents_inference:
110
+ _action_space_inference.append(agent.get_action_space())
111
+
112
+ var agent_onnx_model: ONNXModel
113
+ if agent.onnx_model_path.is_empty():
114
+ assert(
115
+ onnx_models.has(onnx_model_path),
116
+ (
117
+ "Node %s has no onnx model path set " % agent.get_path()
118
+ + "and sync node's control mode is not set to OnnxInference. "
119
+ + "Either add the path to the AIController, "
120
+ + "or if you want to use the path set on sync node instead, "
121
+ + "set control mode to OnnxInference."
122
+ )
123
+ )
124
+ prints(
125
+ "Info: AIController %s" % agent.get_path(),
126
+ "has no onnx model path set.",
127
+ "Using path set on the sync node instead."
128
+ )
129
+ agent_onnx_model = onnx_models[onnx_model_path]
130
+ else:
131
+ if not onnx_models.has(agent.onnx_model_path):
132
+ assert(
133
+ FileAccess.file_exists(agent.onnx_model_path),
134
+ (
135
+ "Onnx Model Path set on %s node does not exist: %s"
136
+ % [agent.get_path(), agent.onnx_model_path]
137
+ )
138
+ )
139
+ onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
140
+ agent_onnx_model = onnx_models[agent.onnx_model_path]
141
+
142
+ agent.onnx_model = agent_onnx_model
143
+ _set_heuristic("model", agents_inference)
144
+
145
+
146
+ func _initialize_demo_recording():
147
+ if agent_demo_record:
148
+ expert_demo_save_path = agent_demo_record.expert_demo_save_path
149
+ assert(
150
+ not expert_demo_save_path.is_empty(),
151
+ "Expert demo save path set in %s is empty." % agent_demo_record.get_path()
152
+ )
153
+
154
+ InputMap.add_action("RemoveLastDemoEpisode")
155
+ InputMap.action_add_event(
156
+ "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
157
+ )
158
+ current_demo_trajectory.resize(2)
159
+ current_demo_trajectory[0] = []
160
+ current_demo_trajectory[1] = []
161
+ agent_demo_record.heuristic = "demo_record"
162
+
163
+
164
+ func _physics_process(_delta):
165
+ # two modes, human control, agent control
166
+ # pause tree, send obs, get actions, set actions, unpause tree
167
+
168
+ _demo_record_process()
169
+
170
+ if n_action_steps % action_repeat != 0:
171
+ n_action_steps += 1
172
+ return
173
+
174
+ n_action_steps += 1
175
+
176
+ _training_process()
177
+ _inference_process()
178
+ _heuristic_process()
179
+
180
+
181
+ func _training_process():
182
+ if connected:
183
+ get_tree().set_pause(true)
184
+
185
+ if just_reset:
186
+ just_reset = false
187
+ var obs = _get_obs_from_agents(agents_training)
188
+
189
+ var reply = {"type": "reset", "obs": obs}
190
+ _send_dict_as_json_message(reply)
191
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
192
+ get_tree().set_pause(false)
193
+ return
194
+
195
+ if need_to_send_obs:
196
+ need_to_send_obs = false
197
+ var reward = _get_reward_from_agents()
198
+ var done = _get_done_from_agents()
199
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
200
+
201
+ var obs = _get_obs_from_agents(agents_training)
202
+
203
+ var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
204
+ _send_dict_as_json_message(reply)
205
+
206
+ var handled = handle_message()
207
+
208
+
209
+ func _inference_process():
210
+ if agents_inference.size() > 0:
211
+ var obs: Array = _get_obs_from_agents(agents_inference)
212
+ var actions = []
213
+
214
+ for agent_id in range(0, agents_inference.size()):
215
+ var action = agents_inference[agent_id].onnx_model.run_inference(
216
+ obs[agent_id]["obs"], 1.0
217
+ )
218
+ action["output"] = clamp_array(action["output"], -1.0, 1.0)
219
+ var action_dict = _extract_action_dict(
220
+ action["output"], _action_space_inference[agent_id]
221
+ )
222
+ actions.append(action_dict)
223
+
224
+ _set_agent_actions(actions, agents_inference)
225
+ _reset_agents_if_done(agents_inference)
226
+ get_tree().set_pause(false)
227
+
228
+
229
+ func _demo_record_process():
230
+ if not agent_demo_record:
231
+ return
232
+
233
+ if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
234
+ print("[Sync script][Demo recorder] Removing last recorded episode.")
235
+ demo_trajectories.remove_at(demo_trajectories.size() - 1)
236
+ print("Remaining episode count: %d" % demo_trajectories.size())
237
+
238
+ if n_action_steps % agent_demo_record.action_repeat != 0:
239
+ return
240
+
241
+ var obs_dict: Dictionary = agent_demo_record.get_obs()
242
+
243
+ # Get the current obs from the agent
244
+ assert(
245
+ obs_dict.has("obs"),
246
+ "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
247
+ )
248
+ current_demo_trajectory[0].append(obs_dict.obs)
249
+
250
+ # Get the action applied for the current obs from the agent
251
+ agent_demo_record.set_action()
252
+ var acts = agent_demo_record.get_action()
253
+
254
+ var terminal = agent_demo_record.get_done()
255
+ # Record actions only for non-terminal states
256
+ if terminal:
257
+ agent_demo_record.set_done_false()
258
+ else:
259
+ current_demo_trajectory[1].append(acts)
260
+
261
+ if terminal:
262
+ #current_demo_trajectory[2].append(true)
263
+ demo_trajectories.append(current_demo_trajectory.duplicate(true))
264
+ print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
265
+ current_demo_trajectory[0].clear()
266
+ current_demo_trajectory[1].clear()
267
+
268
+
269
+ func _heuristic_process():
270
+ for agent in agents_heuristic:
271
+ _reset_agents_if_done(agents_heuristic)
272
+
273
+
274
+ func _extract_action_dict(action_array: Array, action_space: Dictionary):
275
+ var index = 0
276
+ var result = {}
277
+ for key in action_space.keys():
278
+ var size = action_space[key]["size"]
279
+ if action_space[key]["action_type"] == "discrete":
280
+ result[key] = round(action_array[index])
281
+ else:
282
+ result[key] = action_array.slice(index, index + size)
283
+ index += size
284
+
285
+ return result
286
+
287
+
288
+ ## For AIControllers that inherit mode from sync, sets the correct mode.
289
+ func _set_agent_mode(agent: Node):
290
+ var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
291
+
292
+ if agent_inherits_mode:
293
+ match control_mode:
294
+ ControlModes.HUMAN:
295
+ agent.control_mode = agent.ControlModes.HUMAN
296
+ ControlModes.TRAINING:
297
+ agent.control_mode = agent.ControlModes.TRAINING
298
+ ControlModes.ONNX_INFERENCE:
299
+ agent.control_mode = agent.ControlModes.ONNX_INFERENCE
300
+
301
+
302
+ func _get_agents():
303
+ all_agents = get_tree().get_nodes_in_group("AGENT")
304
+ for agent in all_agents:
305
+ _set_agent_mode(agent)
306
+
307
+ if agent.control_mode == agent.ControlModes.TRAINING:
308
+ agents_training.append(agent)
309
+ elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
310
+ agents_inference.append(agent)
311
+ elif agent.control_mode == agent.ControlModes.HUMAN:
312
+ agents_heuristic.append(agent)
313
+ elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
314
+ assert(
315
+ not agent_demo_record,
316
+ "Currently only a single AIController can be used for recording expert demos."
317
+ )
318
+ agent_demo_record = agent
319
+
320
+
321
+ func _set_heuristic(heuristic, agents: Array):
322
+ for agent in agents:
323
+ agent.set_heuristic(heuristic)
324
+
325
+
326
+ func _handshake():
327
+ print("performing handshake")
328
+
329
+ var json_dict = _get_dict_json_message()
330
+ assert(json_dict["type"] == "handshake")
331
+ var major_version = json_dict["major_version"]
332
+ var minor_version = json_dict["minor_version"]
333
+ if major_version != MAJOR_VERSION:
334
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
335
+ if minor_version != MINOR_VERSION:
336
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
337
+
338
+ print("handshake complete")
339
+
340
+
341
+ func _get_dict_json_message():
342
+ # returns a dictionary from of the most recent message
343
+ # this is not waiting
344
+ while stream.get_available_bytes() == 0:
345
+ stream.poll()
346
+ if stream.get_status() != 2:
347
+ print("server disconnected status, closing")
348
+ get_tree().quit()
349
+ return null
350
+
351
+ OS.delay_usec(10)
352
+
353
+ var message = stream.get_string()
354
+ var json_data = JSON.parse_string(message)
355
+
356
+ return json_data
357
+
358
+
359
+ func _send_dict_as_json_message(dict):
360
+ stream.put_string(JSON.stringify(dict, "", false))
361
+
362
+
363
+ func _send_env_info():
364
+ var json_dict = _get_dict_json_message()
365
+ assert(json_dict["type"] == "env_info")
366
+
367
+ var message = {
368
+ "type": "env_info",
369
+ "observation_space": _obs_space,
370
+ "action_space": _action_space,
371
+ "n_agents": len(agents_training)
372
+ }
373
+ _send_dict_as_json_message(message)
374
+
375
+
376
+ func connect_to_server():
377
+ print("Waiting for one second to allow server to start")
378
+ OS.delay_msec(1000)
379
+ print("trying to connect to server")
380
+ stream = StreamPeerTCP.new()
381
+
382
+ # "localhost" was not working on windows VM, had to use the IP
383
+ var ip = "127.0.0.1"
384
+ var port = _get_port()
385
+ var connect = stream.connect_to_host(ip, port)
386
+ stream.set_no_delay(true) # TODO check if this improves performance or not
387
+ stream.poll()
388
+ # Fetch the status until it is either connected (2) or failed to connect (3)
389
+ while stream.get_status() < 2:
390
+ stream.poll()
391
+ return stream.get_status() == 2
392
+
393
+
394
+ func _get_args():
395
+ print("getting command line arguments")
396
+ var arguments = {}
397
+ for argument in OS.get_cmdline_args():
398
+ print(argument)
399
+ if argument.find("=") > -1:
400
+ var key_value = argument.split("=")
401
+ arguments[key_value[0].lstrip("--")] = key_value[1]
402
+ else:
403
+ # Options without an argument will be present in the dictionary,
404
+ # with the value set to an empty string.
405
+ arguments[argument.lstrip("--")] = ""
406
+
407
+ return arguments
408
+
409
+
410
+ func _get_speedup():
411
+ print(args)
412
+ return args.get("speedup", str(speed_up)).to_float()
413
+
414
+
415
+ func _get_port():
416
+ return args.get("port", DEFAULT_PORT).to_int()
417
+
418
+
419
+ func _set_seed():
420
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
421
+ seed(_seed)
422
+
423
+
424
+ func _set_action_repeat():
425
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
426
+
427
+
428
+ func disconnect_from_server():
429
+ stream.disconnect_from_host()
430
+
431
+
432
+ func handle_message() -> bool:
433
+ # get json message: reset, step, close
434
+ var message = _get_dict_json_message()
435
+ if message["type"] == "close":
436
+ print("received close message, closing game")
437
+ get_tree().quit()
438
+ get_tree().set_pause(false)
439
+ return true
440
+
441
+ if message["type"] == "reset":
442
+ print("resetting all agents")
443
+ _reset_agents()
444
+ just_reset = true
445
+ get_tree().set_pause(false)
446
+ #print("resetting forcing draw")
447
+ # RenderingServer.force_draw()
448
+ # var obs = _get_obs_from_agents()
449
+ # print("obs ", obs)
450
+ # var reply = {
451
+ # "type": "reset",
452
+ # "obs": obs
453
+ # }
454
+ # _send_dict_as_json_message(reply)
455
+ return true
456
+
457
+ if message["type"] == "call":
458
+ var method = message["method"]
459
+ var returns = _call_method_on_agents(method)
460
+ var reply = {"type": "call", "returns": returns}
461
+ print("calling method from Python")
462
+ _send_dict_as_json_message(reply)
463
+ return handle_message()
464
+
465
+ if message["type"] == "action":
466
+ var action = message["action"]
467
+ _set_agent_actions(action, agents_training)
468
+ need_to_send_obs = true
469
+ get_tree().set_pause(false)
470
+ return true
471
+
472
+ print("message was not handled")
473
+ return false
474
+
475
+
476
+ func _call_method_on_agents(method):
477
+ var returns = []
478
+ for agent in all_agents:
479
+ returns.append(agent.call(method))
480
+
481
+ return returns
482
+
483
+
484
+ func _reset_agents_if_done(agents = all_agents):
485
+ for agent in agents:
486
+ if agent.get_done():
487
+ agent.set_done_false()
488
+
489
+
490
+ func _reset_agents(agents = all_agents):
491
+ for agent in agents:
492
+ agent.needs_reset = true
493
+ #agent.reset()
494
+
495
+
496
+ func _get_obs_from_agents(agents: Array = all_agents):
497
+ var obs = []
498
+ for agent in agents:
499
+ obs.append(agent.get_obs())
500
+ return obs
501
+
502
+
503
+ func _get_reward_from_agents(agents: Array = agents_training):
504
+ var rewards = []
505
+ for agent in agents:
506
+ rewards.append(agent.get_reward())
507
+ agent.zero_reward()
508
+ return rewards
509
+
510
+
511
+ func _get_done_from_agents(agents: Array = agents_training):
512
+ var dones = []
513
+ for agent in agents:
514
+ var done = agent.get_done()
515
+ if done:
516
+ agent.set_done_false()
517
+ dones.append(done)
518
+ return dones
519
+
520
+
521
+ func _set_agent_actions(actions, agents: Array = all_agents):
522
+ for i in range(len(actions)):
523
+ agents[i].set_action(actions[i])
524
+
525
+
526
+ func clamp_array(arr: Array, min: float, max: float):
527
+ var output: Array = []
528
+ for a in arr:
529
+ output.append(clamp(a, min, max))
530
+ return output
531
+
532
+
533
+ ## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
534
+ func _notification(what):
535
+ if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
536
+ return
537
+
538
+ if what == NOTIFICATION_PREDELETE:
539
+ var json_string = JSON.stringify(demo_trajectories, "", false)
540
+ var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
541
+
542
+ if not file:
543
+ var error: Error = FileAccess.get_open_error()
544
+ assert(not error, "There was an error opening the file: %d" % error)
545
+
546
+ file.store_line(json_string)
547
+ var error = file.get_error()
548
+ assert(not error, "There was an error after trying to write to the file: %d" % error)
SimpleReachGoal/CSharp/icon.svg ADDED
SimpleReachGoal/CSharp/project.godot ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="SimpleReachGoal"
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="SimpleReachGoal"
21
+
22
+ [editor_plugins]
23
+
24
+ enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
SimpleReachGoal/CSharp/scenes/game_scene/AreaPositionRandomizer.cs ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using System.Collections.Generic;
3
+
4
+ public partial class AreaPositionRandomizer : Node3D
5
+ {
6
+ private Area3D area;
7
+ private readonly List<MeshInstance3D> areaSpawnPoints = new();
8
+
9
+ // Called when the node enters the scene tree for the first time.
10
+ public override void _Ready()
11
+ {
12
+ foreach (Node node in GetChildren())
13
+ {
14
+ if (node is Area3D areaNode)
15
+ {
16
+ area = areaNode;
17
+ }
18
+ else if (node is MeshInstance3D mesh)
19
+ {
20
+ areaSpawnPoints.Add(mesh);
21
+ mesh.Visible = false;
22
+ }
23
+ }
24
+ }
25
+
26
+ public void Reset()
27
+ {
28
+ Vector3 newAreaPosition = areaSpawnPoints[GD.RandRange(0, areaSpawnPoints.Count - 1)].GlobalPosition;
29
+ area.GlobalPosition = newAreaPosition;
30
+ }
31
+ }
SimpleReachGoal/CSharp/scenes/game_scene/GameSceneManager.cs ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+
3
+ public partial class GameSceneManager : Node3D
4
+ {
5
+ [Export]
6
+ public AreaPositionRandomizer GoalManager { get; set; }
7
+ [Export]
8
+ public AreaPositionRandomizer ObstacleManager { get; set; }
9
+ [Export]
10
+ public Player Player { get; set; }
11
+
12
+ // Called when the node enters the scene tree for the first time.
13
+ public override void _Ready()
14
+ {
15
+ Reset();
16
+ }
17
+
18
+ public void Reset()
19
+ {
20
+ GoalManager.Reset();
21
+ ObstacleManager.Reset();
22
+ Player.Reset();
23
+ }
24
+ }
SimpleReachGoal/CSharp/scenes/game_scene/game_scene.tscn ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=13 format=3 uid="uid://qofctg4fc0c2"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/game_scene/GameSceneManager.cs" id="1_cplta"]
4
+ [ext_resource type="Script" path="res://scenes/game_scene/AreaPositionRandomizer.cs" id="2_x2fdq"]
5
+ [ext_resource type="PackedScene" uid="uid://fhnd4o88w5p4" path="res://scenes/player/player.tscn" id="3_j13wo"]
6
+
7
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_g301e"]
8
+ transparency = 1
9
+ albedo_color = Color(0, 1, 0.166667, 0.756863)
10
+
11
+ [sub_resource type="BoxMesh" id="BoxMesh_wnjao"]
12
+
13
+ [sub_resource type="BoxShape3D" id="BoxShape3D_mblpq"]
14
+
15
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_irk0a"]
16
+ transparency = 1
17
+ albedo_color = Color(0, 1, 0.166667, 0.313726)
18
+
19
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_t0cxi"]
20
+ transparency = 1
21
+ albedo_color = Color(1, 0, 0, 0.756863)
22
+
23
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_qu1jy"]
24
+ transparency = 1
25
+ albedo_color = Color(1, 0, 0, 0.313726)
26
+
27
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_1ahva"]
28
+ albedo_color = Color(0.8, 0.8, 0.8, 1)
29
+
30
+ [sub_resource type="BoxMesh" id="BoxMesh_eh8qq"]
31
+ material = SubResource("StandardMaterial3D_1ahva")
32
+ size = Vector3(10, 0.1, 10)
33
+
34
+ [sub_resource type="BoxShape3D" id="BoxShape3D_wmgsa"]
35
+ size = Vector3(10, 1, 10)
36
+
37
+ [node name="GameScene" type="Node3D" node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player")]
38
+ script = ExtResource("1_cplta")
39
+ GoalManager = NodePath("GoalManager")
40
+ ObstacleManager = NodePath("ObstacleManager")
41
+ Player = NodePath("Player")
42
+
43
+ [node name="GoalManager" type="Node3D" parent="."]
44
+ script = ExtResource("2_x2fdq")
45
+
46
+ [node name="Goal" type="Area3D" parent="GoalManager"]
47
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
48
+ collision_layer = 2
49
+ monitorable = false
50
+
51
+ [node name="MeshInstance3D" type="MeshInstance3D" parent="GoalManager/Goal"]
52
+ material_override = SubResource("StandardMaterial3D_g301e")
53
+ mesh = SubResource("BoxMesh_wnjao")
54
+
55
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="GoalManager/Goal"]
56
+ shape = SubResource("BoxShape3D_mblpq")
57
+
58
+ [node name="SpawnPosition" type="MeshInstance3D" parent="GoalManager"]
59
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, 4)
60
+ material_override = SubResource("StandardMaterial3D_irk0a")
61
+ mesh = SubResource("BoxMesh_wnjao")
62
+
63
+ [node name="SpawnPosition2" type="MeshInstance3D" parent="GoalManager"]
64
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, 4)
65
+ material_override = SubResource("StandardMaterial3D_irk0a")
66
+ mesh = SubResource("BoxMesh_wnjao")
67
+
68
+ [node name="SpawnPosition3" type="MeshInstance3D" parent="GoalManager"]
69
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 0.5, -4)
70
+ material_override = SubResource("StandardMaterial3D_irk0a")
71
+ mesh = SubResource("BoxMesh_wnjao")
72
+
73
+ [node name="SpawnPosition4" type="MeshInstance3D" parent="GoalManager"]
74
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4, 0.5, -4)
75
+ material_override = SubResource("StandardMaterial3D_irk0a")
76
+ mesh = SubResource("BoxMesh_wnjao")
77
+
78
+ [node name="ObstacleManager" type="Node3D" parent="."]
79
+ script = ExtResource("2_x2fdq")
80
+
81
+ [node name="Obstacle" type="Area3D" parent="ObstacleManager"]
82
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
83
+ collision_layer = 4
84
+ monitorable = false
85
+
86
+ [node name="MeshInstance3D" type="MeshInstance3D" parent="ObstacleManager/Obstacle"]
87
+ material_override = SubResource("StandardMaterial3D_t0cxi")
88
+ mesh = SubResource("BoxMesh_wnjao")
89
+
90
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="ObstacleManager/Obstacle"]
91
+ shape = SubResource("BoxShape3D_mblpq")
92
+
93
+ [node name="SpawnPosition" type="MeshInstance3D" parent="ObstacleManager"]
94
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, -2)
95
+ material_override = SubResource("StandardMaterial3D_qu1jy")
96
+ mesh = SubResource("BoxMesh_wnjao")
97
+
98
+ [node name="SpawnPosition2" type="MeshInstance3D" parent="ObstacleManager"]
99
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 2)
100
+ material_override = SubResource("StandardMaterial3D_qu1jy")
101
+ mesh = SubResource("BoxMesh_wnjao")
102
+
103
+ [node name="SpawnPosition3" type="MeshInstance3D" parent="ObstacleManager"]
104
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 0)
105
+ material_override = SubResource("StandardMaterial3D_qu1jy")
106
+ mesh = SubResource("BoxMesh_wnjao")
107
+
108
+ [node name="SpawnPosition4" type="MeshInstance3D" parent="ObstacleManager"]
109
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 0)
110
+ material_override = SubResource("StandardMaterial3D_qu1jy")
111
+ mesh = SubResource("BoxMesh_wnjao")
112
+
113
+ [node name="SpawnPosition5" type="MeshInstance3D" parent="ObstacleManager"]
114
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -1)
115
+ material_override = SubResource("StandardMaterial3D_qu1jy")
116
+ mesh = SubResource("BoxMesh_wnjao")
117
+
118
+ [node name="SpawnPosition6" type="MeshInstance3D" parent="ObstacleManager"]
119
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, -2)
120
+ material_override = SubResource("StandardMaterial3D_qu1jy")
121
+ mesh = SubResource("BoxMesh_wnjao")
122
+
123
+ [node name="SpawnPosition7" type="MeshInstance3D" parent="ObstacleManager"]
124
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, -2)
125
+ material_override = SubResource("StandardMaterial3D_qu1jy")
126
+ mesh = SubResource("BoxMesh_wnjao")
127
+
128
+ [node name="SpawnPosition8" type="MeshInstance3D" parent="ObstacleManager"]
129
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, -2)
130
+ material_override = SubResource("StandardMaterial3D_qu1jy")
131
+ mesh = SubResource("BoxMesh_wnjao")
132
+
133
+ [node name="SpawnPosition9" type="MeshInstance3D" parent="ObstacleManager"]
134
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -2)
135
+ material_override = SubResource("StandardMaterial3D_qu1jy")
136
+ mesh = SubResource("BoxMesh_wnjao")
137
+
138
+ [node name="SpawnPosition10" type="MeshInstance3D" parent="ObstacleManager"]
139
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, -1)
140
+ material_override = SubResource("StandardMaterial3D_qu1jy")
141
+ mesh = SubResource("BoxMesh_wnjao")
142
+
143
+ [node name="SpawnPosition11" type="MeshInstance3D" parent="ObstacleManager"]
144
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 1)
145
+ material_override = SubResource("StandardMaterial3D_qu1jy")
146
+ mesh = SubResource("BoxMesh_wnjao")
147
+
148
+ [node name="SpawnPosition12" type="MeshInstance3D" parent="ObstacleManager"]
149
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 2, 0.5, 2)
150
+ material_override = SubResource("StandardMaterial3D_qu1jy")
151
+ mesh = SubResource("BoxMesh_wnjao")
152
+
153
+ [node name="SpawnPosition13" type="MeshInstance3D" parent="ObstacleManager"]
154
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0.5, 2)
155
+ material_override = SubResource("StandardMaterial3D_qu1jy")
156
+ mesh = SubResource("BoxMesh_wnjao")
157
+
158
+ [node name="SpawnPosition14" type="MeshInstance3D" parent="ObstacleManager"]
159
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1, 0.5, 2)
160
+ material_override = SubResource("StandardMaterial3D_qu1jy")
161
+ mesh = SubResource("BoxMesh_wnjao")
162
+
163
+ [node name="SpawnPosition15" type="MeshInstance3D" parent="ObstacleManager"]
164
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 2)
165
+ material_override = SubResource("StandardMaterial3D_qu1jy")
166
+ mesh = SubResource("BoxMesh_wnjao")
167
+
168
+ [node name="SpawnPosition16" type="MeshInstance3D" parent="ObstacleManager"]
169
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -2, 0.5, 1)
170
+ material_override = SubResource("StandardMaterial3D_qu1jy")
171
+ mesh = SubResource("BoxMesh_wnjao")
172
+
173
+ [node name="Ground" type="StaticBody3D" parent="."]
174
+
175
+ [node name="MeshInstance3D" type="MeshInstance3D" parent="Ground"]
176
+ mesh = SubResource("BoxMesh_eh8qq")
177
+ skeleton = NodePath("../..")
178
+
179
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="Ground"]
180
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.45, 0)
181
+ shape = SubResource("BoxShape3D_wmgsa")
182
+
183
+ [node name="Player" parent="." node_paths=PackedStringArray("GameSceneManager", "Goal", "Obstacle", "AIController") instance=ExtResource("3_j13wo")]
184
+ GameSceneManager = NodePath("..")
185
+ Goal = NodePath("../GoalManager/Goal")
186
+ Obstacle = NodePath("../ObstacleManager/Obstacle")
187
+ AIController = NodePath("AIController3D")
188
+
189
+ [connection signal="body_entered" from="GoalManager/Goal" to="Player" method="OnGoalBodyEntered"]
190
+ [connection signal="body_entered" from="ObstacleManager/Obstacle" to="Player" method="OnObstacleBodyEntered"]
SimpleReachGoal/CSharp/scenes/player/Player.cs ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+
3
+ public partial class Player : CharacterBody3D
4
+ {
5
+ [Export]
6
+ public GameSceneManager GameSceneManager { get; set; }
7
+ [Export]
8
+ public Area3D Goal { get; set; }
9
+ [Export]
10
+ public Area3D Obstacle { get; set; }
11
+ [Export]
12
+ public Node3D AIController { get; set; }
13
+ [Export]
14
+ public float Speed { get => speed; set => speed = value; }
15
+ public Vector2 RequestedMovement { get; set; }
16
+
17
+ private float speed = 5f;
18
+ private Transform3D initialTransform;
19
+
20
+ public override void _Ready()
21
+ {
22
+ initialTransform = Transform;
23
+ }
24
+
25
+ public override void _PhysicsProcess(double delta)
26
+ {
27
+ if (!IsOnFloor())
28
+ {
29
+ Velocity += GetGravity() * (float)delta;
30
+ }
31
+
32
+ // If controlled by human, takes the keyboard arrows as input
33
+ // otherwise, requested_movement will be set by the AIController based on RL agent's output actions
34
+ if ((string)AIController.Get("heuristic") == "human")
35
+ {
36
+ RequestedMovement = Input.GetVector("ui_left", "ui_right", "ui_up", "ui_down");
37
+ }
38
+
39
+ RequestedMovement = RequestedMovement.LimitLength(1f) * Speed;
40
+
41
+ Velocity = new(RequestedMovement.X, Velocity.Y, RequestedMovement.Y);
42
+
43
+ // We only move when the episode is not marked as done
44
+ // to prevent repeating a possibly wrong action from the previous episode.
45
+ // This is related to the sync node Action Repeat functionality,
46
+ // we don't get a new action for every physics step. This check may
47
+ // not be required for every env, and is not used in all examples.
48
+ if (!(bool)AIController.Get("done"))
49
+ {
50
+ MoveAndSlide();
51
+ }
52
+
53
+ ResetOnPlayerFalling();
54
+
55
+ }
56
+
57
+ // Resets the game if the player has fallen down
58
+ private void ResetOnPlayerFalling()
59
+ {
60
+ if (GlobalPosition.Y < -1.0)
61
+ {
62
+ GameOver(-1.0);
63
+ }
64
+ }
65
+
66
+ // Ends the game, setting an optional reward
67
+ private void GameOver(double reward)
68
+ {
69
+ double currentReward = (double)AIController.Get("reward");
70
+ AIController.Set("reward", currentReward + reward);
71
+ GameSceneManager.Reset();
72
+ }
73
+
74
+ // Resets the player and AIController
75
+ public void Reset()
76
+ {
77
+ AIController.Call("end_episode");
78
+ Transform = initialTransform;
79
+ }
80
+
81
+ // When the goal is entered, we restart the game with a positive reward
82
+ public void OnGoalBodyEntered(Node3D body)
83
+ {
84
+ GameOver(1.0);
85
+ }
86
+
87
+ // When the obstacle is entered, we restart the game with a negative reward
88
+ public void OnObstacleBodyEntered(Node3D body)
89
+ {
90
+ GameOver(-1.0);
91
+ }
92
+ }
SimpleReachGoal/CSharp/scenes/player/player.tscn ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=7 format=3 uid="uid://fhnd4o88w5p4"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/player/Player.cs" id="1_73fx5"]
4
+ [ext_resource type="Script" path="res://scenes/player/player_ai_controller.gd" id="2_suigr"]
5
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3_qsyok"]
6
+
7
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_owc64"]
8
+ albedo_color = Color(0.929563, 0.63943, 7.70092e-07, 1)
9
+
10
+ [sub_resource type="CapsuleMesh" id="CapsuleMesh_jc5om"]
11
+ material = SubResource("StandardMaterial3D_owc64")
12
+ radius = 0.25
13
+ height = 1.0
14
+
15
+ [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_2gph3"]
16
+ radius = 0.25
17
+ height = 1.0
18
+
19
+ [node name="Player" type="CharacterBody3D"]
20
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, 0)
21
+ script = ExtResource("1_73fx5")
22
+
23
+ [node name="MeshInstance3D" type="MeshInstance3D" parent="."]
24
+ mesh = SubResource("CapsuleMesh_jc5om")
25
+ skeleton = NodePath("../..")
26
+
27
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="."]
28
+ shape = SubResource("CapsuleShape3D_2gph3")
29
+
30
+ [node name="AIController3D" type="Node3D" parent="." node_paths=PackedStringArray("player", "raycast_sensors")]
31
+ script = ExtResource("2_suigr")
32
+ player = NodePath("..")
33
+ raycast_sensors = [NodePath("GoalRaycastSensor"), NodePath("ObstacleRaycastSensor"), NodePath("GroundRaycastSensor")]
34
+
35
+ [node name="GoalRaycastSensor" type="Node3D" parent="AIController3D"]
36
+ script = ExtResource("3_qsyok")
37
+ collision_mask = 2
38
+ boolean_class_mask = 0
39
+ n_rays_width = 32.0
40
+ n_rays_height = 1.0
41
+ cone_width = 360.0
42
+ cone_height = 0.0
43
+ collide_with_areas = true
44
+ collide_with_bodies = false
45
+
46
+ [node name="node_0 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
47
+ target_position = Vector3(-0.980171, 0, -9.95185)
48
+ collision_mask = 2
49
+ collide_with_areas = true
50
+ collide_with_bodies = false
51
+
52
+ [node name="node_1 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
53
+ target_position = Vector3(-2.90285, 0, -9.5694)
54
+ collision_mask = 2
55
+ collide_with_areas = true
56
+ collide_with_bodies = false
57
+
58
+ [node name="node_2 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
59
+ target_position = Vector3(-4.71397, 0, -8.81921)
60
+ collision_mask = 2
61
+ collide_with_areas = true
62
+ collide_with_bodies = false
63
+
64
+ [node name="node_3 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
65
+ target_position = Vector3(-6.34393, 0, -7.7301)
66
+ collision_mask = 2
67
+ collide_with_areas = true
68
+ collide_with_bodies = false
69
+
70
+ [node name="node_4 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
71
+ target_position = Vector3(-7.7301, 0, -6.34393)
72
+ collision_mask = 2
73
+ collide_with_areas = true
74
+ collide_with_bodies = false
75
+
76
+ [node name="node_5 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
77
+ target_position = Vector3(-8.81921, 0, -4.71397)
78
+ collision_mask = 2
79
+ collide_with_areas = true
80
+ collide_with_bodies = false
81
+
82
+ [node name="@RayCast3D@57424" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
83
+ target_position = Vector3(-9.5694, 0, -2.90285)
84
+ collision_mask = 2
85
+ collide_with_areas = true
86
+ collide_with_bodies = false
87
+
88
+ [node name="@RayCast3D@57425" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
89
+ target_position = Vector3(-9.95185, 0, -0.980171)
90
+ collision_mask = 2
91
+ collide_with_areas = true
92
+ collide_with_bodies = false
93
+
94
+ [node name="@RayCast3D@57426" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
95
+ target_position = Vector3(-9.95185, 0, 0.980171)
96
+ collision_mask = 2
97
+ collide_with_areas = true
98
+ collide_with_bodies = false
99
+
100
+ [node name="@RayCast3D@57427" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
101
+ target_position = Vector3(-9.5694, 0, 2.90285)
102
+ collision_mask = 2
103
+ collide_with_areas = true
104
+ collide_with_bodies = false
105
+
106
+ [node name="@RayCast3D@57428" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
107
+ target_position = Vector3(-8.81921, 0, 4.71397)
108
+ collision_mask = 2
109
+ collide_with_areas = true
110
+ collide_with_bodies = false
111
+
112
+ [node name="@RayCast3D@57429" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
113
+ target_position = Vector3(-7.7301, 0, 6.34393)
114
+ collision_mask = 2
115
+ collide_with_areas = true
116
+ collide_with_bodies = false
117
+
118
+ [node name="node_12 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
119
+ target_position = Vector3(-6.34393, 0, 7.7301)
120
+ collision_mask = 2
121
+ collide_with_areas = true
122
+ collide_with_bodies = false
123
+
124
+ [node name="node_13 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
125
+ target_position = Vector3(-4.71397, 0, 8.81921)
126
+ collision_mask = 2
127
+ collide_with_areas = true
128
+ collide_with_bodies = false
129
+
130
+ [node name="node_14 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
131
+ target_position = Vector3(-2.90285, 0, 9.5694)
132
+ collision_mask = 2
133
+ collide_with_areas = true
134
+ collide_with_bodies = false
135
+
136
+ [node name="node_15 0" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
137
+ target_position = Vector3(-0.980171, 0, 9.95185)
138
+ collision_mask = 2
139
+ collide_with_areas = true
140
+ collide_with_bodies = false
141
+
142
+ [node name="@RayCast3D@57430" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
143
+ target_position = Vector3(0.980171, 0, 9.95185)
144
+ collision_mask = 2
145
+ collide_with_areas = true
146
+ collide_with_bodies = false
147
+
148
+ [node name="@RayCast3D@57431" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
149
+ target_position = Vector3(2.90285, 0, 9.5694)
150
+ collision_mask = 2
151
+ collide_with_areas = true
152
+ collide_with_bodies = false
153
+
154
+ [node name="@RayCast3D@57432" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
155
+ target_position = Vector3(4.71397, 0, 8.81921)
156
+ collision_mask = 2
157
+ collide_with_areas = true
158
+ collide_with_bodies = false
159
+
160
+ [node name="@RayCast3D@57433" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
161
+ target_position = Vector3(6.34393, 0, 7.7301)
162
+ collision_mask = 2
163
+ collide_with_areas = true
164
+ collide_with_bodies = false
165
+
166
+ [node name="@RayCast3D@57434" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
167
+ target_position = Vector3(7.7301, 0, 6.34393)
168
+ collision_mask = 2
169
+ collide_with_areas = true
170
+ collide_with_bodies = false
171
+
172
+ [node name="@RayCast3D@57435" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
173
+ target_position = Vector3(8.81921, 0, 4.71397)
174
+ collision_mask = 2
175
+ collide_with_areas = true
176
+ collide_with_bodies = false
177
+
178
+ [node name="@RayCast3D@57436" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
179
+ target_position = Vector3(9.5694, 0, 2.90285)
180
+ collision_mask = 2
181
+ collide_with_areas = true
182
+ collide_with_bodies = false
183
+
184
+ [node name="@RayCast3D@57437" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
185
+ target_position = Vector3(9.95185, 0, 0.980171)
186
+ collision_mask = 2
187
+ collide_with_areas = true
188
+ collide_with_bodies = false
189
+
190
+ [node name="@RayCast3D@57438" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
191
+ target_position = Vector3(9.95185, 0, -0.980171)
192
+ collision_mask = 2
193
+ collide_with_areas = true
194
+ collide_with_bodies = false
195
+
196
+ [node name="@RayCast3D@57439" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
197
+ target_position = Vector3(9.5694, 0, -2.90285)
198
+ collision_mask = 2
199
+ collide_with_areas = true
200
+ collide_with_bodies = false
201
+
202
+ [node name="@RayCast3D@57440" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
203
+ target_position = Vector3(8.81921, 0, -4.71397)
204
+ collision_mask = 2
205
+ collide_with_areas = true
206
+ collide_with_bodies = false
207
+
208
+ [node name="@RayCast3D@57441" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
209
+ target_position = Vector3(7.7301, 0, -6.34393)
210
+ collision_mask = 2
211
+ collide_with_areas = true
212
+ collide_with_bodies = false
213
+
214
+ [node name="@RayCast3D@57442" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
215
+ target_position = Vector3(6.34393, 0, -7.7301)
216
+ collision_mask = 2
217
+ collide_with_areas = true
218
+ collide_with_bodies = false
219
+
220
+ [node name="@RayCast3D@57443" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
221
+ target_position = Vector3(4.71397, 0, -8.81921)
222
+ collision_mask = 2
223
+ collide_with_areas = true
224
+ collide_with_bodies = false
225
+
226
+ [node name="@RayCast3D@57444" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
227
+ target_position = Vector3(2.90285, 0, -9.5694)
228
+ collision_mask = 2
229
+ collide_with_areas = true
230
+ collide_with_bodies = false
231
+
232
+ [node name="@RayCast3D@57445" type="RayCast3D" parent="AIController3D/GoalRaycastSensor"]
233
+ target_position = Vector3(0.980171, 0, -9.95185)
234
+ collision_mask = 2
235
+ collide_with_areas = true
236
+ collide_with_bodies = false
237
+
238
+ [node name="ObstacleRaycastSensor" type="Node3D" parent="AIController3D"]
239
+ script = ExtResource("3_qsyok")
240
+ collision_mask = 4
241
+ boolean_class_mask = 0
242
+ n_rays_width = 32.0
243
+ n_rays_height = 1.0
244
+ cone_width = 360.0
245
+ cone_height = 0.0
246
+ collide_with_areas = true
247
+ collide_with_bodies = false
248
+
249
+ [node name="node_0 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
250
+ target_position = Vector3(-0.980171, 0, -9.95185)
251
+ collision_mask = 4
252
+ collide_with_areas = true
253
+ collide_with_bodies = false
254
+
255
+ [node name="node_1 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
256
+ target_position = Vector3(-2.90285, 0, -9.5694)
257
+ collision_mask = 4
258
+ collide_with_areas = true
259
+ collide_with_bodies = false
260
+
261
+ [node name="node_2 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
262
+ target_position = Vector3(-4.71397, 0, -8.81921)
263
+ collision_mask = 4
264
+ collide_with_areas = true
265
+ collide_with_bodies = false
266
+
267
+ [node name="node_3 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
268
+ target_position = Vector3(-6.34393, 0, -7.7301)
269
+ collision_mask = 4
270
+ collide_with_areas = true
271
+ collide_with_bodies = false
272
+
273
+ [node name="node_4 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
274
+ target_position = Vector3(-7.7301, 0, -6.34393)
275
+ collision_mask = 4
276
+ collide_with_areas = true
277
+ collide_with_bodies = false
278
+
279
+ [node name="node_5 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
280
+ target_position = Vector3(-8.81921, 0, -4.71397)
281
+ collision_mask = 4
282
+ collide_with_areas = true
283
+ collide_with_bodies = false
284
+
285
+ [node name="@RayCast3D@56972" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
286
+ target_position = Vector3(-9.5694, 0, -2.90285)
287
+ collision_mask = 4
288
+ collide_with_areas = true
289
+ collide_with_bodies = false
290
+
291
+ [node name="@RayCast3D@56973" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
292
+ target_position = Vector3(-9.95185, 0, -0.980171)
293
+ collision_mask = 4
294
+ collide_with_areas = true
295
+ collide_with_bodies = false
296
+
297
+ [node name="@RayCast3D@56974" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
298
+ target_position = Vector3(-9.95185, 0, 0.980171)
299
+ collision_mask = 4
300
+ collide_with_areas = true
301
+ collide_with_bodies = false
302
+
303
+ [node name="@RayCast3D@56975" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
304
+ target_position = Vector3(-9.5694, 0, 2.90285)
305
+ collision_mask = 4
306
+ collide_with_areas = true
307
+ collide_with_bodies = false
308
+
309
+ [node name="@RayCast3D@56976" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
310
+ target_position = Vector3(-8.81921, 0, 4.71397)
311
+ collision_mask = 4
312
+ collide_with_areas = true
313
+ collide_with_bodies = false
314
+
315
+ [node name="@RayCast3D@56977" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
316
+ target_position = Vector3(-7.7301, 0, 6.34393)
317
+ collision_mask = 4
318
+ collide_with_areas = true
319
+ collide_with_bodies = false
320
+
321
+ [node name="node_12 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
322
+ target_position = Vector3(-6.34393, 0, 7.7301)
323
+ collision_mask = 4
324
+ collide_with_areas = true
325
+ collide_with_bodies = false
326
+
327
+ [node name="node_13 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
328
+ target_position = Vector3(-4.71397, 0, 8.81921)
329
+ collision_mask = 4
330
+ collide_with_areas = true
331
+ collide_with_bodies = false
332
+
333
+ [node name="node_14 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
334
+ target_position = Vector3(-2.90285, 0, 9.5694)
335
+ collision_mask = 4
336
+ collide_with_areas = true
337
+ collide_with_bodies = false
338
+
339
+ [node name="node_15 0" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
340
+ target_position = Vector3(-0.980171, 0, 9.95185)
341
+ collision_mask = 4
342
+ collide_with_areas = true
343
+ collide_with_bodies = false
344
+
345
+ [node name="@RayCast3D@56978" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
346
+ target_position = Vector3(0.980171, 0, 9.95185)
347
+ collision_mask = 4
348
+ collide_with_areas = true
349
+ collide_with_bodies = false
350
+
351
+ [node name="@RayCast3D@56979" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
352
+ target_position = Vector3(2.90285, 0, 9.5694)
353
+ collision_mask = 4
354
+ collide_with_areas = true
355
+ collide_with_bodies = false
356
+
357
+ [node name="@RayCast3D@56980" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
358
+ target_position = Vector3(4.71397, 0, 8.81921)
359
+ collision_mask = 4
360
+ collide_with_areas = true
361
+ collide_with_bodies = false
362
+
363
+ [node name="@RayCast3D@56981" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
364
+ target_position = Vector3(6.34393, 0, 7.7301)
365
+ collision_mask = 4
366
+ collide_with_areas = true
367
+ collide_with_bodies = false
368
+
369
+ [node name="@RayCast3D@56982" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
370
+ target_position = Vector3(7.7301, 0, 6.34393)
371
+ collision_mask = 4
372
+ collide_with_areas = true
373
+ collide_with_bodies = false
374
+
375
+ [node name="@RayCast3D@56983" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
376
+ target_position = Vector3(8.81921, 0, 4.71397)
377
+ collision_mask = 4
378
+ collide_with_areas = true
379
+ collide_with_bodies = false
380
+
381
+ [node name="@RayCast3D@56984" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
382
+ target_position = Vector3(9.5694, 0, 2.90285)
383
+ collision_mask = 4
384
+ collide_with_areas = true
385
+ collide_with_bodies = false
386
+
387
+ [node name="@RayCast3D@56985" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
388
+ target_position = Vector3(9.95185, 0, 0.980171)
389
+ collision_mask = 4
390
+ collide_with_areas = true
391
+ collide_with_bodies = false
392
+
393
+ [node name="@RayCast3D@56986" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
394
+ target_position = Vector3(9.95185, 0, -0.980171)
395
+ collision_mask = 4
396
+ collide_with_areas = true
397
+ collide_with_bodies = false
398
+
399
+ [node name="@RayCast3D@56987" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
400
+ target_position = Vector3(9.5694, 0, -2.90285)
401
+ collision_mask = 4
402
+ collide_with_areas = true
403
+ collide_with_bodies = false
404
+
405
+ [node name="@RayCast3D@56988" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
406
+ target_position = Vector3(8.81921, 0, -4.71397)
407
+ collision_mask = 4
408
+ collide_with_areas = true
409
+ collide_with_bodies = false
410
+
411
+ [node name="@RayCast3D@56989" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
412
+ target_position = Vector3(7.7301, 0, -6.34393)
413
+ collision_mask = 4
414
+ collide_with_areas = true
415
+ collide_with_bodies = false
416
+
417
+ [node name="@RayCast3D@56990" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
418
+ target_position = Vector3(6.34393, 0, -7.7301)
419
+ collision_mask = 4
420
+ collide_with_areas = true
421
+ collide_with_bodies = false
422
+
423
+ [node name="@RayCast3D@56991" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
424
+ target_position = Vector3(4.71397, 0, -8.81921)
425
+ collision_mask = 4
426
+ collide_with_areas = true
427
+ collide_with_bodies = false
428
+
429
+ [node name="@RayCast3D@56992" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
430
+ target_position = Vector3(2.90285, 0, -9.5694)
431
+ collision_mask = 4
432
+ collide_with_areas = true
433
+ collide_with_bodies = false
434
+
435
+ [node name="@RayCast3D@56993" type="RayCast3D" parent="AIController3D/ObstacleRaycastSensor"]
436
+ target_position = Vector3(0.980171, 0, -9.95185)
437
+ collision_mask = 4
438
+ collide_with_areas = true
439
+ collide_with_bodies = false
440
+
441
+ [node name="GroundRaycastSensor" type="Node3D" parent="AIController3D"]
442
+ transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 0, 0)
443
+ script = ExtResource("3_qsyok")
444
+ boolean_class_mask = 0
445
+ n_rays_width = 4.0
446
+ n_rays_height = 4.0
447
+ ray_length = 2.0
448
+ cone_width = 90.0
449
+ cone_height = 90.0
450
+
451
+ [node name="node_0 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
452
+ target_position = Vector3(-0.92388, -1.11114, 1.38268)
453
+
454
+ [node name="@RayCast3D@24718" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
455
+ target_position = Vector3(-1.08979, -0.390181, 1.63099)
456
+
457
+ [node name="@RayCast3D@24719" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
458
+ target_position = Vector3(-1.08979, 0.390181, 1.63099)
459
+
460
+ [node name="@RayCast3D@24720" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
461
+ target_position = Vector3(-0.92388, 1.11114, 1.38268)
462
+
463
+ [node name="node_1 0" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
464
+ target_position = Vector3(-0.324423, -1.11114, 1.63099)
465
+
466
+ [node name="@RayCast3D@24721" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
467
+ target_position = Vector3(-0.382683, -0.390181, 1.92388)
468
+
469
+ [node name="@RayCast3D@24722" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
470
+ target_position = Vector3(-0.382683, 0.390181, 1.92388)
471
+
472
+ [node name="@RayCast3D@24723" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
473
+ target_position = Vector3(-0.324423, 1.11114, 1.63099)
474
+
475
+ [node name="@RayCast3D@24724" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
476
+ target_position = Vector3(0.324423, -1.11114, 1.63099)
477
+
478
+ [node name="@RayCast3D@24725" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
479
+ target_position = Vector3(0.382683, -0.390181, 1.92388)
480
+
481
+ [node name="@RayCast3D@24726" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
482
+ target_position = Vector3(0.382683, 0.390181, 1.92388)
483
+
484
+ [node name="@RayCast3D@24727" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
485
+ target_position = Vector3(0.324423, 1.11114, 1.63099)
486
+
487
+ [node name="@RayCast3D@24728" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
488
+ target_position = Vector3(0.92388, -1.11114, 1.38268)
489
+
490
+ [node name="@RayCast3D@24729" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
491
+ target_position = Vector3(1.08979, -0.390181, 1.63099)
492
+
493
+ [node name="@RayCast3D@24730" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
494
+ target_position = Vector3(1.08979, 0.390181, 1.63099)
495
+
496
+ [node name="@RayCast3D@24731" type="RayCast3D" parent="AIController3D/GroundRaycastSensor"]
497
+ target_position = Vector3(0.92388, 1.11114, 1.38268)
SimpleReachGoal/CSharp/scenes/player/player_ai_controller.gd ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends AIController3D
2
+ class_name PlayerAIController
3
+
4
+ @export var player: Node3D
5
+ @export var raycast_sensors: Array[RayCastSensor3D]
6
+
7
+
8
+ func _physics_process(delta):
9
+ n_steps += 1
10
+
11
+ if n_steps > reset_after:
12
+ player.GameSceneManager.Reset()
13
+
14
+
15
+ func end_episode():
16
+ done = true
17
+ reset()
18
+
19
+
20
+ func get_obs() -> Dictionary:
21
+ var obs: PackedFloat32Array = []
22
+ for sensor in raycast_sensors:
23
+ obs.append_array(sensor.get_observation())
24
+
25
+ var level_size: float = 10
26
+ var relative_goal_position: Vector3 = player.to_local(player.Goal.global_position)
27
+ var relative_obstacle_position: Vector3 = player.to_local(player.Obstacle.global_position)
28
+ obs.append_array(
29
+ [
30
+ relative_goal_position.x / level_size,
31
+ relative_goal_position.z / level_size,
32
+ relative_obstacle_position.x / level_size,
33
+ relative_obstacle_position.z / level_size
34
+ ]
35
+ )
36
+ return {"obs": obs}
37
+
38
+
39
+ func get_reward() -> float:
40
+ return reward
41
+
42
+
43
+ func get_action_space() -> Dictionary:
44
+ return {"move_action": {"size": 2, "action_type": "continuous"}}
45
+
46
+
47
+ func set_action(action) -> void:
48
+ player.RequestedMovement = Vector2(action.move_action[0], action.move_action[1])
SimpleReachGoal/CSharp/scenes/training_scene/training_scene.tscn ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=6 format=3 uid="uid://b12majbajmkqq"]
2
+
3
+ [ext_resource type="PackedScene" uid="uid://qofctg4fc0c2" path="res://scenes/game_scene/game_scene.tscn" id="1_pdcwe"]
4
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_7kqnq"]
5
+
6
+ [sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_kbbm2"]
7
+ sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
8
+ ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1)
9
+
10
+ [sub_resource type="Sky" id="Sky_lpkw7"]
11
+ sky_material = SubResource("ProceduralSkyMaterial_kbbm2")
12
+
13
+ [sub_resource type="Environment" id="Environment_3ytk2"]
14
+ background_mode = 2
15
+ sky = SubResource("Sky_lpkw7")
16
+ tonemap_mode = 2
17
+ glow_enabled = true
18
+
19
+ [node name="TrainingScene" type="Node3D"]
20
+
21
+ [node name="WorldEnvironment" type="WorldEnvironment" parent="."]
22
+ environment = SubResource("Environment_3ytk2")
23
+
24
+ [node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
25
+ transform = Transform3D(-0.866024, -0.433016, 0.250001, 0, 0.499998, 0.866026, -0.500003, 0.749999, -0.43301, 0, 0, 0)
26
+ shadow_enabled = true
27
+
28
+ [node name="GameScene" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
29
+ GoalManager = NodePath("GoalManager")
30
+ ObstacleManager = NodePath("ObstacleManager")
31
+ Player = NodePath("Player")
32
+
33
+ [node name="GameScene2" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
34
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 0)
35
+ GoalManager = NodePath("GoalManager")
36
+ ObstacleManager = NodePath("ObstacleManager")
37
+ Player = NodePath("Player")
38
+
39
+ [node name="GameScene3" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
40
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 0)
41
+ GoalManager = NodePath("GoalManager")
42
+ ObstacleManager = NodePath("ObstacleManager")
43
+ Player = NodePath("Player")
44
+
45
+ [node name="GameScene4" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
46
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 0)
47
+ GoalManager = NodePath("GoalManager")
48
+ ObstacleManager = NodePath("ObstacleManager")
49
+ Player = NodePath("Player")
50
+
51
+ [node name="GameScene5" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
52
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 100)
53
+ GoalManager = NodePath("GoalManager")
54
+ ObstacleManager = NodePath("ObstacleManager")
55
+ Player = NodePath("Player")
56
+
57
+ [node name="GameScene6" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
58
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 100, 0, 100)
59
+ GoalManager = NodePath("GoalManager")
60
+ ObstacleManager = NodePath("ObstacleManager")
61
+ Player = NodePath("Player")
62
+
63
+ [node name="GameScene7" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
64
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 200, 0, 100)
65
+ GoalManager = NodePath("GoalManager")
66
+ ObstacleManager = NodePath("ObstacleManager")
67
+ Player = NodePath("Player")
68
+
69
+ [node name="GameScene8" parent="." node_paths=PackedStringArray("GoalManager", "ObstacleManager", "Player") instance=ExtResource("1_pdcwe")]
70
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 300, 0, 100)
71
+ GoalManager = NodePath("GoalManager")
72
+ ObstacleManager = NodePath("ObstacleManager")
73
+ Player = NodePath("Player")
74
+
75
+ [node name="Camera3D" type="Camera3D" parent="."]
76
+ transform = Transform3D(1, 0, 0, 0, 0.803856, 0.594823, 0, -0.594823, 0.803856, 0, 9.562, 11.843)
77
+ fov = 51.7
78
+
79
+ [node name="Sync" type="Node" parent="."]
80
+ script = ExtResource("2_7kqnq")
81
+ control_mode = 2
82
+ speed_up = 8.0
83
+ onnx_model_path = "SimpleReachGoal.onnx"
SimpleReachGoal/CSharpAll/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Normalize EOL for all files that Git considers text files.
2
+ * text=auto eol=lf
SimpleReachGoal/CSharpAll/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Godot 4+ specific ignores
2
+ .godot/
3
+ android/
SimpleReachGoal/CSharpAll/SimpleReachGoal.csproj ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Godot.NET.Sdk/4.3.0-dev.5">
2
+ <PropertyGroup>
3
+ <TargetFramework>net6.0</TargetFramework>
4
+ <TargetFramework Condition=" '$(GodotTargetPlatform)' == 'android' ">net7.0</TargetFramework>
5
+ <TargetFramework Condition=" '$(GodotTargetPlatform)' == 'ios' ">net8.0</TargetFramework>
6
+ <EnableDynamicLoading>true</EnableDynamicLoading>
7
+ </PropertyGroup>
8
+ <ItemGroup>
9
+ <PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.15.1" />
10
+ </ItemGroup>
11
+ </Project>
SimpleReachGoal/CSharpAll/SimpleReachGoal.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80cdcca6356a62cf997e3f18777c799ca930b53236f4fb2e911edec5c6c78838
3
+ size 40656
SimpleReachGoal/CSharpAll/SimpleReachGoal.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}") = "SimpleReachGoal", "SimpleReachGoal.csproj", "{8B1C40FD-E462-48E5-B273-A0E360A0580B}"
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
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.Debug|Any CPU.Build.0 = Debug|Any CPU
14
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
15
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
16
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
17
+ {8B1C40FD-E462-48E5-B273-A0E360A0580B}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
18
+ EndGlobalSection
19
+ EndGlobal
SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_2d.gd ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+ class_name AIController2D
3
+
4
+ enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
5
+ @export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
6
+ @export var onnx_model_path := ""
7
+ @export var reset_after := 1000
8
+
9
+ @export_group("Record expert demos mode options")
10
+ ## Path where the demos will be saved. The file can later be used for imitation learning.
11
+ @export var expert_demo_save_path: String
12
+ ## The action that erases the last recorded episode from the currently recorded data.
13
+ @export var remove_last_episode_key: InputEvent
14
+ ## Action will be repeated for n frames. Will introduce control lag if larger than 1.
15
+ ## Can be used to ensure that action_repeat on inference and training matches
16
+ ## the recorded demonstrations.
17
+ @export var action_repeat: int = 1
18
+
19
+ var onnx_model: ONNXModel
20
+
21
+ var heuristic := "human"
22
+ var done := false
23
+ var reward := 0.0
24
+ var n_steps := 0
25
+ var needs_reset := false
26
+
27
+ var _player: Node2D
28
+
29
+
30
+ func _ready():
31
+ add_to_group("AGENT")
32
+
33
+
34
+ func init(player: Node2D):
35
+ _player = player
36
+
37
+
38
+ #-- Methods that need implementing using the "extend script" option in Godot --#
39
+ func get_obs() -> Dictionary:
40
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
41
+ return {"obs": []}
42
+
43
+
44
+ func get_reward() -> float:
45
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
46
+ return 0.0
47
+
48
+
49
+ func get_action_space() -> Dictionary:
50
+ assert(
51
+ false,
52
+ "the get get_action_space method is not implemented when extending from ai_controller"
53
+ )
54
+ return {
55
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
56
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
57
+ }
58
+
59
+
60
+ func set_action(action) -> void:
61
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
62
+
63
+
64
+ #-----------------------------------------------------------------------------#
65
+
66
+
67
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
68
+ # Only needed if you are recording expert demos with this AIController
69
+ func get_action() -> Array:
70
+ assert(
71
+ false,
72
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
73
+ )
74
+ return []
75
+
76
+
77
+ # -----------------------------------------------------------------------------#
78
+
79
+
80
+ func _physics_process(delta):
81
+ n_steps += 1
82
+ if n_steps > reset_after:
83
+ needs_reset = true
84
+
85
+
86
+ func get_obs_space():
87
+ # may need overriding if the obs space is complex
88
+ var obs = get_obs()
89
+ return {
90
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
91
+ }
92
+
93
+
94
+ func reset():
95
+ n_steps = 0
96
+ needs_reset = false
97
+
98
+
99
+ func reset_if_done():
100
+ if done:
101
+ reset()
102
+
103
+
104
+ func set_heuristic(h):
105
+ # sets the heuristic from "human" or "model" nothing to change here
106
+ heuristic = h
107
+
108
+
109
+ func get_done():
110
+ return done
111
+
112
+
113
+ func set_done_false():
114
+ done = false
115
+
116
+
117
+ func zero_reward():
118
+ reward = 0.0
SimpleReachGoal/CSharpAll/addons/godot_rl_agents/controller/ai_controller_3d.gd ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name AIController3D
3
+
4
+ enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS }
5
+ @export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
6
+ @export var onnx_model_path := ""
7
+ @export var reset_after := 1000
8
+
9
+ @export_group("Record expert demos mode options")
10
+ ## Path where the demos will be saved. The file can later be used for imitation learning.
11
+ @export var expert_demo_save_path: String
12
+ ## The action that erases the last recorded episode from the currently recorded data.
13
+ @export var remove_last_episode_key: InputEvent
14
+ ## Action will be repeated for n frames. Will introduce control lag if larger than 1.
15
+ ## Can be used to ensure that action_repeat on inference and training matches
16
+ ## the recorded demonstrations.
17
+ @export var action_repeat: int = 1
18
+
19
+ var onnx_model: ONNXModel
20
+
21
+ var heuristic := "human"
22
+ var done := false
23
+ var reward := 0.0
24
+ var n_steps := 0
25
+ var needs_reset := false
26
+
27
+ var _player: Node3D
28
+
29
+
30
+ func _ready():
31
+ add_to_group("AGENT")
32
+
33
+
34
+ func init(player: Node3D):
35
+ _player = player
36
+
37
+
38
+ #-- Methods that need implementing using the "extend script" option in Godot --#
39
+ func get_obs() -> Dictionary:
40
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
41
+ return {"obs": []}
42
+
43
+
44
+ func get_reward() -> float:
45
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
46
+ return 0.0
47
+
48
+
49
+ func get_action_space() -> Dictionary:
50
+ assert(
51
+ false, "the get_action_space method is not implemented when extending from ai_controller"
52
+ )
53
+ return {
54
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
55
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
56
+ }
57
+
58
+
59
+ func set_action(action) -> void:
60
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
61
+
62
+
63
+ #-----------------------------------------------------------------------------#
64
+
65
+
66
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
67
+ # Only needed if you are recording expert demos with this AIController
68
+ func get_action() -> Array:
69
+ assert(
70
+ false,
71
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
72
+ )
73
+ return []
74
+
75
+
76
+ # -----------------------------------------------------------------------------#
77
+
78
+
79
+ func _physics_process(delta):
80
+ n_steps += 1
81
+ if n_steps > reset_after:
82
+ needs_reset = true
83
+
84
+
85
+ func get_obs_space():
86
+ # may need overriding if the obs space is complex
87
+ var obs = get_obs()
88
+ return {
89
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
90
+ }
91
+
92
+
93
+ func reset():
94
+ n_steps = 0
95
+ needs_reset = false
96
+
97
+
98
+ func reset_if_done():
99
+ if done:
100
+ reset()
101
+
102
+
103
+ func set_heuristic(h):
104
+ # sets the heuristic from "human" or "model" nothing to change here
105
+ heuristic = h
106
+
107
+
108
+ func get_done():
109
+ return done
110
+
111
+
112
+ func set_done_false():
113
+ done = false
114
+
115
+
116
+ func zero_reward():
117
+ reward = 0.0
SimpleReachGoal/CSharpAll/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")
SimpleReachGoal/CSharpAll/addons/godot_rl_agents/icon.png ADDED

Git LFS Details

  • SHA256: e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
  • Pointer size: 128 Bytes
  • Size of remote file: 198 Bytes
SimpleReachGoal/CSharpAll/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using Microsoft.ML.OnnxRuntime;
3
+ using Microsoft.ML.OnnxRuntime.Tensors;
4
+ using System.Collections.Generic;
5
+ using System.Linq;
6
+
7
+ namespace GodotONNX
8
+ {
9
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
10
+ public partial class ONNXInference : GodotObject
11
+ {
12
+
13
+ private InferenceSession session;
14
+ /// <summary>
15
+ /// Path to the ONNX model. Use Initialize to change it.
16
+ /// </summary>
17
+ private string modelPath;
18
+ private int batchSize;
19
+
20
+ private SessionOptions SessionOpt;
21
+
22
+ //init function
23
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Initialize/*'/>
24
+ public void Initialize(string Path, int BatchSize)
25
+ {
26
+ modelPath = Path;
27
+ batchSize = BatchSize;
28
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
29
+ session = LoadModel(modelPath);
30
+
31
+ }
32
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
33
+ public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
34
+ {
35
+ //Current model: Any (Godot Rl Agents)
36
+ //Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
37
+
38
+ //Fill the input tensors
39
+ // create span from inputSize
40
+ var span = new float[obs.Count]; //There's probably a better way to do this
41
+ for (int i = 0; i < obs.Count; i++)
42
+ {
43
+ span[i] = obs[i];
44
+ }
45
+
46
+ IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
47
+ {
48
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
49
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
50
+ };
51
+ IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
52
+
53
+ IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
54
+ //We do not use "using" here so we get a better exception explaination later
55
+ try
56
+ {
57
+ results = session.Run(inputs, outputNames);
58
+ }
59
+ catch (OnnxRuntimeException e)
60
+ {
61
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
62
+ GD.Print("Error at inference: ", e);
63
+ return null;
64
+ }
65
+ //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
66
+ Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
67
+ DisposableNamedOnnxValue output1 = results.First();
68
+ DisposableNamedOnnxValue output2 = results.Last();
69
+ Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
70
+ Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
71
+
72
+ foreach (float f in output1.AsEnumerable<float>())
73
+ {
74
+ output1Array.Add(f);
75
+ }
76
+
77
+ foreach (float f in output2.AsEnumerable<float>())
78
+ {
79
+ output2Array.Add(f);
80
+ }
81
+
82
+ output.Add(output1.Name, output1Array);
83
+ output.Add(output2.Name, output2Array);
84
+
85
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
86
+ results.Dispose();
87
+ return output;
88
+ }
89
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
90
+ public InferenceSession LoadModel(string Path)
91
+ {
92
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
93
+ byte[] model = file.GetBuffer((int)file.GetLength());
94
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
95
+ return new InferenceSession(model, SessionOpt); //Load the model
96
+ }
97
+ public void FreeDisposables()
98
+ {
99
+ session.Dispose();
100
+ SessionOpt.Dispose();
101
+ }
102
+ }
103
+ }
SimpleReachGoal/CSharpAll/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
+ }
SimpleReachGoal/CSharpAll/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>