jtatman commited on
Commit
f4d4c4d
·
verified ·
1 Parent(s): 65e6285

Upload folder using huggingface_hub

Browse files
Files changed (49) hide show
  1. .gitattributes +5 -58
  2. .gitignore +2 -0
  3. CartExamples.csproj +10 -0
  4. CartExamples.sln +19 -0
  5. README.md +25 -0
  6. addons/godot_rl_agents/controller/ai_controller_2d.gd +126 -0
  7. addons/godot_rl_agents/controller/ai_controller_3d.gd +125 -0
  8. addons/godot_rl_agents/godot_rl_agents.gd +16 -0
  9. addons/godot_rl_agents/icon.png +3 -0
  10. addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +109 -0
  11. addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
  12. addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
  13. addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml +29 -0
  14. addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd +54 -0
  15. addons/godot_rl_agents/plugin.cfg +7 -0
  16. addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn +48 -0
  17. addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd +235 -0
  18. addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd +25 -0
  19. addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd +118 -0
  20. addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn +7 -0
  21. addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn +6 -0
  22. addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd +258 -0
  23. addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd +25 -0
  24. addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd +63 -0
  25. addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn +35 -0
  26. addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd +185 -0
  27. addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn +27 -0
  28. addons/godot_rl_agents/sync.gd +587 -0
  29. assets/goal.glb +0 -0
  30. assets/map.glb +0 -0
  31. assets/map_grass.png +3 -0
  32. assets/robot.glb +0 -0
  33. icon.svg +1 -0
  34. license.md +5 -0
  35. model.onnx +3 -0
  36. project.godot +51 -0
  37. readme.md +52 -0
  38. scenes/ball/ball.gd +20 -0
  39. scenes/ball/ball.tscn +34 -0
  40. scenes/goal/goal.gd +28 -0
  41. scenes/goal/goal.tscn +97 -0
  42. scenes/goal/goal_visual.tscn +70 -0
  43. scenes/playing_area/map.tscn +151 -0
  44. scenes/playing_area/playing_area.tscn +48 -0
  45. scenes/playing_area/wall.gd +2 -0
  46. scenes/robot/robot.gd +131 -0
  47. scenes/robot/robot.tscn +241 -0
  48. scenes/robot/robot_ai_controller.gd +86 -0
  49. scenes/training_scene/training_scene.tscn +58 -0
.gitattributes CHANGED
@@ -1,58 +1,5 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.lz4 filter=lfs diff=lfs merge=lfs -text
12
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
13
- *.model filter=lfs diff=lfs merge=lfs -text
14
- *.msgpack filter=lfs diff=lfs merge=lfs -text
15
- *.npy filter=lfs diff=lfs merge=lfs -text
16
- *.npz filter=lfs diff=lfs merge=lfs -text
17
- *.onnx filter=lfs diff=lfs merge=lfs -text
18
- *.ot filter=lfs diff=lfs merge=lfs -text
19
- *.parquet filter=lfs diff=lfs merge=lfs -text
20
- *.pb filter=lfs diff=lfs merge=lfs -text
21
- *.pickle filter=lfs diff=lfs merge=lfs -text
22
- *.pkl filter=lfs diff=lfs merge=lfs -text
23
- *.pt filter=lfs diff=lfs merge=lfs -text
24
- *.pth filter=lfs diff=lfs merge=lfs -text
25
- *.rar filter=lfs diff=lfs merge=lfs -text
26
- *.safetensors filter=lfs diff=lfs merge=lfs -text
27
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
28
- *.tar.* filter=lfs diff=lfs merge=lfs -text
29
- *.tar filter=lfs diff=lfs merge=lfs -text
30
- *.tflite filter=lfs diff=lfs merge=lfs -text
31
- *.tgz filter=lfs diff=lfs merge=lfs -text
32
- *.wasm filter=lfs diff=lfs merge=lfs -text
33
- *.xz filter=lfs diff=lfs merge=lfs -text
34
- *.zip filter=lfs diff=lfs merge=lfs -text
35
- *.zst filter=lfs diff=lfs merge=lfs -text
36
- *tfevents* filter=lfs diff=lfs merge=lfs -text
37
- # Audio files - uncompressed
38
- *.pcm filter=lfs diff=lfs merge=lfs -text
39
- *.sam filter=lfs diff=lfs merge=lfs -text
40
- *.raw filter=lfs diff=lfs merge=lfs -text
41
- # Audio files - compressed
42
- *.aac filter=lfs diff=lfs merge=lfs -text
43
- *.flac filter=lfs diff=lfs merge=lfs -text
44
- *.mp3 filter=lfs diff=lfs merge=lfs -text
45
- *.ogg filter=lfs diff=lfs merge=lfs -text
46
- *.wav filter=lfs diff=lfs merge=lfs -text
47
- # Image files - uncompressed
48
- *.bmp filter=lfs diff=lfs merge=lfs -text
49
- *.gif filter=lfs diff=lfs merge=lfs -text
50
- *.png filter=lfs diff=lfs merge=lfs -text
51
- *.tiff filter=lfs diff=lfs merge=lfs -text
52
- # Image files - compressed
53
- *.jpg filter=lfs diff=lfs merge=lfs -text
54
- *.jpeg filter=lfs diff=lfs merge=lfs -text
55
- *.webp filter=lfs diff=lfs merge=lfs -text
56
- # Video files - compressed
57
- *.mp4 filter=lfs diff=lfs merge=lfs -text
58
- *.webm filter=lfs diff=lfs merge=lfs -text
 
