jtatman commited on
Commit
4a9e99c
1 Parent(s): 8ca1961

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. README.md +25 -0
  3. RacingExample.csproj +10 -0
  4. RacingExample.sln +19 -0
  5. addons/godot_rl_agents/controller/ai_controller_2d.gd +82 -0
  6. addons/godot_rl_agents/controller/ai_controller_3d.gd +80 -0
  7. addons/godot_rl_agents/godot_rl_agents.gd +16 -0
  8. addons/godot_rl_agents/icon.png +3 -0
  9. addons/godot_rl_agents/onnx/csharp/ONNXInference.cs +103 -0
  10. addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs +131 -0
  11. addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml +31 -0
  12. addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml +29 -0
  13. addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd +24 -0
  14. addons/godot_rl_agents/plugin.cfg +7 -0
  15. addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn +48 -0
  16. addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd +216 -0
  17. addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd +20 -0
  18. addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd +118 -0
  19. addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn +7 -0
  20. addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn +6 -0
  21. addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd +233 -0
  22. addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd +20 -0
  23. addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd +14 -0
  24. addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn +41 -0
  25. addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd +166 -0
  26. addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn +27 -0
  27. addons/godot_rl_agents/sync.gd +342 -0
  28. asset-license.md +5 -0
  29. icon.svg +1 -0
  30. model.onnx +3 -0
  31. project.godot +51 -0
  32. readme.md +57 -0
  33. scenes/blender/car_base.blend +3 -0
  34. scenes/blender/house.blend +3 -0
  35. scenes/blender/house2.blend +0 -0
  36. scenes/blender/reverse-turbo-powerup.blend +0 -0
  37. scenes/blender/rock.blend +0 -0
  38. scenes/blender/rock2.blend +0 -0
  39. scenes/blender/tree.blend +0 -0
  40. scenes/blender/tree2.blend +0 -0
  41. scenes/blender/tree3.blend +0 -0
  42. scenes/blender/tree4.blend +0 -0
  43. scenes/blender/tree5.blend +0 -0
  44. scenes/blender/trees.blend +3 -0
  45. scenes/blender/turbo-powerup.blend +0 -0
  46. scenes/blender/windmill.blend +3 -0
  47. scenes/car/car.gd +214 -0
  48. scenes/car/car.tscn +281 -0
  49. scenes/car/car_ai_controller.gd +57 -0
  50. scenes/car/car_manager.gd +89 -0
.gitattributes CHANGED
@@ -56,3 +56,7 @@ saved_model/**/* 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
 
 
 
 
 
56
  # Video files - compressed
57
  *.mp4 filter=lfs diff=lfs merge=lfs -text
58
  *.webm filter=lfs diff=lfs merge=lfs -text