1
+ # Normalize EOL for all files that Git considers text files.
2
+ * text=auto eol=lf
3
+ addons/godot_rl_agents/icon.png filter=lfs diff=lfs merge=lfs -text
4
+ assets/map_grass.png filter=lfs diff=lfs merge=lfs -text
5
+ model.onnx filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Godot 4+ specific ignores
2
+ .godot/
CartExamples.csproj ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Godot.NET.Sdk/4.3.0">
2
+ <PropertyGroup>
3
+ <TargetFramework>net6.0</TargetFramework>
4
+ <EnableDynamicLoading>true</EnableDynamicLoading>
5
+ <RootNamespace>GodotRLAgents</RootNamespace>
6
+ </PropertyGroup>
7
+ <ItemGroup>
8
+ <PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.15.1" />
9
+ </ItemGroup>
10
+ </Project>
CartExamples.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}") = "CartExamples", "CartExamples.csproj", "{E883D553-AA7C-4CD8-9C89-A966186B3776}"
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
+ {E883D553-AA7C-4CD8-9C89-A966186B3776}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13
+ {E883D553-AA7C-4CD8-9C89-A966186B3776}.Debug|Any CPU.Build.0 = Debug|Any CPU
14
+ {E883D553-AA7C-4CD8-9C89-A966186B3776}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
15
+ {E883D553-AA7C-4CD8-9C89-A966186B3776}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
16
+ {E883D553-AA7C-4CD8-9C89-A966186B3776}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
17
+ {E883D553-AA7C-4CD8-9C89-A966186B3776}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
18
+ EndGlobalSection
19
+ EndGlobal
README.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: godot-rl
3
+ tags:
4
+ - deep-reinforcement-learning
5
+ - reinforcement-learning
6
+ - godot-rl
7
+ - environments
8
+ - video-games
9
+ ---
10
+
11
+ A RL environment called ScoreTheGoal 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_ScoreTheGoal
22
+ ```
23
+
24
+
25
+
addons/godot_rl_agents/controller/ai_controller_2d.gd ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+ class_name AIController2D
3
+
4
+ enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS } ## Inherit setting from sync node ## Test the environment manually ## Train a model ## Load a pretrained model using an .onnx file ## Record observations and actions for expert demonstrations
5
+ @export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
6
+ ## The path to a trained .onnx model file to use for inference (overrides the path set in sync node).
7
+ @export var onnx_model_path := ""
8
+ ## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance.
9
+ @export var reset_after := 1000
10
+
11
+ @export_group("Record expert demos mode options")
12
+ ## Path where the demos will be saved. The file can later be used for imitation learning.
13
+ @export var expert_demo_save_path: String
14
+ ## The action that erases the last recorded episode from the currently recorded data.
15
+ @export var remove_last_episode_key: InputEvent
16
+ ## Action will be repeated for n frames. Will introduce control lag if larger than 1.
17
+ ## Can be used to ensure that action_repeat on inference and training matches
18
+ ## the recorded demonstrations.
19
+ @export var action_repeat: int = 1
20
+
21
+ @export_group("Multi-policy mode options")
22
+ ## Allows you to set certain agents to use different policies.
23
+ ## Changing has no effect with default SB3 training. Works with Rllib example.
24
+ ## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md
25
+ @export var policy_name: String = "shared_policy"
26
+
27
+ var onnx_model: ONNXModel
28
+
29
+ var heuristic := "human"
30
+ var done := false
31
+ var reward := 0.0
32
+ var n_steps := 0
33
+ var needs_reset := false
34
+
35
+ var _player: Node2D
36
+
37
+
38
+ func _ready():
39
+ add_to_group("AGENT")
40
+
41
+
42
+ func init(player: Node2D):
43
+ _player = player
44
+
45
+
46
+ #-- Methods that need implementing using the "extend script" option in Godot --#
47
+ func get_obs() -> Dictionary:
48
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
49
+ return {"obs": []}
50
+
51
+
52
+ func get_reward() -> float:
53
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
54
+ return 0.0
55
+
56
+
57
+ func get_action_space() -> Dictionary:
58
+ assert(
59
+ false,
60
+ "the get get_action_space method is not implemented when extending from ai_controller"
61
+ )
62
+ return {
63
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
64
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
65
+ }
66
+
67
+
68
+ func set_action(action) -> void:
69
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
70
+
71
+
72
+ #-----------------------------------------------------------------------------#
73
+
74
+
75
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
76
+ # Only needed if you are recording expert demos with this AIController
77
+ func get_action() -> Array:
78
+ assert(
79
+ false,
80
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
81
+ )
82
+ return []
83
+
84
+
85
+ # -----------------------------------------------------------------------------#
86
+
87
+
88
+ func _physics_process(delta):
89
+ n_steps += 1
90
+ if n_steps > reset_after:
91
+ needs_reset = true
92
+
93
+
94
+ func get_obs_space():
95
+ # may need overriding if the obs space is complex
96
+ var obs = get_obs()
97
+ return {
98
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
99
+ }
100
+
101
+
102
+ func reset():
103
+ n_steps = 0
104
+ needs_reset = false
105
+
106
+
107
+ func reset_if_done():
108
+ if done:
109
+ reset()
110
+
111
+
112
+ func set_heuristic(h):
113
+ # sets the heuristic from "human" or "model" nothing to change here
114
+ heuristic = h
115
+
116
+
117
+ func get_done():
118
+ return done
119
+
120
+
121
+ func set_done_false():
122
+ done = false
123
+
124
+
125
+ func zero_reward():
126
+ reward = 0.0
addons/godot_rl_agents/controller/ai_controller_3d.gd ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name AIController3D
3
+
4
+ enum ControlModes { INHERIT_FROM_SYNC, HUMAN, TRAINING, ONNX_INFERENCE, RECORD_EXPERT_DEMOS } ## Inherit setting from sync node ## Test the environment manually ## Train a model ## Load a pretrained model using an .onnx file ## Record observations and actions for expert demonstrations
5
+ @export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC
6
+ ## The path to a trained .onnx model file to use for inference (overrides the path set in sync node).
7
+ @export var onnx_model_path := ""
8
+ ## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance.
9
+ @export var reset_after := 1000
10
+
11
+ @export_group("Record expert demos mode options")
12
+ ## Path where the demos will be saved. The file can later be used for imitation learning.
13
+ @export var expert_demo_save_path: String
14
+ ## The action that erases the last recorded episode from the currently recorded data.
15
+ @export var remove_last_episode_key: InputEvent
16
+ ## Action will be repeated for n frames. Will introduce control lag if larger than 1.
17
+ ## Can be used to ensure that action_repeat on inference and training matches
18
+ ## the recorded demonstrations.
19
+ @export var action_repeat: int = 1
20
+
21
+ @export_group("Multi-policy mode options")
22
+ ## Allows you to set certain agents to use different policies.
23
+ ## Changing has no effect with default SB3 training. Works with Rllib example.
24
+ ## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md
25
+ @export var policy_name: String = "shared_policy"
26
+
27
+ var onnx_model: ONNXModel
28
+
29
+ var heuristic := "human"
30
+ var done := false
31
+ var reward := 0.0
32
+ var n_steps := 0
33
+ var needs_reset := false
34
+
35
+ var _player: Node3D
36
+
37
+
38
+ func _ready():
39
+ add_to_group("AGENT")
40
+
41
+
42
+ func init(player: Node3D):
43
+ _player = player
44
+
45
+
46
+ #-- Methods that need implementing using the "extend script" option in Godot --#
47
+ func get_obs() -> Dictionary:
48
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
49
+ return {"obs": []}
50
+
51
+
52
+ func get_reward() -> float:
53
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
54
+ return 0.0
55
+
56
+
57
+ func get_action_space() -> Dictionary:
58
+ assert(
59
+ false, "the get_action_space method is not implemented when extending from ai_controller"
60
+ )
61
+ return {
62
+ "example_actions_continous": {"size": 2, "action_type": "continuous"},
63
+ "example_actions_discrete": {"size": 2, "action_type": "discrete"},
64
+ }
65
+
66
+
67
+ func set_action(action) -> void:
68
+ assert(false, "the set_action method is not implemented when extending from ai_controller")
69
+
70
+
71
+ #-----------------------------------------------------------------------------#
72
+
73
+
74
+ #-- Methods that sometimes need implementing using the "extend script" option in Godot --#
75
+ # Only needed if you are recording expert demos with this AIController
76
+ func get_action() -> Array:
77
+ assert(
78
+ false,
79
+ "the get_action method is not implemented in extended AIController but demo_recorder is used"
80
+ )
81
+ return []
82
+
83
+
84
+ # -----------------------------------------------------------------------------#
85
+
86
+
87
+ func _physics_process(delta):
88
+ n_steps += 1
89
+ if n_steps > reset_after:
90
+ needs_reset = true
91
+
92
+
93
+ func get_obs_space():
94
+ # may need overriding if the obs space is complex
95
+ var obs = get_obs()
96
+ return {
97
+ "obs": {"size": [len(obs["obs"])], "space": "box"},
98
+ }
99
+
100
+
101
+ func reset():
102
+ n_steps = 0
103
+ needs_reset = false
104
+
105
+
106
+ func reset_if_done():
107
+ if done:
108
+ reset()
109
+
110
+
111
+ func set_heuristic(h):
112
+ # sets the heuristic from "human" or "model" nothing to change here
113
+ heuristic = h
114
+
115
+
116
+ func get_done():
117
+ return done
118
+
119
+
120
+ func set_done_false():
121
+ done = false
122
+
123
+
124
+ func zero_reward():
125
+ reward = 0.0
addons/godot_rl_agents/godot_rl_agents.gd ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends EditorPlugin
3
+
4
+
5
+ func _enter_tree():
6
+ # Initialization of the plugin goes here.
7
+ # Add the new type with a name, a parent type, a script and an icon.
8
+ add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png"))
9
+ #add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png"))
10
+
11
+
12
+ func _exit_tree():
13
+ # Clean-up of the plugin goes here.
14
+ # Always remember to remove it from the engine when deactivated.
15
+ remove_custom_type("Sync")
16
+ #remove_custom_type("RaycastSensor2D2")
addons/godot_rl_agents/icon.png ADDED

Git LFS Details

  • SHA256: e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44
  • Pointer size: 128 Bytes
  • Size of remote file: 198 Bytes
addons/godot_rl_agents/onnx/csharp/ONNXInference.cs ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using Microsoft.ML.OnnxRuntime;
3
+ using Microsoft.ML.OnnxRuntime.Tensors;
4
+ using System.Collections.Generic;
5
+ using System.Linq;
6
+
7
+ namespace GodotONNX
8
+ {
9
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
10
+ public partial class ONNXInference : GodotObject
11
+ {
12
+
13
+ private InferenceSession session;
14
+ /// <summary>
15
+ /// Path to the ONNX model. Use Initialize to change it.
16
+ /// </summary>
17
+ private string modelPath;
18
+ private int batchSize;
19
+
20
+ private SessionOptions SessionOpt;
21
+
22
+ /// <summary>
23
+ /// init function
24
+ /// </summary>
25
+ /// <param name="Path"></param>
26
+ /// <param name="BatchSize"></param>
27
+ /// <returns>Returns the output size of the model</returns>
28
+ public int Initialize(string Path, int BatchSize)
29
+ {
30
+ modelPath = Path;
31
+ batchSize = BatchSize;
32
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
33
+ session = LoadModel(modelPath);
34
+ return session.OutputMetadata["output"].Dimensions[1];
35
+ }
36
+
37
+
38
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
39
+ public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
40
+ {
41
+ //Current model: Any (Godot Rl Agents)
42
+ //Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
43
+
44
+ //Fill the input tensors
45
+ // create span from inputSize
46
+ var span = new float[obs.Count]; //There's probably a better way to do this
47
+ for (int i = 0; i < obs.Count; i++)
48
+ {
49
+ span[i] = obs[i];
50
+ }
51
+
52
+ IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
53
+ {
54
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
55
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
56
+ };
57
+ IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
58
+
59
+ IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
60
+ //We do not use "using" here so we get a better exception explaination later
61
+ try
62
+ {
63
+ results = session.Run(inputs, outputNames);
64
+ }
65
+ catch (OnnxRuntimeException e)
66
+ {
67
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
68
+ GD.Print("Error at inference: ", e);
69
+ return null;
70
+ }
71
+ //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
72
+ Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
73
+ DisposableNamedOnnxValue output1 = results.First();
74
+ DisposableNamedOnnxValue output2 = results.Last();
75
+ Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
76
+ Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
77
+
78
+ foreach (float f in output1.AsEnumerable<float>())
79
+ {
80
+ output1Array.Add(f);
81
+ }
82
+
83
+ foreach (float f in output2.AsEnumerable<float>())
84
+ {
85
+ output2Array.Add(f);
86
+ }
87
+
88
+ output.Add(output1.Name, output1Array);
89
+ output.Add(output2.Name, output2Array);
90
+
91
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
92
+ results.Dispose();
93
+ return output;
94
+ }
95
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
96
+ public InferenceSession LoadModel(string Path)
97
+ {
98
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
99
+ byte[] model = file.GetBuffer((int)file.GetLength());
100
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
101
+ return new InferenceSession(model, SessionOpt); //Load the model
102
+ }
103
+ public void FreeDisposables()
104
+ {
105
+ session.Dispose();
106
+ SessionOpt.Dispose();
107
+ }
108
+ }
109
+ }
addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using Microsoft.ML.OnnxRuntime;
3
+
4
+ namespace GodotONNX
5
+ {
6
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SessionConfigurator/*'/>
7
+
8
+ public static class SessionConfigurator
9
+ {
10
+ public enum ComputeName
11
+ {
12
+ CUDA,
13
+ ROCm,
14
+ DirectML,
15
+ CoreML,
16
+ CPU
17
+ }
18
+
19
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/GetSessionOptions/*'/>
20
+ public static SessionOptions MakeConfiguredSessionOptions()
21
+ {
22
+ SessionOptions sessionOptions = new();
23
+ SetOptions(sessionOptions);
24
+ return sessionOptions;
25
+ }
26
+
27
+ private static void SetOptions(SessionOptions sessionOptions)
28
+ {
29
+ sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
30
+ ApplySystemSpecificOptions(sessionOptions);
31
+ }
32
+
33
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SystemCheck/*'/>
34
+ static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
35
+ {
36
+ //Most code for this function is verbose only, the only reason it exists is to track
37
+ //implementation progress of the different compute APIs.
38
+
39
+ //December 2022: CUDA is not working.
40
+
41
+ string OSName = OS.GetName(); //Get OS Name
42
+
43
+ //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
44
+ // //TODO: Get CPU architecture
45
+
46
+ //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
47
+ //Windows can use OpenVINO (C#) on x64
48
+ //TODO: try TensorRT instead of CUDA
49
+ //TODO: Use OpenVINO for Intel Graphics
50
+
51
+ // Temporarily using CPU on all platforms to avoid errors detected with DML
52
+ ComputeName ComputeAPI = ComputeName.CPU;
53
+
54
+ //match OS and Compute API
55
+ GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
56
+
57
+ // CPU is set by default without appending necessary
58
+ // sessionOptions.AppendExecutionProvider_CPU(0);
59
+
60
+ /*
61
+ switch (OSName)
62
+ {
63
+ case "Windows": //Can use CUDA, DirectML
64
+ if (ComputeAPI is ComputeName.CUDA)
65
+ {
66
+ //CUDA
67
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
68
+ //sessionOptions.AppendExecutionProvider_DML(0);
69
+ }
70
+ else if (ComputeAPI is ComputeName.DirectML)
71
+ {
72
+ //DirectML
73
+ //sessionOptions.AppendExecutionProvider_DML(0);
74
+ }
75
+ break;
76
+ case "X11": //Can use CUDA, ROCm
77
+ if (ComputeAPI is ComputeName.CUDA)
78
+ {
79
+ //CUDA
80
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
81
+ }
82
+ if (ComputeAPI is ComputeName.ROCm)
83
+ {
84
+ //ROCm, only works on x86
85
+ //Research indicates that this has to be compiled as a GDNative plugin
86
+ //GD.Print("ROCm not supported yet, using CPU.");
87
+ //sessionOptions.AppendExecutionProvider_CPU(0);
88
+ }
89
+ break;
90
+ case "macOS": //Can use CoreML
91
+ if (ComputeAPI is ComputeName.CoreML)
92
+ { //CoreML
93
+ //TODO: Needs testing
94
+ //sessionOptions.AppendExecutionProvider_CoreML(0);
95
+ //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
96
+ }
97
+ break;
98
+ default:
99
+ GD.Print("OS not Supported.");
100
+ break;
101
+ }
102
+ */
103
+ }
104
+
105
+
106
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/ComputeCheck/*'/>
107
+ public static ComputeName ComputeCheck()
108
+ {
109
+ string adapterName = Godot.RenderingServer.GetVideoAdapterName();
110
+ //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
111
+ adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
112
+ //TODO: GPU vendors for MacOS, what do they even use these days?
113
+
114
+ if (adapterName.Contains("INTEL"))
115
+ {
116
+ return ComputeName.DirectML;
117
+ }
118
+ if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
119
+ {
120
+ return ComputeName.DirectML;
121
+ }
122
+ if (adapterName.Contains("NVIDIA"))
123
+ {
124
+ return ComputeName.CUDA;
125
+ }
126
+
127
+ GD.Print("Graphics Card not recognized."); //Should use CPU
128
+ return ComputeName.CPU;
129
+ }
130
+ }
131
+ }
addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <docs>
2
+ <members name="ONNXInference">
3
+ <ONNXInference>
4
+ <summary>
5
+ The main <c>ONNXInference</c> Class that handles the inference process.
6
+ </summary>
7
+ </ONNXInference>
8
+ <Initialize>
9
+ <summary>
10
+ Starts the inference process.
11
+ </summary>
12
+ <param name="Path">Path to the ONNX model, expects a path inside resources.</param>
13
+ <param name="BatchSize">How many observations will the model recieve.</param>
14
+ </Initialize>
15
+ <Run>
16
+ <summary>
17
+ Runs the given input through the model and returns the output.
18
+ </summary>
19
+ <param name="obs">Dictionary containing all observations.</param>
20
+ <param name="state_ins">How many different agents are creating these observations.</param>
21
+ <returns>A Dictionary of arrays, containing instructions based on the observations.</returns>
22
+ </Run>
23
+ <Load>
24
+ <summary>
25
+ Loads the given model into the inference process, using the best Execution provider available.
26
+ </summary>
27
+ <param name="Path">Path to the ONNX model, expects a path inside resources.</param>
28
+ <returns>InferenceSession ready to run.</returns>
29
+ </Load>
30
+ </members>
31
+ </docs>
addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <docs>
2
+ <members name="SessionConfigurator">
3
+ <SessionConfigurator>
4
+ <summary>
5
+ The main <c>SessionConfigurator</c> Class that handles the execution options and providers for the inference process.
6
+ </summary>
7
+ </SessionConfigurator>
8
+ <GetSessionOptions>
9
+ <summary>
10
+ Creates a SessionOptions with all available execution providers.
11
+ </summary>
12
+ <returns>SessionOptions with all available execution providers.</returns>
13
+ </GetSessionOptions>
14
+ <SystemCheck>
15
+ <summary>
16
+ Appends any execution provider available in the current system.
17
+ </summary>
18
+ <remarks>
19
+ This function is mainly verbose for tracking implementation progress of different compute APIs.
20
+ </remarks>
21
+ </SystemCheck>
22
+ <ComputeCheck>
23
+ <summary>
24
+ Checks for available GPUs.
25
+ </summary>
26
+ <returns>An integer identifier for each compute platform.</returns>
27
+ </ComputeCheck>
28
+ </members>
29
+ </docs>
addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Resource
2
+ class_name ONNXModel
3
+ var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs")
4
+
5
+ var inferencer = null
6
+
7
+ ## How many action values the model outputs
8
+ var action_output_size: int
9
+
10
+ ## Used to differentiate models
11
+ ## that only output continuous action mean (e.g. sb3, cleanrl export)
12
+ ## versus models that output mean and logstd (e.g. rllib export)
13
+ var action_means_only: bool
14
+
15
+ ## Whether action_means_value has been set already for this model
16
+ var action_means_only_set: bool
17
+
18
+
19
+ # Must provide the path to the model and the batch size
20
+ func _init(model_path, batch_size):
21
+ inferencer = inferencer_script.new()
22
+ action_output_size = inferencer.Initialize(model_path, batch_size)
23
+
24
+
25
+ # This function is the one that will be called from the game,
26
+ # requires the observation as an array and the state_ins as an int
27
+ # returns an Array containing the action the model takes.
28
+ func run_inference(obs: Array, state_ins: int) -> Dictionary:
29
+ if inferencer == null:
30
+ printerr("Inferencer not initialized")
31
+ return {}
32
+ return inferencer.RunInference(obs, state_ins)
33
+
34
+
35
+ func _notification(what):
36
+ if what == NOTIFICATION_PREDELETE:
37
+ inferencer.FreeDisposables()
38
+ inferencer.free()
39
+
40
+
41
+ # Check whether agent uses a continuous actions model with only action means or not
42
+ func set_action_means_only(agent_action_space):
43
+ action_means_only_set = true
44
+ var continuous_only: bool = true
45
+ var continuous_actions: int
46
+ for action in agent_action_space:
47
+ if not agent_action_space[action]["action_type"] == "continuous":
48
+ continuous_only = false
49
+ break
50
+ else:
51
+ continuous_actions += agent_action_space[action]["size"]
52
+ if continuous_only:
53
+ if continuous_actions == action_output_size:
54
+ action_means_only = true
addons/godot_rl_agents/plugin.cfg ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [plugin]
2
+
3
+ name="GodotRLAgents"
4
+ description="Custom nodes for the godot rl agents toolkit "
5
+ author="Edward Beeching"
6
+ version="0.1"
7
+ script="godot_rl_agents.gd"
addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"]
2
+
3
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
4
+
5
+ [sub_resource type="GDScript" id="2"]
6
+ script/source = "extends Node2D
7
+
8
+
9
+
10
+ func _physics_process(delta: float) -> void:
11
+ print(\"step start\")
12
+
13
+ "
14
+
15
+ [sub_resource type="GDScript" id="1"]
16
+ script/source = "extends RayCast2D
17
+
18
+ var steps = 1
19
+
20
+ func _physics_process(delta: float) -> void:
21
+ print(\"processing raycast\")
22
+ steps += 1
23
+ if steps % 2:
24
+ force_raycast_update()
25
+
26
+ print(is_colliding())
27
+ "
28
+
29
+ [sub_resource type="CircleShape2D" id="3"]
30
+
31
+ [node name="ExampleRaycastSensor2D" type="Node2D"]
32
+ script = SubResource("2")
33
+
34
+ [node name="ExampleAgent" type="Node2D" parent="."]
35
+ position = Vector2(573, 314)
36
+ rotation = 0.286234
37
+
38
+ [node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"]
39
+ script = ExtResource("1")
40
+
41
+ [node name="TestRayCast2D" type="RayCast2D" parent="."]
42
+ script = SubResource("1")
43
+
44
+ [node name="StaticBody2D" type="StaticBody2D" parent="."]
45
+ position = Vector2(1, 52)
46
+
47
+ [node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"]
48
+ shape = SubResource("3")
addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor2D
3
+ class_name GridSensor2D
4
+
5
+ @export var debug_view := false:
6
+ get:
7
+ return debug_view
8
+ set(value):
9
+ debug_view = value
10
+ _update()
11
+
12
+ @export_flags_2d_physics var detection_mask := 0:
13
+ get:
14
+ return detection_mask
15
+ set(value):
16
+ detection_mask = value
17
+ _update()
18
+
19
+ @export var collide_with_areas := false:
20
+ get:
21
+ return collide_with_areas
22
+ set(value):
23
+ collide_with_areas = value
24
+ _update()
25
+
26
+ @export var collide_with_bodies := true:
27
+ get:
28
+ return collide_with_bodies
29
+ set(value):
30
+ collide_with_bodies = value
31
+ _update()
32
+
33
+ @export_range(1, 200, 0.1) var cell_width := 20.0:
34
+ get:
35
+ return cell_width
36
+ set(value):
37
+ cell_width = value
38
+ _update()
39
+
40
+ @export_range(1, 200, 0.1) var cell_height := 20.0:
41
+ get:
42
+ return cell_height
43
+ set(value):
44
+ cell_height = value
45
+ _update()
46
+
47
+ @export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
48
+ get:
49
+ return grid_size_x
50
+ set(value):
51
+ grid_size_x = value
52
+ _update()
53
+
54
+ @export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
55
+ get:
56
+ return grid_size_y
57
+ set(value):
58
+ grid_size_y = value
59
+ _update()
60
+
61
+ var _obs_buffer: PackedFloat64Array
62
+ var _rectangle_shape: RectangleShape2D
63
+ var _collision_mapping: Dictionary
64
+ var _n_layers_per_cell: int
65
+
66
+ var _highlighted_cell_color: Color
67
+ var _standard_cell_color: Color
68
+
69
+
70
+ func get_observation():
71
+ return _obs_buffer
72
+
73
+
74
+ func _update():
75
+ if Engine.is_editor_hint():
76
+ if is_node_ready():
77
+ _spawn_nodes()
78
+
79
+
80
+ func _ready() -> void:
81
+ _set_colors()
82
+
83
+ if Engine.is_editor_hint():
84
+ if get_child_count() == 0:
85
+ _spawn_nodes()
86
+ else:
87
+ _spawn_nodes()
88
+
89
+
90
+ func _set_colors() -> void:
91
+ _standard_cell_color = Color(100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
92
+ _highlighted_cell_color = Color(255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0)
93
+
94
+
95
+ func _get_collision_mapping() -> Dictionary:
96
+ # defines which layer is mapped to which cell obs index
97
+ var total_bits = 0
98
+ var collision_mapping = {}
99
+ for i in 32:
100
+ var bit_mask = 2 ** i
101
+ if (detection_mask & bit_mask) > 0:
102
+ collision_mapping[i] = total_bits
103
+ total_bits += 1
104
+
105
+ return collision_mapping
106
+
107
+
108
+ func _spawn_nodes():
109
+ for cell in get_children():
110
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
111
+ cell.queue_free()
112
+
113
+ _collision_mapping = _get_collision_mapping()
114
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
115
+ # allocate memory for the observations
116
+ _n_layers_per_cell = len(_collision_mapping)
117
+ _obs_buffer = PackedFloat64Array()
118
+ _obs_buffer.resize(grid_size_x * grid_size_y * _n_layers_per_cell)
119
+ _obs_buffer.fill(0)
120
+ #prints(len(_obs_buffer), _obs_buffer )
121
+
122
+ _rectangle_shape = RectangleShape2D.new()
123
+ _rectangle_shape.set_size(Vector2(cell_width, cell_height))
124
+
125
+ var shift := Vector2(
126
+ -(grid_size_x / 2) * cell_width,
127
+ -(grid_size_y / 2) * cell_height,
128
+ )
129
+
130
+ for i in grid_size_x:
131
+ for j in grid_size_y:
132
+ var cell_position = Vector2(i * cell_width, j * cell_height) + shift
133
+ _create_cell(i, j, cell_position)
134
+
135
+
136
+ func _create_cell(i: int, j: int, position: Vector2):
137
+ var cell := Area2D.new()
138
+ cell.position = position
139
+ cell.name = "GridCell %s %s" % [i, j]
140
+ cell.modulate = _standard_cell_color
141
+
142
+ if collide_with_areas:
143
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
144
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
145
+
146
+ if collide_with_bodies:
147
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
148
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
149
+
150
+ cell.collision_layer = 0
151
+ cell.collision_mask = detection_mask
152
+ cell.monitorable = true
153
+ add_child(cell)
154
+ cell.set_owner(get_tree().edited_scene_root)
155
+
156
+ var col_shape := CollisionShape2D.new()
157
+ col_shape.shape = _rectangle_shape
158
+ col_shape.name = "CollisionShape2D"
159
+ cell.add_child(col_shape)
160
+ col_shape.set_owner(get_tree().edited_scene_root)
161
+
162
+ if debug_view:
163
+ var quad = MeshInstance2D.new()
164
+ quad.name = "MeshInstance2D"
165
+ var quad_mesh = QuadMesh.new()
166
+
167
+ quad_mesh.set_size(Vector2(cell_width, cell_height))
168
+
169
+ quad.mesh = quad_mesh
170
+ cell.add_child(quad)
171
+ quad.set_owner(get_tree().edited_scene_root)
172
+
173
+
174
+ func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
175
+ for key in _collision_mapping:
176
+ var bit_mask = 2 ** key
177
+ if (collision_layer & bit_mask) > 0:
178
+ var collison_map_index = _collision_mapping[key]
179
+
180
+ var obs_index = (
181
+ (cell_i * grid_size_x * _n_layers_per_cell)
182
+ + (cell_j * _n_layers_per_cell)
183
+ + collison_map_index
184
+ )
185
+ #prints(obs_index, cell_i, cell_j)
186
+ if entered:
187
+ _obs_buffer[obs_index] += 1
188
+ else:
189
+ _obs_buffer[obs_index] -= 1
190
+
191
+
192
+ func _toggle_cell(cell_i: int, cell_j: int):
193
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
194
+
195
+ if cell == null:
196
+ print("cell not found, returning")
197
+
198
+ var n_hits = 0
199
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
200
+ for i in _n_layers_per_cell:
201
+ n_hits += _obs_buffer[start_index + i]
202
+
203
+ if n_hits > 0:
204
+ cell.modulate = _highlighted_cell_color
205
+ else:
206
+ cell.modulate = _standard_cell_color
207
+
208
+
209
+ func _on_cell_area_entered(area: Area2D, cell_i: int, cell_j: int):
210
+ #prints("_on_cell_area_entered", cell_i, cell_j)
211
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
212
+ if debug_view:
213
+ _toggle_cell(cell_i, cell_j)
214
+ #print(_obs_buffer)
215
+
216
+
217
+ func _on_cell_area_exited(area: Area2D, cell_i: int, cell_j: int):
218
+ #prints("_on_cell_area_exited", cell_i, cell_j)
219
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
220
+ if debug_view:
221
+ _toggle_cell(cell_i, cell_j)
222
+
223
+
224
+ func _on_cell_body_entered(body: Node2D, cell_i: int, cell_j: int):
225
+ #prints("_on_cell_body_entered", cell_i, cell_j)
226
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
227
+ if debug_view:
228
+ _toggle_cell(cell_i, cell_j)
229
+
230
+
231
+ func _on_cell_body_exited(body: Node2D, cell_i: int, cell_j: int):
232
+ #prints("_on_cell_body_exited", cell_i, cell_j)
233
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
234
+ if debug_view:
235
+ _toggle_cell(cell_i, cell_j)
addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+ class_name ISensor2D
3
+
4
+ var _obs: Array = []
5
+ var _active := false
6
+
7
+
8
+ func get_observation():
9
+ pass
10
+
11
+
12
+ func activate():
13
+ _active = true
14
+
15
+
16
+ func deactivate():
17
+ _active = false
18
+
19
+
20
+ func _update_observation():
21
+ pass
22
+
23
+
24
+ func reset():
25
+ pass
addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor2D
3
+ class_name RaycastSensor2D
4
+
5
+ @export_flags_2d_physics var collision_mask := 1:
6
+ get:
7
+ return collision_mask
8
+ set(value):
9
+ collision_mask = value
10
+ _update()
11
+
12
+ @export var collide_with_areas := false:
13
+ get:
14
+ return collide_with_areas
15
+ set(value):
16
+ collide_with_areas = value
17
+ _update()
18
+
19
+ @export var collide_with_bodies := true:
20
+ get:
21
+ return collide_with_bodies
22
+ set(value):
23
+ collide_with_bodies = value
24
+ _update()
25
+
26
+ @export var n_rays := 16.0:
27
+ get:
28
+ return n_rays
29
+ set(value):
30
+ n_rays = value
31
+ _update()
32
+
33
+ @export_range(5, 3000, 5.0) var ray_length := 200:
34
+ get:
35
+ return ray_length
36
+ set(value):
37
+ ray_length = value
38
+ _update()
39
+ @export_range(5, 360, 5.0) var cone_width := 360.0:
40
+ get:
41
+ return cone_width
42
+ set(value):
43
+ cone_width = value
44
+ _update()
45
+
46
+ @export var debug_draw := true:
47
+ get:
48
+ return debug_draw
49
+ set(value):
50
+ debug_draw = value
51
+ _update()
52
+
53
+ var _angles = []
54
+ var rays := []
55
+
56
+
57
+ func _update():
58
+ if Engine.is_editor_hint():
59
+ if debug_draw:
60
+ _spawn_nodes()
61
+ else:
62
+ for ray in get_children():
63
+ if ray is RayCast2D:
64
+ remove_child(ray)
65
+
66
+
67
+ func _ready() -> void:
68
+ _spawn_nodes()
69
+
70
+
71
+ func _spawn_nodes():
72
+ for ray in rays:
73
+ ray.queue_free()
74
+ rays = []
75
+
76
+ _angles = []
77
+ var step = cone_width / (n_rays)
78
+ var start = step / 2 - cone_width / 2
79
+
80
+ for i in n_rays:
81
+ var angle = start + i * step
82
+ var ray = RayCast2D.new()
83
+ ray.set_target_position(
84
+ Vector2(ray_length * cos(deg_to_rad(angle)), ray_length * sin(deg_to_rad(angle)))
85
+ )
86
+ ray.set_name("node_" + str(i))
87
+ ray.enabled = false
88
+ ray.collide_with_areas = collide_with_areas
89
+ ray.collide_with_bodies = collide_with_bodies
90
+ ray.collision_mask = collision_mask
91
+ add_child(ray)
92
+ rays.append(ray)
93
+
94
+ _angles.append(start + i * step)
95
+
96
+
97
+ func get_observation() -> Array:
98
+ return self.calculate_raycasts()
99
+
100
+
101
+ func calculate_raycasts() -> Array:
102
+ var result = []
103
+ for ray in rays:
104
+ ray.enabled = true
105
+ ray.force_raycast_update()
106
+ var distance = _get_raycast_distance(ray)
107
+ result.append(distance)
108
+ ray.enabled = false
109
+ return result
110
+
111
+
112
+ func _get_raycast_distance(ray: RayCast2D) -> float:
113
+ if !ray.is_colliding():
114
+ return 0.0
115
+
116
+ var distance = (global_position - ray.get_collision_point()).length()
117
+ distance = clamp(distance, 0.0, ray_length)
118
+ return (ray_length - distance) / ray_length
addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"]
2
+
3
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"]
4
+
5
+ [node name="RaycastSensor2D" type="Node2D"]
6
+ script = ExtResource("1")
7
+ n_rays = 17.0
addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ [gd_scene format=3 uid="uid://biu787qh4woik"]
2
+
3
+ [node name="ExampleRaycastSensor3D" type="Node3D"]
4
+
5
+ [node name="Camera3D" type="Camera3D" parent="."]
6
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146)
addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor3D
3
+ class_name GridSensor3D
4
+
5
+ @export var debug_view := false:
6
+ get:
7
+ return debug_view
8
+ set(value):
9
+ debug_view = value
10
+ _update()
11
+
12
+ @export_flags_3d_physics var detection_mask := 0:
13
+ get:
14
+ return detection_mask
15
+ set(value):
16
+ detection_mask = value
17
+ _update()
18
+
19
+ @export var collide_with_areas := false:
20
+ get:
21
+ return collide_with_areas
22
+ set(value):
23
+ collide_with_areas = value
24
+ _update()
25
+
26
+ @export var collide_with_bodies := false:
27
+ # NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
28
+ get:
29
+ return collide_with_bodies
30
+ set(value):
31
+ collide_with_bodies = value
32
+ _update()
33
+
34
+ @export_range(0.1, 2, 0.1) var cell_width := 1.0:
35
+ get:
36
+ return cell_width
37
+ set(value):
38
+ cell_width = value
39
+ _update()
40
+
41
+ @export_range(0.1, 2, 0.1) var cell_height := 1.0:
42
+ get:
43
+ return cell_height
44
+ set(value):
45
+ cell_height = value
46
+ _update()
47
+
48
+ @export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
49
+ get:
50
+ return grid_size_x
51
+ set(value):
52
+ grid_size_x = value
53
+ _update()
54
+
55
+ @export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
56
+ get:
57
+ return grid_size_z
58
+ set(value):
59
+ grid_size_z = value
60
+ _update()
61
+
62
+ var _obs_buffer: PackedFloat64Array
63
+ var _box_shape: BoxShape3D
64
+ var _collision_mapping: Dictionary
65
+ var _n_layers_per_cell: int
66
+
67
+ var _highlighted_box_material: StandardMaterial3D
68
+ var _standard_box_material: StandardMaterial3D
69
+
70
+
71
+ func get_observation():
72
+ return _obs_buffer
73
+
74
+
75
+ func reset():
76
+ _obs_buffer.fill(0)
77
+
78
+
79
+ func _update():
80
+ if Engine.is_editor_hint():
81
+ if is_node_ready():
82
+ _spawn_nodes()
83
+
84
+
85
+ func _ready() -> void:
86
+ _make_materials()
87
+
88
+ if Engine.is_editor_hint():
89
+ if get_child_count() == 0:
90
+ _spawn_nodes()
91
+ else:
92
+ _spawn_nodes()
93
+
94
+
95
+ func _make_materials() -> void:
96
+ if _highlighted_box_material != null and _standard_box_material != null:
97
+ return
98
+
99
+ _standard_box_material = StandardMaterial3D.new()
100
+ _standard_box_material.set_transparency(1) # ALPHA
101
+ _standard_box_material.albedo_color = Color(
102
+ 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
103
+ )
104
+
105
+ _highlighted_box_material = StandardMaterial3D.new()
106
+ _highlighted_box_material.set_transparency(1) # ALPHA
107
+ _highlighted_box_material.albedo_color = Color(
108
+ 255.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0, 100.0 / 255.0
109
+ )
110
+
111
+
112
+ func _get_collision_mapping() -> Dictionary:
113
+ # defines which layer is mapped to which cell obs index
114
+ var total_bits = 0
115
+ var collision_mapping = {}
116
+ for i in 32:
117
+ var bit_mask = 2 ** i
118
+ if (detection_mask & bit_mask) > 0:
119
+ collision_mapping[i] = total_bits
120
+ total_bits += 1
121
+
122
+ return collision_mapping
123
+
124
+
125
+ func _spawn_nodes():
126
+ for cell in get_children():
127
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
128
+ cell.queue_free()
129
+
130
+ _collision_mapping = _get_collision_mapping()
131
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
132
+ # allocate memory for the observations
133
+ _n_layers_per_cell = len(_collision_mapping)
134
+ _obs_buffer = PackedFloat64Array()
135
+ _obs_buffer.resize(grid_size_x * grid_size_z * _n_layers_per_cell)
136
+ _obs_buffer.fill(0)
137
+ #prints(len(_obs_buffer), _obs_buffer )
138
+
139
+ _box_shape = BoxShape3D.new()
140
+ _box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
141
+
142
+ var shift := Vector3(
143
+ -(grid_size_x / 2) * cell_width,
144
+ 0,
145
+ -(grid_size_z / 2) * cell_width,
146
+ )
147
+
148
+ for i in grid_size_x:
149
+ for j in grid_size_z:
150
+ var cell_position = Vector3(i * cell_width, 0.0, j * cell_width) + shift
151
+ _create_cell(i, j, cell_position)
152
+
153
+
154
+ func _create_cell(i: int, j: int, position: Vector3):
155
+ var cell := Area3D.new()
156
+ cell.position = position
157
+ cell.name = "GridCell %s %s" % [i, j]
158
+
159
+ if collide_with_areas:
160
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
161
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
162
+
163
+ if collide_with_bodies:
164
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
165
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
166
+
167
+ # cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
168
+ # cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
169
+
170
+ cell.collision_layer = 0
171
+ cell.collision_mask = detection_mask
172
+ cell.monitorable = true
173
+ cell.input_ray_pickable = false
174
+ add_child(cell)
175
+ cell.set_owner(get_tree().edited_scene_root)
176
+
177
+ var col_shape := CollisionShape3D.new()
178
+ col_shape.shape = _box_shape
179
+ col_shape.name = "CollisionShape3D"
180
+ cell.add_child(col_shape)
181
+ col_shape.set_owner(get_tree().edited_scene_root)
182
+
183
+ if debug_view:
184
+ var box = MeshInstance3D.new()
185
+ box.name = "MeshInstance3D"
186
+ var box_mesh = BoxMesh.new()
187
+
188
+ box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
189
+ box_mesh.material = _standard_box_material
190
+
191
+ box.mesh = box_mesh
192
+ cell.add_child(box)
193
+ box.set_owner(get_tree().edited_scene_root)
194
+
195
+
196
+ func _update_obs(cell_i: int, cell_j: int, collision_layer: int, entered: bool):
197
+ for key in _collision_mapping:
198
+ var bit_mask = 2 ** key
199
+ if (collision_layer & bit_mask) > 0:
200
+ var collison_map_index = _collision_mapping[key]
201
+
202
+ var obs_index = (
203
+ (cell_i * grid_size_x * _n_layers_per_cell)
204
+ + (cell_j * _n_layers_per_cell)
205
+ + collison_map_index
206
+ )
207
+ #prints(obs_index, cell_i, cell_j)
208
+ if entered:
209
+ _obs_buffer[obs_index] += 1
210
+ else:
211
+ _obs_buffer[obs_index] -= 1
212
+
213
+
214
+ func _toggle_cell(cell_i: int, cell_j: int):
215
+ var cell = get_node_or_null("GridCell %s %s" % [cell_i, cell_j])
216
+
217
+ if cell == null:
218
+ print("cell not found, returning")
219
+
220
+ var n_hits = 0
221
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
222
+ for i in _n_layers_per_cell:
223
+ n_hits += _obs_buffer[start_index + i]
224
+
225
+ var cell_mesh = cell.get_node_or_null("MeshInstance3D")
226
+ if n_hits > 0:
227
+ cell_mesh.mesh.material = _highlighted_box_material
228
+ else:
229
+ cell_mesh.mesh.material = _standard_box_material
230
+
231
+
232
+ func _on_cell_area_entered(area: Area3D, cell_i: int, cell_j: int):
233
+ #prints("_on_cell_area_entered", cell_i, cell_j)
234
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
235
+ if debug_view:
236
+ _toggle_cell(cell_i, cell_j)
237
+ #print(_obs_buffer)
238
+
239
+
240
+ func _on_cell_area_exited(area: Area3D, cell_i: int, cell_j: int):
241
+ #prints("_on_cell_area_exited", cell_i, cell_j)
242
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
243
+ if debug_view:
244
+ _toggle_cell(cell_i, cell_j)
245
+
246
+
247
+ func _on_cell_body_entered(body: Node3D, cell_i: int, cell_j: int):
248
+ #prints("_on_cell_body_entered", cell_i, cell_j)
249
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
250
+ if debug_view:
251
+ _toggle_cell(cell_i, cell_j)
252
+
253
+
254
+ func _on_cell_body_exited(body: Node3D, cell_i: int, cell_j: int):
255
+ #prints("_on_cell_body_exited", cell_i, cell_j)
256
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
257
+ if debug_view:
258
+ _toggle_cell(cell_i, cell_j)
addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name ISensor3D
3
+
4
+ var _obs: Array = []
5
+ var _active := false
6
+
7
+
8
+ func get_observation():
9
+ pass
10
+
11
+
12
+ func activate():
13
+ _active = true
14
+
15
+
16
+ func deactivate():
17
+ _active = false
18
+
19
+
20
+ func _update_observation():
21
+ pass
22
+
23
+
24
+ func reset():
25
+ pass
addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name RGBCameraSensor3D
3
+ var camera_pixels = null
4
+
5
+ @onready var camera_texture := $Control/CameraTexture as Sprite2D
6
+ @onready var processed_texture := $Control/ProcessedTexture as Sprite2D
7
+ @onready var sub_viewport := $SubViewport as SubViewport
8
+ @onready var displayed_image: ImageTexture
9
+
10
+ @export var render_image_resolution := Vector2(36, 36)
11
+ ## Display size does not affect rendered or sent image resolution.
12
+ ## Scale is relative to either render image or downscale image resolution
13
+ ## depending on which mode is set.
14
+ @export var displayed_image_scale_factor := Vector2(8, 8)
15
+
16
+ @export_group("Downscale image options")
17
+ ## Enable to downscale the rendered image before sending the obs.
18
+ @export var downscale_image: bool = false
19
+ ## If downscale_image is true, will display the downscaled image instead of rendered image.
20
+ @export var display_downscaled_image: bool = true
21
+ ## This is the resolution of the image that will be sent after downscaling
22
+ @export var resized_image_resolution := Vector2(36, 36)
23
+
24
+
25
+ func _ready():
26
+ sub_viewport.size = render_image_resolution
27
+ camera_texture.scale = displayed_image_scale_factor
28
+
29
+ if downscale_image and display_downscaled_image:
30
+ camera_texture.visible = false
31
+ processed_texture.scale = displayed_image_scale_factor
32
+ else:
33
+ processed_texture.visible = false
34
+
35
+
36
+ func get_camera_pixel_encoding():
37
+ var image := camera_texture.get_texture().get_image() as Image
38
+
39
+ if downscale_image:
40
+ image.resize(
41
+ resized_image_resolution.x, resized_image_resolution.y, Image.INTERPOLATE_NEAREST
42
+ )
43
+ if display_downscaled_image:
44
+ if not processed_texture.texture:
45
+ displayed_image = ImageTexture.create_from_image(image)
46
+ processed_texture.texture = displayed_image
47
+ else:
48
+ displayed_image.update(image)
49
+
50
+ return image.get_data().hex_encode()
51
+
52
+
53
+ func get_camera_shape() -> Array:
54
+ var size = resized_image_resolution if downscale_image else render_image_resolution
55
+
56
+ assert(
57
+ size.x >= 36 and size.y >= 36,
58
+ "Camera sensor sent image resolution must be 36x36 or larger."
59
+ )
60
+ if sub_viewport.transparent_bg:
61
+ return [4, size.y, size.x]
62
+ else:
63
+ return [3, size.y, size.x]
addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="ViewportTexture_y72s3"]
6
+ viewport_path = NodePath("SubViewport")
7
+
8
+ [node name="RGBCameraSensor3D" type="Node3D"]
9
+ script = ExtResource("1")
10
+
11
+ [node name="RemoteTransform" type="RemoteTransform3D" parent="."]
12
+ remote_path = NodePath("../SubViewport/Camera")
13
+
14
+ [node name="SubViewport" type="SubViewport" parent="."]
15
+ size = Vector2i(36, 36)
16
+ render_target_update_mode = 3
17
+
18
+ [node name="Camera" 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
+ metadata/_edit_use_anchors_ = true
29
+
30
+ [node name="CameraTexture" type="Sprite2D" parent="Control"]
31
+ texture = SubResource("ViewportTexture_y72s3")
32
+ centered = false
33
+
34
+ [node name="ProcessedTexture" type="Sprite2D" parent="Control"]
35
+ centered = false
addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor3D
3
+ class_name RayCastSensor3D
4
+ @export_flags_3d_physics var collision_mask = 1:
5
+ get:
6
+ return collision_mask
7
+ set(value):
8
+ collision_mask = value
9
+ _update()
10
+ @export_flags_3d_physics var boolean_class_mask = 1:
11
+ get:
12
+ return boolean_class_mask
13
+ set(value):
14
+ boolean_class_mask = value
15
+ _update()
16
+
17
+ @export var n_rays_width := 6.0:
18
+ get:
19
+ return n_rays_width
20
+ set(value):
21
+ n_rays_width = value
22
+ _update()
23
+
24
+ @export var n_rays_height := 6.0:
25
+ get:
26
+ return n_rays_height
27
+ set(value):
28
+ n_rays_height = value
29
+ _update()
30
+
31
+ @export var ray_length := 10.0:
32
+ get:
33
+ return ray_length
34
+ set(value):
35
+ ray_length = value
36
+ _update()
37
+
38
+ @export var cone_width := 60.0:
39
+ get:
40
+ return cone_width
41
+ set(value):
42
+ cone_width = value
43
+ _update()
44
+
45
+ @export var cone_height := 60.0:
46
+ get:
47
+ return cone_height
48
+ set(value):
49
+ cone_height = value
50
+ _update()
51
+
52
+ @export var collide_with_areas := false:
53
+ get:
54
+ return collide_with_areas
55
+ set(value):
56
+ collide_with_areas = value
57
+ _update()
58
+
59
+ @export var collide_with_bodies := true:
60
+ get:
61
+ return collide_with_bodies
62
+ set(value):
63
+ collide_with_bodies = value
64
+ _update()
65
+
66
+ @export var class_sensor := false
67
+
68
+ var rays := []
69
+ var geo = null
70
+
71
+
72
+ func _update():
73
+ if Engine.is_editor_hint():
74
+ if is_node_ready():
75
+ _spawn_nodes()
76
+
77
+
78
+ func _ready() -> void:
79
+ if Engine.is_editor_hint():
80
+ if get_child_count() == 0:
81
+ _spawn_nodes()
82
+ else:
83
+ _spawn_nodes()
84
+
85
+
86
+ func _spawn_nodes():
87
+ print("spawning nodes")
88
+ for ray in get_children():
89
+ ray.queue_free()
90
+ if geo:
91
+ geo.clear()
92
+ #$Lines.remove_points()
93
+ rays = []
94
+
95
+ var horizontal_step = cone_width / (n_rays_width)
96
+ var vertical_step = cone_height / (n_rays_height)
97
+
98
+ var horizontal_start = horizontal_step / 2 - cone_width / 2
99
+ var vertical_start = vertical_step / 2 - cone_height / 2
100
+
101
+ var points = []
102
+
103
+ for i in n_rays_width:
104
+ for j in n_rays_height:
105
+ var angle_w = horizontal_start + i * horizontal_step
106
+ var angle_h = vertical_start + j * vertical_step
107
+ #angle_h = 0.0
108
+ var ray = RayCast3D.new()
109
+ var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
110
+ ray.set_target_position(cast_to)
111
+
112
+ points.append(cast_to)
113
+
114
+ ray.set_name("node_" + str(i) + " " + str(j))
115
+ ray.enabled = true
116
+ ray.collide_with_bodies = collide_with_bodies
117
+ ray.collide_with_areas = collide_with_areas
118
+ ray.collision_mask = collision_mask
119
+ add_child(ray)
120
+ ray.set_owner(get_tree().edited_scene_root)
121
+ rays.append(ray)
122
+ ray.force_raycast_update()
123
+
124
+
125
+ # if Engine.editor_hint:
126
+ # _create_debug_lines(points)
127
+
128
+
129
+ func _create_debug_lines(points):
130
+ if not geo:
131
+ geo = ImmediateMesh.new()
132
+ add_child(geo)
133
+
134
+ geo.clear()
135
+ geo.begin(Mesh.PRIMITIVE_LINES)
136
+ for point in points:
137
+ geo.set_color(Color.AQUA)
138
+ geo.add_vertex(Vector3.ZERO)
139
+ geo.add_vertex(point)
140
+ geo.end()
141
+
142
+
143
+ func display():
144
+ if geo:
145
+ geo.display()
146
+
147
+
148
+ func to_spherical_coords(r, inc, azimuth) -> Vector3:
149
+ return Vector3(
150
+ r * sin(deg_to_rad(inc)) * cos(deg_to_rad(azimuth)),
151
+ r * sin(deg_to_rad(azimuth)),
152
+ r * cos(deg_to_rad(inc)) * cos(deg_to_rad(azimuth))
153
+ )
154
+
155
+
156
+ func get_observation() -> Array:
157
+ return self.calculate_raycasts()
158
+
159
+
160
+ func calculate_raycasts() -> Array:
161
+ var result = []
162
+ for ray in rays:
163
+ ray.set_enabled(true)
164
+ ray.force_raycast_update()
165
+ var distance = _get_raycast_distance(ray)
166
+
167
+ result.append(distance)
168
+ if class_sensor:
169
+ var hit_class: float = 0
170
+ if ray.get_collider():
171
+ var hit_collision_layer = ray.get_collider().collision_layer
172
+ hit_collision_layer = hit_collision_layer & collision_mask
173
+ hit_class = (hit_collision_layer & boolean_class_mask) > 0
174
+ result.append(float(hit_class))
175
+ ray.set_enabled(false)
176
+ return result
177
+
178
+
179
+ func _get_raycast_distance(ray: RayCast3D) -> float:
180
+ if !ray.is_colliding():
181
+ return 0.0
182
+
183
+ var distance = (global_transform.origin - ray.get_collision_point()).length()
184
+ distance = clamp(distance, 0.0, ray_length)
185
+ return (ray_length - distance) / ray_length
addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"]
2
+
3
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"]
4
+
5
+ [node name="RaycastSensor3D" type="Node3D"]
6
+ script = ExtResource("1")
7
+ n_rays_width = 4.0
8
+ n_rays_height = 2.0
9
+ ray_length = 11.0
10
+
11
+ [node name="node_1 0" type="RayCast3D" parent="."]
12
+ target_position = Vector3(-1.38686, -2.84701, 10.5343)
13
+
14
+ [node name="node_1 1" type="RayCast3D" parent="."]
15
+ target_position = Vector3(-1.38686, 2.84701, 10.5343)
16
+
17
+ [node name="node_2 0" type="RayCast3D" parent="."]
18
+ target_position = Vector3(1.38686, -2.84701, 10.5343)
19
+
20
+ [node name="node_2 1" type="RayCast3D" parent="."]
21
+ target_position = Vector3(1.38686, 2.84701, 10.5343)
22
+
23
+ [node name="node_3 0" type="RayCast3D" parent="."]
24
+ target_position = Vector3(4.06608, -2.84701, 9.81639)
25
+
26
+ [node name="node_3 1" type="RayCast3D" parent="."]
27
+ target_position = Vector3(4.06608, 2.84701, 9.81639)
addons/godot_rl_agents/sync.gd ADDED
@@ -0,0 +1,587 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node
2
+ class_name Sync
3
+
4
+ # --fixed-fps 2000 --disable-render-loop
5
+
6
+ enum ControlModes { HUMAN, TRAINING, ONNX_INFERENCE } ## Test the environment manually ## Train a model ## Load a pretrained model using an .onnx file
7
+ @export var control_mode: ControlModes = ControlModes.TRAINING
8
+ ## Action will be repeated for n frames (Godot physics steps).
9
+ @export_range(1, 10, 1, "or_greater") var action_repeat := 8
10
+ ## Speeds up the physics in the environment to enable faster training.
11
+ @export_range(0, 10, 0.1, "or_greater") var speed_up := 1.0
12
+ ## The path to a trained .onnx model file to use for inference (only needed for the 'Onnx Inference' control mode).
13
+ @export var onnx_model_path := ""
14
+
15
+ # Onnx model stored for each requested path
16
+ var onnx_models: Dictionary
17
+
18
+ @onready var start_time = Time.get_ticks_msec()
19
+
20
+ const MAJOR_VERSION := "0"
21
+ const MINOR_VERSION := "7"
22
+ const DEFAULT_PORT := "11008"
23
+ const DEFAULT_SEED := "1"
24
+ var stream: StreamPeerTCP = null
25
+ var connected = false
26
+ var message_center
27
+ var should_connect = true
28
+
29
+ var all_agents: Array
30
+ var agents_training: Array
31
+ ## Policy name of each agent, for use with multi-policy multi-agent RL cases
32
+ var agents_training_policy_names: Array[String] = ["shared_policy"]
33
+ var agents_inference: Array
34
+ var agents_heuristic: Array
35
+
36
+ ## For recording expert demos
37
+ var agent_demo_record: Node
38
+ ## File path for writing recorded trajectories
39
+ var expert_demo_save_path: String
40
+ ## Stores recorded trajectories
41
+ var demo_trajectories: Array
42
+ ## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead)
43
+ var current_demo_trajectory: Array
44
+
45
+ var need_to_send_obs = false
46
+ var args = null
47
+ var initialized = false
48
+ var just_reset = false
49
+ var onnx_model = null
50
+ var n_action_steps = 0
51
+
52
+ var _action_space_training: Array[Dictionary] = []
53
+ var _action_space_inference: Array[Dictionary] = []
54
+ var _obs_space_training: Array[Dictionary] = []
55
+
56
+
57
+ # Called when the node enters the scene tree for the first time.
58
+ func _ready():
59
+ await get_parent().ready
60
+ get_tree().set_pause(true)
61
+ _initialize()
62
+ await get_tree().create_timer(1.0).timeout
63
+ get_tree().set_pause(false)
64
+
65
+
66
+ func _initialize():
67
+ _get_agents()
68
+ args = _get_args()
69
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
70
+ Engine.time_scale = _get_speedup() * 1.0
71
+ prints(
72
+ "physics ticks",
73
+ Engine.physics_ticks_per_second,
74
+ Engine.time_scale,
75
+ _get_speedup(),
76
+ speed_up
77
+ )
78
+
79
+ _set_heuristic("human", all_agents)
80
+
81
+ _initialize_training_agents()
82
+ _initialize_inference_agents()
83
+ _initialize_demo_recording()
84
+
85
+ _set_seed()
86
+ _set_action_repeat()
87
+ initialized = true
88
+
89
+
90
+ func _initialize_training_agents():
91
+ if agents_training.size() > 0:
92
+ _obs_space_training.resize(agents_training.size())
93
+ _action_space_training.resize(agents_training.size())
94
+ for agent_idx in range(0, agents_training.size()):
95
+ _obs_space_training[agent_idx] = agents_training[agent_idx].get_obs_space()
96
+ _action_space_training[agent_idx] = agents_training[agent_idx].get_action_space()
97
+ connected = connect_to_server()
98
+ if connected:
99
+ _set_heuristic("model", agents_training)
100
+ _handshake()
101
+ _send_env_info()
102
+ else:
103
+ push_warning(
104
+ "Couldn't connect to Python server, using human controls instead. ",
105
+ "Did you start the training server using e.g. `gdrl` from the console?"
106
+ )
107
+
108
+
109
+ func _initialize_inference_agents():
110
+ if agents_inference.size() > 0:
111
+ if control_mode == ControlModes.ONNX_INFERENCE:
112
+ assert(
113
+ FileAccess.file_exists(onnx_model_path),
114
+ "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path
115
+ )
116
+ onnx_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1)
117
+
118
+ for agent in agents_inference:
119
+ var action_space = agent.get_action_space()
120
+ _action_space_inference.append(action_space)
121
+
122
+ var agent_onnx_model: ONNXModel
123
+ if agent.onnx_model_path.is_empty():
124
+ assert(
125
+ onnx_models.has(onnx_model_path),
126
+ (
127
+ "Node %s has no onnx model path set " % agent.get_path()
128
+ + "and sync node's control mode is not set to OnnxInference. "
129
+ + "Either add the path to the AIController, "
130
+ + "or if you want to use the path set on sync node instead, "
131
+ + "set control mode to OnnxInference."
132
+ )
133
+ )
134
+ prints(
135
+ "Info: AIController %s" % agent.get_path(),
136
+ "has no onnx model path set.",
137
+ "Using path set on the sync node instead."
138
+ )
139
+ agent_onnx_model = onnx_models[onnx_model_path]
140
+ else:
141
+ if not onnx_models.has(agent.onnx_model_path):
142
+ assert(
143
+ FileAccess.file_exists(agent.onnx_model_path),
144
+ (
145
+ "Onnx Model Path set on %s node does not exist: %s"
146
+ % [agent.get_path(), agent.onnx_model_path]
147
+ )
148
+ )
149
+ onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1)
150
+ agent_onnx_model = onnx_models[agent.onnx_model_path]
151
+
152
+ agent.onnx_model = agent_onnx_model
153
+ if not agent_onnx_model.action_means_only_set:
154
+ agent_onnx_model.set_action_means_only(action_space)
155
+
156
+ _set_heuristic("model", agents_inference)
157
+
158
+
159
+ func _initialize_demo_recording():
160
+ if agent_demo_record:
161
+ expert_demo_save_path = agent_demo_record.expert_demo_save_path
162
+ assert(
163
+ not expert_demo_save_path.is_empty(),
164
+ "Expert demo save path set in %s is empty." % agent_demo_record.get_path()
165
+ )
166
+
167
+ InputMap.add_action("RemoveLastDemoEpisode")
168
+ InputMap.action_add_event(
169
+ "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key
170
+ )
171
+ current_demo_trajectory.resize(2)
172
+ current_demo_trajectory[0] = []
173
+ current_demo_trajectory[1] = []
174
+ agent_demo_record.heuristic = "demo_record"
175
+
176
+
177
+ func _physics_process(_delta):
178
+ # two modes, human control, agent control
179
+ # pause tree, send obs, get actions, set actions, unpause tree
180
+
181
+ _demo_record_process()
182
+
183
+ if n_action_steps % action_repeat != 0:
184
+ n_action_steps += 1
185
+ return
186
+
187
+ n_action_steps += 1
188
+
189
+ _training_process()
190
+ _inference_process()
191
+ _heuristic_process()
192
+
193
+
194
+ func _training_process():
195
+ if connected:
196
+ get_tree().set_pause(true)
197
+
198
+ if just_reset:
199
+ just_reset = false
200
+ var obs = _get_obs_from_agents(agents_training)
201
+
202
+ var reply = {"type": "reset", "obs": obs}
203
+ _send_dict_as_json_message(reply)
204
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
205
+ get_tree().set_pause(false)
206
+ return
207
+
208
+ if need_to_send_obs:
209
+ need_to_send_obs = false
210
+ var reward = _get_reward_from_agents()
211
+ var done = _get_done_from_agents()
212
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
213
+
214
+ var obs = _get_obs_from_agents(agents_training)
215
+
216
+ var reply = {"type": "step", "obs": obs, "reward": reward, "done": done}
217
+ _send_dict_as_json_message(reply)
218
+
219
+ var handled = handle_message()
220
+
221
+
222
+ func _inference_process():
223
+ if agents_inference.size() > 0:
224
+ var obs: Array = _get_obs_from_agents(agents_inference)
225
+ var actions = []
226
+
227
+ for agent_id in range(0, agents_inference.size()):
228
+ var model: ONNXModel = agents_inference[agent_id].onnx_model
229
+ var action = model.run_inference(obs[agent_id]["obs"], 1.0)
230
+ var action_dict = _extract_action_dict(
231
+ action["output"], _action_space_inference[agent_id], model.action_means_only
232
+ )
233
+ actions.append(action_dict)
234
+
235
+ _set_agent_actions(actions, agents_inference)
236
+ _reset_agents_if_done(agents_inference)
237
+ get_tree().set_pause(false)
238
+
239
+
240
+ func _demo_record_process():
241
+ if not agent_demo_record:
242
+ return
243
+
244
+ if Input.is_action_just_pressed("RemoveLastDemoEpisode"):
245
+ print("[Sync script][Demo recorder] Removing last recorded episode.")
246
+ demo_trajectories.remove_at(demo_trajectories.size() - 1)
247
+ print("Remaining episode count: %d" % demo_trajectories.size())
248
+
249
+ if n_action_steps % agent_demo_record.action_repeat != 0:
250
+ return
251
+
252
+ var obs_dict: Dictionary = agent_demo_record.get_obs()
253
+
254
+ # Get the current obs from the agent
255
+ assert(
256
+ obs_dict.has("obs"),
257
+ "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from."
258
+ )
259
+ current_demo_trajectory[0].append(obs_dict.obs)
260
+
261
+ # Get the action applied for the current obs from the agent
262
+ agent_demo_record.set_action()
263
+ var acts = agent_demo_record.get_action()
264
+
265
+ var terminal = agent_demo_record.get_done()
266
+ # Record actions only for non-terminal states
267
+ if terminal:
268
+ agent_demo_record.set_done_false()
269
+ else:
270
+ current_demo_trajectory[1].append(acts)
271
+
272
+ if terminal:
273
+ #current_demo_trajectory[2].append(true)
274
+ demo_trajectories.append(current_demo_trajectory.duplicate(true))
275
+ print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size())
276
+ current_demo_trajectory[0].clear()
277
+ current_demo_trajectory[1].clear()
278
+
279
+
280
+ func _heuristic_process():
281
+ for agent in agents_heuristic:
282
+ _reset_agents_if_done(agents_heuristic)
283
+
284
+
285
+ func _extract_action_dict(action_array: Array, action_space: Dictionary, action_means_only: bool):
286
+ var index = 0
287
+ var result = {}
288
+ for key in action_space.keys():
289
+ var size = action_space[key]["size"]
290
+ var action_type = action_space[key]["action_type"]
291
+ if action_type == "discrete":
292
+ var largest_logit: float # Value of the largest logit for this action in the actions array
293
+ var largest_logit_idx: int # Index of the largest logit for this action in the actions array
294
+ for logit_idx in range(0, size):
295
+ var logit_value = action_array[index + logit_idx]
296
+ if logit_value > largest_logit:
297
+ largest_logit = logit_value
298
+ largest_logit_idx = logit_idx
299
+ result[key] = largest_logit_idx # Index of the largest logit is the discrete action value
300
+ index += size
301
+ elif action_type == "continuous":
302
+ # For continous actions, we only take the action mean values
303
+ result[key] = clamp_array(action_array.slice(index, index + size), -1.0, 1.0)
304
+ if action_means_only:
305
+ index += size # model only outputs action means, so we move index by size
306
+ else:
307
+ index += size * 2 # model outputs logstd after action mean, we skip the logstd part
308
+
309
+ else:
310
+ assert(
311
+ false,
312
+ (
313
+ 'Only "discrete" and "continuous" action types supported. Found: %s action type set.'
314
+ % action_type
315
+ )
316
+ )
317
+
318
+ return result
319
+
320
+
321
+ ## For AIControllers that inherit mode from sync, sets the correct mode.
322
+ func _set_agent_mode(agent: Node):
323
+ var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC
324
+
325
+ if agent_inherits_mode:
326
+ match control_mode:
327
+ ControlModes.HUMAN:
328
+ agent.control_mode = agent.ControlModes.HUMAN
329
+ ControlModes.TRAINING:
330
+ agent.control_mode = agent.ControlModes.TRAINING
331
+ ControlModes.ONNX_INFERENCE:
332
+ agent.control_mode = agent.ControlModes.ONNX_INFERENCE
333
+
334
+
335
+ func _get_agents():
336
+ all_agents = get_tree().get_nodes_in_group("AGENT")
337
+ for agent in all_agents:
338
+ _set_agent_mode(agent)
339
+
340
+ if agent.control_mode == agent.ControlModes.TRAINING:
341
+ agents_training.append(agent)
342
+ elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE:
343
+ agents_inference.append(agent)
344
+ elif agent.control_mode == agent.ControlModes.HUMAN:
345
+ agents_heuristic.append(agent)
346
+ elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS:
347
+ assert(
348
+ not agent_demo_record,
349
+ "Currently only a single AIController can be used for recording expert demos."
350
+ )
351
+ agent_demo_record = agent
352
+
353
+ var training_agent_count = agents_training.size()
354
+ agents_training_policy_names.resize(training_agent_count)
355
+ for i in range(0, training_agent_count):
356
+ agents_training_policy_names[i] = agents_training[i].policy_name
357
+
358
+
359
+ func _set_heuristic(heuristic, agents: Array):
360
+ for agent in agents:
361
+ agent.set_heuristic(heuristic)
362
+
363
+
364
+ func _handshake():
365
+ print("performing handshake")
366
+
367
+ var json_dict = _get_dict_json_message()
368
+ assert(json_dict["type"] == "handshake")
369
+ var major_version = json_dict["major_version"]
370
+ var minor_version = json_dict["minor_version"]
371
+ if major_version != MAJOR_VERSION:
372
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
373
+ if minor_version != MINOR_VERSION:
374
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
375
+
376
+ print("handshake complete")
377
+
378
+
379
+ func _get_dict_json_message():
380
+ # returns a dictionary from of the most recent message
381
+ # this is not waiting
382
+ while stream.get_available_bytes() == 0:
383
+ stream.poll()
384
+ if stream.get_status() != 2:
385
+ print("server disconnected status, closing")
386
+ get_tree().quit()
387
+ return null
388
+
389
+ OS.delay_usec(10)
390
+
391
+ var message = stream.get_string()
392
+ var json_data = JSON.parse_string(message)
393
+
394
+ return json_data
395
+
396
+
397
+ func _send_dict_as_json_message(dict):
398
+ stream.put_string(JSON.stringify(dict, "", false))
399
+
400
+
401
+ func _send_env_info():
402
+ var json_dict = _get_dict_json_message()
403
+ assert(json_dict["type"] == "env_info")
404
+
405
+ var message = {
406
+ "type": "env_info",
407
+ "observation_space": _obs_space_training,
408
+ "action_space": _action_space_training,
409
+ "n_agents": len(agents_training),
410
+ "agent_policy_names": agents_training_policy_names
411
+ }
412
+ _send_dict_as_json_message(message)
413
+
414
+
415
+ func connect_to_server():
416
+ print("Waiting for one second to allow server to start")
417
+ OS.delay_msec(1000)
418
+ print("trying to connect to server")
419
+ stream = StreamPeerTCP.new()
420
+
421
+ # "localhost" was not working on windows VM, had to use the IP
422
+ var ip = "127.0.0.1"
423
+ var port = _get_port()
424
+ var connect = stream.connect_to_host(ip, port)
425
+ stream.set_no_delay(true) # TODO check if this improves performance or not
426
+ stream.poll()
427
+ # Fetch the status until it is either connected (2) or failed to connect (3)
428
+ while stream.get_status() < 2:
429
+ stream.poll()
430
+ return stream.get_status() == 2
431
+
432
+
433
+ func _get_args():
434
+ print("getting command line arguments")
435
+ var arguments = {}
436
+ for argument in OS.get_cmdline_args():
437
+ print(argument)
438
+ if argument.find("=") > -1:
439
+ var key_value = argument.split("=")
440
+ arguments[key_value[0].lstrip("--")] = key_value[1]
441
+ else:
442
+ # Options without an argument will be present in the dictionary,
443
+ # with the value set to an empty string.
444
+ arguments[argument.lstrip("--")] = ""
445
+
446
+ return arguments
447
+
448
+
449
+ func _get_speedup():
450
+ print(args)
451
+ return args.get("speedup", str(speed_up)).to_float()
452
+
453
+
454
+ func _get_port():
455
+ return args.get("port", DEFAULT_PORT).to_int()
456
+
457
+
458
+ func _set_seed():
459
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
460
+ seed(_seed)
461
+
462
+
463
+ func _set_action_repeat():
464
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
465
+
466
+
467
+ func disconnect_from_server():
468
+ stream.disconnect_from_host()
469
+
470
+
471
+ func handle_message() -> bool:
472
+ # get json message: reset, step, close
473
+ var message = _get_dict_json_message()
474
+ if message["type"] == "close":
475
+ print("received close message, closing game")
476
+ get_tree().quit()
477
+ get_tree().set_pause(false)
478
+ return true
479
+
480
+ if message["type"] == "reset":
481
+ print("resetting all agents")
482
+ _reset_agents()
483
+ just_reset = true
484
+ get_tree().set_pause(false)
485
+ #print("resetting forcing draw")
486
+ # RenderingServer.force_draw()
487
+ # var obs = _get_obs_from_agents()
488
+ # print("obs ", obs)
489
+ # var reply = {
490
+ # "type": "reset",
491
+ # "obs": obs
492
+ # }
493
+ # _send_dict_as_json_message(reply)
494
+ return true
495
+
496
+ if message["type"] == "call":
497
+ var method = message["method"]
498
+ var returns = _call_method_on_agents(method)
499
+ var reply = {"type": "call", "returns": returns}
500
+ print("calling method from Python")
501
+ _send_dict_as_json_message(reply)
502
+ return handle_message()
503
+
504
+ if message["type"] == "action":
505
+ var action = message["action"]
506
+ _set_agent_actions(action, agents_training)
507
+ need_to_send_obs = true
508
+ get_tree().set_pause(false)
509
+ return true
510
+
511
+ print("message was not handled")
512
+ return false
513
+
514
+
515
+ func _call_method_on_agents(method):
516
+ var returns = []
517
+ for agent in all_agents:
518
+ returns.append(agent.call(method))
519
+
520
+ return returns
521
+
522
+
523
+ func _reset_agents_if_done(agents = all_agents):
524
+ for agent in agents:
525
+ if agent.get_done():
526
+ agent.set_done_false()
527
+
528
+
529
+ func _reset_agents(agents = all_agents):
530
+ for agent in agents:
531
+ agent.needs_reset = true
532
+ #agent.reset()
533
+
534
+
535
+ func _get_obs_from_agents(agents: Array = all_agents):
536
+ var obs = []
537
+ for agent in agents:
538
+ obs.append(agent.get_obs())
539
+ return obs
540
+
541
+
542
+ func _get_reward_from_agents(agents: Array = agents_training):
543
+ var rewards = []
544
+ for agent in agents:
545
+ rewards.append(agent.get_reward())
546
+ agent.zero_reward()
547
+ return rewards
548
+
549
+
550
+ func _get_done_from_agents(agents: Array = agents_training):
551
+ var dones = []
552
+ for agent in agents:
553
+ var done = agent.get_done()
554
+ if done:
555
+ agent.set_done_false()
556
+ dones.append(done)
557
+ return dones
558
+
559
+
560
+ func _set_agent_actions(actions, agents: Array = all_agents):
561
+ for i in range(len(actions)):
562
+ agents[i].set_action(actions[i])
563
+
564
+
565
+ func clamp_array(arr: Array, min: float, max: float):
566
+ var output: Array = []
567
+ for a in arr:
568
+ output.append(clamp(a, min, max))
569
+ return output
570
+
571
+
572
+ ## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor)
573
+ func _notification(what):
574
+ if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty():
575
+ return
576
+
577
+ if what == NOTIFICATION_PREDELETE:
578
+ var json_string = JSON.stringify(demo_trajectories, "", false)
579
+ var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE)
580
+
581
+ if not file:
582
+ var error: Error = FileAccess.get_open_error()
583
+ assert(not error, "There was an error opening the file: %d" % error)
584
+
585
+ file.store_line(json_string)
586
+ var error = file.get_error()
587
+ assert(not error, "There was an error after trying to write to the file: %d" % error)
assets/goal.glb ADDED
Binary file (9.06 kB). View file
 
assets/map.glb ADDED
Binary file (288 kB). View file
 
assets/map_grass.png ADDED

Git LFS Details

  • SHA256: 814d1330279a614636d5ed10bf0c906d1054d4c0f64cda93a35fda78bf3e6844
  • Pointer size: 130 Bytes
  • Size of remote file: 57.9 kB
assets/robot.glb ADDED
Binary file (135 kB). View file
 
icon.svg ADDED
license.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ScoreTheGoal Environment made by Ivan Dodic (https://github.com/Ivan-267)
2
+
3
+ The following license is only for the graphical assets in the folder "assets", specifically .glb and .png files:
4
+ Author: Ivan Dodic (https://github.com/Ivan-267),
5
+ License: https://creativecommons.org/licenses/by/4.0/
model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:087ca30229cec32ae0f2cc688e993b0a3b6f978015e33a4eee24478f67d8fa61
3
+ size 287750
project.godot ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="ScoreTheGoal"
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="CartExamples"
21
+
22
+ [editor_plugins]
23
+
24
+ enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
25
+
26
+ [input]
27
+
28
+ move_forward={
29
+ "deadzone": 0.5,
30
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":119,"location":0,"echo":false,"script":null)
31
+ , Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194320,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
32
+ ]
33
+ }
34
+ move_back={
35
+ "deadzone": 0.5,
36
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":115,"location":0,"echo":false,"script":null)
37
+ , Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194322,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
38
+ ]
39
+ }
40
+ turn_left={
41
+ "deadzone": 0.5,
42
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":97,"location":0,"echo":false,"script":null)
43
+ , Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194319,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
44
+ ]
45
+ }
46
+ turn_right={
47
+ "deadzone": 0.5,
48
+ "events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":100,"location":0,"echo":false,"script":null)
49
+ , Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194321,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
50
+ ]
51
+ }
readme.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Score the goal environment
2
+
3
+ https://github.com/user-attachments/assets/c2763df6-5338-4eec-9e5b-4c89e3e65f51
4
+
5
+ ## Goal:
6
+
7
+ The robot must push the ball into the correct goal. Only a single collision with the ball is allowed, after which the robot’s movement is disabled until the end of the episode.
8
+
9
+ ## Observations:
10
+
11
+ - Position of the ball relative to the player,
12
+ - position of the each goal relative to the player,
13
+ - for each goal, whether the goal is the "correct goal" as 0 or 1,
14
+ - whether the ball was already hit in episode (movement is disabled after hitting the ball),
15
+ - observations from the wall raycast sensor (it's not allowed to hit a wall)
16
+
17
+ ## Actions:
18
+
19
+ ```python
20
+ func get_action_space() -> Dictionary:
21
+ return {
22
+ "accelerate": {"size": 1, "action_type": "continuous"},
23
+ "steer": {"size": 1, "action_type": "continuous"},
24
+ }
25
+ ```
26
+
27
+ ## Running inference:
28
+
29
+ If you’d just like to test the env using the pre-trained onnx model, you can click on the `sync` node in the training scene, then switch to `Control Mode: Onnx Inference` in the inspector on the right and start the game.
30
+
31
+ ## Training:
32
+
33
+ There’s an included onnx file that was trained with https://github.com/edbeeching/godot_rl_agents/blob/main/examples/stable_baselines3_example.py, modified to use SAC with hyperparameters set as below (for instructions on using SAC, also check https://github.com/edbeeching/godot_rl_agents/pull/198):
34
+
35
+ ```python
36
+ model: SAC = SAC(
37
+ "MlpPolicy",
38
+ env,
39
+ gradient_steps=8,
40
+ verbose=2,
41
+ tensorboard_log=args.experiment_dir,
42
+ )
43
+ ```
44
+
45
+ CL arguments used (also onnx export and model saving was used, enable as needed):
46
+
47
+ ```python
48
+ --speedup=8
49
+ --n_parallel=8
50
+ ```
51
+
52
+ Training was done for ~3.1 million steps with manual stopping.
scenes/ball/ball.gd ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends RigidBody3D
2
+
3
+ class_name Ball
4
+
5
+ var category: int
6
+ var correct_goal: Goal
7
+
8
+ var _material: StandardMaterial3D
9
+
10
+
11
+ func set_random_category(category_count: int):
12
+ if not (_material):
13
+ var mesh: MeshInstance3D = $MeshInstance3D
14
+ _material = mesh.get_active_material(0)
15
+ category = randi_range(0, category_count - 1)
16
+ _material.albedo_color = Color.from_hsv(category / float(category_count), 0.8, 1.0)
17
+
18
+
19
+ func get_category() -> int:
20
+ return category
scenes/ball/ball.tscn ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=6 format=3 uid="uid://cih6afjthxjso"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/ball/ball.gd" id="1_0lp3q"]
4
+
5
+ [sub_resource type="PhysicsMaterial" id="PhysicsMaterial_0ednm"]
6
+ friction = 0.5
7
+ bounce = 1.0
8
+
9
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_mswji"]
10
+ resource_local_to_scene = true
11
+
12
+ [sub_resource type="SphereMesh" id="SphereMesh_yhrp3"]
13
+ resource_local_to_scene = true
14
+ material = SubResource("StandardMaterial3D_mswji")
15
+ radius = 0.338
16
+ height = 0.675
17
+
18
+ [sub_resource type="SphereShape3D" id="SphereShape3D_ppi6w"]
19
+ radius = 0.338
20
+
21
+ [node name="Ball" type="RigidBody3D"]
22
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.294903, 3.09716)
23
+ collision_layer = 2
24
+ collision_mask = 5
25
+ mass = 0.25
26
+ physics_material_override = SubResource("PhysicsMaterial_0ednm")
27
+ lock_rotation = true
28
+ script = ExtResource("1_0lp3q")
29
+
30
+ [node name="MeshInstance3D" type="MeshInstance3D" parent="."]
31
+ mesh = SubResource("SphereMesh_yhrp3")
32
+
33
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="."]
34
+ shape = SubResource("SphereShape3D_ppi6w")
scenes/goal/goal.gd ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name Goal
3
+
4
+ @onready var _mesh: MeshInstance3D = $goal/Cube_001
5
+ signal ball_entered_goal(ball_goal_category_match)
6
+ signal robot_entered_goal
7
+ var _category: int
8
+ var _material: ShaderMaterial
9
+
10
+
11
+ func set_category(category: int, category_count: int):
12
+ _category = category
13
+ if not (_material):
14
+ _material = _mesh.material_override
15
+ _material.set_shader_parameter(
16
+ "albedo", Color.from_hsv(category / float(category_count), 0.8, 1.0)
17
+ )
18
+
19
+
20
+ func _on_area_3d_body_entered(node: Node3D):
21
+ if node is Ball:
22
+ ball_entered_goal.emit(node.category == _category)
23
+ elif node is Robot:
24
+ robot_entered_goal.emit()
25
+
26
+
27
+ func get_category() -> int:
28
+ return _category
scenes/goal/goal.tscn ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=7 format=3 uid="uid://dsujj2charlnu"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/goal/goal.gd" id="1_2meav"]
4
+ [ext_resource type="PackedScene" uid="uid://br8oux3ppivpn" path="res://scenes/goal/goal_visual.tscn" id="2_if6ad"]
5
+
6
+ [sub_resource type="Shader" id="Shader_eprhu"]
7
+ code = "// NOTE: Shader automatically converted from Godot Engine 4.3.stable.mono's StandardMaterial3D.
8
+ // Adds sway to the goal category flags
9
+
10
+ shader_type spatial;
11
+ render_mode blend_mix, depth_draw_opaque, cull_disabled, diffuse_burley, specular_schlick_ggx;
12
+
13
+ uniform vec4 albedo : source_color;
14
+ uniform sampler2D texture_albedo : source_color, filter_linear_mipmap, repeat_enable;
15
+ uniform float point_size : hint_range(0.1, 128.0, 0.1);
16
+
17
+ uniform float roughness : hint_range(0.0, 1.0);
18
+ uniform sampler2D texture_metallic : hint_default_white, filter_linear_mipmap, repeat_enable;
19
+ uniform vec4 metallic_texture_channel;
20
+ uniform sampler2D texture_roughness : hint_roughness_r, filter_linear_mipmap, repeat_enable;
21
+
22
+ uniform float specular : hint_range(0.0, 1.0, 0.01);
23
+ uniform float metallic : hint_range(0.0, 1.0, 0.01);
24
+
25
+ uniform vec3 uv1_scale;
26
+ uniform vec3 uv1_offset;
27
+ uniform vec3 uv2_scale;
28
+ uniform vec3 uv2_offset;
29
+
30
+ void vertex() {
31
+ UV = UV * uv1_scale.xy + uv1_offset.xy;
32
+ float offset = VERTEX.x * sin(VERTEX.x * 20.0 + 5.0 * TIME);
33
+ VERTEX.z += 0.2 * offset;
34
+ VERTEX.y += 0.05 * offset;
35
+ }
36
+
37
+ void fragment() {
38
+ vec2 base_uv = UV;
39
+
40
+ vec4 albedo_tex = texture(texture_albedo, base_uv);
41
+ ALBEDO = albedo.rgb * albedo_tex.rgb;
42
+
43
+ float metallic_tex = dot(texture(texture_metallic, base_uv), metallic_texture_channel);
44
+ METALLIC = metallic_tex * metallic;
45
+ SPECULAR = specular;
46
+
47
+ vec4 roughness_texture_channel = vec4(1.0, 0.0, 0.0, 0.0);
48
+ float roughness_tex = dot(texture(texture_roughness, base_uv), roughness_texture_channel);
49
+ ROUGHNESS = roughness_tex * roughness;
50
+ }
51
+ "
52
+
53
+ [sub_resource type="ShaderMaterial" id="ShaderMaterial_xnr6a"]
54
+ resource_local_to_scene = true
55
+ render_priority = 0
56
+ shader = SubResource("Shader_eprhu")
57
+ shader_parameter/albedo = Color(0, 1, 0, 1)
58
+ shader_parameter/point_size = 1.0
59
+ shader_parameter/roughness = 1.0
60
+ shader_parameter/metallic_texture_channel = null
61
+ shader_parameter/specular = 0.5
62
+ shader_parameter/metallic = 0.0
63
+ shader_parameter/uv1_scale = Vector3(1, 1, 1)
64
+ shader_parameter/uv1_offset = Vector3(0, 0, 0)
65
+ shader_parameter/uv2_scale = Vector3(1, 1, 1)
66
+ shader_parameter/uv2_offset = Vector3(0, 0, 0)
67
+
68
+ [sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_d674o"]
69
+ points = PackedVector3Array(-1.3, 0.935, 0.9, 1.3, 0.935, 0.9, -1.825, -1, -0.4, 1.825, -1, -0.4, -1.3, 0.935, 1, 1.3, 0.935, 1, -1.825, -1, 1, 1.825, -1, 1)
70
+
71
+ [sub_resource type="ConcavePolygonShape3D" id="ConcavePolygonShape3D_frrwl"]
72
+ data = PackedVector3Array(-1.9897, 0, -1, -1.266, 1.8117, -1.0001, -1.3927, 1.9898, -1, -1.9897, 0, -1, -1.7547, 0, -1.0001, -1.266, 1.8117, -1.0001, -1.3927, 1.9898, -1, 1.266, 1.8115, -0.9999, 1.3927, 1.9898, -1, -1.3927, 1.9898, -1, -1.266, 1.8117, -1.0001, 1.266, 1.8115, -0.9999, 1.7137, 0, 0.6995, -1.2716, 1.8012, -0.458, -1.7138, 0, 0.6995, 1.7137, 0, 0.6995, 1.2734, 1.8013, -0.458, -1.2716, 1.8012, -0.458, 1.3927, 1.9898, -1, 1.7549, 0, -0.9999, 1.9897, 0, -1, 1.3927, 1.9898, -1, 1.266, 1.8115, -0.9999, 1.7549, 0, -0.9999, 1.2589, 1.8012, -0.9899, -1.2716, 1.8012, -0.458, 1.2734, 1.8013, -0.458, 1.2589, 1.8012, -0.9899, -1.2588, 1.8013, -0.9901, -1.2716, 1.8012, -0.458, 1.7445, 0, -0.9899, 1.2734, 1.8013, -0.458, 1.7137, 0, 0.6995, 1.7445, 0, -0.9899, 1.2589, 1.8012, -0.9899, 1.2734, 1.8013, -0.458, -1.7138, 0, 0.6995, -1.2588, 1.8013, -0.9901, -1.7444, 0, -0.9901, -1.7138, 0, 0.6995, -1.2716, 1.8012, -0.458, -1.2588, 1.8013, -0.9901, -1.2588, 1.8013, -0.9901, -1.7547, 0, -1.0001, -1.7444, 0, -0.9901, -1.2588, 1.8013, -0.9901, -1.266, 1.8117, -1.0001, -1.7547, 0, -1.0001, -1.266, 1.8117, -1.0001, 1.2589, 1.8012, -0.9899, 1.266, 1.8115, -0.9999, -1.266, 1.8117, -1.0001, -1.2588, 1.8013, -0.9901, 1.2589, 1.8012, -0.9899, 1.266, 1.8115, -0.9999, 1.7445, 0, -0.9899, 1.7549, 0, -0.9999, 1.266, 1.8115, -0.9999, 1.2589, 1.8012, -0.9899, 1.7445, 0, -0.9899, -1.3927, 1.9898, -1, -2, 0, -0.99, -1.9897, 0, -1, -1.3927, 1.9898, -1, -1.4, 2, -0.99, -2, 0, -0.99, -1.4, 2, -0.99, 1.3927, 1.9898, -1, 1.4, 2, -0.99, -1.4, 2, -0.99, -1.3927, 1.9898, -1, 1.3927, 1.9898, -1, 1.4, 2, -0.99, 1.9897, 0, -1, 2, 0, -0.99, 1.4, 2, -0.99, 1.3927, 1.9898, -1, 1.9897, 0, -1, 2, 0, 1, -1.399, 2, -0.3653, 1.401, 2, -0.3653, 2, 0, 1, -2, 0, 1, -1.399, 2, -0.3653, 1.4, 2, -0.99, -1.399, 2, -0.3653, -1.4, 2, -0.99, 1.4, 2, -0.99, 1.401, 2, -0.3653, -1.399, 2, -0.3653, 2, 0, -0.99, 1.401, 2, -0.3653, 1.4, 2, -0.99, 2, 0, -0.99, 2, 0, 1, 1.401, 2, -0.3653, -2, 0, 1, -1.4, 2, -0.99, -1.399, 2, -0.3653, -2, 0, 1, -2, 0, -0.99, -1.4, 2, -0.99, -2, 0, 1, -1.9897, 0, -1, -2, 0, -0.99, -1.9897, 0, -1, -1.7444, 0, -0.9901, -1.7548, 0, -1.0001, -1.9897, 0, -1, -1.7138, 0, 0.6995, -1.7444, 0, -0.9901, 1.9896, 0, -1, 2, 0, 1, 2, 0, -0.99, 1.7445, 0, -0.9899, 1.9896, 0, -1, 1.7549, 0, -0.9999, 1.7137, 0, 0.6995, 1.9896, 0, -1, 1.7445, 0, -0.9899, -2, 0, 1, -1.7138, 0, 0.6995, -1.9897, 0, -1, 1.7137, 0, 0.6995, 2, 0, 1, 1.9896, 0, -1, -2, 0, 1, 1.7137, 0, 0.6995, -1.7138, 0, 0.6995, -2, 0, 1, 2, 0, 1, 1.7137, 0, 0.6995)
73
+
74
+ [node name="Goal" type="StaticBody3D"]
75
+ script = ExtResource("1_2meav")
76
+
77
+ [node name="goal" parent="." instance=ExtResource("2_if6ad")]
78
+ transform = Transform3D(-1, 0, -8.74228e-08, 0, 1, 0, 8.74228e-08, 0, -1, 0, 0, 0)
79
+
80
+ [node name="Cube_001" parent="goal" index="2"]
81
+ material_override = SubResource("ShaderMaterial_xnr6a")
82
+
83
+ [node name="Area3D" type="Area3D" parent="."]
84
+ collision_layer = 4
85
+ collision_mask = 3
86
+
87
+ [node name="CollisionShape3D2" type="CollisionShape3D" parent="Area3D"]
88
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.907776, -0.509382)
89
+ shape = SubResource("ConvexPolygonShape3D_d674o")
90
+
91
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="."]
92
+ transform = Transform3D(-1, 0, -8.74228e-08, 0, 1, 0, 8.74228e-08, 0, -1, 0, 0, 0)
93
+ shape = SubResource("ConcavePolygonShape3D_frrwl")
94
+
95
+ [connection signal="body_entered" from="Area3D" to="." method="_on_area_3d_body_entered"]
96
+
97
+ [editable path="goal"]
scenes/goal/goal_visual.tscn ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=4 format=3 uid="uid://br8oux3ppivpn"]
2
+
3
+ [ext_resource type="PackedScene" uid="uid://c6kw3obr7npgk" path="res://assets/goal.glb" id="1_m6qkg"]
4
+
5
+ [sub_resource type="Shader" id="Shader_eprhu"]
6
+ code = "// NOTE: Shader automatically converted from Godot Engine 4.3.stable.mono's StandardMaterial3D.
7
+ // Adds sway to the goal category flags
8
+
9
+ shader_type spatial;
10
+ render_mode blend_mix, depth_draw_opaque, cull_back, diffuse_burley, specular_schlick_ggx;
11
+
12
+ uniform vec4 albedo : source_color;
13
+ uniform sampler2D texture_albedo : source_color, filter_linear_mipmap, repeat_enable;
14
+ uniform float point_size : hint_range(0.1, 128.0, 0.1);
15
+
16
+ uniform float roughness : hint_range(0.0, 1.0);
17
+ uniform sampler2D texture_metallic : hint_default_white, filter_linear_mipmap, repeat_enable;
18
+ uniform vec4 metallic_texture_channel;
19
+ uniform sampler2D texture_roughness : hint_roughness_r, filter_linear_mipmap, repeat_enable;
20
+
21
+ uniform float specular : hint_range(0.0, 1.0, 0.01);
22
+ uniform float metallic : hint_range(0.0, 1.0, 0.01);
23
+
24
+ uniform vec3 uv1_scale;
25
+ uniform vec3 uv1_offset;
26
+ uniform vec3 uv2_scale;
27
+ uniform vec3 uv2_offset;
28
+
29
+ void vertex() {
30
+ UV = UV * uv1_scale.xy + uv1_offset.xy;
31
+ float offset = VERTEX.x * sin(VERTEX.x * 20.0 + 5.0 * TIME);
32
+ VERTEX.z += 0.2 * offset;
33
+ VERTEX.y += 0.05 * offset;
34
+ }
35
+
36
+ void fragment() {
37
+ vec2 base_uv = UV;
38
+
39
+ vec4 albedo_tex = texture(texture_albedo, base_uv);
40
+ ALBEDO = albedo.rgb * albedo_tex.rgb;
41
+
42
+ float metallic_tex = dot(texture(texture_metallic, base_uv), metallic_texture_channel);
43
+ METALLIC = metallic_tex * metallic;
44
+ SPECULAR = specular;
45
+
46
+ vec4 roughness_texture_channel = vec4(1.0, 0.0, 0.0, 0.0);
47
+ float roughness_tex = dot(texture(texture_roughness, base_uv), roughness_texture_channel);
48
+ ROUGHNESS = roughness_tex * roughness;
49
+ }
50
+ "
51
+
52
+ [sub_resource type="ShaderMaterial" id="ShaderMaterial_3lno6"]
53
+ resource_local_to_scene = true
54
+ render_priority = 0
55
+ shader = SubResource("Shader_eprhu")
56
+ shader_parameter/albedo = Color(0, 1, 0, 1)
57
+ shader_parameter/point_size = 1.0
58
+ shader_parameter/roughness = 1.0
59
+ shader_parameter/metallic_texture_channel = null
60
+ shader_parameter/specular = 0.5
61
+ shader_parameter/metallic = 0.0
62
+ shader_parameter/uv1_scale = Vector3(1, 1, 1)
63
+ shader_parameter/uv1_offset = Vector3(0, 0, 0)
64
+ shader_parameter/uv2_scale = Vector3(1, 1, 1)
65
+ shader_parameter/uv2_offset = Vector3(0, 0, 0)
66
+
67
+ [node name="goal" instance=ExtResource("1_m6qkg")]
68
+
69
+ [node name="Cube_001" parent="." index="2"]
70
+ material_override = SubResource("ShaderMaterial_3lno6")
scenes/playing_area/map.tscn ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=14 format=3 uid="uid://dnbjyfak5tnxx"]
2
+
3
+ [ext_resource type="PackedScene" uid="uid://dlqx5cg51oy75" path="res://assets/map.glb" id="1_o8st6"]
4
+ [ext_resource type="Texture2D" uid="uid://n4awd2gdd5al" path="res://assets/map_grass.png" id="2_16q2n"]
5
+ [ext_resource type="Script" path="res://scenes/playing_area/wall.gd" id="3_yaxie"]
6
+
7
+ [sub_resource type="Gradient" id="Gradient_bprsk"]
8
+ colors = PackedColorArray(0.79, 0.79, 0.79, 1, 1, 1, 1, 1)
9
+
10
+ [sub_resource type="FastNoiseLite" id="FastNoiseLite_7cu0y"]
11
+ seed = 1255
12
+ frequency = 0.0058
13
+ fractal_octaves = 8
14
+ fractal_lacunarity = 3.155
15
+
16
+ [sub_resource type="NoiseTexture2D" id="NoiseTexture2D_n5v7u"]
17
+ seamless = true
18
+ normalize = false
19
+ color_ramp = SubResource("Gradient_bprsk")
20
+ noise = SubResource("FastNoiseLite_7cu0y")
21
+
22
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_c2583"]
23
+ albedo_color = Color(2.14182e-06, 0.56847, 7.70092e-07, 1)
24
+ albedo_texture = SubResource("NoiseTexture2D_n5v7u")
25
+
26
+ [sub_resource type="Shader" id="Shader_2vpqo"]
27
+ code = "// NOTE: Shader automatically converted from Godot Engine 4.3.stable.mono's StandardMaterial3D.
28
+ // Added some grass swaying
29
+
30
+ shader_type spatial;
31
+ render_mode blend_mix, depth_draw_opaque, cull_disabled, diffuse_burley, specular_schlick_ggx, unshaded;
32
+
33
+ uniform vec4 albedo : source_color;
34
+ uniform sampler2D texture_albedo : source_color, filter_linear_mipmap, repeat_enable;
35
+ uniform float point_size : hint_range(0.1, 128.0, 0.1);
36
+
37
+ uniform float roughness : hint_range(0.0, 1.0);
38
+ uniform sampler2D texture_metallic : hint_default_white, filter_linear_mipmap, repeat_enable;
39
+ uniform vec4 metallic_texture_channel;
40
+ uniform sampler2D texture_roughness : hint_roughness_r, filter_linear_mipmap, repeat_enable;
41
+
42
+ uniform float specular : hint_range(0.0, 1.0, 0.01);
43
+ uniform float metallic : hint_range(0.0, 1.0, 0.01);
44
+
45
+ uniform vec3 uv1_scale;
46
+ uniform vec3 uv1_offset;
47
+ uniform vec3 uv2_scale;
48
+ uniform vec3 uv2_offset;
49
+
50
+ void vertex() {
51
+ UV = UV * uv1_scale.xy + uv1_offset.xy;
52
+ VERTEX.x += (VERTEX.y) * sin(TIME * 1.0) * 0.1;
53
+ VERTEX.z += (VERTEX.y) * cos(0.5 + TIME * 0.5) * 0.1;
54
+ }
55
+
56
+ void fragment() {
57
+ vec2 base_uv = UV;
58
+
59
+ vec4 albedo_tex = texture(texture_albedo, base_uv);
60
+ ALBEDO = albedo.rgb * albedo_tex.rgb;
61
+
62
+ float metallic_tex = dot(texture(texture_metallic, base_uv), metallic_texture_channel);
63
+ METALLIC = metallic_tex * metallic;
64
+ SPECULAR = specular;
65
+
66
+ vec4 roughness_texture_channel = vec4(1.0, 0.0, 0.0, 0.0);
67
+ float roughness_tex = dot(texture(texture_roughness, base_uv), roughness_texture_channel);
68
+ ROUGHNESS = roughness_tex * roughness;
69
+ ALPHA *= albedo.a * albedo_tex.a;
70
+ }
71
+ "
72
+
73
+ [sub_resource type="ShaderMaterial" id="ShaderMaterial_mruej"]
74
+ render_priority = 0
75
+ shader = SubResource("Shader_2vpqo")
76
+ shader_parameter/albedo = Color(1, 1, 1, 1)
77
+ shader_parameter/point_size = 1.0
78
+ shader_parameter/roughness = 1.0
79
+ shader_parameter/metallic_texture_channel = null
80
+ shader_parameter/specular = 0.0
81
+ shader_parameter/metallic = 0.0
82
+ shader_parameter/uv1_scale = Vector3(1, 1, 1)
83
+ shader_parameter/uv1_offset = Vector3(0, 0, 0)
84
+ shader_parameter/uv2_scale = Vector3(1, 1, 1)
85
+ shader_parameter/uv2_offset = Vector3(0, 0, 0)
86
+ shader_parameter/texture_albedo = ExtResource("2_16q2n")
87
+
88
+ [sub_resource type="PhysicsMaterial" id="PhysicsMaterial_2masj"]
89
+
90
+ [sub_resource type="BoxShape3D" id="BoxShape3D_chcpu"]
91
+ size = Vector3(22, 1.025, 22)
92
+
93
+ [sub_resource type="BoxShape3D" id="BoxShape3D_7b7uh"]
94
+ size = Vector3(1, 1.025, 18)
95
+
96
+ [sub_resource type="BoxShape3D" id="BoxShape3D_52jdx"]
97
+ size = Vector3(1, 1.025, 2.145)
98
+
99
+ [node name="map" instance=ExtResource("1_o8st6")]
100
+
101
+ [node name="Ground" parent="." index="0"]
102
+ material_override = SubResource("StandardMaterial3D_c2583")
103
+
104
+ [node name="grassplane1" parent="grass" index="0"]
105
+ material_override = SubResource("ShaderMaterial_mruej")
106
+
107
+ [node name="Ground2" type="StaticBody3D" parent="." index="17"]
108
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0)
109
+ physics_material_override = SubResource("PhysicsMaterial_2masj")
110
+
111
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="Ground2" index="0"]
112
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.5, 0)
113
+ shape = SubResource("BoxShape3D_chcpu")
114
+
115
+ [node name="Wall" type="StaticBody3D" parent="." index="18"]
116
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0)
117
+ collision_layer = 8
118
+ physics_material_override = SubResource("PhysicsMaterial_2masj")
119
+ script = ExtResource("3_yaxie")
120
+
121
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="Wall" index="0"]
122
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -7.94042, 0.416386, 0)
123
+ shape = SubResource("BoxShape3D_7b7uh")
124
+
125
+ [node name="CollisionShape3D2" type="CollisionShape3D" parent="Wall" index="1"]
126
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 7.94, 0.416386, 0)
127
+ shape = SubResource("BoxShape3D_7b7uh")
128
+
129
+ [node name="CollisionShape3D3" type="CollisionShape3D" parent="Wall" index="2"]
130
+ transform = Transform3D(-4.37114e-08, 0, -1, 0, 1, 0, 1, 0, -4.37114e-08, 0, 0.416386, -9.4)
131
+ shape = SubResource("BoxShape3D_7b7uh")
132
+
133
+ [node name="CollisionShape3D4" type="CollisionShape3D" parent="Wall" index="3"]
134
+ transform = Transform3D(-4.37114e-08, 0, -1, 0, 1, 0, 1, 0, -4.37114e-08, 0, 0.416386, 9.4)
135
+ shape = SubResource("BoxShape3D_7b7uh")
136
+
137
+ [node name="CollisionShape3D5" type="CollisionShape3D" parent="Wall" index="4"]
138
+ transform = Transform3D(-0.765202, 0, -0.64379, 0, 1, 0, 0.64379, 0, -0.765202, -7.51943, 0.416386, 8.95088)
139
+ shape = SubResource("BoxShape3D_52jdx")
140
+
141
+ [node name="CollisionShape3D6" type="CollisionShape3D" parent="Wall" index="5"]
142
+ transform = Transform3D(-0.764921, 0, 0.644123, 0, 1, 0, -0.644123, 0, -0.764921, 7.519, 0.416386, 8.951)
143
+ shape = SubResource("BoxShape3D_52jdx")
144
+
145
+ [node name="CollisionShape3D7" type="CollisionShape3D" parent="Wall" index="6"]
146
+ transform = Transform3D(-0.764921, 0, 0.644123, 0, 1, 0, -0.644123, 0, -0.764921, -7.519, 0.416386, -8.951)
147
+ shape = SubResource("BoxShape3D_52jdx")
148
+
149
+ [node name="CollisionShape3D8" type="CollisionShape3D" parent="Wall" index="7"]
150
+ transform = Transform3D(-0.764921, 0, -0.644123, 0, 1, 0, 0.644123, 0, -0.764921, 7.519, 0.416386, -8.951)
151
+ shape = SubResource("BoxShape3D_52jdx")
scenes/playing_area/playing_area.tscn ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=5 format=3 uid="uid://7rc10s44c2v"]
2
+
3
+ [ext_resource type="PackedScene" uid="uid://dnbjyfak5tnxx" path="res://scenes/playing_area/map.tscn" id="1_y8ivg"]
4
+ [ext_resource type="PackedScene" uid="uid://dsujj2charlnu" path="res://scenes/goal/goal.tscn" id="2_3qsoh"]
5
+ [ext_resource type="PackedScene" uid="uid://cih6afjthxjso" path="res://scenes/ball/ball.tscn" id="2_ytls0"]
6
+ [ext_resource type="PackedScene" uid="uid://bpb5ld8ygwbin" path="res://scenes/robot/robot.tscn" id="3_82lnl"]
7
+
8
+ [node name="playing_area" type="Node3D"]
9
+
10
+ [node name="map" parent="." instance=ExtResource("1_y8ivg")]
11
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -0.8, 0)
12
+
13
+ [node name="Goal" parent="." instance=ExtResource("2_3qsoh")]
14
+ transform = Transform3D(-1, 0, -1.50996e-07, 0, 1, 0, 1.50996e-07, 0, -1, 0, 0, 7)
15
+
16
+ [node name="Goal2" parent="." instance=ExtResource("2_3qsoh")]
17
+ transform = Transform3D(-0.906308, 0, -0.422618, 0, 1, 0, 0.422618, 0, -0.906308, 4.5, 0, 6)
18
+
19
+ [node name="Goal3" parent="." instance=ExtResource("2_3qsoh")]
20
+ transform = Transform3D(-0.906308, 0, 0.422618, 0, 1, 0, -0.422618, 0, -0.906308, -4.5, 0, 6)
21
+
22
+ [node name="Ball" parent="." instance=ExtResource("2_ytls0")]
23
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.344, -2.09863)
24
+ collision_mask = 13
25
+ axis_lock_linear_y = true
26
+ mass = 0.5
27
+ gravity_scale = 0.0
28
+ continuous_cd = true
29
+ contact_monitor = true
30
+ max_contacts_reported = 3
31
+
32
+ [node name="Robot" parent="." node_paths=PackedStringArray("ball", "goals") instance=ExtResource("3_82lnl")]
33
+ transform = Transform3D(-1, 0, -8.74228e-08, 0, 1, 0, 8.74228e-08, 0, -1, 0, 0.313375, -5.28)
34
+ collision_mask = 15
35
+ contact_monitor = true
36
+ max_contacts_reported = 1
37
+ ball = NodePath("../Ball")
38
+ goals = [NodePath("../Goal"), NodePath("../Goal2"), NodePath("../Goal3")]
39
+ category_count = 3
40
+
41
+ [connection signal="ball_entered_goal" from="Goal" to="Robot" method="_on_ball_entered_goal"]
42
+ [connection signal="robot_entered_goal" from="Goal" to="Robot" method="_on_robot_entered_goal"]
43
+ [connection signal="ball_entered_goal" from="Goal2" to="Robot" method="_on_ball_entered_goal"]
44
+ [connection signal="robot_entered_goal" from="Goal2" to="Robot" method="_on_robot_entered_goal"]
45
+ [connection signal="ball_entered_goal" from="Goal3" to="Robot" method="_on_ball_entered_goal"]
46
+ [connection signal="robot_entered_goal" from="Goal3" to="Robot" method="_on_robot_entered_goal"]
47
+ [connection signal="body_entered" from="Ball" to="Robot" method="_on_ball_body_entered"]
48
+ [connection signal="body_entered" from="Robot" to="Robot" method="_on_body_entered"]
scenes/playing_area/wall.gd ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ extends StaticBody3D
2
+ class_name Wall
scenes/robot/robot.gd ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends RigidBody3D
2
+ class_name Robot
3
+
4
+ @export var ball: Ball
5
+ @export var goals: Array[Goal]
6
+ @export var category_count: int
7
+
8
+ @onready var ai_controller: AIController3D = $AIController3D
9
+ @onready var animation_player: AnimationPlayer = $robot/AnimationPlayer
10
+
11
+ var acceleration: float = 700
12
+ var torque_multiplier: float = 60
13
+ var requested_acceleration: float
14
+ var requested_steering: float
15
+ var initial_transform: Transform3D
16
+ var ball_hit: bool
17
+
18
+
19
+ func _ready():
20
+ initial_transform = transform
21
+ ai_controller.init(self)
22
+ reset_goals()
23
+ reset_ball(true)
24
+
25
+
26
+ func get_ball() -> Ball:
27
+ return ball
28
+
29
+
30
+ func reset():
31
+ transform = initial_transform
32
+ ball_hit = false
33
+ linear_velocity = Vector3.ZERO
34
+ angular_velocity = Vector3.ZERO
35
+ reset_ball(true)
36
+
37
+
38
+ func reset_goals():
39
+ var starting_category: int = randi() % category_count
40
+ var i: int = 0
41
+ for goal in goals:
42
+ goal.set_category(i, category_count)
43
+ i += 1
44
+
45
+
46
+ func reset_ball(randomize_category: bool = false):
47
+ # Set a slightly randomized ball position
48
+ var ball_position := Vector3(randf_range(-0.2, 0.2), 0.3, randf_range(-1.8, -2.2))
49
+ # Randomize the ball category
50
+ if randomize_category:
51
+ ball.set_random_category(category_count)
52
+ ball.position = ball_position
53
+ ball.rotation = Vector3.ZERO
54
+ ball.linear_velocity = Vector3.ZERO
55
+ ball.angular_velocity = Vector3.ZERO
56
+
57
+ # Set the correct goal reference
58
+ for goal in goals:
59
+ if goal.get_category() == ball.category:
60
+ ball.correct_goal = goal
61
+
62
+
63
+ func _physics_process(_delta):
64
+ reset_if_needed()
65
+
66
+ if ai_controller.heuristic == "human":
67
+ requested_acceleration = (
68
+ Input.get_action_strength("move_forward") - Input.get_action_strength("move_back")
69
+ )
70
+ requested_steering = (
71
+ Input.get_action_strength("turn_left") - Input.get_action_strength("turn_right")
72
+ )
73
+
74
+ var force: Vector3 = requested_acceleration * acceleration * -global_transform.basis.z
75
+ var torque: Vector3 = requested_steering * torque_multiplier * Vector3.UP
76
+
77
+ if requested_acceleration < 0:
78
+ # Slows down movement in reverse
79
+ requested_acceleration /= 2.0
80
+
81
+ # Only applies movement if the ball hasn't been hit already
82
+ if not ball_hit:
83
+ apply_central_force(force)
84
+ apply_torque(torque)
85
+
86
+ handle_animation(linear_velocity)
87
+
88
+
89
+ func handle_animation(velocity: Vector3):
90
+ if velocity.length() > 0.05:
91
+ animation_player.play("walking", -1, 1.75)
92
+ else:
93
+ animation_player.play("idle")
94
+
95
+
96
+ func reset_if_needed():
97
+ if ai_controller.needs_reset:
98
+ reset()
99
+ ai_controller.reset()
100
+
101
+
102
+ func _on_ball_entered_goal(ball_goal_category_match: bool):
103
+ if ball_goal_category_match:
104
+ game_over(1)
105
+ else:
106
+ game_over(-1)
107
+
108
+
109
+ func _on_ball_body_entered(body):
110
+ if body is Robot:
111
+ ball_hit = true
112
+ ai_controller.reward += (ball.linear_velocity.normalized().dot(
113
+ ball.global_position.direction_to(ball.correct_goal.global_position)
114
+ ))
115
+ elif body is Wall or body is Goal:
116
+ game_over(-1)
117
+
118
+
119
+ func game_over(reward: float = 0):
120
+ ai_controller.reward += reward
121
+ ai_controller.needs_reset = true
122
+ ai_controller.done = true
123
+
124
+
125
+ func _on_body_entered(body: Node) -> void:
126
+ if body is Wall:
127
+ game_over(-1)
128
+
129
+
130
+ func _on_robot_entered_goal() -> void:
131
+ game_over(-1)
scenes/robot/robot.tscn ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=11 format=3 uid="uid://bpb5ld8ygwbin"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/robot/robot.gd" id="1_yxci0"]
4
+ [ext_resource type="Script" path="res://scenes/robot/robot_ai_controller.gd" id="2_j3f46"]
5
+ [ext_resource type="PackedScene" uid="uid://8en54a6bd0v3" path="res://assets/robot.glb" id="3_5ag0g"]
6
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3_64dgq"]
7
+
8
+ [sub_resource type="PhysicsMaterial" id="PhysicsMaterial_cp7ux"]
9
+
10
+ [sub_resource type="Animation" id="Animation_2kfmf"]
11
+ length = 0.001
12
+ tracks/0/type = "value"
13
+ tracks/0/imported = false
14
+ tracks/0/enabled = true
15
+ tracks/0/path = NodePath("Robot/Arm:rotation")
16
+ tracks/0/interp = 1
17
+ tracks/0/loop_wrap = true
18
+ tracks/0/keys = {
19
+ "times": PackedFloat32Array(0),
20
+ "transitions": PackedFloat32Array(1),
21
+ "update": 0,
22
+ "values": [Vector3(0, 0, 0)]
23
+ }
24
+ tracks/1/type = "value"
25
+ tracks/1/imported = false
26
+ tracks/1/enabled = true
27
+ tracks/1/path = NodePath("Robot/Arm_001:rotation")
28
+ tracks/1/interp = 1
29
+ tracks/1/loop_wrap = true
30
+ tracks/1/keys = {
31
+ "times": PackedFloat32Array(0),
32
+ "transitions": PackedFloat32Array(1),
33
+ "update": 0,
34
+ "values": [Vector3(0, 0, 0)]
35
+ }
36
+ tracks/2/type = "value"
37
+ tracks/2/imported = false
38
+ tracks/2/enabled = true
39
+ tracks/2/path = NodePath("Robot/Torso:position")
40
+ tracks/2/interp = 1
41
+ tracks/2/loop_wrap = true
42
+ tracks/2/keys = {
43
+ "times": PackedFloat32Array(0),
44
+ "transitions": PackedFloat32Array(1),
45
+ "update": 0,
46
+ "values": [Vector3(0, 0, 0)]
47
+ }
48
+ tracks/3/type = "value"
49
+ tracks/3/imported = false
50
+ tracks/3/enabled = true
51
+ tracks/3/path = NodePath("Robot/Head:position")
52
+ tracks/3/interp = 1
53
+ tracks/3/loop_wrap = true
54
+ tracks/3/keys = {
55
+ "times": PackedFloat32Array(0),
56
+ "transitions": PackedFloat32Array(1),
57
+ "update": 0,
58
+ "values": [Vector3(0, 0, 0)]
59
+ }
60
+ tracks/4/type = "value"
61
+ tracks/4/imported = false
62
+ tracks/4/enabled = true
63
+ tracks/4/path = NodePath("Robot/Head:rotation")
64
+ tracks/4/interp = 1
65
+ tracks/4/loop_wrap = true
66
+ tracks/4/keys = {
67
+ "times": PackedFloat32Array(0),
68
+ "transitions": PackedFloat32Array(1),
69
+ "update": 0,
70
+ "values": [Vector3(0, 0, 0)]
71
+ }
72
+
73
+ [sub_resource type="Animation" id="Animation_ly00x"]
74
+ resource_name = "idle"
75
+ length = 4.0
76
+ loop_mode = 1
77
+ tracks/0/type = "value"
78
+ tracks/0/imported = false
79
+ tracks/0/enabled = true
80
+ tracks/0/path = NodePath("Robot/Arm:rotation")
81
+ tracks/0/interp = 2
82
+ tracks/0/loop_wrap = true
83
+ tracks/0/keys = {
84
+ "times": PackedFloat32Array(0, 2),
85
+ "transitions": PackedFloat32Array(1, 1),
86
+ "update": 0,
87
+ "values": [Vector3(0, 0, 0), Vector3(0.349066, 0, 0.0610865)]
88
+ }
89
+ tracks/1/type = "value"
90
+ tracks/1/imported = false
91
+ tracks/1/enabled = true
92
+ tracks/1/path = NodePath("Robot/Arm_001:rotation")
93
+ tracks/1/interp = 2
94
+ tracks/1/loop_wrap = true
95
+ tracks/1/keys = {
96
+ "times": PackedFloat32Array(0, 2),
97
+ "transitions": PackedFloat32Array(1, 1),
98
+ "update": 0,
99
+ "values": [Vector3(0, 0, 0), Vector3(-0.349066, 0, -0.148353)]
100
+ }
101
+ tracks/2/type = "value"
102
+ tracks/2/imported = false
103
+ tracks/2/enabled = true
104
+ tracks/2/path = NodePath("Robot/Head:rotation")
105
+ tracks/2/interp = 2
106
+ tracks/2/loop_wrap = true
107
+ tracks/2/keys = {
108
+ "times": PackedFloat32Array(0, 1, 2, 3),
109
+ "transitions": PackedFloat32Array(1, 1, 1, 1),
110
+ "update": 0,
111
+ "values": [Vector3(0, 0, 0), Vector3(0, 0.162316, 0.0488692), Vector3(0, 0, 0), Vector3(0.139626, -0.178024, 0.0226893)]
112
+ }
113
+
114
+ [sub_resource type="Animation" id="Animation_6jb0l"]
115
+ resource_name = "idle"
116
+ loop_mode = 1
117
+ tracks/0/type = "value"
118
+ tracks/0/imported = false
119
+ tracks/0/enabled = true
120
+ tracks/0/path = NodePath("Robot/Arm:rotation")
121
+ tracks/0/interp = 2
122
+ tracks/0/loop_wrap = true
123
+ tracks/0/keys = {
124
+ "times": PackedFloat32Array(0, 0.5),
125
+ "transitions": PackedFloat32Array(1, 1),
126
+ "update": 0,
127
+ "values": [Vector3(0, 0, 0), Vector3(0, -0.174533, 0)]
128
+ }
129
+ tracks/1/type = "value"
130
+ tracks/1/imported = false
131
+ tracks/1/enabled = true
132
+ tracks/1/path = NodePath("Robot/Arm_001:rotation")
133
+ tracks/1/interp = 2
134
+ tracks/1/loop_wrap = true
135
+ tracks/1/keys = {
136
+ "times": PackedFloat32Array(0, 0.5),
137
+ "transitions": PackedFloat32Array(1, 1),
138
+ "update": 0,
139
+ "values": [Vector3(0, 0, 0), Vector3(0, 0.174533, 0)]
140
+ }
141
+ tracks/2/type = "value"
142
+ tracks/2/imported = false
143
+ tracks/2/enabled = true
144
+ tracks/2/path = NodePath("Robot/Torso:position")
145
+ tracks/2/interp = 2
146
+ tracks/2/loop_wrap = true
147
+ tracks/2/keys = {
148
+ "times": PackedFloat32Array(0, 0.25, 0.5),
149
+ "transitions": PackedFloat32Array(1, 1, 1),
150
+ "update": 0,
151
+ "values": [Vector3(0, 0, 0), Vector3(0, -0.01, 0), Vector3(0, 0, 0)]
152
+ }
153
+ tracks/3/type = "value"
154
+ tracks/3/imported = false
155
+ tracks/3/enabled = true
156
+ tracks/3/path = NodePath("Robot/Head:position")
157
+ tracks/3/interp = 1
158
+ tracks/3/loop_wrap = true
159
+ tracks/3/keys = {
160
+ "times": PackedFloat32Array(0, 0.5),
161
+ "transitions": PackedFloat32Array(1, 1),
162
+ "update": 0,
163
+ "values": [Vector3(0, 0, 0), Vector3(0, -0.02, 0)]
164
+ }
165
+ tracks/4/type = "value"
166
+ tracks/4/imported = false
167
+ tracks/4/enabled = true
168
+ tracks/4/path = NodePath("Robot/Head:rotation")
169
+ tracks/4/interp = 1
170
+ tracks/4/loop_wrap = true
171
+ tracks/4/keys = {
172
+ "times": PackedFloat32Array(0, 0.25, 0.5),
173
+ "transitions": PackedFloat32Array(1, 1, 1),
174
+ "update": 0,
175
+ "values": [Vector3(0, 0, 0), Vector3(-0.0349066, 0, 0), Vector3(0, 0, 0)]
176
+ }
177
+
178
+ [sub_resource type="AnimationLibrary" id="AnimationLibrary_g7kmm"]
179
+ _data = {
180
+ "RESET": SubResource("Animation_2kfmf"),
181
+ "idle": SubResource("Animation_ly00x"),
182
+ "walking": SubResource("Animation_6jb0l")
183
+ }
184
+
185
+ [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_y5hda"]
186
+ height = 1.29947
187
+
188
+ [node name="Robot" type="RigidBody3D"]
189
+ collision_mask = 7
190
+ axis_lock_angular_x = true
191
+ axis_lock_angular_z = true
192
+ mass = 10.0
193
+ physics_material_override = SubResource("PhysicsMaterial_cp7ux")
194
+ continuous_cd = true
195
+ linear_damp = 10.0
196
+ angular_damp = 10.0
197
+ script = ExtResource("1_yxci0")
198
+
199
+ [node name="AIController3D" type="Node3D" parent="." groups=["AGENT"]]
200
+ script = ExtResource("2_j3f46")
201
+ playing_area_x_size = 20.0
202
+ playing_area_z_size = 20.0
203
+ reset_after = 350
204
+
205
+ [node name="WallRaycastSensor" type="Node3D" parent="AIController3D"]
206
+ transform = Transform3D(0.707107, 0, 0.707107, 0, 1, 0, -0.707107, 0, 0.707107, 0, 0.250552, 0)
207
+ script = ExtResource("3_64dgq")
208
+ collision_mask = 8
209
+ n_rays_width = 4.0
210
+ n_rays_height = 1.0
211
+ cone_width = 360.0
212
+ cone_height = 0.0
213
+
214
+ [node name="@RayCast3D@90672" type="RayCast3D" parent="AIController3D/WallRaycastSensor"]
215
+ target_position = Vector3(-7.07107, 0, -7.07107)
216
+ collision_mask = 8
217
+
218
+ [node name="@RayCast3D@90673" type="RayCast3D" parent="AIController3D/WallRaycastSensor"]
219
+ target_position = Vector3(-7.07107, 0, 7.07107)
220
+ collision_mask = 8
221
+
222
+ [node name="@RayCast3D@90674" type="RayCast3D" parent="AIController3D/WallRaycastSensor"]
223
+ target_position = Vector3(7.07107, 0, 7.07107)
224
+ collision_mask = 8
225
+
226
+ [node name="@RayCast3D@90675" type="RayCast3D" parent="AIController3D/WallRaycastSensor"]
227
+ target_position = Vector3(7.07107, 0, -7.07107)
228
+ collision_mask = 8
229
+
230
+ [node name="robot" parent="." instance=ExtResource("3_5ag0g")]
231
+ transform = Transform3D(-8.74228e-08, 0, 2, 0, 2, 0, -2, 0, -8.74228e-08, 0, 0, 0)
232
+
233
+ [node name="AnimationPlayer" type="AnimationPlayer" parent="robot"]
234
+ libraries = {
235
+ "": SubResource("AnimationLibrary_g7kmm")
236
+ }
237
+ autoplay = "idle"
238
+
239
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="."]
240
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.4, 0)
241
+ shape = SubResource("CapsuleShape3D_y5hda")
scenes/robot/robot_ai_controller.gd ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends AIController3D
2
+ class_name RobotAIController
3
+
4
+ @export var playing_area_x_size: float = 1
5
+ @export var playing_area_z_size: float = 1
6
+
7
+ @onready var _playing_area_half_x_size: float = playing_area_x_size / 2
8
+ @onready var _playing_area_half_z_size: float = playing_area_z_size / 2
9
+
10
+ var ball: Ball
11
+ var wall_raycast_sensor: RayCastSensor3D
12
+
13
+
14
+ ## In the observations for this example, we include:
15
+ ## Position of the ball relative to the player,
16
+ ## position of the each goal relative to the player,
17
+ ## for each goal, whether the goal is the "correct goal" as 0 or 1,
18
+ ## whether the ball was already hit in episode (movement is disabled after hitting the ball),
19
+ ## observations from the wall raycast sensor (it's not allowed to hit a wall)
20
+ func get_obs() -> Dictionary:
21
+ _player = _player as Robot
22
+
23
+ if not ball:
24
+ ball = _player.get_ball()
25
+
26
+ if not wall_raycast_sensor:
27
+ wall_raycast_sensor = $WallRaycastSensor
28
+
29
+ var observations: Array[float] = []
30
+
31
+ var ball_position = _player.to_local(ball.global_position)
32
+ ball_position.x /= playing_area_x_size
33
+ ball_position.z /= playing_area_z_size
34
+
35
+ observations.append_array([ball_position.x, ball_position.z])
36
+
37
+ for goal in _player.goals:
38
+ var goal_in_player_reference: Vector3 = _player.to_local(goal.global_position)
39
+ goal_in_player_reference.x /= playing_area_x_size
40
+ goal_in_player_reference.z /= playing_area_z_size
41
+
42
+ var target_goal := false
43
+ if goal == ball.correct_goal:
44
+ target_goal = true
45
+
46
+ observations.append_array(
47
+ [goal_in_player_reference.x, goal_in_player_reference.z, float(target_goal)]
48
+ )
49
+
50
+ observations.append(float(_player.ball_hit))
51
+
52
+ observations.append_array(wall_raycast_sensor.get_observation())
53
+
54
+ return {"obs": observations}
55
+
56
+
57
+ func get_one_hot_encoded_category(category: int, number_of_categories: int):
58
+ var result: Array[int]
59
+ result.resize(number_of_categories)
60
+ result.fill(0)
61
+ result[category] = 1
62
+ return result
63
+
64
+
65
+ func _physics_process(delta):
66
+ n_steps += 1
67
+ if n_steps > reset_after:
68
+ reward -= 1
69
+ needs_reset = true
70
+ done = true
71
+
72
+
73
+ func get_reward() -> float:
74
+ return reward
75
+
76
+
77
+ func get_action_space() -> Dictionary:
78
+ return {
79
+ "accelerate": {"size": 1, "action_type": "continuous"},
80
+ "steer": {"size": 1, "action_type": "continuous"},
81
+ }
82
+
83
+
84
+ func set_action(action) -> void:
85
+ _player.requested_acceleration = action.accelerate[0]
86
+ _player.requested_steering = action.steer[0]
scenes/training_scene/training_scene.tscn ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=6 format=3 uid="uid://c0uxnb5f6avih"]
2
+
3
+ [ext_resource type="PackedScene" uid="uid://7rc10s44c2v" path="res://scenes/playing_area/playing_area.tscn" id="2_6guts"]
4
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_8lo5l"]
5
+
6
+ [sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_dfpdn"]
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_i3bom"]
11
+ sky_material = SubResource("ProceduralSkyMaterial_dfpdn")
12
+
13
+ [sub_resource type="Environment" id="Environment_mmgmg"]
14
+ background_mode = 2
15
+ sky = SubResource("Sky_i3bom")
16
+ tonemap_mode = 2
17
+ ssao_detail = 0.65
18
+ glow_enabled = true
19
+
20
+ [node name="training_scene" type="Node3D"]
21
+
22
+ [node name="WorldEnvironment" type="WorldEnvironment" parent="."]
23
+ environment = SubResource("Environment_mmgmg")
24
+
25
+ [node name="DirectionalLight3D" type="DirectionalLight3D" parent="."]
26
+ transform = Transform3D(-0.866023, -0.433016, 0.250001, 0, 0.499998, 0.866027, -0.500003, 0.749999, -0.43301, 0, 0, 0)
27
+ shadow_enabled = true
28
+
29
+ [node name="playing_area" parent="." instance=ExtResource("2_6guts")]
30
+
31
+ [node name="playing_area2" parent="." instance=ExtResource("2_6guts")]
32
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 24, 0, 0)
33
+
34
+ [node name="playing_area3" parent="." instance=ExtResource("2_6guts")]
35
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -24)
36
+
37
+ [node name="playing_area4" parent="." instance=ExtResource("2_6guts")]
38
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 24, 0, -24)
39
+
40
+ [node name="playing_area5" parent="." instance=ExtResource("2_6guts")]
41
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -48, 0, 0)
42
+
43
+ [node name="playing_area6" parent="." instance=ExtResource("2_6guts")]
44
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -24, 0, 0)
45
+
46
+ [node name="playing_area7" parent="." instance=ExtResource("2_6guts")]
47
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -48, 0, -24)
48
+
49
+ [node name="playing_area8" parent="." instance=ExtResource("2_6guts")]
50
+ transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -24, 0, -24)
51
+
52
+ [node name="Camera3D" type="Camera3D" parent="."]
53
+ transform = Transform3D(-1, 4.9391e-08, -7.21337e-08, 0, 0.825114, 0.564967, 8.74228e-08, 0.564967, -0.825113, 0, 9.668, -39.385)
54
+ fov = 64.7
55
+
56
+ [node name="Sync" type="Node" parent="."]
57
+ script = ExtResource("2_8lo5l")
58
+ onnx_model_path = "model.onnx"