59
+ scenes/blender/car_base.blend filter=lfs diff=lfs merge=lfs -text
60
+ scenes/blender/house.blend filter=lfs diff=lfs merge=lfs -text
61
+ scenes/blender/trees.blend filter=lfs diff=lfs merge=lfs -text
62
+ scenes/blender/windmill.blend filter=lfs diff=lfs merge=lfs -text
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 HovercraftRacing 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_HovercraftRacing
22
+ ```
23
+
24
+
25
+
RacingExample.csproj ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ <Project Sdk="Godot.NET.Sdk/4.2.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>
RacingExample.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}") = "RacingExample", "RacingExample.csproj", "{E2999C40-6DD8-43BC-9D9A-473B12290385}"
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
+ {E2999C40-6DD8-43BC-9D9A-473B12290385}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
13
+ {E2999C40-6DD8-43BC-9D9A-473B12290385}.Debug|Any CPU.Build.0 = Debug|Any CPU
14
+ {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU
15
+ {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU
16
+ {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU
17
+ {E2999C40-6DD8-43BC-9D9A-473B12290385}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU
18
+ EndGlobalSection
19
+ EndGlobal
addons/godot_rl_agents/controller/ai_controller_2d.gd ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+ class_name AIController2D
3
+
4
+ @export var reset_after := 1000
5
+
6
+ var heuristic := "human"
7
+ var done := false
8
+ var reward := 0.0
9
+ var n_steps := 0
10
+ var needs_reset := false
11
+
12
+ var _player: Node2D
13
+
14
+ func _ready():
15
+ add_to_group("AGENT")
16
+
17
+ func init(player: Node2D):
18
+ _player = player
19
+
20
+ #-- Methods that need implementing using the "extend script" option in Godot --#
21
+ func get_obs() -> Dictionary:
22
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
23
+ return {"obs":[]}
24
+
25
+ func get_reward() -> float:
26
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
27
+ return 0.0
28
+
29
+ func get_action_space() -> Dictionary:
30
+ assert(false, "the get get_action_space method is not implemented when extending from ai_controller")
31
+ return {
32
+ "example_actions_continous" : {
33
+ "size": 2,
34
+ "action_type": "continuous"
35
+ },
36
+ "example_actions_discrete" : {
37
+ "size": 2,
38
+ "action_type": "discrete"
39
+ },
40
+ }
41
+
42
+ func set_action(action) -> void:
43
+ assert(false, "the get set_action method is not implemented when extending from ai_controller")
44
+ # -----------------------------------------------------------------------------#
45
+
46
+ func _physics_process(delta):
47
+ n_steps += 1
48
+ if n_steps > reset_after:
49
+ needs_reset = true
50
+
51
+ func get_obs_space():
52
+ # may need overriding if the obs space is complex
53
+ var obs = get_obs()
54
+ return {
55
+ "obs": {
56
+ "size": [len(obs["obs"])],
57
+ "space": "box"
58
+ },
59
+ }
60
+
61
+ func reset():
62
+ n_steps = 0
63
+ needs_reset = false
64
+
65
+ func reset_if_done():
66
+ if done:
67
+ reset()
68
+
69
+ func set_heuristic(h):
70
+ # sets the heuristic from "human" or "model" nothing to change here
71
+ heuristic = h
72
+
73
+ func get_done():
74
+ return done
75
+
76
+ func set_done_false():
77
+ done = false
78
+
79
+ func zero_reward():
80
+ reward = 0.0
81
+
82
+
addons/godot_rl_agents/controller/ai_controller_3d.gd ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name AIController3D
3
+
4
+ @export var reset_after := 1000
5
+
6
+ var heuristic := "human"
7
+ var done := false
8
+ var reward := 0.0
9
+ var n_steps := 0
10
+ var needs_reset := false
11
+
12
+ var _player: Node3D
13
+
14
+ func _ready():
15
+ add_to_group("AGENT")
16
+
17
+ func init(player: Node3D):
18
+ _player = player
19
+
20
+ #-- Methods that need implementing using the "extend script" option in Godot --#
21
+ func get_obs() -> Dictionary:
22
+ assert(false, "the get_obs method is not implemented when extending from ai_controller")
23
+ return {"obs":[]}
24
+
25
+ func get_reward() -> float:
26
+ assert(false, "the get_reward method is not implemented when extending from ai_controller")
27
+ return 0.0
28
+
29
+ func get_action_space() -> Dictionary:
30
+ assert(false, "the get get_action_space method is not implemented when extending from ai_controller")
31
+ return {
32
+ "example_actions_continous" : {
33
+ "size": 2,
34
+ "action_type": "continuous"
35
+ },
36
+ "example_actions_discrete" : {
37
+ "size": 2,
38
+ "action_type": "discrete"
39
+ },
40
+ }
41
+
42
+ func set_action(action) -> void:
43
+ assert(false, "the get set_action method is not implemented when extending from ai_controller")
44
+ # -----------------------------------------------------------------------------#
45
+
46
+ func _physics_process(delta):
47
+ n_steps += 1
48
+ if n_steps > reset_after:
49
+ needs_reset = true
50
+
51
+ func get_obs_space():
52
+ # may need overriding if the obs space is complex
53
+ var obs = get_obs()
54
+ return {
55
+ "obs": {
56
+ "size": [len(obs["obs"])],
57
+ "space": "box"
58
+ },
59
+ }
60
+
61
+ func reset():
62
+ n_steps = 0
63
+ needs_reset = false
64
+
65
+ func reset_if_done():
66
+ if done:
67
+ reset()
68
+
69
+ func set_heuristic(h):
70
+ # sets the heuristic from "human" or "model" nothing to change here
71
+ heuristic = h
72
+
73
+ func get_done():
74
+ return done
75
+
76
+ func set_done_false():
77
+ done = false
78
+
79
+ func zero_reward():
80
+ reward = 0.0
addons/godot_rl_agents/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,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using Microsoft.ML.OnnxRuntime;
3
+ using Microsoft.ML.OnnxRuntime.Tensors;
4
+ using System.Collections.Generic;
5
+ using System.Linq;
6
+
7
+ namespace GodotONNX
8
+ {
9
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/ONNXInference/*'/>
10
+ public partial class ONNXInference : GodotObject
11
+ {
12
+
13
+ private InferenceSession session;
14
+ /// <summary>
15
+ /// Path to the ONNX model. Use Initialize to change it.
16
+ /// </summary>
17
+ private string modelPath;
18
+ private int batchSize;
19
+
20
+ private SessionOptions SessionOpt;
21
+
22
+ //init function
23
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Initialize/*'/>
24
+ public void Initialize(string Path, int BatchSize)
25
+ {
26
+ modelPath = Path;
27
+ batchSize = BatchSize;
28
+ SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions();
29
+ session = LoadModel(modelPath);
30
+
31
+ }
32
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Run/*'/>
33
+ public Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> RunInference(Godot.Collections.Array<float> obs, int state_ins)
34
+ {
35
+ //Current model: Any (Godot Rl Agents)
36
+ //Expects a tensor of shape [batch_size, input_size] type float named obs and a tensor of shape [batch_size] type float named state_ins
37
+
38
+ //Fill the input tensors
39
+ // create span from inputSize
40
+ var span = new float[obs.Count]; //There's probably a better way to do this
41
+ for (int i = 0; i < obs.Count; i++)
42
+ {
43
+ span[i] = obs[i];
44
+ }
45
+
46
+ IReadOnlyCollection<NamedOnnxValue> inputs = new List<NamedOnnxValue>
47
+ {
48
+ NamedOnnxValue.CreateFromTensor("obs", new DenseTensor<float>(span, new int[] { batchSize, obs.Count })),
49
+ NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor<float>(new float[] { state_ins }, new int[] { batchSize }))
50
+ };
51
+ IReadOnlyCollection<string> outputNames = new List<string> { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names
52
+
53
+ IDisposableReadOnlyCollection<DisposableNamedOnnxValue> results;
54
+ //We do not use "using" here so we get a better exception explaination later
55
+ try
56
+ {
57
+ results = session.Run(inputs, outputNames);
58
+ }
59
+ catch (OnnxRuntimeException e)
60
+ {
61
+ //This error usually means that the model is not compatible with the input, beacause of the input shape (size)
62
+ GD.Print("Error at inference: ", e);
63
+ return null;
64
+ }
65
+ //Can't convert IEnumerable<float> to Variant, so we have to convert it to an array or something
66
+ Godot.Collections.Dictionary<string, Godot.Collections.Array<float>> output = new Godot.Collections.Dictionary<string, Godot.Collections.Array<float>>();
67
+ DisposableNamedOnnxValue output1 = results.First();
68
+ DisposableNamedOnnxValue output2 = results.Last();
69
+ Godot.Collections.Array<float> output1Array = new Godot.Collections.Array<float>();
70
+ Godot.Collections.Array<float> output2Array = new Godot.Collections.Array<float>();
71
+
72
+ foreach (float f in output1.AsEnumerable<float>())
73
+ {
74
+ output1Array.Add(f);
75
+ }
76
+
77
+ foreach (float f in output2.AsEnumerable<float>())
78
+ {
79
+ output2Array.Add(f);
80
+ }
81
+
82
+ output.Add(output1.Name, output1Array);
83
+ output.Add(output2.Name, output2Array);
84
+
85
+ //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]}
86
+ results.Dispose();
87
+ return output;
88
+ }
89
+ /// <include file='docs/ONNXInference.xml' path='docs/members[@name="ONNXInference"]/Load/*'/>
90
+ public InferenceSession LoadModel(string Path)
91
+ {
92
+ using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read);
93
+ byte[] model = file.GetBuffer((int)file.GetLength());
94
+ //file.Close(); file.Dispose(); //Close the file, then dispose the reference.
95
+ return new InferenceSession(model, SessionOpt); //Load the model
96
+ }
97
+ public void FreeDisposables()
98
+ {
99
+ session.Dispose();
100
+ SessionOpt.Dispose();
101
+ }
102
+ }
103
+ }
addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ using Godot;
2
+ using Microsoft.ML.OnnxRuntime;
3
+
4
+ namespace GodotONNX
5
+ {
6
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SessionConfigurator/*'/>
7
+
8
+ public static class SessionConfigurator
9
+ {
10
+ public enum ComputeName
11
+ {
12
+ CUDA,
13
+ ROCm,
14
+ DirectML,
15
+ CoreML,
16
+ CPU
17
+ }
18
+
19
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/GetSessionOptions/*'/>
20
+ public static SessionOptions MakeConfiguredSessionOptions()
21
+ {
22
+ SessionOptions sessionOptions = new();
23
+ SetOptions(sessionOptions);
24
+ return sessionOptions;
25
+ }
26
+
27
+ private static void SetOptions(SessionOptions sessionOptions)
28
+ {
29
+ sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING;
30
+ ApplySystemSpecificOptions(sessionOptions);
31
+ }
32
+
33
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/SystemCheck/*'/>
34
+ static public void ApplySystemSpecificOptions(SessionOptions sessionOptions)
35
+ {
36
+ //Most code for this function is verbose only, the only reason it exists is to track
37
+ //implementation progress of the different compute APIs.
38
+
39
+ //December 2022: CUDA is not working.
40
+
41
+ string OSName = OS.GetName(); //Get OS Name
42
+
43
+ //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API
44
+ // //TODO: Get CPU architecture
45
+
46
+ //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++)
47
+ //Windows can use OpenVINO (C#) on x64
48
+ //TODO: try TensorRT instead of CUDA
49
+ //TODO: Use OpenVINO for Intel Graphics
50
+
51
+ // Temporarily using CPU on all platforms to avoid errors detected with DML
52
+ ComputeName ComputeAPI = ComputeName.CPU;
53
+
54
+ //match OS and Compute API
55
+ GD.Print($"OS: {OSName} Compute API: {ComputeAPI}");
56
+
57
+ // CPU is set by default without appending necessary
58
+ // sessionOptions.AppendExecutionProvider_CPU(0);
59
+
60
+ /*
61
+ switch (OSName)
62
+ {
63
+ case "Windows": //Can use CUDA, DirectML
64
+ if (ComputeAPI is ComputeName.CUDA)
65
+ {
66
+ //CUDA
67
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
68
+ //sessionOptions.AppendExecutionProvider_DML(0);
69
+ }
70
+ else if (ComputeAPI is ComputeName.DirectML)
71
+ {
72
+ //DirectML
73
+ //sessionOptions.AppendExecutionProvider_DML(0);
74
+ }
75
+ break;
76
+ case "X11": //Can use CUDA, ROCm
77
+ if (ComputeAPI is ComputeName.CUDA)
78
+ {
79
+ //CUDA
80
+ //sessionOptions.AppendExecutionProvider_CUDA(0);
81
+ }
82
+ if (ComputeAPI is ComputeName.ROCm)
83
+ {
84
+ //ROCm, only works on x86
85
+ //Research indicates that this has to be compiled as a GDNative plugin
86
+ //GD.Print("ROCm not supported yet, using CPU.");
87
+ //sessionOptions.AppendExecutionProvider_CPU(0);
88
+ }
89
+ break;
90
+ case "macOS": //Can use CoreML
91
+ if (ComputeAPI is ComputeName.CoreML)
92
+ { //CoreML
93
+ //TODO: Needs testing
94
+ //sessionOptions.AppendExecutionProvider_CoreML(0);
95
+ //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub
96
+ }
97
+ break;
98
+ default:
99
+ GD.Print("OS not Supported.");
100
+ break;
101
+ }
102
+ */
103
+ }
104
+
105
+
106
+ /// <include file='docs/SessionConfigurator.xml' path='docs/members[@name="SessionConfigurator"]/ComputeCheck/*'/>
107
+ public static ComputeName ComputeCheck()
108
+ {
109
+ string adapterName = Godot.RenderingServer.GetVideoAdapterName();
110
+ //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor();
111
+ adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo(""));
112
+ //TODO: GPU vendors for MacOS, what do they even use these days?
113
+
114
+ if (adapterName.Contains("INTEL"))
115
+ {
116
+ return ComputeName.DirectML;
117
+ }
118
+ if (adapterName.Contains("AMD") || adapterName.Contains("RADEON"))
119
+ {
120
+ return ComputeName.DirectML;
121
+ }
122
+ if (adapterName.Contains("NVIDIA"))
123
+ {
124
+ return ComputeName.CUDA;
125
+ }
126
+
127
+ GD.Print("Graphics Card not recognized."); //Should use CPU
128
+ return ComputeName.CPU;
129
+ }
130
+ }
131
+ }
addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <docs>
2
+ <members name="ONNXInference">
3
+ <ONNXInference>
4
+ <summary>
5
+ The main <c>ONNXInference</c> Class that handles the inference process.
6
+ </summary>
7
+ </ONNXInference>
8
+ <Initialize>
9
+ <summary>
10
+ Starts the inference process.
11
+ </summary>
12
+ <param name="Path">Path to the ONNX model, expects a path inside resources.</param>
13
+ <param name="BatchSize">How many observations will the model recieve.</param>
14
+ </Initialize>
15
+ <Run>
16
+ <summary>
17
+ Runs the given input through the model and returns the output.
18
+ </summary>
19
+ <param name="obs">Dictionary containing all observations.</param>
20
+ <param name="state_ins">How many different agents are creating these observations.</param>
21
+ <returns>A Dictionary of arrays, containing instructions based on the observations.</returns>
22
+ </Run>
23
+ <Load>
24
+ <summary>
25
+ Loads the given model into the inference process, using the best Execution provider available.
26
+ </summary>
27
+ <param name="Path">Path to the ONNX model, expects a path inside resources.</param>
28
+ <returns>InferenceSession ready to run.</returns>
29
+ </Load>
30
+ </members>
31
+ </docs>
addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <docs>
2
+ <members name="SessionConfigurator">
3
+ <SessionConfigurator>
4
+ <summary>
5
+ The main <c>SessionConfigurator</c> Class that handles the execution options and providers for the inference process.
6
+ </summary>
7
+ </SessionConfigurator>
8
+ <GetSessionOptions>
9
+ <summary>
10
+ Creates a SessionOptions with all available execution providers.
11
+ </summary>
12
+ <returns>SessionOptions with all available execution providers.</returns>
13
+ </GetSessionOptions>
14
+ <SystemCheck>
15
+ <summary>
16
+ Appends any execution provider available in the current system.
17
+ </summary>
18
+ <remarks>
19
+ This function is mainly verbose for tracking implementation progress of different compute APIs.
20
+ </remarks>
21
+ </SystemCheck>
22
+ <ComputeCheck>
23
+ <summary>
24
+ Checks for available GPUs.
25
+ </summary>
26
+ <returns>An integer identifier for each compute platform.</returns>
27
+ </ComputeCheck>
28
+ </members>
29
+ </docs>
addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Must provide the path to the model and the batch size
8
+ func _init(model_path, batch_size):
9
+ inferencer = inferencer_script.new()
10
+ inferencer.Initialize(model_path, batch_size)
11
+
12
+ # This function is the one that will be called from the game,
13
+ # requires the observation as an array and the state_ins as an int
14
+ # returns an Array containing the action the model takes.
15
+ func run_inference(obs : Array, state_ins : int) -> Dictionary:
16
+ if inferencer == null:
17
+ printerr("Inferencer not initialized")
18
+ return {}
19
+ return inferencer.RunInference(obs, state_ins)
20
+
21
+ func _notification(what):
22
+ if what == NOTIFICATION_PREDELETE:
23
+ inferencer.FreeDisposables()
24
+ inferencer.free()
addons/godot_rl_agents/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,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor2D
3
+ class_name GridSensor2D
4
+
5
+ @export var debug_view := false:
6
+ get: return debug_view
7
+ set(value):
8
+ debug_view = value
9
+ _update()
10
+
11
+ @export_flags_2d_physics var detection_mask := 0:
12
+ get: return detection_mask
13
+ set(value):
14
+ detection_mask = value
15
+ _update()
16
+
17
+ @export var collide_with_areas := false:
18
+ get: return collide_with_areas
19
+ set(value):
20
+ collide_with_areas = value
21
+ _update()
22
+
23
+ @export var collide_with_bodies := true:
24
+ get: return collide_with_bodies
25
+ set(value):
26
+ collide_with_bodies = value
27
+ _update()
28
+
29
+ @export_range(1, 200, 0.1) var cell_width := 20.0:
30
+ get: return cell_width
31
+ set(value):
32
+ cell_width = value
33
+ _update()
34
+
35
+ @export_range(1, 200, 0.1) var cell_height := 20.0:
36
+ get: return cell_height
37
+ set(value):
38
+ cell_height = value
39
+ _update()
40
+
41
+ @export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
42
+ get: return grid_size_x
43
+ set(value):
44
+ grid_size_x = value
45
+ _update()
46
+
47
+ @export_range(1, 21, 2, "or_greater") var grid_size_y := 3:
48
+ get: return grid_size_y
49
+ set(value):
50
+ grid_size_y = value
51
+ _update()
52
+
53
+ var _obs_buffer: PackedFloat64Array
54
+ var _rectangle_shape: RectangleShape2D
55
+ var _collision_mapping: Dictionary
56
+ var _n_layers_per_cell: int
57
+
58
+ var _highlighted_cell_color: Color
59
+ var _standard_cell_color: Color
60
+
61
+ func get_observation():
62
+ return _obs_buffer
63
+
64
+ func _update():
65
+ if Engine.is_editor_hint():
66
+ if is_node_ready():
67
+ _spawn_nodes()
68
+
69
+ func _ready() -> void:
70
+ _set_colors()
71
+
72
+ if Engine.is_editor_hint():
73
+ if get_child_count() == 0:
74
+ _spawn_nodes()
75
+ else:
76
+ _spawn_nodes()
77
+
78
+
79
+ func _set_colors() -> void:
80
+ _standard_cell_color = Color(100.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0)
81
+ _highlighted_cell_color = Color(255.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0)
82
+
83
+ func _get_collision_mapping() -> Dictionary:
84
+ # defines which layer is mapped to which cell obs index
85
+ var total_bits = 0
86
+ var collision_mapping = {}
87
+ for i in 32:
88
+ var bit_mask = 2**i
89
+ if (detection_mask & bit_mask) > 0:
90
+ collision_mapping[i] = total_bits
91
+ total_bits += 1
92
+
93
+ return collision_mapping
94
+
95
+ func _spawn_nodes():
96
+ for cell in get_children():
97
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
98
+ cell.queue_free()
99
+
100
+ _collision_mapping = _get_collision_mapping()
101
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
102
+ # allocate memory for the observations
103
+ _n_layers_per_cell = len(_collision_mapping)
104
+ _obs_buffer = PackedFloat64Array()
105
+ _obs_buffer.resize(grid_size_x*grid_size_y*_n_layers_per_cell)
106
+ _obs_buffer.fill(0)
107
+ #prints(len(_obs_buffer), _obs_buffer )
108
+
109
+ _rectangle_shape = RectangleShape2D.new()
110
+ _rectangle_shape.set_size(Vector2(cell_width, cell_height))
111
+
112
+ var shift := Vector2(
113
+ -(grid_size_x/2)*cell_width,
114
+ -(grid_size_y/2)*cell_height,
115
+ )
116
+
117
+ for i in grid_size_x:
118
+ for j in grid_size_y:
119
+ var cell_position = Vector2(i*cell_width, j*cell_height) + shift
120
+ _create_cell(i, j, cell_position)
121
+
122
+
123
+ func _create_cell(i:int, j:int, position: Vector2):
124
+ var cell : = Area2D.new()
125
+ cell.position = position
126
+ cell.name = "GridCell %s %s" %[i, j]
127
+ cell.modulate = _standard_cell_color
128
+
129
+ if collide_with_areas:
130
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
131
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
132
+
133
+ if collide_with_bodies:
134
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
135
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
136
+
137
+ cell.collision_layer = 0
138
+ cell.collision_mask = detection_mask
139
+ cell.monitorable = true
140
+ add_child(cell)
141
+ cell.set_owner(get_tree().edited_scene_root)
142
+
143
+ var col_shape : = CollisionShape2D.new()
144
+ col_shape.shape = _rectangle_shape
145
+ col_shape.name = "CollisionShape2D"
146
+ cell.add_child(col_shape)
147
+ col_shape.set_owner(get_tree().edited_scene_root)
148
+
149
+ if debug_view:
150
+ var quad = MeshInstance2D.new()
151
+ quad.name = "MeshInstance2D"
152
+ var quad_mesh = QuadMesh.new()
153
+
154
+ quad_mesh.set_size(Vector2(cell_width, cell_height))
155
+
156
+ quad.mesh = quad_mesh
157
+ cell.add_child(quad)
158
+ quad.set_owner(get_tree().edited_scene_root)
159
+
160
+ func _update_obs(cell_i:int, cell_j:int, collision_layer:int, entered: bool):
161
+ for key in _collision_mapping:
162
+ var bit_mask = 2**key
163
+ if (collision_layer & bit_mask) > 0:
164
+ var collison_map_index = _collision_mapping[key]
165
+
166
+ var obs_index = (
167
+ (cell_i * grid_size_x * _n_layers_per_cell) +
168
+ (cell_j * _n_layers_per_cell) +
169
+ collison_map_index
170
+ )
171
+ #prints(obs_index, cell_i, cell_j)
172
+ if entered:
173
+ _obs_buffer[obs_index] += 1
174
+ else:
175
+ _obs_buffer[obs_index] -= 1
176
+
177
+ func _toggle_cell(cell_i:int, cell_j:int):
178
+ var cell = get_node_or_null("GridCell %s %s" %[cell_i, cell_j])
179
+
180
+ if cell == null:
181
+ print("cell not found, returning")
182
+
183
+ var n_hits = 0
184
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
185
+ for i in _n_layers_per_cell:
186
+ n_hits += _obs_buffer[start_index+i]
187
+
188
+ if n_hits > 0:
189
+ cell.modulate = _highlighted_cell_color
190
+ else:
191
+ cell.modulate = _standard_cell_color
192
+
193
+ func _on_cell_area_entered(area:Area2D, cell_i:int, cell_j:int):
194
+ #prints("_on_cell_area_entered", cell_i, cell_j)
195
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
196
+ if debug_view:
197
+ _toggle_cell(cell_i, cell_j)
198
+ #print(_obs_buffer)
199
+
200
+ func _on_cell_area_exited(area:Area2D, cell_i:int, cell_j:int):
201
+ #prints("_on_cell_area_exited", cell_i, cell_j)
202
+ _update_obs(cell_i, cell_j, area.collision_layer, false)
203
+ if debug_view:
204
+ _toggle_cell(cell_i, cell_j)
205
+
206
+ func _on_cell_body_entered(body: Node2D, cell_i:int, cell_j:int):
207
+ #prints("_on_cell_body_entered", cell_i, cell_j)
208
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
209
+ if debug_view:
210
+ _toggle_cell(cell_i, cell_j)
211
+
212
+ func _on_cell_body_exited(body: Node2D, cell_i:int, cell_j:int):
213
+ #prints("_on_cell_body_exited", cell_i, cell_j)
214
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
215
+ if debug_view:
216
+ _toggle_cell(cell_i, cell_j)
addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node2D
2
+ class_name ISensor2D
3
+
4
+ var _obs : Array = []
5
+ var _active := false
6
+
7
+ func get_observation():
8
+ pass
9
+
10
+ func activate():
11
+ _active = true
12
+
13
+ func deactivate():
14
+ _active = false
15
+
16
+ func _update_observation():
17
+ pass
18
+
19
+ func reset():
20
+ 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: return collision_mask
7
+ set(value):
8
+ collision_mask = value
9
+ _update()
10
+
11
+ @export var collide_with_areas := false:
12
+ get: return collide_with_areas
13
+ set(value):
14
+ collide_with_areas = value
15
+ _update()
16
+
17
+ @export var collide_with_bodies := true:
18
+ get: return collide_with_bodies
19
+ set(value):
20
+ collide_with_bodies = value
21
+ _update()
22
+
23
+ @export var n_rays := 16.0:
24
+ get: return n_rays
25
+ set(value):
26
+ n_rays = value
27
+ _update()
28
+
29
+ @export_range(5,200,5.0) var ray_length := 200:
30
+ get: return ray_length
31
+ set(value):
32
+ ray_length = value
33
+ _update()
34
+ @export_range(5,360,5.0) var cone_width := 360.0:
35
+ get: return cone_width
36
+ set(value):
37
+ cone_width = value
38
+ _update()
39
+
40
+ @export var debug_draw := true :
41
+ get: return debug_draw
42
+ set(value):
43
+ debug_draw = value
44
+ _update()
45
+
46
+
47
+ var _angles = []
48
+ var rays := []
49
+
50
+ func _update():
51
+ if Engine.is_editor_hint():
52
+ if debug_draw:
53
+ _spawn_nodes()
54
+ else:
55
+ for ray in get_children():
56
+ if ray is RayCast2D:
57
+ remove_child(ray)
58
+
59
+ func _ready() -> void:
60
+ _spawn_nodes()
61
+
62
+ func _spawn_nodes():
63
+ for ray in rays:
64
+ ray.queue_free()
65
+ rays = []
66
+
67
+ _angles = []
68
+ var step = cone_width / (n_rays)
69
+ var start = step/2 - cone_width/2
70
+
71
+ for i in n_rays:
72
+ var angle = start + i * step
73
+ var ray = RayCast2D.new()
74
+ ray.set_target_position(Vector2(
75
+ ray_length*cos(deg_to_rad(angle)),
76
+ ray_length*sin(deg_to_rad(angle))
77
+ ))
78
+ ray.set_name("node_"+str(i))
79
+ ray.enabled = true
80
+ ray.collide_with_areas = collide_with_areas
81
+ ray.collide_with_bodies = collide_with_bodies
82
+ ray.collision_mask = collision_mask
83
+ add_child(ray)
84
+ rays.append(ray)
85
+
86
+
87
+ _angles.append(start + i * step)
88
+
89
+
90
+ func _physics_process(delta: float) -> void:
91
+ if self._active:
92
+ self._obs = calculate_raycasts()
93
+
94
+ func get_observation() -> Array:
95
+ if len(self._obs) == 0:
96
+ print("obs was null, forcing raycast update")
97
+ return self.calculate_raycasts()
98
+ return self._obs
99
+
100
+
101
+ func calculate_raycasts() -> Array:
102
+ var result = []
103
+ for ray in rays:
104
+ ray.force_raycast_update()
105
+ var distance = _get_raycast_distance(ray)
106
+ result.append(distance)
107
+ return result
108
+
109
+ func _get_raycast_distance(ray : RayCast2D) -> float :
110
+ if !ray.is_colliding():
111
+ return 0.0
112
+
113
+ var distance = (global_position - ray.get_collision_point()).length()
114
+ distance = clamp(distance, 0.0, ray_length)
115
+ return (ray_length - distance) / ray_length
116
+
117
+
118
+
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,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor3D
3
+ class_name GridSensor3D
4
+
5
+ @export var debug_view := false:
6
+ get: return debug_view
7
+ set(value):
8
+ debug_view = value
9
+ _update()
10
+
11
+ @export_flags_3d_physics var detection_mask := 0:
12
+ get: return detection_mask
13
+ set(value):
14
+ detection_mask = value
15
+ _update()
16
+
17
+ @export var collide_with_areas := false:
18
+ get: return collide_with_areas
19
+ set(value):
20
+ collide_with_areas = value
21
+ _update()
22
+
23
+ @export var collide_with_bodies := false:
24
+ # NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them
25
+ get: return collide_with_bodies
26
+ set(value):
27
+ collide_with_bodies = value
28
+ _update()
29
+
30
+ @export_range(0.1, 2, 0.1) var cell_width := 1.0:
31
+ get: return cell_width
32
+ set(value):
33
+ cell_width = value
34
+ _update()
35
+
36
+ @export_range(0.1, 2, 0.1) var cell_height := 1.0:
37
+ get: return cell_height
38
+ set(value):
39
+ cell_height = value
40
+ _update()
41
+
42
+ @export_range(1, 21, 2, "or_greater") var grid_size_x := 3:
43
+ get: return grid_size_x
44
+ set(value):
45
+ grid_size_x = value
46
+ _update()
47
+
48
+ @export_range(1, 21, 2, "or_greater") var grid_size_z := 3:
49
+ get: return grid_size_z
50
+ set(value):
51
+ grid_size_z = value
52
+ _update()
53
+
54
+ var _obs_buffer: PackedFloat64Array
55
+ var _box_shape: BoxShape3D
56
+ var _collision_mapping: Dictionary
57
+ var _n_layers_per_cell: int
58
+
59
+ var _highlighted_box_material: StandardMaterial3D
60
+ var _standard_box_material: StandardMaterial3D
61
+
62
+ func get_observation():
63
+ return _obs_buffer
64
+
65
+ func reset():
66
+ _obs_buffer.fill(0)
67
+
68
+ func _update():
69
+ if Engine.is_editor_hint():
70
+ if is_node_ready():
71
+ _spawn_nodes()
72
+
73
+ func _ready() -> void:
74
+ _make_materials()
75
+
76
+ if Engine.is_editor_hint():
77
+ if get_child_count() == 0:
78
+ _spawn_nodes()
79
+ else:
80
+ _spawn_nodes()
81
+
82
+ func _make_materials() -> void:
83
+ if _highlighted_box_material != null and _standard_box_material != null:
84
+ return
85
+
86
+ _standard_box_material = StandardMaterial3D.new()
87
+ _standard_box_material.set_transparency(1) # ALPHA
88
+ _standard_box_material.albedo_color = Color(100.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0)
89
+
90
+ _highlighted_box_material = StandardMaterial3D.new()
91
+ _highlighted_box_material.set_transparency(1) # ALPHA
92
+ _highlighted_box_material.albedo_color = Color(255.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0)
93
+
94
+ func _get_collision_mapping() -> Dictionary:
95
+ # defines which layer is mapped to which cell obs index
96
+ var total_bits = 0
97
+ var collision_mapping = {}
98
+ for i in 32:
99
+ var bit_mask = 2**i
100
+ if (detection_mask & bit_mask) > 0:
101
+ collision_mapping[i] = total_bits
102
+ total_bits += 1
103
+
104
+ return collision_mapping
105
+
106
+ func _spawn_nodes():
107
+ for cell in get_children():
108
+ cell.name = "_%s" % cell.name # Otherwise naming below will fail
109
+ cell.queue_free()
110
+
111
+ _collision_mapping = _get_collision_mapping()
112
+ #prints("collision_mapping", _collision_mapping, len(_collision_mapping))
113
+ # allocate memory for the observations
114
+ _n_layers_per_cell = len(_collision_mapping)
115
+ _obs_buffer = PackedFloat64Array()
116
+ _obs_buffer.resize(grid_size_x*grid_size_z*_n_layers_per_cell)
117
+ _obs_buffer.fill(0)
118
+ #prints(len(_obs_buffer), _obs_buffer )
119
+
120
+ _box_shape = BoxShape3D.new()
121
+ _box_shape.set_size(Vector3(cell_width, cell_height, cell_width))
122
+
123
+ var shift := Vector3(
124
+ -(grid_size_x/2)*cell_width,
125
+ 0,
126
+ -(grid_size_z/2)*cell_width,
127
+ )
128
+
129
+ for i in grid_size_x:
130
+ for j in grid_size_z:
131
+ var cell_position = Vector3(i*cell_width, 0.0, j*cell_width) + shift
132
+ _create_cell(i, j, cell_position)
133
+
134
+
135
+ func _create_cell(i:int, j:int, position: Vector3):
136
+ var cell : = Area3D.new()
137
+ cell.position = position
138
+ cell.name = "GridCell %s %s" %[i, j]
139
+
140
+ if collide_with_areas:
141
+ cell.area_entered.connect(_on_cell_area_entered.bind(i, j))
142
+ cell.area_exited.connect(_on_cell_area_exited.bind(i, j))
143
+
144
+ if collide_with_bodies:
145
+ cell.body_entered.connect(_on_cell_body_entered.bind(i, j))
146
+ cell.body_exited.connect(_on_cell_body_exited.bind(i, j))
147
+
148
+ # cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j))
149
+ # cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j))
150
+
151
+ cell.collision_layer = 0
152
+ cell.collision_mask = detection_mask
153
+ cell.monitorable = true
154
+ cell.input_ray_pickable = false
155
+ add_child(cell)
156
+ cell.set_owner(get_tree().edited_scene_root)
157
+
158
+ var col_shape : = CollisionShape3D.new()
159
+ col_shape.shape = _box_shape
160
+ col_shape.name = "CollisionShape3D"
161
+ cell.add_child(col_shape)
162
+ col_shape.set_owner(get_tree().edited_scene_root)
163
+
164
+ if debug_view:
165
+ var box = MeshInstance3D.new()
166
+ box.name = "MeshInstance3D"
167
+ var box_mesh = BoxMesh.new()
168
+
169
+ box_mesh.set_size(Vector3(cell_width, cell_height, cell_width))
170
+ box_mesh.material = _standard_box_material
171
+
172
+ box.mesh = box_mesh
173
+ cell.add_child(box)
174
+ box.set_owner(get_tree().edited_scene_root)
175
+
176
+ func _update_obs(cell_i:int, cell_j:int, collision_layer:int, entered: bool):
177
+ for key in _collision_mapping:
178
+ var bit_mask = 2**key
179
+ if (collision_layer & bit_mask) > 0:
180
+ var collison_map_index = _collision_mapping[key]
181
+
182
+ var obs_index = (
183
+ (cell_i * grid_size_x * _n_layers_per_cell) +
184
+ (cell_j * _n_layers_per_cell) +
185
+ collison_map_index
186
+ )
187
+ #prints(obs_index, cell_i, cell_j)
188
+ if entered:
189
+ _obs_buffer[obs_index] += 1
190
+ else:
191
+ _obs_buffer[obs_index] -= 1
192
+
193
+ func _toggle_cell(cell_i:int, cell_j:int):
194
+ var cell = get_node_or_null("GridCell %s %s" %[cell_i, cell_j])
195
+
196
+ if cell == null:
197
+ print("cell not found, returning")
198
+
199
+ var n_hits = 0
200
+ var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell)
201
+ for i in _n_layers_per_cell:
202
+ n_hits += _obs_buffer[start_index+i]
203
+
204
+ var cell_mesh = cell.get_node_or_null("MeshInstance3D")
205
+ if n_hits > 0:
206
+ cell_mesh.mesh.material = _highlighted_box_material
207
+ else:
208
+ cell_mesh.mesh.material = _standard_box_material
209
+
210
+ func _on_cell_area_entered(area:Area3D, cell_i:int, cell_j:int):
211
+ #prints("_on_cell_area_entered", cell_i, cell_j)
212
+ _update_obs(cell_i, cell_j, area.collision_layer, true)
213
+ if debug_view:
214
+ _toggle_cell(cell_i, cell_j)
215
+ #print(_obs_buffer)
216
+
217
+ func _on_cell_area_exited(area:Area3D, 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
+ func _on_cell_body_entered(body: Node3D, cell_i:int, cell_j:int):
224
+ #prints("_on_cell_body_entered", cell_i, cell_j)
225
+ _update_obs(cell_i, cell_j, body.collision_layer, true)
226
+ if debug_view:
227
+ _toggle_cell(cell_i, cell_j)
228
+
229
+ func _on_cell_body_exited(body: Node3D, cell_i:int, cell_j:int):
230
+ #prints("_on_cell_body_exited", cell_i, cell_j)
231
+ _update_obs(cell_i, cell_j, body.collision_layer, false)
232
+ if debug_view:
233
+ _toggle_cell(cell_i, cell_j)
addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name ISensor3D
3
+
4
+ var _obs : Array = []
5
+ var _active := false
6
+
7
+ func get_observation():
8
+ pass
9
+
10
+ func activate():
11
+ _active = true
12
+
13
+ func deactivate():
14
+ _active = false
15
+
16
+ func _update_observation():
17
+ pass
18
+
19
+ func reset():
20
+ pass
addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ class_name RGBCameraSensor3D
3
+ var camera_pixels = null
4
+
5
+ @onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D
6
+
7
+ func get_camera_pixel_encoding():
8
+ return camera_texture.get_texture().get_image().get_data().hex_encode()
9
+
10
+ func get_camera_shape()-> Array:
11
+ if $SubViewport.transparent_bg:
12
+ return [$SubViewport.size[0], $SubViewport.size[1], 4]
13
+ else:
14
+ return [$SubViewport.size[0], $SubViewport.size[1], 3]
addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"]
2
+
3
+ [ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"]
4
+
5
+ [sub_resource type="ViewportTexture" id="1"]
6
+ viewport_path = NodePath("SubViewport")
7
+
8
+ [node name="RGBCameraSensor3D" type="Node3D"]
9
+ script = ExtResource("1")
10
+
11
+ [node name="RemoteTransform3D" type="RemoteTransform3D" parent="."]
12
+ remote_path = NodePath("../SubViewport/Camera3D")
13
+
14
+ [node name="SubViewport" type="SubViewport" parent="."]
15
+ size = Vector2i(32, 32)
16
+ render_target_update_mode = 3
17
+
18
+ [node name="Camera3D" type="Camera3D" parent="SubViewport"]
19
+ near = 0.5
20
+
21
+ [node name="Control" type="Control" parent="."]
22
+ layout_mode = 3
23
+ anchors_preset = 15
24
+ anchor_right = 1.0
25
+ anchor_bottom = 1.0
26
+ grow_horizontal = 2
27
+ grow_vertical = 2
28
+
29
+ [node name="TextureRect" type="ColorRect" parent="Control"]
30
+ layout_mode = 0
31
+ offset_left = 1096.0
32
+ offset_top = 534.0
33
+ offset_right = 1114.0
34
+ offset_bottom = 552.0
35
+ scale = Vector2(10, 10)
36
+ color = Color(0.00784314, 0.00784314, 0.00784314, 1)
37
+
38
+ [node name="CameraTexture" type="Sprite2D" parent="Control/TextureRect"]
39
+ texture = SubResource("1")
40
+ offset = Vector2(9, 9)
41
+ flip_v = true
addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @tool
2
+ extends ISensor3D
3
+ class_name RayCastSensor3D
4
+ @export_flags_3d_physics var collision_mask = 1:
5
+ get: return collision_mask
6
+ set(value):
7
+ collision_mask = value
8
+ _update()
9
+ @export_flags_3d_physics var boolean_class_mask = 1:
10
+ get: return boolean_class_mask
11
+ set(value):
12
+ boolean_class_mask = value
13
+ _update()
14
+
15
+ @export var n_rays_width := 6.0:
16
+ get: return n_rays_width
17
+ set(value):
18
+ n_rays_width = value
19
+ _update()
20
+
21
+ @export var n_rays_height := 6.0:
22
+ get: return n_rays_height
23
+ set(value):
24
+ n_rays_height = value
25
+ _update()
26
+
27
+ @export var ray_length := 10.0:
28
+ get: return ray_length
29
+ set(value):
30
+ ray_length = value
31
+ _update()
32
+
33
+ @export var cone_width := 60.0:
34
+ get: return cone_width
35
+ set(value):
36
+ cone_width = value
37
+ _update()
38
+
39
+ @export var cone_height := 60.0:
40
+ get: return cone_height
41
+ set(value):
42
+ cone_height = value
43
+ _update()
44
+
45
+ @export var collide_with_areas := false:
46
+ get: return collide_with_areas
47
+ set(value):
48
+ collide_with_areas = value
49
+ _update()
50
+
51
+ @export var collide_with_bodies := true:
52
+ get: return collide_with_bodies
53
+ set(value):
54
+ collide_with_bodies = value
55
+ _update()
56
+
57
+ @export var class_sensor := false
58
+
59
+ var rays := []
60
+ var geo = null
61
+
62
+ func _update():
63
+ if Engine.is_editor_hint():
64
+ if is_node_ready():
65
+ _spawn_nodes()
66
+
67
+ func _ready() -> void:
68
+ if Engine.is_editor_hint():
69
+ if get_child_count() == 0:
70
+ _spawn_nodes()
71
+ else:
72
+ _spawn_nodes()
73
+
74
+ func _spawn_nodes():
75
+ print("spawning nodes")
76
+ for ray in get_children():
77
+ ray.queue_free()
78
+ if geo:
79
+ geo.clear()
80
+ #$Lines.remove_points()
81
+ rays = []
82
+
83
+ var horizontal_step = cone_width / (n_rays_width)
84
+ var vertical_step = cone_height / (n_rays_height)
85
+
86
+ var horizontal_start = horizontal_step/2 - cone_width/2
87
+ var vertical_start = vertical_step/2 - cone_height/2
88
+
89
+ var points = []
90
+
91
+ for i in n_rays_width:
92
+ for j in n_rays_height:
93
+ var angle_w = horizontal_start + i * horizontal_step
94
+ var angle_h = vertical_start + j * vertical_step
95
+ #angle_h = 0.0
96
+ var ray = RayCast3D.new()
97
+ var cast_to = to_spherical_coords(ray_length, angle_w, angle_h)
98
+ ray.set_target_position(cast_to)
99
+
100
+ points.append(cast_to)
101
+
102
+ ray.set_name("node_"+str(i)+" "+str(j))
103
+ ray.enabled = true
104
+ ray.collide_with_bodies = collide_with_bodies
105
+ ray.collide_with_areas = collide_with_areas
106
+ ray.collision_mask = collision_mask
107
+ add_child(ray)
108
+ ray.set_owner(get_tree().edited_scene_root)
109
+ rays.append(ray)
110
+ ray.force_raycast_update()
111
+
112
+ # if Engine.editor_hint:
113
+ # _create_debug_lines(points)
114
+
115
+ func _create_debug_lines(points):
116
+ if not geo:
117
+ geo = ImmediateMesh.new()
118
+ add_child(geo)
119
+
120
+ geo.clear()
121
+ geo.begin(Mesh.PRIMITIVE_LINES)
122
+ for point in points:
123
+ geo.set_color(Color.AQUA)
124
+ geo.add_vertex(Vector3.ZERO)
125
+ geo.add_vertex(point)
126
+ geo.end()
127
+
128
+ func display():
129
+ if geo:
130
+ geo.display()
131
+
132
+ func to_spherical_coords(r, inc, azimuth) -> Vector3:
133
+ return Vector3(
134
+ r*sin(deg_to_rad(inc))*cos(deg_to_rad(azimuth)),
135
+ r*sin(deg_to_rad(azimuth)),
136
+ r*cos(deg_to_rad(inc))*cos(deg_to_rad(azimuth))
137
+ )
138
+
139
+ func get_observation() -> Array:
140
+ return self.calculate_raycasts()
141
+
142
+ func calculate_raycasts() -> Array:
143
+ var result = []
144
+ for ray in rays:
145
+ ray.set_enabled(true)
146
+ ray.force_raycast_update()
147
+ var distance = _get_raycast_distance(ray)
148
+
149
+ result.append(distance)
150
+ if class_sensor:
151
+ var hit_class = 0
152
+ if ray.get_collider():
153
+ var hit_collision_layer = ray.get_collider().collision_layer
154
+ hit_collision_layer = hit_collision_layer & collision_mask
155
+ hit_class = (hit_collision_layer & boolean_class_mask) > 0
156
+ result.append(hit_class)
157
+ ray.set_enabled(false)
158
+ return result
159
+
160
+ func _get_raycast_distance(ray : RayCast3D) -> float :
161
+ if !ray.is_colliding():
162
+ return 0.0
163
+
164
+ var distance = (global_transform.origin - ray.get_collision_point()).length()
165
+ distance = clamp(distance, 0.0, ray_length)
166
+ 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,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node
2
+
3
+ # --fixed-fps 2000 --disable-render-loop
4
+
5
+ enum ControlModes {HUMAN, TRAINING, ONNX_INFERENCE}
6
+ @export var control_mode: ControlModes = ControlModes.TRAINING
7
+ @export_range(1, 10, 1, "or_greater") var action_repeat := 8
8
+ @export_range(1, 10, 1, "or_greater") var speed_up = 1
9
+ @export var onnx_model_path := ""
10
+
11
+ @onready var start_time = Time.get_ticks_msec()
12
+
13
+ const MAJOR_VERSION := "0"
14
+ const MINOR_VERSION := "3"
15
+ const DEFAULT_PORT := "11008"
16
+ const DEFAULT_SEED := "1"
17
+ var stream : StreamPeerTCP = null
18
+ var connected = false
19
+ var message_center
20
+ var should_connect = true
21
+ var agents
22
+ var need_to_send_obs = false
23
+ var args = null
24
+ var initialized = false
25
+ var just_reset = false
26
+ var onnx_model = null
27
+ var n_action_steps = 0
28
+
29
+ var _action_space : Dictionary
30
+ var _obs_space : Dictionary
31
+
32
+ # Called when the node enters the scene tree for the first time.
33
+ func _ready():
34
+ await get_tree().root.ready
35
+ get_tree().set_pause(true)
36
+ _initialize()
37
+ await get_tree().create_timer(1.0).timeout
38
+ get_tree().set_pause(false)
39
+
40
+ func _initialize():
41
+ _get_agents()
42
+ _obs_space = agents[0].get_obs_space()
43
+ _action_space = agents[0].get_action_space()
44
+ args = _get_args()
45
+ Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body.
46
+ Engine.time_scale = _get_speedup() * 1.0
47
+ prints("physics ticks", Engine.physics_ticks_per_second, Engine.time_scale, _get_speedup(), speed_up)
48
+
49
+ _set_heuristic("human")
50
+ match control_mode:
51
+ ControlModes.TRAINING:
52
+ connected = connect_to_server()
53
+ if connected:
54
+ _set_heuristic("model")
55
+ _handshake()
56
+ _send_env_info()
57
+ else:
58
+ push_warning("Couldn't connect to Python server, using human controls instead. ",
59
+ "Did you start the training server using e.g. `gdrl` from the console?")
60
+ ControlModes.ONNX_INFERENCE:
61
+ assert(FileAccess.file_exists(onnx_model_path), "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path)
62
+ onnx_model = ONNXModel.new(onnx_model_path, 1)
63
+ _set_heuristic("model")
64
+
65
+ _set_seed()
66
+ _set_action_repeat()
67
+ initialized = true
68
+
69
+ func _physics_process(_delta):
70
+ # two modes, human control, agent control
71
+ # pause tree, send obs, get actions, set actions, unpause tree
72
+ if n_action_steps % action_repeat != 0:
73
+ n_action_steps += 1
74
+ return
75
+
76
+ n_action_steps += 1
77
+
78
+ if connected:
79
+ get_tree().set_pause(true)
80
+
81
+ if just_reset:
82
+ just_reset = false
83
+ var obs = _get_obs_from_agents()
84
+
85
+ var reply = {
86
+ "type": "reset",
87
+ "obs": obs
88
+ }
89
+ _send_dict_as_json_message(reply)
90
+ # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick
91
+ get_tree().set_pause(false)
92
+ return
93
+
94
+ if need_to_send_obs:
95
+ need_to_send_obs = false
96
+ var reward = _get_reward_from_agents()
97
+ var done = _get_done_from_agents()
98
+ #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR
99
+
100
+ var obs = _get_obs_from_agents()
101
+
102
+ var reply = {
103
+ "type": "step",
104
+ "obs": obs,
105
+ "reward": reward,
106
+ "done": done
107
+ }
108
+ _send_dict_as_json_message(reply)
109
+
110
+ var handled = handle_message()
111
+
112
+ elif onnx_model != null:
113
+ var obs : Array = _get_obs_from_agents()
114
+
115
+ var actions = []
116
+ for o in obs:
117
+ var action = onnx_model.run_inference(o["obs"], 1.0)
118
+ action["output"] = clamp_array(action["output"], -1.0, 1.0)
119
+ var action_dict = _extract_action_dict(action["output"])
120
+ actions.append(action_dict)
121
+
122
+ _set_agent_actions(actions)
123
+ need_to_send_obs = true
124
+ get_tree().set_pause(false)
125
+ _reset_agents_if_done()
126
+
127
+ else:
128
+ _reset_agents_if_done()
129
+
130
+ func _extract_action_dict(action_array: Array):
131
+ var index = 0
132
+ var result = {}
133
+ for key in _action_space.keys():
134
+ var size = _action_space[key]["size"]
135
+ if _action_space[key]["action_type"] == "discrete":
136
+ result[key] = round(action_array[index])
137
+ else:
138
+ result[key] = action_array.slice(index,index+size)
139
+ index += size
140
+
141
+ return result
142
+
143
+ func _get_agents():
144
+ agents = get_tree().get_nodes_in_group("AGENT")
145
+
146
+ func _set_heuristic(heuristic):
147
+ for agent in agents:
148
+ agent.set_heuristic(heuristic)
149
+
150
+ func _handshake():
151
+ print("performing handshake")
152
+
153
+ var json_dict = _get_dict_json_message()
154
+ assert(json_dict["type"] == "handshake")
155
+ var major_version = json_dict["major_version"]
156
+ var minor_version = json_dict["minor_version"]
157
+ if major_version != MAJOR_VERSION:
158
+ print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION)
159
+ if minor_version != MINOR_VERSION:
160
+ print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION)
161
+
162
+ print("handshake complete")
163
+
164
+ func _get_dict_json_message():
165
+ # returns a dictionary from of the most recent message
166
+ # this is not waiting
167
+ while stream.get_available_bytes() == 0:
168
+ stream.poll()
169
+ if stream.get_status() != 2:
170
+ print("server disconnected status, closing")
171
+ get_tree().quit()
172
+ return null
173
+
174
+ OS.delay_usec(10)
175
+
176
+ var message = stream.get_string()
177
+ var json_data = JSON.parse_string(message)
178
+
179
+ return json_data
180
+
181
+ func _send_dict_as_json_message(dict):
182
+ stream.put_string(JSON.stringify(dict, "", false))
183
+
184
+ func _send_env_info():
185
+ var json_dict = _get_dict_json_message()
186
+ assert(json_dict["type"] == "env_info")
187
+
188
+
189
+ var message = {
190
+ "type" : "env_info",
191
+ "observation_space": _obs_space,
192
+ "action_space":_action_space,
193
+ "n_agents": len(agents)
194
+ }
195
+ _send_dict_as_json_message(message)
196
+
197
+ func connect_to_server():
198
+ print("Waiting for one second to allow server to start")
199
+ OS.delay_msec(1000)
200
+ print("trying to connect to server")
201
+ stream = StreamPeerTCP.new()
202
+
203
+ # "localhost" was not working on windows VM, had to use the IP
204
+ var ip = "127.0.0.1"
205
+ var port = _get_port()
206
+ var connect = stream.connect_to_host(ip, port)
207
+ stream.set_no_delay(true) # TODO check if this improves performance or not
208
+ stream.poll()
209
+ # Fetch the status until it is either connected (2) or failed to connect (3)
210
+ while stream.get_status() < 2:
211
+ stream.poll()
212
+ return stream.get_status() == 2
213
+
214
+ func _get_args():
215
+ print("getting command line arguments")
216
+ var arguments = {}
217
+ for argument in OS.get_cmdline_args():
218
+ print(argument)
219
+ if argument.find("=") > -1:
220
+ var key_value = argument.split("=")
221
+ arguments[key_value[0].lstrip("--")] = key_value[1]
222
+ else:
223
+ # Options without an argument will be present in the dictionary,
224
+ # with the value set to an empty string.
225
+ arguments[argument.lstrip("--")] = ""
226
+
227
+ return arguments
228
+
229
+ func _get_speedup():
230
+ print(args)
231
+ return args.get("speedup", str(speed_up)).to_int()
232
+
233
+ func _get_port():
234
+ return args.get("port", DEFAULT_PORT).to_int()
235
+
236
+ func _set_seed():
237
+ var _seed = args.get("env_seed", DEFAULT_SEED).to_int()
238
+ seed(_seed)
239
+
240
+ func _set_action_repeat():
241
+ action_repeat = args.get("action_repeat", str(action_repeat)).to_int()
242
+
243
+ func disconnect_from_server():
244
+ stream.disconnect_from_host()
245
+
246
+
247
+
248
+ func handle_message() -> bool:
249
+ # get json message: reset, step, close
250
+ var message = _get_dict_json_message()
251
+ if message["type"] == "close":
252
+ print("received close message, closing game")
253
+ get_tree().quit()
254
+ get_tree().set_pause(false)
255
+ return true
256
+
257
+ if message["type"] == "reset":
258
+ print("resetting all agents")
259
+ _reset_all_agents()
260
+ just_reset = true
261
+ get_tree().set_pause(false)
262
+ #print("resetting forcing draw")
263
+ # RenderingServer.force_draw()
264
+ # var obs = _get_obs_from_agents()
265
+ # print("obs ", obs)
266
+ # var reply = {
267
+ # "type": "reset",
268
+ # "obs": obs
269
+ # }
270
+ # _send_dict_as_json_message(reply)
271
+ return true
272
+
273
+ if message["type"] == "call":
274
+ var method = message["method"]
275
+ var returns = _call_method_on_agents(method)
276
+ var reply = {
277
+ "type": "call",
278
+ "returns": returns
279
+ }
280
+ print("calling method from Python")
281
+ _send_dict_as_json_message(reply)
282
+ return handle_message()
283
+
284
+ if message["type"] == "action":
285
+ var action = message["action"]
286
+ _set_agent_actions(action)
287
+ need_to_send_obs = true
288
+ get_tree().set_pause(false)
289
+ return true
290
+
291
+ print("message was not handled")
292
+ return false
293
+
294
+ func _call_method_on_agents(method):
295
+ var returns = []
296
+ for agent in agents:
297
+ returns.append(agent.call(method))
298
+
299
+ return returns
300
+
301
+
302
+ func _reset_agents_if_done():
303
+ for agent in agents:
304
+ if agent.get_done():
305
+ agent.set_done_false()
306
+
307
+ func _reset_all_agents():
308
+ for agent in agents:
309
+ agent.needs_reset = true
310
+ #agent.reset()
311
+
312
+ func _get_obs_from_agents():
313
+ var obs = []
314
+ for agent in agents:
315
+ obs.append(agent.get_obs())
316
+
317
+ return obs
318
+
319
+ func _get_reward_from_agents():
320
+ var rewards = []
321
+ for agent in agents:
322
+ rewards.append(agent.get_reward())
323
+ agent.zero_reward()
324
+ return rewards
325
+
326
+ func _get_done_from_agents():
327
+ var dones = []
328
+ for agent in agents:
329
+ var done = agent.get_done()
330
+ if done: agent.set_done_false()
331
+ dones.append(done)
332
+ return dones
333
+
334
+ func _set_agent_actions(actions):
335
+ for i in range(len(actions)):
336
+ agents[i].set_action(actions[i])
337
+
338
+ func clamp_array(arr : Array, min:float, max:float):
339
+ var output : Array = []
340
+ for a in arr:
341
+ output.append(clamp(a, min, max))
342
+ return output
asset-license.md ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Hovercraft Racing Environment made by Ivan-267 using Godot, Godot RL Agents, and Blender.
2
+
3
+ The following license is only for the assets (.blend files) in the folder "scenes/blender":
4
+ Author: https://github.com/Ivan-267
5
+ License: https://creativecommons.org/licenses/by/4.0/
icon.svg ADDED
model.onnx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0363b72528e3814052e3d156d490660cfbb5ccac7eae94506345daadcd899fea
3
+ size 31693
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="HovercraftRacingExample"
14
+ run/main_scene="res://scenes/main_scene/main_scene.tscn"
15
+ config/features=PackedStringArray("4.2", "C#", "GL Compatibility")
16
+ config/icon="res://icon.svg"
17
+
18
+ [dotnet]
19
+
20
+ project/assembly_name="RacingExample"
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,"echo":false,"script":null)
31
+ ]
32
+ }
33
+ move_backward={
34
+ "deadzone": 0.5,
35
+ "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,"echo":false,"script":null)
36
+ ]
37
+ }
38
+ steer_left={
39
+ "deadzone": 0.5,
40
+ "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,"echo":false,"script":null)
41
+ ]
42
+ }
43
+ steer_right={
44
+ "deadzone": 0.5,
45
+ "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,"echo":false,"script":null)
46
+ ]
47
+ }
48
+
49
+ [rendering]
50
+
51
+ renderer/rendering_method.mobile="gl_compatibility"
readme.md ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Hovercraft Racing Environment
2
+
3
+ https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/09cfa8ef-4d1a-46d3-a38a-0b7cdf1e1000
4
+
5
+ A 1v1 hovercraft racing environment with:
6
+
7
+ - `Human VS AI` (use `WASD` keys to control the car), or `AI vs AI` mode,
8
+ - Adjustable number of laps (can be set to 0 for infinite race),
9
+ - Basic powerups (push forward or push backward).
10
+
11
+ ### Observations:
12
+ - Velocity of the car in local reference,
13
+ - 3 sampled `next track points` in the car's local reference,
14
+ - Wall detecting raycast sensor observations,
15
+ - Other car detecting raycast sensor observations,
16
+ - Position of the other car in the current car's local reference,
17
+ - Position of the nearest powerup in the car's local reference,
18
+ - Category of the powerup, as there are only two powerups it can be either `[0, 1]` or `[1, 0]`.
19
+
20
+ ### Action space:
21
+ ```gdscript
22
+ func get_action_space() -> Dictionary:
23
+ return {
24
+ "acceleration": {"size": 1, "action_type": "continuous"},
25
+ "steering": {"size": 1, "action_type": "continuous"},
26
+ }
27
+ ```
28
+
29
+ ### Rewards:
30
+ - Step reward based on the car's track offset difference from the previous step (advancing on the track gives a positive reward, moving backward gives a negative reward),
31
+ - Negative step reward for moving backward,
32
+ - Negative reward for colliding with a wall or the other car,
33
+ - Optional reward for driving over a powerup (can be adjusted in Godot Editor in the scene of the powerup), currently set to 0 for both powerups.
34
+
35
+ ### Game over / episode end conditions:
36
+ ![image](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/d9fdf617-0c4a-479e-8feb-cab9880345e6)
37
+
38
+ The episode ends for each car after each lap in infinite race mode if `total laps` is set to 0, without restarting the cars,
39
+ or if larger than 0, after the set amount of total laps has been completed by any car, in that case the winner is announced (except in training mode), and the cars are automatically restarted for the next race.
40
+
41
+ `Seconds Until Race Begins` is only applicable to inference (`AI vs AI` or `Player vs AI` modes).
42
+
43
+ ### Running inference with the pretrained onnx model:
44
+ ![image](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/2f9dfd2b-9835-42e0-9bf5-5f45e896967b)
45
+
46
+ After opening the project in Godot, open the main_scene (should open by default), select a game mode, and click on `Play`.
47
+
48
+ ### Training:
49
+
50
+ - Set the game mode to `Training` before starting starting training. You can use for instance the [sb3 example](https://github.com/edbeeching/godot_rl_agents/blob/main/examples/stable_baselines3_example.py) to train.
51
+
52
+ - In the `game_scene`'s `Cars` node, there's a property `Number of Car Groups To Spawn` which allows multiple car groups to spawn and collect experiences during training (during inference, only 1 car group is spawned). Since this is a `1v1` example, each car group is set so a car can only collide with the other car from its own group and the walls. This is done by the car manager script by setting each car to its own physics layer and adjusting the masks (also for the raycast sensor that detects the other car). Settings this value too high may make the environment not work correctly, as there is a limit in the number of physics layers available.
53
+
54
+ ![image](https://github.com/edbeeching/godot_rl_agents_examples/assets/61947090/94752856-8729-4cde-8151-3aaf65bab155)
55
+
56
+
57
+
scenes/blender/car_base.blend ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b91e60c28c39a4883d9f44f608a22e5e4ac24a8a78d0f0594138337799263427
3
+ size 1041840
scenes/blender/house.blend ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0b0f9b041e2bc25ce73615eeedf71077c977abac7d622fa975422f8ab8b51277
3
+ size 1014696
scenes/blender/house2.blend ADDED
Binary file (999 kB). View file
 
scenes/blender/reverse-turbo-powerup.blend ADDED
Binary file (872 kB). View file
 
scenes/blender/rock.blend ADDED
Binary file (867 kB). View file
 
scenes/blender/rock2.blend ADDED
Binary file (873 kB). View file
 
scenes/blender/tree.blend ADDED
Binary file (880 kB). View file
 
scenes/blender/tree2.blend ADDED
Binary file (880 kB). View file
 
scenes/blender/tree3.blend ADDED
Binary file (880 kB). View file
 
scenes/blender/tree4.blend ADDED
Binary file (881 kB). View file
 
scenes/blender/tree5.blend ADDED
Binary file (880 kB). View file
 
scenes/blender/trees.blend ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9bd34b01af16242b00dd4d066188d7f296bd77977dcc2060b07235896dd0ecd6
3
+ size 1064524
scenes/blender/turbo-powerup.blend ADDED
Binary file (872 kB). View file
 
scenes/blender/windmill.blend ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd027e7e1eb33692ed1b2f500b8222fab0d843cb19848abc1961b8e4125dcea3
3
+ size 1041636
scenes/car/car.gd ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends RigidBody3D
2
+ class_name Car
3
+
4
+ var track: Track
5
+ var other_car: Car
6
+
7
+ # Car performance settings
8
+ var acceleration = 30.0
9
+ var torque = 7.0
10
+ var backward_acceleration_ratio = 0.75
11
+
12
+ @onready var ai_controller: CarAIController = $CarAIController
13
+ @onready var raycast_sensor_wall: RayCastSensor3D = $RayCastSensorWall
14
+ @onready var raycast_sensor_other_car: RayCastSensorAddSetCollisionMaskValue = $RayCastSensorOtherCar
15
+ @onready var camera: Camera3D = $"Camera3D"
16
+
17
+ var ui: UI
18
+ var thrusters: Array[Thruster]
19
+
20
+ ## Set by AIController during inference
21
+ var requested_acceleration: float
22
+ ## Set by AIController during inference
23
+ var requested_steering: float
24
+
25
+ # Track related data
26
+ var track_length: float
27
+ var previous_offset: float
28
+ var next_checkpoint_offset: float
29
+ var current_offset: float
30
+ var laps_passed: int
31
+ var first_checkpoint_offset: float
32
+
33
+
34
+ # Game settings data
35
+ var infinite_race: bool
36
+ var total_laps: int
37
+ var seconds_until_race_begins: int
38
+ var training_mode: bool
39
+
40
+ var initial_transform: Transform3D
41
+ var _just_reset: bool
42
+
43
+
44
+ func _ready():
45
+ thrusters.append_array(
46
+ [
47
+ get_node("Thruster1Particles"),
48
+ get_node("Thruster2Particles")
49
+ ]
50
+ )
51
+
52
+ ai_controller.init(self)
53
+ initial_transform = global_transform
54
+ track_length = track.track_path.curve.get_baked_length()
55
+ first_checkpoint_offset = track_length / 30.0
56
+
57
+
58
+ func reset():
59
+ laps_passed = 0
60
+ next_checkpoint_offset = first_checkpoint_offset
61
+
62
+ global_transform = initial_transform
63
+
64
+ for thruster in thrusters:
65
+ thruster.set_thruster_strength(0)
66
+
67
+ if not training_mode:
68
+ if camera.current:
69
+ ui.set_current_lap_text(laps_passed + 1)
70
+ ui.show_get_ready_text(seconds_until_race_begins)
71
+
72
+ process_mode = Node.PROCESS_MODE_DISABLED
73
+ await get_tree().create_timer(seconds_until_race_begins, true, true).timeout
74
+ process_mode = Node.PROCESS_MODE_INHERIT
75
+
76
+ _just_reset = true
77
+
78
+ func _integrate_forces(state):
79
+ if _just_reset:
80
+ state.linear_velocity = Vector3.ZERO
81
+ state.angular_velocity = Vector3.ZERO
82
+ state.transform = initial_transform
83
+ _just_reset = false
84
+
85
+
86
+ func get_next_checkpoint_offset() -> float:
87
+ return fmod(next_checkpoint_offset + track_length / 30.0, track_length)
88
+
89
+
90
+ func get_other_car_position_in_local_reference() -> Array[float]:
91
+ var local_position = (
92
+ to_local(global_position - other_car.global_position).limit_length(150.0) / 150.0
93
+ )
94
+ return [local_position.x, local_position.z]
95
+
96
+
97
+ func _physics_process(_delta):
98
+ if ai_controller.needs_reset:
99
+ ai_controller.reset()
100
+ reset()
101
+
102
+ var acceleration_to_apply := 0.0
103
+ var steering_to_apply := 0.0
104
+
105
+ if ai_controller.heuristic == "human":
106
+ update_track_related_data()
107
+
108
+ if Input.is_action_pressed("move_forward"):
109
+ acceleration_to_apply += acceleration
110
+ if Input.is_action_pressed("move_backward"):
111
+ acceleration_to_apply -= acceleration * backward_acceleration_ratio
112
+
113
+ if Input.is_action_pressed("steer_left"):
114
+ steering_to_apply += torque
115
+ if Input.is_action_pressed("steer_right"):
116
+ steering_to_apply -= torque
117
+ else:
118
+ if requested_acceleration < 0:
119
+ requested_acceleration *= backward_acceleration_ratio
120
+ acceleration_to_apply = requested_acceleration * acceleration
121
+ steering_to_apply = requested_steering * torque
122
+
123
+ apply_central_force(global_transform.basis.z * acceleration_to_apply)
124
+ apply_torque(global_transform.basis.y * steering_to_apply)
125
+
126
+ for thruster in thrusters:
127
+ thruster.set_thruster_strength(abs(acceleration_to_apply) * 0.05)
128
+
129
+
130
+ func handle_victory():
131
+ if laps_passed >= total_laps and other_car.laps_passed < total_laps:
132
+ if not training_mode:
133
+ ui.show_winner_text(name, seconds_until_race_begins)
134
+ await get_tree().create_timer(seconds_until_race_begins, true, true).timeout
135
+
136
+ _end_episode(0)
137
+ other_car._end_episode(0)
138
+
139
+
140
+ ## Updates any data needed before the AI controller sends observations
141
+ func prepare_for_sending_obs():
142
+ update_track_related_data()
143
+
144
+
145
+ ## Update the data for tracking the current progress along the track
146
+ func update_track_related_data():
147
+ update_current_offset()
148
+ update_checkpoint()
149
+
150
+
151
+ func update_current_offset():
152
+ current_offset = track.track_path.curve.get_closest_offset(global_position)
153
+
154
+
155
+ func update_checkpoint():
156
+ if abs(current_offset - next_checkpoint_offset) < (track_length / 60.0):
157
+ next_checkpoint_offset = get_next_checkpoint_offset()
158
+ if is_equal_approx(next_checkpoint_offset, track_length / 30.0):
159
+ laps_passed += 1
160
+ if camera.current and not training_mode:
161
+ ui.set_current_lap_text(laps_passed + 1)
162
+ if not infinite_race:
163
+ handle_victory()
164
+ else:
165
+ _end_episode()
166
+
167
+
168
+ func update_reward():
169
+ var offset_difference = current_offset - previous_offset
170
+
171
+ if offset_difference > (track_length / 2.0):
172
+ offset_difference = offset_difference - track_length
173
+
174
+ if offset_difference < -(track_length / 2.0):
175
+ offset_difference = offset_difference + track_length
176
+
177
+ ## Reward for moving along the track (positive or negative depending on direction)
178
+ ai_controller.reward += offset_difference / 10.0
179
+
180
+ ## Backward movement penalty
181
+ ai_controller.reward += min(0.0, get_normalized_velocity_in_player_reference().z + 0.1) * 5.0
182
+
183
+ previous_offset = current_offset
184
+ pass
185
+
186
+
187
+ func get_next_track_points(num_points: int, step_size: float) -> Array:
188
+ var temp_array: Array[float] = []
189
+ var closest_offset = current_offset
190
+
191
+ for i in range(0, num_points):
192
+ var current_point = track.track_path.curve.sample_baked(
193
+ fmod(closest_offset + step_size * (i + 1), track_length)
194
+ )
195
+ var local = to_local(current_point) / (num_points * step_size)
196
+ temp_array.append_array([local.x, local.z])
197
+ return temp_array
198
+
199
+
200
+ func _end_episode(final_reward: float = 0.0):
201
+ ai_controller.reward += final_reward
202
+ ai_controller.done = true
203
+ ai_controller.reset()
204
+
205
+ if not infinite_race:
206
+ reset()
207
+
208
+
209
+ func get_normalized_velocity_in_player_reference():
210
+ return (global_transform.basis.inverse() * linear_velocity).limit_length(42.0) / 42.0
211
+
212
+
213
+ func _on_body_entered(_body):
214
+ ai_controller.reward -= 4.0
scenes/car/car.tscn ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [gd_scene load_steps=16 format=3 uid="uid://c68mety64bigp"]
2
+
3
+ [ext_resource type="Script" path="res://scenes/car/car.gd" id="1_0gshy"]
4
+ [ext_resource type="PackedScene" uid="uid://c7pyws8sguicn" path="res://scenes/blender/car_base.blend" id="2_lbr3a"]
5
+ [ext_resource type="Script" path="res://scenes/car/propeller.gd" id="3_s0gu7"]
6
+ [ext_resource type="Script" path="res://scenes/car/raycast_sensor_3d_add_set_collision_mask_value.gd" id="4_e1dys"]
7
+ [ext_resource type="Script" path="res://scenes/car/car_ai_controller.gd" id="5_e2db2"]
8
+ [ext_resource type="Script" path="res://scenes/car/thruster.gd" id="6_k7k6o"]
9
+
10
+ [sub_resource type="PhysicsMaterial" id="PhysicsMaterial_ypfti"]
11
+ friction = 0.55
12
+
13
+ [sub_resource type="CapsuleShape3D" id="CapsuleShape3D_av0n1"]
14
+ radius = 1.86536
15
+ height = 3.80065
16
+
17
+ [sub_resource type="Gradient" id="Gradient_mgod5"]
18
+ offsets = PackedFloat32Array(0, 0.481113, 0.578529)
19
+ colors = PackedColorArray(1, 0.635294, 0, 1, 0.811765, 0.109804, 0, 0.0235294, 0, 0, 0, 0.0784314)
20
+
21
+ [sub_resource type="GradientTexture1D" id="GradientTexture1D_vuvka"]
22
+ gradient = SubResource("Gradient_mgod5")
23
+
24
+ [sub_resource type="ParticleProcessMaterial" id="ParticleProcessMaterial_3cba4"]
25
+ resource_local_to_scene = true
26
+ direction = Vector3(0, 0, -1)
27
+ spread = 2.0
28
+ initial_velocity_min = 0.02
29
+ initial_velocity_max = 0.1
30
+ gravity = Vector3(0, 0, 0)
31
+ scale_min = 0.5
32
+ color_ramp = SubResource("GradientTexture1D_vuvka")
33
+
34
+ [sub_resource type="Gradient" id="Gradient_nm2v8"]
35
+ colors = PackedColorArray(1, 1, 1, 1, 1, 1, 1, 0)
36
+
37
+ [sub_resource type="GradientTexture2D" id="GradientTexture2D_vf6a5"]
38
+ gradient = SubResource("Gradient_nm2v8")
39
+ fill = 1
40
+ fill_from = Vector2(0.5, 0.5)
41
+ fill_to = Vector2(0, 0.5)
42
+
43
+ [sub_resource type="StandardMaterial3D" id="StandardMaterial3D_618ls"]
44
+ transparency = 1
45
+ shading_mode = 0
46
+ vertex_color_use_as_albedo = true
47
+ albedo_texture = SubResource("GradientTexture2D_vf6a5")
48
+ billboard_mode = 3
49
+ particles_anim_h_frames = 1
50
+ particles_anim_v_frames = 1
51
+ particles_anim_loop = false
52
+
53
+ [sub_resource type="QuadMesh" id="QuadMesh_4n6j1"]
54
+ material = SubResource("StandardMaterial3D_618ls")
55
+ size = Vector2(0.1, 0.1)
56
+
57
+ [node name="Car" type="RigidBody3D"]
58
+ collision_layer = 0
59
+ collision_mask = 0
60
+ axis_lock_linear_y = true
61
+ axis_lock_angular_x = true
62
+ axis_lock_angular_z = true
63
+ physics_material_override = SubResource("PhysicsMaterial_ypfti")
64
+ continuous_cd = true
65
+ max_contacts_reported = 1
66
+ contact_monitor = true
67
+ linear_damp = 1.0
68
+ angular_damp = 1.0
69
+ script = ExtResource("1_0gshy")
70
+
71
+ [node name="car_base" parent="." instance=ExtResource("2_lbr3a")]
72
+
73
+ [node name="Propeller" parent="car_base" index="5"]
74
+ process_mode = 1
75
+ script = ExtResource("3_s0gu7")
76
+
77
+ [node name="Propeller_001" parent="car_base" index="6"]
78
+ process_mode = 1
79
+ script = ExtResource("3_s0gu7")
80
+
81
+ [node name="Propeller_002" parent="car_base" index="7"]
82
+ process_mode = 1
83
+ script = ExtResource("3_s0gu7")
84
+
85
+ [node name="Propeller_003" parent="car_base" index="8"]
86
+ process_mode = 1
87
+ script = ExtResource("3_s0gu7")
88
+
89
+ [node name="CollisionShape3D" type="CollisionShape3D" parent="."]
90
+ transform = Transform3D(0.5, 0, 0, 0, -2.18557e-08, -0.5, 0, 0.5, -2.18557e-08, 0, 0.102682, 4.48839e-09)
91
+ shape = SubResource("CapsuleShape3D_av0n1")
92
+
93
+ [node name="RayCastSensorWall" type="Node3D" parent="."]
94
+ script = ExtResource("4_e1dys")
95
+ n_rays_width = 17.0
96
+ n_rays_height = 1.0
97
+ ray_length = 45.0
98
+ cone_width = 360.0
99
+ cone_height = 0.0
100
+ collide_with_areas = true
101
+
102
+ [node name="@RayCast3D@70840" type="RayCast3D" parent="RayCastSensorWall"]
103
+ target_position = Vector3(-8.26873, 0, -44.2338)
104
+ collide_with_areas = true
105
+
106
+ [node name="@RayCast3D@70841" type="RayCast3D" parent="RayCastSensorWall"]
107
+ target_position = Vector3(-23.6894, 0, -38.2598)
108
+ collide_with_areas = true
109
+
110
+ [node name="@RayCast3D@70842" type="RayCast3D" parent="RayCastSensorWall"]
111
+ target_position = Vector3(-35.9108, 0, -27.1186)
112
+ collide_with_areas = true
113
+
114
+ [node name="@RayCast3D@70843" type="RayCast3D" parent="RayCastSensorWall"]
115
+ target_position = Vector3(-43.2822, 0, -12.3148)
116
+ collide_with_areas = true
117
+
118
+ [node name="@RayCast3D@70844" type="RayCast3D" parent="RayCastSensorWall"]
119
+ target_position = Vector3(-44.808, 0, 4.15208)
120
+ collide_with_areas = true
121
+
122
+ [node name="@RayCast3D@70845" type="RayCast3D" parent="RayCastSensorWall"]
123
+ target_position = Vector3(-40.2823, 0, 20.0582)
124
+ collide_with_areas = true
125
+
126
+ [node name="@RayCast3D@70846" type="RayCast3D" parent="RayCastSensorWall"]
127
+ target_position = Vector3(-30.3163, 0, 33.2554)
128
+ collide_with_areas = true
129
+
130
+ [node name="@RayCast3D@70847" type="RayCast3D" parent="RayCastSensorWall"]
131
+ target_position = Vector3(-16.2559, 0, 41.9613)
132
+ collide_with_areas = true
133
+
134
+ [node name="@RayCast3D@70848" type="RayCast3D" parent="RayCastSensorWall"]
135
+ target_position = Vector3(0, 0, 45)
136
+ collide_with_areas = true
137
+
138
+ [node name="@RayCast3D@70849" type="RayCast3D" parent="RayCastSensorWall"]
139
+ target_position = Vector3(16.2559, 0, 41.9613)
140
+ collide_with_areas = true
141
+
142
+ [node name="@RayCast3D@70850" type="RayCast3D" parent="RayCastSensorWall"]
143
+ target_position = Vector3(30.3163, 0, 33.2554)
144
+ collide_with_areas = true
145
+
146
+ [node name="@RayCast3D@70851" type="RayCast3D" parent="RayCastSensorWall"]
147
+ target_position = Vector3(40.2823, 0, 20.0582)
148
+ collide_with_areas = true
149
+
150
+ [node name="@RayCast3D@70852" type="RayCast3D" parent="RayCastSensorWall"]
151
+ target_position = Vector3(44.808, 0, 4.15208)
152
+ collide_with_areas = true
153
+
154
+ [node name="@RayCast3D@70853" type="RayCast3D" parent="RayCastSensorWall"]
155
+ target_position = Vector3(43.2822, 0, -12.3148)
156
+ collide_with_areas = true
157
+
158
+ [node name="@RayCast3D@70854" type="RayCast3D" parent="RayCastSensorWall"]
159
+ target_position = Vector3(35.9108, 0, -27.1186)
160
+ collide_with_areas = true
161
+
162
+ [node name="@RayCast3D@70855" type="RayCast3D" parent="RayCastSensorWall"]
163
+ target_position = Vector3(23.6894, 0, -38.2598)
164
+ collide_with_areas = true
165
+
166
+ [node name="@RayCast3D@70856" type="RayCast3D" parent="RayCastSensorWall"]
167
+ target_position = Vector3(8.26873, 0, -44.2338)
168
+ collide_with_areas = true
169
+
170
+ [node name="RayCastSensorOtherCar" type="Node3D" parent="."]
171
+ script = ExtResource("4_e1dys")
172
+ collision_mask = 0
173
+ boolean_class_mask = 0
174
+ n_rays_width = 17.0
175
+ n_rays_height = 1.0
176
+ ray_length = 45.0
177
+ cone_width = 360.0
178
+ cone_height = 0.0
179
+ collide_with_areas = true
180
+
181
+ [node name="_RayCast3D_70840" type="RayCast3D" parent="RayCastSensorOtherCar"]
182
+ target_position = Vector3(-8.26873, 0, -44.2338)
183
+ collide_with_areas = true
184
+
185
+ [node name="_RayCast3D_70841" type="RayCast3D" parent="RayCastSensorOtherCar"]
186
+ target_position = Vector3(-23.6894, 0, -38.2598)
187
+ collide_with_areas = true
188
+
189
+ [node name="_RayCast3D_70842" type="RayCast3D" parent="RayCastSensorOtherCar"]
190
+ target_position = Vector3(-35.9108, 0, -27.1186)
191
+ collide_with_areas = true
192
+
193
+ [node name="_RayCast3D_70843" type="RayCast3D" parent="RayCastSensorOtherCar"]
194
+ target_position = Vector3(-43.2822, 0, -12.3148)
195
+ collide_with_areas = true
196
+
197
+ [node name="_RayCast3D_70844" type="RayCast3D" parent="RayCastSensorOtherCar"]
198
+ target_position = Vector3(-44.808, 0, 4.15208)
199
+ collide_with_areas = true
200
+
201
+ [node name="_RayCast3D_70845" type="RayCast3D" parent="RayCastSensorOtherCar"]
202
+ target_position = Vector3(-40.2823, 0, 20.0582)
203
+ collide_with_areas = true
204
+
205
+ [node name="_RayCast3D_70846" type="RayCast3D" parent="RayCastSensorOtherCar"]
206
+ target_position = Vector3(-30.3163, 0, 33.2554)
207
+ collide_with_areas = true
208
+
209
+ [node name="_RayCast3D_70847" type="RayCast3D" parent="RayCastSensorOtherCar"]
210
+ target_position = Vector3(-16.2559, 0, 41.9613)
211
+ collide_with_areas = true
212
+
213
+ [node name="_RayCast3D_70848" type="RayCast3D" parent="RayCastSensorOtherCar"]
214
+ target_position = Vector3(0, 0, 45)
215
+ collide_with_areas = true
216
+
217
+ [node name="_RayCast3D_70849" type="RayCast3D" parent="RayCastSensorOtherCar"]
218
+ target_position = Vector3(16.2559, 0, 41.9613)
219
+ collide_with_areas = true
220
+
221
+ [node name="_RayCast3D_70850" type="RayCast3D" parent="RayCastSensorOtherCar"]
222
+ target_position = Vector3(30.3163, 0, 33.2554)
223
+ collide_with_areas = true
224
+
225
+ [node name="_RayCast3D_70851" type="RayCast3D" parent="RayCastSensorOtherCar"]
226
+ target_position = Vector3(40.2823, 0, 20.0582)
227
+ collide_with_areas = true
228
+
229
+ [node name="_RayCast3D_70852" type="RayCast3D" parent="RayCastSensorOtherCar"]
230
+ target_position = Vector3(44.808, 0, 4.15208)
231
+ collide_with_areas = true
232
+
233
+ [node name="_RayCast3D_70853" type="RayCast3D" parent="RayCastSensorOtherCar"]
234
+ target_position = Vector3(43.2822, 0, -12.3148)
235
+ collide_with_areas = true
236
+
237
+ [node name="_RayCast3D_70854" type="RayCast3D" parent="RayCastSensorOtherCar"]
238
+ target_position = Vector3(35.9108, 0, -27.1186)
239
+ collide_with_areas = true
240
+
241
+ [node name="_RayCast3D_70855" type="RayCast3D" parent="RayCastSensorOtherCar"]
242
+ target_position = Vector3(23.6894, 0, -38.2598)
243
+ collide_with_areas = true
244
+
245
+ [node name="_RayCast3D_70856" type="RayCast3D" parent="RayCastSensorOtherCar"]
246
+ target_position = Vector3(8.26873, 0, -44.2338)
247
+ collide_with_areas = true
248
+
249
+ [node name="CarAIController" type="Node3D" parent="."]
250
+ script = ExtResource("5_e2db2")
251
+ reset_after = 50000
252
+
253
+ [node name="Thruster1Particles" type="GPUParticles3D" parent="."]
254
+ process_mode = 1
255
+ transform = Transform3D(15.625, 0, 0, 0, 15.625, -6.8299e-07, 0, 6.8299e-07, 15.625, 0.106975, -0.128882, -0.737488)
256
+ amount = 32
257
+ lifetime = 0.23
258
+ local_coords = true
259
+ trail_lifetime = 0.2
260
+ process_material = SubResource("ParticleProcessMaterial_3cba4")
261
+ draw_pass_1 = SubResource("QuadMesh_4n6j1")
262
+ script = ExtResource("6_k7k6o")
263
+
264
+ [node name="Thruster2Particles" type="GPUParticles3D" parent="."]
265
+ process_mode = 1
266
+ transform = Transform3D(15.625, 0, 0, 0, 15.625, -6.8299e-07, 0, 6.8299e-07, 15.625, -0.106975, -0.128882, -0.737487)
267
+ amount = 32
268
+ lifetime = 0.23
269
+ local_coords = true
270
+ trail_lifetime = 0.2
271
+ process_material = SubResource("ParticleProcessMaterial_3cba4")
272
+ draw_pass_1 = SubResource("QuadMesh_4n6j1")
273
+ script = ExtResource("6_k7k6o")
274
+
275
+ [node name="Camera3D" type="Camera3D" parent="."]
276
+ transform = Transform3D(-1, -1.90707e-08, 8.53174e-08, 0, 0.975917, 0.218143, -8.74228e-08, 0.218143, -0.975917, 0, 0.94, -3.37)
277
+
278
+ [connection signal="body_entered" from="." to="." method="_on_body_entered"]
279
+ [connection signal="body_exited" from="." to="." method="_on_body_exited"]
280
+
281
+ [editable path="car_base"]
scenes/car/car_ai_controller.gd ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends AIController3D
2
+ class_name CarAIController
3
+
4
+ var track: Track
5
+
6
+ var human_controlled_on_inference: bool
7
+
8
+
9
+ func reset():
10
+ n_steps = 0
11
+ needs_reset = false
12
+
13
+
14
+ func get_obs_for_car(car: Car):
15
+ var player_velocity = car.get_normalized_velocity_in_player_reference()
16
+ var observations: Array = [player_velocity.x, player_velocity.z, car.angular_velocity.y / 5.0]
17
+
18
+ observations.append_array(car.get_next_track_points(3, 20))
19
+ observations.append_array(car.raycast_sensor_wall.get_observation())
20
+ observations.append_array(car.raycast_sensor_other_car.get_observation())
21
+ observations.append_array(car.get_other_car_position_in_local_reference())
22
+
23
+ var closest_powerup = track.get_closest_powerup(car.global_position) as Powerup
24
+ var powerup_relative_position = (
25
+ (car.to_local(closest_powerup.global_position)).limit_length(150) / 150.0
26
+ )
27
+ var powerup_obs: Array[float] = [powerup_relative_position.x, powerup_relative_position.z]
28
+ powerup_obs.append_array(closest_powerup.category_as_array_one_hot_encoded)
29
+ observations.append_array(powerup_obs)
30
+ return observations
31
+
32
+
33
+ func get_obs() -> Dictionary:
34
+ _player.prepare_for_sending_obs()
35
+ return {"obs": get_obs_for_car(_player)}
36
+
37
+
38
+ func get_reward() -> float:
39
+ _player.update_reward()
40
+ return reward
41
+
42
+
43
+ func get_action_space() -> Dictionary:
44
+ return {
45
+ "acceleration": {"size": 1, "action_type": "continuous"},
46
+ "steering": {"size": 1, "action_type": "continuous"},
47
+ }
48
+
49
+
50
+ ## This override disables restarting the episode due to timeout
51
+ func _physics_process(_delta):
52
+ n_steps += 1
53
+
54
+
55
+ func set_action(action) -> void:
56
+ _player.requested_acceleration = clampf(action.acceleration[0], -1.0, 1.0)
57
+ _player.requested_steering = clampf(action.steering[0], -1.0, 1.0)
scenes/car/car_manager.gd ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+
3
+ class_name CarManager
4
+
5
+ @export var track: Track
6
+ @export var car_scene: PackedScene
7
+
8
+ ## Each car group consists of 2 cars
9
+ @export var number_of_car_groups_to_spawn: int = 2
10
+
11
+ var ui: UI
12
+
13
+ var training_mode: bool = true
14
+ var player_vs_ai_mode: bool = false
15
+ var infinite_race: bool = true
16
+ var total_laps: int
17
+ var seconds_until_race_begins: int
18
+
19
+
20
+ # Called when the node enters the scene tree for the first time.
21
+ func _ready():
22
+ spawn_cars(number_of_car_groups_to_spawn)
23
+
24
+
25
+ func spawn_cars(car_group_amount):
26
+ if not training_mode:
27
+ car_group_amount = 1
28
+
29
+ var car1color: Color = Color.from_hsv(randf_range(0, 1), 0.6, 0.6)
30
+ var car2color: Color = car1color
31
+ car2color.h = fmod(car1color.h + randf_range(0.2, 0.8), 1.0)
32
+
33
+ var player_car_id: int = randi_range(0, 1)
34
+
35
+ for group_id in range(0, car_group_amount):
36
+ var spawned_cars: Array[Car] = []
37
+
38
+ for car_id in range(0, 2):
39
+ var car = car_scene.instantiate() as Car
40
+ car.name = "AI-%d%d" % [group_id, car_id]
41
+ car.track = track
42
+
43
+ # Detect collision with walls
44
+ car.set_collision_mask_value(1, true)
45
+
46
+ # Detect collision with other car
47
+ var current_car_layer := 2 + car_id + (group_id * 2)
48
+ var other_car_layer := 2 + ((car_id + 1) % 2) + (group_id * 2)
49
+ car.set_collision_layer_value(current_car_layer, true)
50
+ car.set_collision_mask_value(other_car_layer, true)
51
+
52
+ var car_transform: Transform3D = track.track_path.curve.sample_baked_with_rotation(0.0)
53
+ car_transform = car_transform.rotated_local(Vector3.UP, PI)
54
+ car_transform.origin += Vector3.UP
55
+ car_transform.origin += car_transform.basis.x * (car_id * 2.0 - 1.5)
56
+ car.global_transform = car_transform
57
+
58
+ car.infinite_race = infinite_race
59
+ car.total_laps = total_laps
60
+ car.ui = ui
61
+ car.seconds_until_race_begins = seconds_until_race_begins
62
+ car.training_mode = training_mode
63
+
64
+ var car_body: MeshInstance3D = car.get_node("car_base/Body") as MeshInstance3D
65
+ var new_material: StandardMaterial3D = (
66
+ car_body.get_active_material(0).duplicate() as StandardMaterial3D
67
+ )
68
+
69
+ var color: Color = car1color if car_id == 0 else car2color
70
+ new_material.albedo_color = color
71
+ car_body.set_surface_override_material(0, new_material)
72
+
73
+ spawned_cars.append(car)
74
+ add_child(car)
75
+
76
+ if car_id == 1:
77
+ car.other_car = spawned_cars[0]
78
+ spawned_cars[0].other_car = car
79
+
80
+ if player_vs_ai_mode and player_car_id == car_id:
81
+ car.name = "Player"
82
+ car.get_node("Camera3D").current = true
83
+ car.get_node("CarAIController").human_controlled_on_inference = true
84
+
85
+ # Raycast detect collision with other car
86
+ car.raycast_sensor_other_car.set_collision_mask_value(other_car_layer, true)
87
+ car.ai_controller.track = track
88
+
89
+ car.reset()