diff --git a/.gitattributes b/.gitattributes index 28df5f900b358436f0267334b3e3e9af33f917ba..0157449d0dd1a6725c8de274d8365cba87760832 100644 --- a/.gitattributes +++ b/.gitattributes @@ -53,3 +53,12 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.jpg filter=lfs diff=lfs merge=lfs -text *.jpeg filter=lfs diff=lfs merge=lfs -text *.webp filter=lfs diff=lfs merge=lfs -text +blender/level1.blend filter=lfs diff=lfs merge=lfs -text +blender/level2.blend filter=lfs diff=lfs merge=lfs -text +blender/level3.blend filter=lfs diff=lfs merge=lfs -text +blender/level4.blend filter=lfs diff=lfs merge=lfs -text +blender/level5.blend filter=lfs diff=lfs merge=lfs -text +blender/level6.blend filter=lfs diff=lfs merge=lfs -text +blender/level7.blend filter=lfs diff=lfs merge=lfs -text +blender/level8.blend filter=lfs diff=lfs merge=lfs -text +blender/robot.blend filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2bcd960e6729cdcd618a050b2267773a90e8c7e0 --- /dev/null +++ b/README.md @@ -0,0 +1,25 @@ +--- +library_name: godot-rl +tags: +- deep-reinforcement-learning +- reinforcement-learning +- godot-rl +- environments +- video-games +--- + +A RL environment called MultiLevelRobot for the Godot Game Engine. + +This environment was created with: https://github.com/edbeeching/godot_rl_agents + + +## Downloading the environment + +After installing Godot RL Agents, download the environment with: + +``` +gdrl.env_from_hub -r edbeeching/godot_rl_MultiLevelRobot +``` + + + diff --git a/RobotEnv.csproj b/RobotEnv.csproj new file mode 100644 index 0000000000000000000000000000000000000000..435059a3c54cfc3fa495a9efba51bbaf02e59199 --- /dev/null +++ b/RobotEnv.csproj @@ -0,0 +1,10 @@ + + + net6.0 + true + GodotRLAgents + + + + + \ No newline at end of file diff --git a/RobotEnv.sln b/RobotEnv.sln new file mode 100644 index 0000000000000000000000000000000000000000..5a87fcbf353b96b2b353e2b4d1cbf09d05028bbb --- /dev/null +++ b/RobotEnv.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RobotEnv", "RobotEnv.csproj", "{C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + ExportDebug|Any CPU = ExportDebug|Any CPU + ExportRelease|Any CPU = ExportRelease|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU + {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU + {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU + {C8D3517D-AA7F-40D8-B8D8-6FD3D270B2B9}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU + EndGlobalSection +EndGlobal diff --git a/addons/godot_rl_agents/controller/ai_controller_2d.gd b/addons/godot_rl_agents/controller/ai_controller_2d.gd new file mode 100644 index 0000000000000000000000000000000000000000..e9080f0115c0729a12ace5f712c9e41e7ed252e4 --- /dev/null +++ b/addons/godot_rl_agents/controller/ai_controller_2d.gd @@ -0,0 +1,82 @@ +extends Node2D +class_name AIController2D + +@export var reset_after := 1000 + +var heuristic := "human" +var done := false +var reward := 0.0 +var n_steps := 0 +var needs_reset := false + +var _player: Node2D + +func _ready(): + add_to_group("AGENT") + +func init(player: Node2D): + _player = player + +#-- Methods that need implementing using the "extend script" option in Godot --# +func get_obs() -> Dictionary: + assert(false, "the get_obs method is not implemented when extending from ai_controller") + return {"obs":[]} + +func get_reward() -> float: + assert(false, "the get_reward method is not implemented when extending from ai_controller") + return 0.0 + +func get_action_space() -> Dictionary: + assert(false, "the get get_action_space method is not implemented when extending from ai_controller") + return { + "example_actions_continous" : { + "size": 2, + "action_type": "continuous" + }, + "example_actions_discrete" : { + "size": 2, + "action_type": "discrete" + }, + } + +func set_action(action) -> void: + assert(false, "the get set_action method is not implemented when extending from ai_controller") +# -----------------------------------------------------------------------------# + +func _physics_process(delta): + n_steps += 1 + if n_steps > reset_after: + needs_reset = true + +func get_obs_space(): + # may need overriding if the obs space is complex + var obs = get_obs() + return { + "obs": { + "size": [len(obs["obs"])], + "space": "box" + }, + } + +func reset(): + n_steps = 0 + needs_reset = false + +func reset_if_done(): + if done: + reset() + +func set_heuristic(h): + # sets the heuristic from "human" or "model" nothing to change here + heuristic = h + +func get_done(): + return done + +func set_done_false(): + done = false + +func zero_reward(): + reward = 0.0 + + diff --git a/addons/godot_rl_agents/controller/ai_controller_3d.gd b/addons/godot_rl_agents/controller/ai_controller_3d.gd new file mode 100644 index 0000000000000000000000000000000000000000..d256b2acf9697d69b7b9fc31f5b0a0c708c7e2ae --- /dev/null +++ b/addons/godot_rl_agents/controller/ai_controller_3d.gd @@ -0,0 +1,80 @@ +extends Node3D +class_name AIController3D + +@export var reset_after := 1000 + +var heuristic := "human" +var done := false +var reward := 0.0 +var n_steps := 0 +var needs_reset := false + +var _player: Node3D + +func _ready(): + add_to_group("AGENT") + +func init(player: Node3D): + _player = player + +#-- Methods that need implementing using the "extend script" option in Godot --# +func get_obs() -> Dictionary: + assert(false, "the get_obs method is not implemented when extending from ai_controller") + return {"obs":[]} + +func get_reward() -> float: + assert(false, "the get_reward method is not implemented when extending from ai_controller") + return 0.0 + +func get_action_space() -> Dictionary: + assert(false, "the get get_action_space method is not implemented when extending from ai_controller") + return { + "example_actions_continous" : { + "size": 2, + "action_type": "continuous" + }, + "example_actions_discrete" : { + "size": 2, + "action_type": "discrete" + }, + } + +func set_action(action) -> void: + assert(false, "the get set_action method is not implemented when extending from ai_controller") +# -----------------------------------------------------------------------------# + +func _physics_process(delta): + n_steps += 1 + if n_steps > reset_after: + needs_reset = true + +func get_obs_space(): + # may need overriding if the obs space is complex + var obs = get_obs() + return { + "obs": { + "size": [len(obs["obs"])], + "space": "box" + }, + } + +func reset(): + n_steps = 0 + needs_reset = false + +func reset_if_done(): + if done: + reset() + +func set_heuristic(h): + # sets the heuristic from "human" or "model" nothing to change here + heuristic = h + +func get_done(): + return done + +func set_done_false(): + done = false + +func zero_reward(): + reward = 0.0 diff --git a/addons/godot_rl_agents/godot_rl_agents.gd b/addons/godot_rl_agents/godot_rl_agents.gd new file mode 100644 index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296 --- /dev/null +++ b/addons/godot_rl_agents/godot_rl_agents.gd @@ -0,0 +1,16 @@ +@tool +extends EditorPlugin + + +func _enter_tree(): + # Initialization of the plugin goes here. + # Add the new type with a name, a parent type, a script and an icon. + add_custom_type("Sync", "Node", preload("sync.gd"), preload("icon.png")) + #add_custom_type("RaycastSensor2D2", "Node", preload("raycast_sensor_2d.gd"), preload("icon.png")) + + +func _exit_tree(): + # Clean-up of the plugin goes here. + # Always remember to remove it from the engine when deactivated. + remove_custom_type("Sync") + #remove_custom_type("RaycastSensor2D2") diff --git a/addons/godot_rl_agents/icon.png b/addons/godot_rl_agents/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d --- /dev/null +++ b/addons/godot_rl_agents/icon.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e3a8bc372d3313ce1ede4e7554472e37b322178b9488bfb709e296585abd3c44 +size 198 diff --git a/addons/godot_rl_agents/icon.png.import b/addons/godot_rl_agents/icon.png.import new file mode 100644 index 0000000000000000000000000000000000000000..e8510ca4a85c28f11e1943102d9009941b037a1b --- /dev/null +++ b/addons/godot_rl_agents/icon.png.import @@ -0,0 +1,34 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://d3feirleqrsjv" +path="res://.godot/imported/icon.png-45a871b53434e556222f5901d598ab34.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://addons/godot_rl_agents/icon.png" +dest_files=["res://.godot/imported/icon.png-45a871b53434e556222f5901d598ab34.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 diff --git a/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs new file mode 100644 index 0000000000000000000000000000000000000000..0741f0f263f34fffc44993e2b11a7544b0384ca1 --- /dev/null +++ b/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs @@ -0,0 +1,103 @@ +using Godot; +using Microsoft.ML.OnnxRuntime; +using Microsoft.ML.OnnxRuntime.Tensors; +using System.Collections.Generic; +using System.Linq; + +namespace GodotONNX +{ + /// + public partial class ONNXInference : GodotObject + { + + private InferenceSession session; + /// + /// Path to the ONNX model. Use Initialize to change it. + /// + private string modelPath; + private int batchSize; + + private SessionOptions SessionOpt; + + //init function + /// + public void Initialize(string Path, int BatchSize) + { + modelPath = Path; + batchSize = BatchSize; + SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions(); + session = LoadModel(modelPath); + + } + /// + public Godot.Collections.Dictionary> RunInference(Godot.Collections.Array obs, int state_ins) + { + //Current model: Any (Godot Rl Agents) + //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 + + //Fill the input tensors + // create span from inputSize + var span = new float[obs.Count]; //There's probably a better way to do this + for (int i = 0; i < obs.Count; i++) + { + span[i] = obs[i]; + } + + IReadOnlyCollection inputs = new List + { + NamedOnnxValue.CreateFromTensor("obs", new DenseTensor(span, new int[] { batchSize, obs.Count })), + NamedOnnxValue.CreateFromTensor("state_ins", new DenseTensor(new float[] { state_ins }, new int[] { batchSize })) + }; + IReadOnlyCollection outputNames = new List { "output", "state_outs" }; //ONNX is sensible to these names, as well as the input names + + IDisposableReadOnlyCollection results; + //We do not use "using" here so we get a better exception explaination later + try + { + results = session.Run(inputs, outputNames); + } + catch (OnnxRuntimeException e) + { + //This error usually means that the model is not compatible with the input, beacause of the input shape (size) + GD.Print("Error at inference: ", e); + return null; + } + //Can't convert IEnumerable to Variant, so we have to convert it to an array or something + Godot.Collections.Dictionary> output = new Godot.Collections.Dictionary>(); + DisposableNamedOnnxValue output1 = results.First(); + DisposableNamedOnnxValue output2 = results.Last(); + Godot.Collections.Array output1Array = new Godot.Collections.Array(); + Godot.Collections.Array output2Array = new Godot.Collections.Array(); + + foreach (float f in output1.AsEnumerable()) + { + output1Array.Add(f); + } + + foreach (float f in output2.AsEnumerable()) + { + output2Array.Add(f); + } + + output.Add(output1.Name, output1Array); + output.Add(output2.Name, output2Array); + + //Output is a dictionary of arrays, ex: { "output" : [0.1, 0.2, 0.3, 0.4, ...], "state_outs" : [0.5, ...]} + results.Dispose(); + return output; + } + /// + public InferenceSession LoadModel(string Path) + { + using Godot.FileAccess file = FileAccess.Open(Path, Godot.FileAccess.ModeFlags.Read); + byte[] model = file.GetBuffer((int)file.GetLength()); + //file.Close(); file.Dispose(); //Close the file, then dispose the reference. + return new InferenceSession(model, SessionOpt); //Load the model + } + public void FreeDisposables() + { + session.Dispose(); + SessionOpt.Dispose(); + } + } +} diff --git a/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs new file mode 100644 index 0000000000000000000000000000000000000000..ad7a41cfee0dc3d497d9c1d03bd0752b09d49f3a --- /dev/null +++ b/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs @@ -0,0 +1,131 @@ +using Godot; +using Microsoft.ML.OnnxRuntime; + +namespace GodotONNX +{ + /// + + public static class SessionConfigurator + { + public enum ComputeName + { + CUDA, + ROCm, + DirectML, + CoreML, + CPU + } + + /// + public static SessionOptions MakeConfiguredSessionOptions() + { + SessionOptions sessionOptions = new(); + SetOptions(sessionOptions); + return sessionOptions; + } + + private static void SetOptions(SessionOptions sessionOptions) + { + sessionOptions.LogSeverityLevel = OrtLoggingLevel.ORT_LOGGING_LEVEL_WARNING; + ApplySystemSpecificOptions(sessionOptions); + } + + /// + static public void ApplySystemSpecificOptions(SessionOptions sessionOptions) + { + //Most code for this function is verbose only, the only reason it exists is to track + //implementation progress of the different compute APIs. + + //December 2022: CUDA is not working. + + string OSName = OS.GetName(); //Get OS Name + + //ComputeName ComputeAPI = ComputeCheck(); //Get Compute API + // //TODO: Get CPU architecture + + //Linux can use OpenVINO (C#) on x64 and ROCm on x86 (GDNative/C++) + //Windows can use OpenVINO (C#) on x64 + //TODO: try TensorRT instead of CUDA + //TODO: Use OpenVINO for Intel Graphics + + // Temporarily using CPU on all platforms to avoid errors detected with DML + ComputeName ComputeAPI = ComputeName.CPU; + + //match OS and Compute API + GD.Print($"OS: {OSName} Compute API: {ComputeAPI}"); + + // CPU is set by default without appending necessary + // sessionOptions.AppendExecutionProvider_CPU(0); + + /* + switch (OSName) + { + case "Windows": //Can use CUDA, DirectML + if (ComputeAPI is ComputeName.CUDA) + { + //CUDA + //sessionOptions.AppendExecutionProvider_CUDA(0); + //sessionOptions.AppendExecutionProvider_DML(0); + } + else if (ComputeAPI is ComputeName.DirectML) + { + //DirectML + //sessionOptions.AppendExecutionProvider_DML(0); + } + break; + case "X11": //Can use CUDA, ROCm + if (ComputeAPI is ComputeName.CUDA) + { + //CUDA + //sessionOptions.AppendExecutionProvider_CUDA(0); + } + if (ComputeAPI is ComputeName.ROCm) + { + //ROCm, only works on x86 + //Research indicates that this has to be compiled as a GDNative plugin + //GD.Print("ROCm not supported yet, using CPU."); + //sessionOptions.AppendExecutionProvider_CPU(0); + } + break; + case "macOS": //Can use CoreML + if (ComputeAPI is ComputeName.CoreML) + { //CoreML + //TODO: Needs testing + //sessionOptions.AppendExecutionProvider_CoreML(0); + //CoreML on ARM64, out of the box, on x64 needs .tar file from GitHub + } + break; + default: + GD.Print("OS not Supported."); + break; + } + */ + } + + + /// + public static ComputeName ComputeCheck() + { + string adapterName = Godot.RenderingServer.GetVideoAdapterName(); + //string adapterVendor = Godot.RenderingServer.GetVideoAdapterVendor(); + adapterName = adapterName.ToUpper(new System.Globalization.CultureInfo("")); + //TODO: GPU vendors for MacOS, what do they even use these days? + + if (adapterName.Contains("INTEL")) + { + return ComputeName.DirectML; + } + if (adapterName.Contains("AMD") || adapterName.Contains("RADEON")) + { + return ComputeName.DirectML; + } + if (adapterName.Contains("NVIDIA")) + { + return ComputeName.CUDA; + } + + GD.Print("Graphics Card not recognized."); //Should use CPU + return ComputeName.CPU; + } + } +} diff --git a/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml new file mode 100644 index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8 --- /dev/null +++ b/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml @@ -0,0 +1,31 @@ + + + + + The main ONNXInference Class that handles the inference process. + + + + + Starts the inference process. + + Path to the ONNX model, expects a path inside resources. + How many observations will the model recieve. + + + + Runs the given input through the model and returns the output. + + Dictionary containing all observations. + How many different agents are creating these observations. + A Dictionary of arrays, containing instructions based on the observations. + + + + Loads the given model into the inference process, using the best Execution provider available. + + Path to the ONNX model, expects a path inside resources. + InferenceSession ready to run. + + + \ No newline at end of file diff --git a/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml new file mode 100644 index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2 --- /dev/null +++ b/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml @@ -0,0 +1,29 @@ + + + + + The main SessionConfigurator Class that handles the execution options and providers for the inference process. + + + + + Creates a SessionOptions with all available execution providers. + + SessionOptions with all available execution providers. + + + + Appends any execution provider available in the current system. + + + This function is mainly verbose for tracking implementation progress of different compute APIs. + + + + + Checks for available GPUs. + + An integer identifier for each compute platform. + + + \ No newline at end of file diff --git a/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd new file mode 100644 index 0000000000000000000000000000000000000000..c7b14b350db11cb32f433e6b6cff6470d6cda7cf --- /dev/null +++ b/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd @@ -0,0 +1,24 @@ +extends Resource +class_name ONNXModel +var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs") + +var inferencer = null + +# Must provide the path to the model and the batch size +func _init(model_path, batch_size): + inferencer = inferencer_script.new() + inferencer.Initialize(model_path, batch_size) + +# This function is the one that will be called from the game, +# requires the observation as an array and the state_ins as an int +# returns an Array containing the action the model takes. +func run_inference(obs : Array, state_ins : int) -> Dictionary: + if inferencer == null: + printerr("Inferencer not initialized") + return {} + return inferencer.RunInference(obs, state_ins) + +func _notification(what): + if what == NOTIFICATION_PREDELETE: + inferencer.FreeDisposables() + inferencer.free() diff --git a/addons/godot_rl_agents/plugin.cfg b/addons/godot_rl_agents/plugin.cfg new file mode 100644 index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d --- /dev/null +++ b/addons/godot_rl_agents/plugin.cfg @@ -0,0 +1,7 @@ +[plugin] + +name="GodotRLAgents" +description="Custom nodes for the godot rl agents toolkit " +author="Edward Beeching" +version="0.1" +script="godot_rl_agents.gd" diff --git a/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn @@ -0,0 +1,48 @@ +[gd_scene load_steps=5 format=3 uid="uid://ddeq7mn1ealyc"] + +[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"] + +[sub_resource type="GDScript" id="2"] +script/source = "extends Node2D + + + +func _physics_process(delta: float) -> void: + print(\"step start\") + +" + +[sub_resource type="GDScript" id="1"] +script/source = "extends RayCast2D + +var steps = 1 + +func _physics_process(delta: float) -> void: + print(\"processing raycast\") + steps += 1 + if steps % 2: + force_raycast_update() + + print(is_colliding()) +" + +[sub_resource type="CircleShape2D" id="3"] + +[node name="ExampleRaycastSensor2D" type="Node2D"] +script = SubResource("2") + +[node name="ExampleAgent" type="Node2D" parent="."] +position = Vector2(573, 314) +rotation = 0.286234 + +[node name="RaycastSensor2D" type="Node2D" parent="ExampleAgent"] +script = ExtResource("1") + +[node name="TestRayCast2D" type="RayCast2D" parent="."] +script = SubResource("1") + +[node name="StaticBody2D" type="StaticBody2D" parent="."] +position = Vector2(1, 52) + +[node name="CollisionShape2D" type="CollisionShape2D" parent="StaticBody2D"] +shape = SubResource("3") diff --git a/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..12f29570b72916d60a6bae6fc2fb0a9ddbcd0be2 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd @@ -0,0 +1,216 @@ +@tool +extends ISensor2D +class_name GridSensor2D + +@export var debug_view := false: + get: return debug_view + set(value): + debug_view = value + _update() + +@export_flags_2d_physics var detection_mask := 0: + get: return detection_mask + set(value): + detection_mask = value + _update() + +@export var collide_with_areas := false: + get: return collide_with_areas + set(value): + collide_with_areas = value + _update() + +@export var collide_with_bodies := true: + get: return collide_with_bodies + set(value): + collide_with_bodies = value + _update() + +@export_range(1, 200, 0.1) var cell_width := 20.0: + get: return cell_width + set(value): + cell_width = value + _update() + +@export_range(1, 200, 0.1) var cell_height := 20.0: + get: return cell_height + set(value): + cell_height = value + _update() + +@export_range(1, 21, 2, "or_greater") var grid_size_x := 3: + get: return grid_size_x + set(value): + grid_size_x = value + _update() + +@export_range(1, 21, 2, "or_greater") var grid_size_y := 3: + get: return grid_size_y + set(value): + grid_size_y = value + _update() + +var _obs_buffer: PackedFloat64Array +var _rectangle_shape: RectangleShape2D +var _collision_mapping: Dictionary +var _n_layers_per_cell: int + +var _highlighted_cell_color: Color +var _standard_cell_color: Color + +func get_observation(): + return _obs_buffer + +func _update(): + if Engine.is_editor_hint(): + if is_node_ready(): + _spawn_nodes() + +func _ready() -> void: + _set_colors() + + if Engine.is_editor_hint(): + if get_child_count() == 0: + _spawn_nodes() + else: + _spawn_nodes() + + +func _set_colors() -> void: + _standard_cell_color = Color(100.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0) + _highlighted_cell_color = Color(255.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0) + +func _get_collision_mapping() -> Dictionary: + # defines which layer is mapped to which cell obs index + var total_bits = 0 + var collision_mapping = {} + for i in 32: + var bit_mask = 2**i + if (detection_mask & bit_mask) > 0: + collision_mapping[i] = total_bits + total_bits += 1 + + return collision_mapping + +func _spawn_nodes(): + for cell in get_children(): + cell.name = "_%s" % cell.name # Otherwise naming below will fail + cell.queue_free() + + _collision_mapping = _get_collision_mapping() + #prints("collision_mapping", _collision_mapping, len(_collision_mapping)) + # allocate memory for the observations + _n_layers_per_cell = len(_collision_mapping) + _obs_buffer = PackedFloat64Array() + _obs_buffer.resize(grid_size_x*grid_size_y*_n_layers_per_cell) + _obs_buffer.fill(0) + #prints(len(_obs_buffer), _obs_buffer ) + + _rectangle_shape = RectangleShape2D.new() + _rectangle_shape.set_size(Vector2(cell_width, cell_height)) + + var shift := Vector2( + -(grid_size_x/2)*cell_width, + -(grid_size_y/2)*cell_height, + ) + + for i in grid_size_x: + for j in grid_size_y: + var cell_position = Vector2(i*cell_width, j*cell_height) + shift + _create_cell(i, j, cell_position) + + +func _create_cell(i:int, j:int, position: Vector2): + var cell : = Area2D.new() + cell.position = position + cell.name = "GridCell %s %s" %[i, j] + cell.modulate = _standard_cell_color + + if collide_with_areas: + cell.area_entered.connect(_on_cell_area_entered.bind(i, j)) + cell.area_exited.connect(_on_cell_area_exited.bind(i, j)) + + if collide_with_bodies: + cell.body_entered.connect(_on_cell_body_entered.bind(i, j)) + cell.body_exited.connect(_on_cell_body_exited.bind(i, j)) + + cell.collision_layer = 0 + cell.collision_mask = detection_mask + cell.monitorable = true + add_child(cell) + cell.set_owner(get_tree().edited_scene_root) + + var col_shape : = CollisionShape2D.new() + col_shape.shape = _rectangle_shape + col_shape.name = "CollisionShape2D" + cell.add_child(col_shape) + col_shape.set_owner(get_tree().edited_scene_root) + + if debug_view: + var quad = MeshInstance2D.new() + quad.name = "MeshInstance2D" + var quad_mesh = QuadMesh.new() + + quad_mesh.set_size(Vector2(cell_width, cell_height)) + + quad.mesh = quad_mesh + cell.add_child(quad) + quad.set_owner(get_tree().edited_scene_root) + +func _update_obs(cell_i:int, cell_j:int, collision_layer:int, entered: bool): + for key in _collision_mapping: + var bit_mask = 2**key + if (collision_layer & bit_mask) > 0: + var collison_map_index = _collision_mapping[key] + + var obs_index = ( + (cell_i * grid_size_x * _n_layers_per_cell) + + (cell_j * _n_layers_per_cell) + + collison_map_index + ) + #prints(obs_index, cell_i, cell_j) + if entered: + _obs_buffer[obs_index] += 1 + else: + _obs_buffer[obs_index] -= 1 + +func _toggle_cell(cell_i:int, cell_j:int): + var cell = get_node_or_null("GridCell %s %s" %[cell_i, cell_j]) + + if cell == null: + print("cell not found, returning") + + var n_hits = 0 + var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell) + for i in _n_layers_per_cell: + n_hits += _obs_buffer[start_index+i] + + if n_hits > 0: + cell.modulate = _highlighted_cell_color + else: + cell.modulate = _standard_cell_color + +func _on_cell_area_entered(area:Area2D, cell_i:int, cell_j:int): + #prints("_on_cell_area_entered", cell_i, cell_j) + _update_obs(cell_i, cell_j, area.collision_layer, true) + if debug_view: + _toggle_cell(cell_i, cell_j) + #print(_obs_buffer) + +func _on_cell_area_exited(area:Area2D, cell_i:int, cell_j:int): + #prints("_on_cell_area_exited", cell_i, cell_j) + _update_obs(cell_i, cell_j, area.collision_layer, false) + if debug_view: + _toggle_cell(cell_i, cell_j) + +func _on_cell_body_entered(body: Node2D, cell_i:int, cell_j:int): + #prints("_on_cell_body_entered", cell_i, cell_j) + _update_obs(cell_i, cell_j, body.collision_layer, true) + if debug_view: + _toggle_cell(cell_i, cell_j) + +func _on_cell_body_exited(body: Node2D, cell_i:int, cell_j:int): + #prints("_on_cell_body_exited", cell_i, cell_j) + _update_obs(cell_i, cell_j, body.collision_layer, false) + if debug_view: + _toggle_cell(cell_i, cell_j) diff --git a/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..ec20f08a8d37cf1232fc12d8ee4f23b5ba845602 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd @@ -0,0 +1,20 @@ +extends Node2D +class_name ISensor2D + +var _obs : Array = [] +var _active := false + +func get_observation(): + pass + +func activate(): + _active = true + +func deactivate(): + _active = false + +func _update_observation(): + pass + +func reset(): + pass diff --git a/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..09363c409f59b0ef1d68131b77c0a2cba71805d8 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd @@ -0,0 +1,118 @@ +@tool +extends ISensor2D +class_name RaycastSensor2D + +@export_flags_2d_physics var collision_mask := 1: + get: return collision_mask + set(value): + collision_mask = value + _update() + +@export var collide_with_areas := false: + get: return collide_with_areas + set(value): + collide_with_areas = value + _update() + +@export var collide_with_bodies := true: + get: return collide_with_bodies + set(value): + collide_with_bodies = value + _update() + +@export var n_rays := 16.0: + get: return n_rays + set(value): + n_rays = value + _update() + +@export_range(5,200,5.0) var ray_length := 200: + get: return ray_length + set(value): + ray_length = value + _update() +@export_range(5,360,5.0) var cone_width := 360.0: + get: return cone_width + set(value): + cone_width = value + _update() + +@export var debug_draw := true : + get: return debug_draw + set(value): + debug_draw = value + _update() + + +var _angles = [] +var rays := [] + +func _update(): + if Engine.is_editor_hint(): + if debug_draw: + _spawn_nodes() + else: + for ray in get_children(): + if ray is RayCast2D: + remove_child(ray) + +func _ready() -> void: + _spawn_nodes() + +func _spawn_nodes(): + for ray in rays: + ray.queue_free() + rays = [] + + _angles = [] + var step = cone_width / (n_rays) + var start = step/2 - cone_width/2 + + for i in n_rays: + var angle = start + i * step + var ray = RayCast2D.new() + ray.set_target_position(Vector2( + ray_length*cos(deg_to_rad(angle)), + ray_length*sin(deg_to_rad(angle)) + )) + ray.set_name("node_"+str(i)) + ray.enabled = true + ray.collide_with_areas = collide_with_areas + ray.collide_with_bodies = collide_with_bodies + ray.collision_mask = collision_mask + add_child(ray) + rays.append(ray) + + + _angles.append(start + i * step) + + +func _physics_process(delta: float) -> void: + if self._active: + self._obs = calculate_raycasts() + +func get_observation() -> Array: + if len(self._obs) == 0: + print("obs was null, forcing raycast update") + return self.calculate_raycasts() + return self._obs + + +func calculate_raycasts() -> Array: + var result = [] + for ray in rays: + ray.force_raycast_update() + var distance = _get_raycast_distance(ray) + result.append(distance) + return result + +func _get_raycast_distance(ray : RayCast2D) -> float : + if !ray.is_colliding(): + return 0.0 + + var distance = (global_position - ray.get_collision_point()).length() + distance = clamp(distance, 0.0, ray_length) + return (ray_length - distance) / ray_length + + + diff --git a/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn @@ -0,0 +1,7 @@ +[gd_scene load_steps=2 format=3 uid="uid://drvfihk5esgmv"] + +[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd" id="1"] + +[node name="RaycastSensor2D" type="Node2D"] +script = ExtResource("1") +n_rays = 17.0 diff --git a/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn @@ -0,0 +1,6 @@ +[gd_scene format=3 uid="uid://biu787qh4woik"] + +[node name="ExampleRaycastSensor3D" type="Node3D"] + +[node name="Camera3D" type="Camera3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.804183, 0, 2.70146) diff --git a/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..cfce8a84b57661c40662f7b2d53ea5243da54b7e --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd @@ -0,0 +1,233 @@ +@tool +extends ISensor3D +class_name GridSensor3D + +@export var debug_view := false: + get: return debug_view + set(value): + debug_view = value + _update() + +@export_flags_3d_physics var detection_mask := 0: + get: return detection_mask + set(value): + detection_mask = value + _update() + +@export var collide_with_areas := false: + get: return collide_with_areas + set(value): + collide_with_areas = value + _update() + +@export var collide_with_bodies := false: + # NOTE! The sensor will not detect StaticBody3D, add an area to static bodies to detect them + get: return collide_with_bodies + set(value): + collide_with_bodies = value + _update() + +@export_range(0.1, 2, 0.1) var cell_width := 1.0: + get: return cell_width + set(value): + cell_width = value + _update() + +@export_range(0.1, 2, 0.1) var cell_height := 1.0: + get: return cell_height + set(value): + cell_height = value + _update() + +@export_range(1, 21, 2, "or_greater") var grid_size_x := 3: + get: return grid_size_x + set(value): + grid_size_x = value + _update() + +@export_range(1, 21, 2, "or_greater") var grid_size_z := 3: + get: return grid_size_z + set(value): + grid_size_z = value + _update() + +var _obs_buffer: PackedFloat64Array +var _box_shape: BoxShape3D +var _collision_mapping: Dictionary +var _n_layers_per_cell: int + +var _highlighted_box_material: StandardMaterial3D +var _standard_box_material: StandardMaterial3D + +func get_observation(): + return _obs_buffer + +func reset(): + _obs_buffer.fill(0) + +func _update(): + if Engine.is_editor_hint(): + if is_node_ready(): + _spawn_nodes() + +func _ready() -> void: + _make_materials() + + if Engine.is_editor_hint(): + if get_child_count() == 0: + _spawn_nodes() + else: + _spawn_nodes() + +func _make_materials() -> void: + if _highlighted_box_material != null and _standard_box_material != null: + return + + _standard_box_material = StandardMaterial3D.new() + _standard_box_material.set_transparency(1) # ALPHA + _standard_box_material.albedo_color = Color(100.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0) + + _highlighted_box_material = StandardMaterial3D.new() + _highlighted_box_material.set_transparency(1) # ALPHA + _highlighted_box_material.albedo_color = Color(255.0/255.0, 100.0/255.0, 100.0/255.0, 100.0/255.0) + +func _get_collision_mapping() -> Dictionary: + # defines which layer is mapped to which cell obs index + var total_bits = 0 + var collision_mapping = {} + for i in 32: + var bit_mask = 2**i + if (detection_mask & bit_mask) > 0: + collision_mapping[i] = total_bits + total_bits += 1 + + return collision_mapping + +func _spawn_nodes(): + for cell in get_children(): + cell.name = "_%s" % cell.name # Otherwise naming below will fail + cell.queue_free() + + _collision_mapping = _get_collision_mapping() + #prints("collision_mapping", _collision_mapping, len(_collision_mapping)) + # allocate memory for the observations + _n_layers_per_cell = len(_collision_mapping) + _obs_buffer = PackedFloat64Array() + _obs_buffer.resize(grid_size_x*grid_size_z*_n_layers_per_cell) + _obs_buffer.fill(0) + #prints(len(_obs_buffer), _obs_buffer ) + + _box_shape = BoxShape3D.new() + _box_shape.set_size(Vector3(cell_width, cell_height, cell_width)) + + var shift := Vector3( + -(grid_size_x/2)*cell_width, + 0, + -(grid_size_z/2)*cell_width, + ) + + for i in grid_size_x: + for j in grid_size_z: + var cell_position = Vector3(i*cell_width, 0.0, j*cell_width) + shift + _create_cell(i, j, cell_position) + + +func _create_cell(i:int, j:int, position: Vector3): + var cell : = Area3D.new() + cell.position = position + cell.name = "GridCell %s %s" %[i, j] + + if collide_with_areas: + cell.area_entered.connect(_on_cell_area_entered.bind(i, j)) + cell.area_exited.connect(_on_cell_area_exited.bind(i, j)) + + if collide_with_bodies: + cell.body_entered.connect(_on_cell_body_entered.bind(i, j)) + cell.body_exited.connect(_on_cell_body_exited.bind(i, j)) + +# cell.body_shape_entered.connect(_on_cell_body_shape_entered.bind(i, j)) +# cell.body_shape_exited.connect(_on_cell_body_shape_exited.bind(i, j)) + + cell.collision_layer = 0 + cell.collision_mask = detection_mask + cell.monitorable = true + cell.input_ray_pickable = false + add_child(cell) + cell.set_owner(get_tree().edited_scene_root) + + var col_shape : = CollisionShape3D.new() + col_shape.shape = _box_shape + col_shape.name = "CollisionShape3D" + cell.add_child(col_shape) + col_shape.set_owner(get_tree().edited_scene_root) + + if debug_view: + var box = MeshInstance3D.new() + box.name = "MeshInstance3D" + var box_mesh = BoxMesh.new() + + box_mesh.set_size(Vector3(cell_width, cell_height, cell_width)) + box_mesh.material = _standard_box_material + + box.mesh = box_mesh + cell.add_child(box) + box.set_owner(get_tree().edited_scene_root) + +func _update_obs(cell_i:int, cell_j:int, collision_layer:int, entered: bool): + for key in _collision_mapping: + var bit_mask = 2**key + if (collision_layer & bit_mask) > 0: + var collison_map_index = _collision_mapping[key] + + var obs_index = ( + (cell_i * grid_size_x * _n_layers_per_cell) + + (cell_j * _n_layers_per_cell) + + collison_map_index + ) + #prints(obs_index, cell_i, cell_j) + if entered: + _obs_buffer[obs_index] += 1 + else: + _obs_buffer[obs_index] -= 1 + +func _toggle_cell(cell_i:int, cell_j:int): + var cell = get_node_or_null("GridCell %s %s" %[cell_i, cell_j]) + + if cell == null: + print("cell not found, returning") + + var n_hits = 0 + var start_index = (cell_i * grid_size_x * _n_layers_per_cell) + (cell_j * _n_layers_per_cell) + for i in _n_layers_per_cell: + n_hits += _obs_buffer[start_index+i] + + var cell_mesh = cell.get_node_or_null("MeshInstance3D") + if n_hits > 0: + cell_mesh.mesh.material = _highlighted_box_material + else: + cell_mesh.mesh.material = _standard_box_material + +func _on_cell_area_entered(area:Area3D, cell_i:int, cell_j:int): + #prints("_on_cell_area_entered", cell_i, cell_j) + _update_obs(cell_i, cell_j, area.collision_layer, true) + if debug_view: + _toggle_cell(cell_i, cell_j) + #print(_obs_buffer) + +func _on_cell_area_exited(area:Area3D, cell_i:int, cell_j:int): + #prints("_on_cell_area_exited", cell_i, cell_j) + _update_obs(cell_i, cell_j, area.collision_layer, false) + if debug_view: + _toggle_cell(cell_i, cell_j) + +func _on_cell_body_entered(body: Node3D, cell_i:int, cell_j:int): + #prints("_on_cell_body_entered", cell_i, cell_j) + _update_obs(cell_i, cell_j, body.collision_layer, true) + if debug_view: + _toggle_cell(cell_i, cell_j) + +func _on_cell_body_exited(body: Node3D, cell_i:int, cell_j:int): + #prints("_on_cell_body_exited", cell_i, cell_j) + _update_obs(cell_i, cell_j, body.collision_layer, false) + if debug_view: + _toggle_cell(cell_i, cell_j) diff --git a/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..d57503b5006e9384c4a9ce7de348d74a5b58d322 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd @@ -0,0 +1,20 @@ +extends Node3D +class_name ISensor3D + +var _obs : Array = [] +var _active := false + +func get_observation(): + pass + +func activate(): + _active = true + +func deactivate(): + _active = false + +func _update_observation(): + pass + +func reset(): + pass diff --git a/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..959bc5a7e07b09a526e52671d91dee30813da962 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd @@ -0,0 +1,11 @@ +extends Node3D +class_name RGBCameraSensor3D +var camera_pixels = null + +@onready var camera_texture := $Control/TextureRect/CameraTexture as Sprite2D + +func get_camera_pixel_encoding(): + return camera_texture.get_texture().get_data().data["data"].hex_encode() + +func get_camera_shape()-> Array: + return [$SubViewport.size[0], $SubViewport.size[1], 4] diff --git a/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..052b5577db16ab7d25f5f473a539b3099f400db8 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn @@ -0,0 +1,41 @@ +[gd_scene load_steps=3 format=3 uid="uid://baaywi3arsl2m"] + +[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd" id="1"] + +[sub_resource type="ViewportTexture" id="1"] +viewport_path = NodePath("SubViewport") + +[node name="RGBCameraSensor3D" type="Node3D"] +script = ExtResource("1") + +[node name="RemoteTransform3D" type="RemoteTransform3D" parent="."] +remote_path = NodePath("../SubViewport/Camera3D") + +[node name="SubViewport" type="SubViewport" parent="."] +size = Vector2i(32, 32) +render_target_update_mode = 3 + +[node name="Camera3D" type="Camera3D" parent="SubViewport"] +near = 0.5 + +[node name="Control" type="Control" parent="."] +layout_mode = 3 +anchors_preset = 15 +anchor_right = 1.0 +anchor_bottom = 1.0 +grow_horizontal = 2 +grow_vertical = 2 + +[node name="TextureRect" type="ColorRect" parent="Control"] +layout_mode = 0 +offset_left = 1096.0 +offset_top = 534.0 +offset_right = 1114.0 +offset_bottom = 552.0 +scale = Vector2(10, 10) +color = Color(0.00784314, 0.00784314, 0.00784314, 1) + +[node name="CameraTexture" type="Sprite2D" parent="Control/TextureRect"] +texture = SubResource("1") +offset = Vector2(9, 9) +flip_v = true diff --git a/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..ad18ee6ef0867fb4dcb3630785d2d715a5917497 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd @@ -0,0 +1,166 @@ +@tool +extends ISensor3D +class_name RayCastSensor3D +@export_flags_3d_physics var collision_mask = 1: + get: return collision_mask + set(value): + collision_mask = value + _update() +@export_flags_3d_physics var boolean_class_mask = 1: + get: return boolean_class_mask + set(value): + boolean_class_mask = value + _update() + +@export var n_rays_width := 6.0: + get: return n_rays_width + set(value): + n_rays_width = value + _update() + +@export var n_rays_height := 6.0: + get: return n_rays_height + set(value): + n_rays_height = value + _update() + +@export var ray_length := 10.0: + get: return ray_length + set(value): + ray_length = value + _update() + +@export var cone_width := 60.0: + get: return cone_width + set(value): + cone_width = value + _update() + +@export var cone_height := 60.0: + get: return cone_height + set(value): + cone_height = value + _update() + +@export var collide_with_areas := false: + get: return collide_with_areas + set(value): + collide_with_areas = value + _update() + +@export var collide_with_bodies := true: + get: return collide_with_bodies + set(value): + collide_with_bodies = value + _update() + +@export var class_sensor := false + +var rays := [] +var geo = null + +func _update(): + if Engine.is_editor_hint(): + if is_node_ready(): + _spawn_nodes() + +func _ready() -> void: + if Engine.is_editor_hint(): + if get_child_count() == 0: + _spawn_nodes() + else: + _spawn_nodes() + +func _spawn_nodes(): + print("spawning nodes") + for ray in get_children(): + ray.queue_free() + if geo: + geo.clear() + #$Lines.remove_points() + rays = [] + + var horizontal_step = cone_width / (n_rays_width) + var vertical_step = cone_height / (n_rays_height) + + var horizontal_start = horizontal_step/2 - cone_width/2 + var vertical_start = vertical_step/2 - cone_height/2 + + var points = [] + + for i in n_rays_width: + for j in n_rays_height: + var angle_w = horizontal_start + i * horizontal_step + var angle_h = vertical_start + j * vertical_step + #angle_h = 0.0 + var ray = RayCast3D.new() + var cast_to = to_spherical_coords(ray_length, angle_w, angle_h) + ray.set_target_position(cast_to) + + points.append(cast_to) + + ray.set_name("node_"+str(i)+" "+str(j)) + ray.enabled = true + ray.collide_with_bodies = collide_with_bodies + ray.collide_with_areas = collide_with_areas + ray.collision_mask = collision_mask + add_child(ray) + ray.set_owner(get_tree().edited_scene_root) + rays.append(ray) + ray.force_raycast_update() + +# if Engine.editor_hint: +# _create_debug_lines(points) + +func _create_debug_lines(points): + if not geo: + geo = ImmediateMesh.new() + add_child(geo) + + geo.clear() + geo.begin(Mesh.PRIMITIVE_LINES) + for point in points: + geo.set_color(Color.AQUA) + geo.add_vertex(Vector3.ZERO) + geo.add_vertex(point) + geo.end() + +func display(): + if geo: + geo.display() + +func to_spherical_coords(r, inc, azimuth) -> Vector3: + return Vector3( + r*sin(deg_to_rad(inc))*cos(deg_to_rad(azimuth)), + r*sin(deg_to_rad(azimuth)), + r*cos(deg_to_rad(inc))*cos(deg_to_rad(azimuth)) + ) + +func get_observation() -> Array: + return self.calculate_raycasts() + +func calculate_raycasts() -> Array: + var result = [] + for ray in rays: + ray.set_enabled(true) + ray.force_raycast_update() + var distance = _get_raycast_distance(ray) + + result.append(distance) + if class_sensor: + var hit_class: float = 0 + if ray.get_collider(): + var hit_collision_layer = ray.get_collider().collision_layer + hit_collision_layer = hit_collision_layer & collision_mask + hit_class = (hit_collision_layer & boolean_class_mask) > 0 + result.append(float(hit_class)) + ray.set_enabled(false) + return result + +func _get_raycast_distance(ray : RayCast3D) -> float : + if !ray.is_colliding(): + return 0.0 + + var distance = (global_transform.origin - ray.get_collision_point()).length() + distance = clamp(distance, 0.0, ray_length) + return (ray_length - distance) / ray_length diff --git a/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55 --- /dev/null +++ b/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn @@ -0,0 +1,27 @@ +[gd_scene load_steps=2 format=3 uid="uid://b803cbh1fmy66"] + +[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="1"] + +[node name="RaycastSensor3D" type="Node3D"] +script = ExtResource("1") +n_rays_width = 4.0 +n_rays_height = 2.0 +ray_length = 11.0 + +[node name="node_1 0" type="RayCast3D" parent="."] +target_position = Vector3(-1.38686, -2.84701, 10.5343) + +[node name="node_1 1" type="RayCast3D" parent="."] +target_position = Vector3(-1.38686, 2.84701, 10.5343) + +[node name="node_2 0" type="RayCast3D" parent="."] +target_position = Vector3(1.38686, -2.84701, 10.5343) + +[node name="node_2 1" type="RayCast3D" parent="."] +target_position = Vector3(1.38686, 2.84701, 10.5343) + +[node name="node_3 0" type="RayCast3D" parent="."] +target_position = Vector3(4.06608, -2.84701, 9.81639) + +[node name="node_3 1" type="RayCast3D" parent="."] +target_position = Vector3(4.06608, 2.84701, 9.81639) diff --git a/addons/godot_rl_agents/sync.gd b/addons/godot_rl_agents/sync.gd new file mode 100644 index 0000000000000000000000000000000000000000..4f26101df8de62bd26c67f1be0246c675a7f1d4f --- /dev/null +++ b/addons/godot_rl_agents/sync.gd @@ -0,0 +1,342 @@ +extends Node + +# --fixed-fps 2000 --disable-render-loop + +enum ControlModes {HUMAN, TRAINING, ONNX_INFERENCE} +@export var control_mode: ControlModes = ControlModes.TRAINING +@export_range(1, 10, 1, "or_greater") var action_repeat := 8 +@export_range(1, 10, 1, "or_greater") var speed_up = 1 +@export var onnx_model_path := "" + +@onready var start_time = Time.get_ticks_msec() + +const MAJOR_VERSION := "0" +const MINOR_VERSION := "3" +const DEFAULT_PORT := "11008" +const DEFAULT_SEED := "1" +var stream : StreamPeerTCP = null +var connected = false +var message_center +var should_connect = true +var agents +var need_to_send_obs = false +var args = null +var initialized = false +var just_reset = false +var onnx_model = null +var n_action_steps = 0 + +var _action_space : Dictionary +var _obs_space : Dictionary + +# Called when the node enters the scene tree for the first time. +func _ready(): + await get_tree().root.ready + get_tree().set_pause(true) + _initialize() + await get_tree().create_timer(1.0).timeout + get_tree().set_pause(false) + +func _initialize(): + _get_agents() + _obs_space = agents[0].get_obs_space() + _action_space = agents[0].get_action_space() + args = _get_args() + Engine.physics_ticks_per_second = _get_speedup() * 60 # Replace with function body. + Engine.time_scale = _get_speedup() * 1.0 + prints("physics ticks", Engine.physics_ticks_per_second, Engine.time_scale, _get_speedup(), speed_up) + + _set_heuristic("human") + match control_mode: + ControlModes.TRAINING: + connected = connect_to_server() + if connected: + _set_heuristic("model") + _handshake() + _send_env_info() + else: + push_warning("Couldn't connect to Python server, using human controls instead. ", + "Did you start the training server using e.g. `gdrl` from the console?") + ControlModes.ONNX_INFERENCE: + assert(FileAccess.file_exists(onnx_model_path), "Onnx Model Path set on Sync node does not exist: %s" % onnx_model_path) + onnx_model = ONNXModel.new(onnx_model_path, 1) + _set_heuristic("model") + + _set_seed() + _set_action_repeat() + initialized = true + +func _physics_process(_delta): + # two modes, human control, agent control + # pause tree, send obs, get actions, set actions, unpause tree + if n_action_steps % action_repeat != 0: + n_action_steps += 1 + return + + n_action_steps += 1 + + if connected: + get_tree().set_pause(true) + + if just_reset: + just_reset = false + var obs = _get_obs_from_agents() + + var reply = { + "type": "reset", + "obs": obs + } + _send_dict_as_json_message(reply) + # this should go straight to getting the action and setting it checked the agent, no need to perform one phyics tick + get_tree().set_pause(false) + return + + if need_to_send_obs: + need_to_send_obs = false + var reward = _get_reward_from_agents() + var done = _get_done_from_agents() + #_reset_agents_if_done() # this ensures the new observation is from the next env instance : NEEDS REFACTOR + + var obs = _get_obs_from_agents() + + var reply = { + "type": "step", + "obs": obs, + "reward": reward, + "done": done + } + _send_dict_as_json_message(reply) + + var handled = handle_message() + + elif onnx_model != null: + var obs : Array = _get_obs_from_agents() + + var actions = [] + for o in obs: + var action = onnx_model.run_inference(o["obs"], 1.0) + action["output"] = clamp_array(action["output"], -1.0, 1.0) + var action_dict = _extract_action_dict(action["output"]) + actions.append(action_dict) + + _set_agent_actions(actions) + need_to_send_obs = true + get_tree().set_pause(false) + _reset_agents_if_done() + + else: + _reset_agents_if_done() + +func _extract_action_dict(action_array: Array): + var index = 0 + var result = {} + for key in _action_space.keys(): + var size = _action_space[key]["size"] + if _action_space[key]["action_type"] == "discrete": + result[key] = round(action_array[index]) + else: + result[key] = action_array.slice(index,index+size) + index += size + + return result + +func _get_agents(): + agents = get_tree().get_nodes_in_group("AGENT") + +func _set_heuristic(heuristic): + for agent in agents: + agent.set_heuristic(heuristic) + +func _handshake(): + print("performing handshake") + + var json_dict = _get_dict_json_message() + assert(json_dict["type"] == "handshake") + var major_version = json_dict["major_version"] + var minor_version = json_dict["minor_version"] + if major_version != MAJOR_VERSION: + print("WARNING: major verison mismatch ", major_version, " ", MAJOR_VERSION) + if minor_version != MINOR_VERSION: + print("WARNING: minor verison mismatch ", minor_version, " ", MINOR_VERSION) + + print("handshake complete") + +func _get_dict_json_message(): + # returns a dictionary from of the most recent message + # this is not waiting + while stream.get_available_bytes() == 0: + stream.poll() + if stream.get_status() != 2: + print("server disconnected status, closing") + get_tree().quit() + return null + + OS.delay_usec(10) + + var message = stream.get_string() + var json_data = JSON.parse_string(message) + + return json_data + +func _send_dict_as_json_message(dict): + stream.put_string(JSON.stringify(dict)) + +func _send_env_info(): + var json_dict = _get_dict_json_message() + assert(json_dict["type"] == "env_info") + + + var message = { + "type" : "env_info", + "observation_space": _obs_space, + "action_space":_action_space, + "n_agents": len(agents) + } + _send_dict_as_json_message(message) + +func connect_to_server(): + print("Waiting for one second to allow server to start") + OS.delay_msec(1000) + print("trying to connect to server") + stream = StreamPeerTCP.new() + + # "localhost" was not working on windows VM, had to use the IP + var ip = "127.0.0.1" + var port = _get_port() + var connect = stream.connect_to_host(ip, port) + stream.set_no_delay(true) # TODO check if this improves performance or not + stream.poll() + # Fetch the status until it is either connected (2) or failed to connect (3) + while stream.get_status() < 2: + stream.poll() + return stream.get_status() == 2 + +func _get_args(): + print("getting command line arguments") + var arguments = {} + for argument in OS.get_cmdline_args(): + print(argument) + if argument.find("=") > -1: + var key_value = argument.split("=") + arguments[key_value[0].lstrip("--")] = key_value[1] + else: + # Options without an argument will be present in the dictionary, + # with the value set to an empty string. + arguments[argument.lstrip("--")] = "" + + return arguments + +func _get_speedup(): + print(args) + return args.get("speedup", str(speed_up)).to_int() + +func _get_port(): + return args.get("port", DEFAULT_PORT).to_int() + +func _set_seed(): + var _seed = args.get("env_seed", DEFAULT_SEED).to_int() + seed(_seed) + +func _set_action_repeat(): + action_repeat = args.get("action_repeat", str(action_repeat)).to_int() + +func disconnect_from_server(): + stream.disconnect_from_host() + + + +func handle_message() -> bool: + # get json message: reset, step, close + var message = _get_dict_json_message() + if message["type"] == "close": + print("received close message, closing game") + get_tree().quit() + get_tree().set_pause(false) + return true + + if message["type"] == "reset": + print("resetting all agents") + _reset_all_agents() + just_reset = true + get_tree().set_pause(false) + #print("resetting forcing draw") +# RenderingServer.force_draw() +# var obs = _get_obs_from_agents() +# print("obs ", obs) +# var reply = { +# "type": "reset", +# "obs": obs +# } +# _send_dict_as_json_message(reply) + return true + + if message["type"] == "call": + var method = message["method"] + var returns = _call_method_on_agents(method) + var reply = { + "type": "call", + "returns": returns + } + print("calling method from Python") + _send_dict_as_json_message(reply) + return handle_message() + + if message["type"] == "action": + var action = message["action"] + _set_agent_actions(action) + need_to_send_obs = true + get_tree().set_pause(false) + return true + + print("message was not handled") + return false + +func _call_method_on_agents(method): + var returns = [] + for agent in agents: + returns.append(agent.call(method)) + + return returns + + +func _reset_agents_if_done(): + for agent in agents: + if agent.get_done(): + agent.set_done_false() + +func _reset_all_agents(): + for agent in agents: + agent.needs_reset = true + #agent.reset() + +func _get_obs_from_agents(): + var obs = [] + for agent in agents: + obs.append(agent.get_obs()) + + return obs + +func _get_reward_from_agents(): + var rewards = [] + for agent in agents: + rewards.append(agent.get_reward()) + agent.zero_reward() + return rewards + +func _get_done_from_agents(): + var dones = [] + for agent in agents: + var done = agent.get_done() + if done: agent.set_done_false() + dones.append(done) + return dones + +func _set_agent_actions(actions): + for i in range(len(actions)): + agents[i].set_action(actions[i]) + +func clamp_array(arr : Array, min:float, max:float): + var output : Array = [] + for a in arr: + output.append(clamp(a, min, max)) + return output diff --git a/asset-license.md b/asset-license.md new file mode 100644 index 0000000000000000000000000000000000000000..5c43c7fc148977ab4188320c727b96d8018f228d --- /dev/null +++ b/asset-license.md @@ -0,0 +1,5 @@ +Multilevel Robot Environment made by Ivan-267 using Godot, Godot RL Agents, and Blender. + +The following license is only for the assets (.blend files and tile.png file) in the folder "blender": +Author: https://github.com/Ivan-267 +License: https://creativecommons.org/licenses/by/4.0/ \ No newline at end of file diff --git a/blender/level1.blend b/blender/level1.blend new file mode 100644 index 0000000000000000000000000000000000000000..8dac40330880467e2767adc3979b1026bc395bcc --- /dev/null +++ b/blender/level1.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afeb2e63830a078f2add33ad716f42a31e5936471094f78bbd9d6aeb90630beb +size 1025844 diff --git a/blender/level1.blend.import b/blender/level1.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..8e583ac069282f19802869915d6453e4d5c3064a --- /dev/null +++ b/blender/level1.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://cu202rkqaw88u" +path="res://.godot/imported/level1.blend-b72f2e5a158cc5ac303c6d8d0ac235e7.scn" + +[deps] + +source_file="res://blender/level1.blend" +dest_files=["res://.godot/imported/level1.blend-b72f2e5a158cc5ac303c6d8d0ac235e7.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level2.blend b/blender/level2.blend new file mode 100644 index 0000000000000000000000000000000000000000..0a981eb4e04eddc7e4b427b4e8509aa508895b64 --- /dev/null +++ b/blender/level2.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d49d163c6444015be9d7c7a991360bdc2116b3eb7e51677ada6ae64d9b517b3c +size 1039336 diff --git a/blender/level2.blend.import b/blender/level2.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..ee5ed420629e0f5585ca3a9ed5f1f840a81e85da --- /dev/null +++ b/blender/level2.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://b8v7217vqur6p" +path="res://.godot/imported/level2.blend-738538dd19f246c1fbaddf96fe19e2a6.scn" + +[deps] + +source_file="res://blender/level2.blend" +dest_files=["res://.godot/imported/level2.blend-738538dd19f246c1fbaddf96fe19e2a6.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level3.blend b/blender/level3.blend new file mode 100644 index 0000000000000000000000000000000000000000..014cf5b95a8239f79db3fc130a2eb58cfd6df305 --- /dev/null +++ b/blender/level3.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31b14b02da8d3c0574a8ea64edc072c614282885b8282bcca768999854fa8699 +size 1089812 diff --git a/blender/level3.blend.import b/blender/level3.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..0ef79c426ab4cce43118e154124003e50f07349d --- /dev/null +++ b/blender/level3.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://st0k2hlqro7c" +path="res://.godot/imported/level3.blend-28a28f85acf5d3b14e3e0c83a6f124e2.scn" + +[deps] + +source_file="res://blender/level3.blend" +dest_files=["res://.godot/imported/level3.blend-28a28f85acf5d3b14e3e0c83a6f124e2.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level4.blend b/blender/level4.blend new file mode 100644 index 0000000000000000000000000000000000000000..805971fec2eb05b3489d08e99c4a323fc8af48c9 --- /dev/null +++ b/blender/level4.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abbd2bcf69db058832bf2617ebe06a510a07d1b6b2efaa4bfea1546c90748483 +size 1038732 diff --git a/blender/level4.blend.import b/blender/level4.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..3d66887d5a27916af293835ca124fe81671bd8e7 --- /dev/null +++ b/blender/level4.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://vsctcxf4mqr7" +path="res://.godot/imported/level4.blend-8aeb104811ae2940dee51c50f3cc060f.scn" + +[deps] + +source_file="res://blender/level4.blend" +dest_files=["res://.godot/imported/level4.blend-8aeb104811ae2940dee51c50f3cc060f.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level5.blend b/blender/level5.blend new file mode 100644 index 0000000000000000000000000000000000000000..8df733091db6d4d1ef563f8652d9d22f4c7d1d13 --- /dev/null +++ b/blender/level5.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f7af77b7898ea312b627d3dc47629811ec14e8956a74a424d2166759e850c63 +size 1077468 diff --git a/blender/level5.blend.import b/blender/level5.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..946bccb35ee3520e07dde1f0f055e5d6fe388206 --- /dev/null +++ b/blender/level5.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://cy2cdoijs2df5" +path="res://.godot/imported/level5.blend-bc3fa2e16a59455ab89817b3e2a20156.scn" + +[deps] + +source_file="res://blender/level5.blend" +dest_files=["res://.godot/imported/level5.blend-bc3fa2e16a59455ab89817b3e2a20156.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level6.blend b/blender/level6.blend new file mode 100644 index 0000000000000000000000000000000000000000..d7b7cf8ab2d9fcfc942fd867193b60478d703290 --- /dev/null +++ b/blender/level6.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8192893af9188a37ab9e7bc119df4f198c171430e03066e30b02c4c113b644e +size 1071312 diff --git a/blender/level6.blend.import b/blender/level6.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..a9ad73767176641bcf51d357983c9b46d0b8bf0b --- /dev/null +++ b/blender/level6.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://btqxapruwdnad" +path="res://.godot/imported/level6.blend-a6efbf337c5b556b3212a61b06bc56a1.scn" + +[deps] + +source_file="res://blender/level6.blend" +dest_files=["res://.godot/imported/level6.blend-a6efbf337c5b556b3212a61b06bc56a1.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level7.blend b/blender/level7.blend new file mode 100644 index 0000000000000000000000000000000000000000..c6c1211d44a0bce4dc732d627064aebc8d696741 --- /dev/null +++ b/blender/level7.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8222b4d7f6a75ea9a30d28f5da0a1573d27eb158cc323c3d40443057a2732bb +size 1154300 diff --git a/blender/level7.blend.import b/blender/level7.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..449ec58ec863bbeabc860b0ae8e9a2f2dbdc5c50 --- /dev/null +++ b/blender/level7.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://befgek1bcfiwd" +path="res://.godot/imported/level7.blend-17eeca2b1b64856bf21c35efc326d52f.scn" + +[deps] + +source_file="res://blender/level7.blend" +dest_files=["res://.godot/imported/level7.blend-17eeca2b1b64856bf21c35efc326d52f.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/level8.blend b/blender/level8.blend new file mode 100644 index 0000000000000000000000000000000000000000..5086a2e4e09009dc51a8b05e0c7ef56ee6b47dd3 --- /dev/null +++ b/blender/level8.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5a7d7f5713d40a93ae61225fa4aa342e45363e21af358635e62f94db29192ce5 +size 1352264 diff --git a/blender/level8.blend.import b/blender/level8.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..36e0e29a09fbf7f14ac4b665ecd254370ced7264 --- /dev/null +++ b/blender/level8.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://r6yewh1xvn2p" +path="res://.godot/imported/level8.blend-b2ccf8b8dd5a76de8df19d3b702415b7.scn" + +[deps] + +source_file="res://blender/level8.blend" +dest_files=["res://.godot/imported/level8.blend-b2ccf8b8dd5a76de8df19d3b702415b7.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/robot.blend b/blender/robot.blend new file mode 100644 index 0000000000000000000000000000000000000000..c5bd083e212cde5fa8ffc1d7800b414917da5eca --- /dev/null +++ b/blender/robot.blend @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:319ed9a4664add8676fe7984c37d98bd158ca9ed3c22643fc33a3d383054a2ff +size 1279692 diff --git a/blender/robot.blend.import b/blender/robot.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..88e945bbd8357ec5ead08b4dc983e2d239b022a3 --- /dev/null +++ b/blender/robot.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://bqc1i412oou13" +path="res://.godot/imported/robot.blend-000de9eae232532a839543b86cedcbd7.scn" + +[deps] + +source_file="res://blender/robot.blend" +dest_files=["res://.godot/imported/robot.blend-000de9eae232532a839543b86cedcbd7.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/blender/tile.png b/blender/tile.png new file mode 100644 index 0000000000000000000000000000000000000000..d74e5b3a40e923465f1171d923eaa587e0c3b845 --- /dev/null +++ b/blender/tile.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e5ec9b9a7c1ad0b566aba682e82e69303601fc69ccd799920fb3a652844c1672 +size 191 diff --git a/blender/tile.png.import b/blender/tile.png.import new file mode 100644 index 0000000000000000000000000000000000000000..0ed9b8c54492a9f6cdc830f0223a5d47cf47ea67 --- /dev/null +++ b/blender/tile.png.import @@ -0,0 +1,35 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://dcbhpixpdr664" +path.s3tc="res://.godot/imported/tile.png-b213b6d3071f364dd3a4da14568403ed.s3tc.ctex" +metadata={ +"imported_formats": ["s3tc_bptc"], +"vram_texture": true +} + +[deps] + +source_file="res://blender/tile.png" +dest_files=["res://.godot/imported/tile.png-b213b6d3071f364dd3a4da14568403ed.s3tc.ctex"] + +[params] + +compress/mode=2 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=true +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=0 diff --git a/cube_test.blend.import b/cube_test.blend.import new file mode 100644 index 0000000000000000000000000000000000000000..fc764e857880caf8d807d15746c551714f3e53a0 --- /dev/null +++ b/cube_test.blend.import @@ -0,0 +1,50 @@ +[remap] + +importer="scene" +importer_version=1 +type="PackedScene" +uid="uid://35ov1um06drc" +path="res://.godot/imported/cube_test.blend-76b2b49637f3d9843635b9bded606dc2.scn" + +[deps] + +source_file="res://cube_test.blend" +dest_files=["res://.godot/imported/cube_test.blend-76b2b49637f3d9843635b9bded606dc2.scn"] + +[params] + +nodes/root_type="" +nodes/root_name="" +nodes/apply_root_scale=true +nodes/root_scale=1.0 +meshes/ensure_tangents=true +meshes/generate_lods=true +meshes/create_shadow_meshes=true +meshes/light_baking=1 +meshes/lightmap_texel_size=0.2 +meshes/force_disable_compression=false +skins/use_named_skins=true +animation/import=true +animation/fps=30 +animation/trimming=false +animation/remove_immutable_tracks=true +import_script/path="" +_subresources={} +gltf/naming_version=1 +gltf/embedded_image_handling=1 +blender/nodes/visible=0 +blender/nodes/punctual_lights=true +blender/nodes/cameras=true +blender/nodes/custom_properties=true +blender/nodes/modifiers=1 +blender/meshes/colors=false +blender/meshes/uvs=true +blender/meshes/normals=true +blender/meshes/tangents=true +blender/meshes/skins=2 +blender/meshes/export_bones_deforming_mesh_only=false +blender/materials/unpack_enabled=true +blender/materials/export_materials=1 +blender/animation/limit_playback=true +blender/animation/always_sample=true +blender/animation/group_tracks=true diff --git a/icon.svg b/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..b370ceb72740b9a759fe11b364f0d4de27df42f8 --- /dev/null +++ b/icon.svg @@ -0,0 +1 @@ + diff --git a/icon.svg.import b/icon.svg.import new file mode 100644 index 0000000000000000000000000000000000000000..d374d6e5dd042209ea8e2384425a099cdb47437f --- /dev/null +++ b/icon.svg.import @@ -0,0 +1,37 @@ +[remap] + +importer="texture" +type="CompressedTexture2D" +uid="uid://bgi5dat1hoeko" +path="res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex" +metadata={ +"vram_texture": false +} + +[deps] + +source_file="res://icon.svg" +dest_files=["res://.godot/imported/icon.svg-218a8f2b3041327d8a5756f3a245f83b.ctex"] + +[params] + +compress/mode=0 +compress/high_quality=false +compress/lossy_quality=0.7 +compress/hdr_compression=1 +compress/normal_map=0 +compress/channel_pack=0 +mipmaps/generate=false +mipmaps/limit=-1 +roughness/mode=0 +roughness/src_normal="" +process/fix_alpha_border=true +process/premult_alpha=false +process/normal_map_invert_y=false +process/hdr_as_srgb=false +process/hdr_clamp_exposure=false +process/size_limit=0 +detect_3d/compress_to=1 +svg/scale=1.0 +editor/scale_with_editor_scale=false +editor/convert_colors_with_editor_theme=false diff --git a/onnx/robot.onnx b/onnx/robot.onnx new file mode 100644 index 0000000000000000000000000000000000000000..c71131af37e1d844834a950df0316f4281652a56 --- /dev/null +++ b/onnx/robot.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:905a560ddc6471975fae68efb01a059d4bc375bbd8dce2dcdcd97348630ca8e6 +size 35792 diff --git a/project.godot b/project.godot new file mode 100644 index 0000000000000000000000000000000000000000..bb36b0d426f7c7111a64e99dc90c0c7ffa28982c --- /dev/null +++ b/project.godot @@ -0,0 +1,28 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. +; +; Format: +; [section] ; section goes between [] +; param=value ; assign values to parameters + +config_version=5 + +[application] + +config/name="MultiLevelRobotEnv" +run/main_scene="res://training_scene/training_scene.tscn" +config/features=PackedStringArray("4.2", "C#", "Forward Plus") +config/icon="res://icon.svg" + +[dotnet] + +project/assembly_name="RobotEnv" + +[editor_plugins] + +enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg") + +[physics] + +3d/solver/solver_iterations=10 diff --git a/readme.md b/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..360b7ef8a0e186a69d797fa8a226096cc5e86070 --- /dev/null +++ b/readme.md @@ -0,0 +1,41 @@ +## Multilevel Robot Environment + +A simple minigame environment with multiple mini-levels for the robot to pass. +For levels that feature coins, all coins must be picked up before proceeding to the next level is possible. +The final level features some enemy robots to avoid. + +### Observations: +- Current n_steps / reset_after, +- Position of the current level's goal in the robot's local reference, +- Position of the closest coin in the robot's local reference, +- Position of the closest enemy in the robot's local reference, +- Movement direction of the closest enemy, +- Robot velocity, +- Whether all coins for the current level have been collected (0 or 1) + +### Action space: +```gdscript +func get_action_space() -> Dictionary: + return { + "movement" : { + "size": 2, + "action_type": "continuous" + } + } +``` + +### Rewards: +- Positive reward for picking up a coin, +- Negative reward (and episode end) on collision with enemy robot, +- Negative reward (and episode end) on robot falling down, +- Positive reward (and episode end) on robot reaching the end of the level by passing through the portal at the end of the level, +- Positive reward every time the robot gets closer to the portal than the previous minimum distance (min distance is restarted each episode). + +### Game over / episode end conditions: +An episode ends if the robot falls, collides with an enemy robot or finishes a level by passing through the portal. + +### Running inference with the pretrained onnx model: +After opening the project in Godot, open the training_scene and click on `Run Current Scene` or press `F6` + +### Training: +The default scene (training_scene) can be used for training. \ No newline at end of file diff --git a/scenes/game_scene/camera3d.gd b/scenes/game_scene/camera3d.gd new file mode 100644 index 0000000000000000000000000000000000000000..9f8c4b48075bf2bc8e2a1d15d757b1393f89ca1c --- /dev/null +++ b/scenes/game_scene/camera3d.gd @@ -0,0 +1,6 @@ +extends Camera3D +@export var robot: Robot + + +func _physics_process(_delta): + global_position.z = robot.global_position.z diff --git a/scenes/game_scene/game_scene.tscn b/scenes/game_scene/game_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..597e8e005a768102b295b000bbcde7ce4d9de075 --- /dev/null +++ b/scenes/game_scene/game_scene.tscn @@ -0,0 +1,23 @@ +[gd_scene load_steps=4 format=3 uid="uid://bsp37y3hehf5y"] + +[ext_resource type="PackedScene" uid="uid://bxcp6s8r0wtrv" path="res://scenes/level/level_manager.tscn" id="1_abkah"] +[ext_resource type="PackedScene" uid="uid://3gt386v3b1ej" path="res://scenes/robot/robot.tscn" id="2_au3n6"] +[ext_resource type="Script" path="res://scenes/game_scene/camera3d.gd" id="3_mlkq4"] + +[node name="GameScene" type="Node3D"] + +[node name="LevelManager" parent="." node_paths=PackedStringArray("robot") instance=ExtResource("1_abkah")] +robot = NodePath("../Node3D/Robot") + +[node name="Node3D" type="Node3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.222733, -100.474) + +[node name="Robot" parent="Node3D" node_paths=PackedStringArray("level_manager") instance=ExtResource("2_au3n6")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.358, 2.013, 0) +level_manager = NodePath("../../LevelManager") + +[node name="Camera3D" type="Camera3D" parent="Node3D" node_paths=PackedStringArray("robot")] +transform = Transform3D(0.00349064, -0.689615, 0.724168, 0, 0.724172, 0.68962, -0.999994, -0.00240721, 0.00252782, 15.548, 15.428, 0) +fov = 76.8 +script = ExtResource("3_mlkq4") +robot = NodePath("../Robot") diff --git a/scenes/level/coin.gd b/scenes/level/coin.gd new file mode 100644 index 0000000000000000000000000000000000000000..4c43cbe5d862d1331bf68c81caea7d366e37053d --- /dev/null +++ b/scenes/level/coin.gd @@ -0,0 +1,7 @@ +extends Node3D +class_name Coin + +var coin_rotation_speed := 1.5 + +func _physics_process(delta): + rotate_y(coin_rotation_speed * delta) \ No newline at end of file diff --git a/scenes/level/enemy.gd b/scenes/level/enemy.gd new file mode 100644 index 0000000000000000000000000000000000000000..917bc856d5953066943749506222ae993c16faeb --- /dev/null +++ b/scenes/level/enemy.gd @@ -0,0 +1,27 @@ +extends Node3D +class_name Enemy + +var speed: float = 5.0 +var movement_direction: int = 1 +var rotation_speed: float = 10.0 + +var wheels: Array[Node3D] + + +func _init(): + wheels.append(find_child("Wheels*")) + + +func _physics_process(delta): + global_position += (-global_basis.z * speed * delta) + update_wheels_and_visual_rotation(delta) + + +func on_wall_hit(_wall): + movement_direction = -movement_direction + rotate_y(PI) + + +func update_wheels_and_visual_rotation(delta): + for wheel in wheels: + wheel.rotate_object_local(Vector3.LEFT, speed * delta) diff --git a/scenes/level/level_goal.tscn b/scenes/level/level_goal.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a7003f6a5e1185101771a2b35b2074f6ef61c8e3 --- /dev/null +++ b/scenes/level/level_goal.tscn @@ -0,0 +1,13 @@ +[gd_scene load_steps=2 format=3 uid="uid://80hnrx1b7044"] + +[sub_resource type="BoxShape3D" id="BoxShape3D_pujb7"] +size = Vector3(12, 24, 12) + +[node name="LevelGoal" type="Area3D"] +transform = Transform3D(0.2, 0, 0, 0, 0.2, 0, 0, 0, 0.2, 0, 0, 0) +collision_mask = 0 +monitoring = false + +[node name="CollisionShape3D" type="CollisionShape3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 5.5, 0) +shape = SubResource("BoxShape3D_pujb7") diff --git a/scenes/level/level_manager.gd b/scenes/level/level_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..1549b2d030311f512d7047db71cdcd34689c3db3 --- /dev/null +++ b/scenes/level/level_manager.gd @@ -0,0 +1,139 @@ +extends Node3D +class_name LevelManager + +@export var robot: Robot +@export var level_goal_scene: PackedScene + +@onready var levels = get_children() + +var coins_in_level: Array[Array] +var active_coins_in_level_count: Array[int] +var enemies: Array[Enemy] + +var level_start_points: Array +var level_goals: Array + + +func _ready(): + for node in find_children("Coin_*", "MeshInstance3D"): + node.set_script(Coin) + node.set_physics_process(true) + + + level_start_points.resize(levels.size()) + level_goals.resize(levels.size()) + active_coins_in_level_count.resize(levels.size()) + active_coins_in_level_count.fill(0) + coins_in_level.resize(levels.size()) + + for level_id in range(0, levels.size()): + var start_node = levels[level_id].find_child("Start*") + level_start_points[level_id] = start_node.get_children() + var end_node = levels[level_id].find_child("End*") + level_goals[level_id] = end_node.get_children() + for goal in level_goals[level_id]: + var level_goal_area = level_goal_scene.instantiate() + goal.add_child(level_goal_area) + goal.visible = false + level_goal_area.position = Vector3.ZERO + var coins = levels[level_id].find_child("Coins*") + if coins: + active_coins_in_level_count[level_id] = coins.get_child_count() + for node in coins.get_children(): + var coin = node as MeshInstance3D + var coin_area = Area3D.new() + var coin_area_shape = CollisionShape3D.new() + coin_area_shape.shape = SphereShape3D.new() + coin_area.add_child(coin_area_shape) + coin_area.monitorable = true + coin_area.set_collision_layer_value(1, false) + coin_area.set_collision_layer_value(2, true) + var coin_parent = coin.get_parent() + coin_parent.add_child(coin_area) + coin_area.global_position = coin.global_position + coin.reparent(coin_area) + if not coins_in_level[level_id]: + coins_in_level[level_id] = [] + coins_in_level[level_id].append(coin_area) + + var enemy_parent = levels[level_id].find_child("Enemies*") as Node3D + if enemy_parent: + for enemy in enemy_parent.get_children(): + enemy = enemy as Node3D + var enemy_area = Area3D.new() + var enemy_area_shape = CollisionShape3D.new() + enemy_area_shape.shape = SphereShape3D.new() + enemy_area.add_child(enemy_area_shape) + enemy_area.monitorable = true + enemy_area.monitoring = true + enemy_area.set_collision_layer_value(1, false) + enemy_area.set_collision_layer_value(4, true) + enemy_area.set_collision_mask_value(1, true) + enemy.set_script(Enemy) + enemy.set_physics_process(true) + enemy.add_child(enemy_area) + enemy_area.connect("body_entered", enemy.on_wall_hit) + enemies.append(enemy) + + +func randomize_goal(level_id: int): + var active_goal_id = randi_range(0, level_goals[level_id].size() - 1) + for goal_id in range(0, level_goals[level_id].size()): + var goal = level_goals[level_id][goal_id] + if goal_id == active_goal_id: + goal.visible = true + goal.process_mode = Node.PROCESS_MODE_INHERIT + else: + goal.visible = false + goal.process_mode = Node.PROCESS_MODE_DISABLED + return level_goals[level_id][active_goal_id].global_transform + + +func get_closest_enemy(from_global_position: Vector3): + var closest_enemy: Enemy + var smallest_distance: float = INF + for enemy in enemies: + var distance: float = enemy.global_position.distance_to(from_global_position) + if distance < smallest_distance: + smallest_distance = distance + closest_enemy = enemy + return closest_enemy + + +func get_closest_active_coin(from_global_position: Vector3, level: int): + var closest_coin: Area3D + var smallest_distance: float = INF + for coin in coins_in_level[level]: + if coin.visible == false: + continue + var distance: float = coin.global_position.distance_to(from_global_position) + if distance < smallest_distance: + smallest_distance = distance + closest_coin = coin + return closest_coin + + +func deactivate_coin(coin: Area3D, current_level: int): + active_coins_in_level_count[current_level] -= 1 + coin.set_deferred("monitorable", false) + coin.visible = false + coin.process_mode = Node.PROCESS_MODE_DISABLED + + +func check_all_coins_collected(current_level: int) -> bool: + return active_coins_in_level_count[current_level] == 0 + + +func reset_coins(current_level: int): + var coins: Array = coins_in_level[current_level] + for coin in coins: + if not coin.visible: + coin.set_deferred("monitorable", true) + coin.visible = true + coin.process_mode = Node.PROCESS_MODE_INHERIT + active_coins_in_level_count[current_level] = coins.size() + + +func get_spawn_position(level: int) -> Vector3: + var start_points: Array[Node] = level_start_points[min(level, levels.size() - 1)] + return start_points.pick_random().global_position diff --git a/scenes/level/level_manager.tscn b/scenes/level/level_manager.tscn new file mode 100644 index 0000000000000000000000000000000000000000..4536434aefda80933b27908a0ef9b5de349c1b8f --- /dev/null +++ b/scenes/level/level_manager.tscn @@ -0,0 +1,126 @@ +[gd_scene load_steps=20 format=3 uid="uid://bxcp6s8r0wtrv"] + +[ext_resource type="Script" path="res://scenes/level/level_manager.gd" id="1_oxntu"] +[ext_resource type="PackedScene" uid="uid://80hnrx1b7044" path="res://scenes/level/level_goal.tscn" id="2_3sw7s"] +[ext_resource type="PackedScene" uid="uid://3cv3ug8eqq5g" path="res://blender/level1.blend" id="2_cvyct"] +[ext_resource type="PackedScene" uid="uid://bj3h1gfvjx4o3" path="res://blender/level2.blend" id="3_45u06"] +[ext_resource type="PackedScene" uid="uid://bgxwkjg6h2hsg" path="res://blender/level3.blend" id="4_gacmy"] +[ext_resource type="PackedScene" uid="uid://chdhm660dxkc2" path="res://blender/level4.blend" id="5_ujbu2"] +[ext_resource type="PackedScene" uid="uid://bkx03yluwo37t" path="res://blender/level5.blend" id="6_b5l34"] +[ext_resource type="PackedScene" uid="uid://1e8aj3ofbxor" path="res://blender/level6.blend" id="7_kgnb3"] +[ext_resource type="PackedScene" uid="uid://cxvcclen623pg" path="res://blender/level7.blend" id="8_hc0fw"] +[ext_resource type="PackedScene" uid="uid://iwcxg7id188g" path="res://blender/level8.blend" id="9_mgkso"] + +[sub_resource type="BoxShape3D" id="BoxShape3D_pjtgt"] +size = Vector3(20, 1.16858, 4) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_e57tg"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_swuxu"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_a6rin"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_o2xrm"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_7r61w"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_0n41c"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_fdcwt"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[sub_resource type="ConvexPolygonShape3D" id="ConvexPolygonShape3D_oqnta"] +points = PackedVector3Array(-1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, 1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918, 1.3918, -1.3918, -1.3918, 1.3918, 1.3918, 1.3918, -1.3918, -1.3918) + +[node name="LevelManager" type="Node3D"] +script = ExtResource("1_oxntu") +level_goal_scene = ExtResource("2_3sw7s") + +[node name="level1" parent="." instance=ExtResource("2_cvyct")] + +[node name="level2" parent="." instance=ExtResource("3_45u06")] + +[node name="level3" parent="." instance=ExtResource("4_gacmy")] + +[node name="ConveyorBelt" type="Area3D" parent="level3"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.06282, -50.1) +collision_layer = 4 +collision_mask = 0 +monitoring = false + +[node name="CollisionShape3D" type="CollisionShape3D" parent="level3/ConveyorBelt"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.380676, 0) +shape = SubResource("BoxShape3D_pjtgt") + +[node name="ConveyorBelt2" type="Area3D" parent="level3"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.06282, -56.3) +collision_layer = 4 +collision_mask = 0 +monitoring = false + +[node name="CollisionShape3D" type="CollisionShape3D" parent="level3/ConveyorBelt2"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.380676, 0) +shape = SubResource("BoxShape3D_pjtgt") + +[node name="ConveyorBelt3" type="Area3D" parent="level3"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1.06282, -62.3) +collision_layer = 4 +collision_mask = 0 +monitoring = false + +[node name="CollisionShape3D" type="CollisionShape3D" parent="level3/ConveyorBelt3"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.380676, 0) +shape = SubResource("BoxShape3D_pjtgt") + +[node name="level4" parent="." instance=ExtResource("5_ujbu2")] + +[node name="level5" parent="." instance=ExtResource("6_b5l34")] + +[node name="level6" parent="." instance=ExtResource("7_kgnb3")] + +[node name="level7" parent="." instance=ExtResource("8_hc0fw")] + +[node name="StaticBody3D" type="StaticBody3D" parent="level7"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0.5, -237) + +[node name="CollisionShape3D2" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4.4, 2, 4.23811) +shape = SubResource("ConvexPolygonShape3D_e57tg") + +[node name="CollisionShape3D3" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1.6, 2, 4.23811) +shape = SubResource("ConvexPolygonShape3D_swuxu") + +[node name="CollisionShape3D4" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1.2, 2, 4.23811) +shape = SubResource("ConvexPolygonShape3D_a6rin") + +[node name="CollisionShape3D5" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 2, 4.23811) +shape = SubResource("ConvexPolygonShape3D_o2xrm") + +[node name="CollisionShape3D6" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -4, 2, -2.0619) +shape = SubResource("ConvexPolygonShape3D_7r61w") + +[node name="CollisionShape3D7" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 4.4, 2, -2.0619) +shape = SubResource("ConvexPolygonShape3D_0n41c") + +[node name="CollisionShape3D8" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 1.6, 2, -2.08191) +shape = SubResource("ConvexPolygonShape3D_fdcwt") + +[node name="CollisionShape3D9" type="CollisionShape3D" parent="level7/StaticBody3D"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -1.2, 2, -2.0619) +shape = SubResource("ConvexPolygonShape3D_oqnta") + +[node name="level8" parent="." instance=ExtResource("9_mgkso")] + +[editable path="level8"] diff --git a/scenes/robot/RobotAIController.gd b/scenes/robot/RobotAIController.gd new file mode 100644 index 0000000000000000000000000000000000000000..fda8d6769bb71802d5f17aa97518584191c70dec --- /dev/null +++ b/scenes/robot/RobotAIController.gd @@ -0,0 +1,104 @@ +extends AIController3D +class_name RobotAIController + +@onready var robot: Robot = get_parent() +@onready var sensors: Array[Node] = $"../Sensors".get_children() +@onready var level_manager = robot.level_manager + +var closest_goal_position + +func reset(): + super.reset() + closest_goal_position = xz_distance(robot.global_position, + robot.current_goal_transform.origin) + +func _physics_process(_delta): + n_steps += 1 + if n_steps > reset_after: + needs_reset = true + done = true + reward -= 1 + +func get_obs() -> Dictionary: + var velocity: Vector3 = robot.get_real_velocity().limit_length(20.0) / 20.0 + + var current_goal_position: Vector3 = robot.current_goal_transform.origin + var local_goal_position = robot.to_local(current_goal_position).limit_length(40.0) / 40.0 + + var closest_coin = level_manager.get_closest_active_coin(robot.global_position, robot.current_level) + var closest_coin_position: Vector3 = Vector3.ZERO + + if closest_coin: + closest_coin_position = robot.to_local(closest_coin.global_position) + if closest_coin_position.length() > 30.0: + closest_coin_position = Vector3.ZERO + + var closest_enemy: Enemy = level_manager.get_closest_enemy(robot.global_position) + var closest_enemy_position: Vector3 = Vector3.ZERO + var closest_enemy_direction: float = 0.0 + + if closest_enemy: + closest_enemy_position = robot.to_local(closest_enemy.global_position) + closest_enemy_direction = float(closest_enemy.movement_direction) + if closest_enemy_position.length() > 30.0: + closest_enemy_position = Vector3.ZERO + closest_enemy_direction = 0.0 + + + var observations: Array[float] = [ + float(n_steps) / reset_after, + local_goal_position.x, + local_goal_position.y, + local_goal_position.z, + closest_coin_position.x, + closest_coin_position.y, + closest_coin_position.z, + closest_enemy_position.x, + closest_enemy_position.y, + closest_enemy_position.z, + closest_enemy_direction, + velocity.x, + velocity.y, + velocity.z, + float(robot.level_manager.check_all_coins_collected(robot.current_level)) + ] + observations.append_array(get_raycast_sensor_obs()) + + return {"obs": observations} + +func xz_distance(vector1: Vector3, vector2: Vector3): + var vec1_xz := Vector2(vector1.x, vector1.z) + var vec2_xz := Vector2(vector2.x, vector2.z) + return vec1_xz.distance_to(vec2_xz) + +func get_reward() -> float: + var current_goal_position = xz_distance(robot.global_position, + robot.current_goal_transform.origin) + + if not closest_goal_position: + closest_goal_position = current_goal_position + + if current_goal_position < closest_goal_position: + reward += (closest_goal_position - current_goal_position) / 10.0 + closest_goal_position = current_goal_position + return reward + +func get_action_space() -> Dictionary: + return { + "movement" : { + "size": 2, + "action_type": "continuous" + } + } + +func set_action(action) -> void: + robot.requested_movement = Vector3( + clampf(action.movement[0], -1.0, 1.0), + 0.0, + clampf(action.movement[1], -1.0, 1.0)).limit_length(1.0) + +func get_raycast_sensor_obs(): + var all_raycast_sensor_obs: Array[float] = [] + for raycast_sensor in sensors: + all_raycast_sensor_obs.append_array(raycast_sensor.get_observation()) + return all_raycast_sensor_obs diff --git a/scenes/robot/robot.gd b/scenes/robot/robot.gd new file mode 100644 index 0000000000000000000000000000000000000000..7b93c16fd617cd58242abe43e2dff0227c6454a3 --- /dev/null +++ b/scenes/robot/robot.gd @@ -0,0 +1,167 @@ +extends CharacterBody3D +class_name Robot + +@export var level_manager: LevelManager +@export var wheels: Array[Node3D] + +@export var acceleration: float = 25.0 +@export var rotation_speed: float = 15.0 +@export var friction: float = 15.0 +@export var max_horizontal_speed: float = 10.0 + +@export var gravity := Vector3.DOWN * 16.0 + +@onready var robot_visual: Node3D = $"robot" +@onready var ai_controller: RobotAIController = $AIController3D + +var current_level: int +var next_level + +var requested_movement: Vector3 +var max_level_reached: int = 0 +var current_goal_transform: Transform3D +var previous_distance_to_goal: float + +var conveyor_belt_areas_entered: int +var conveyor_belt_direction: int +var conveyor_belt_speed: float = 15.0 + + +func _ready(): + reset() + + +func reset(): + velocity = Vector3.ZERO + global_position = level_manager.get_spawn_position(current_level) + current_goal_transform = level_manager.randomize_goal(current_level) + previous_distance_to_goal = global_position.distance_to(current_goal_transform.origin) + + +func _physics_process(delta): + reset_on_needs_reset() + handle_movement(delta) + + +func reset_on_needs_reset(): + if ai_controller.needs_reset: + level_manager.reset_coins(current_level) + if next_level == null: + if randi_range(1, 6) == 1: + current_level = randi_range(0, current_level) + else: + current_level = next_level + next_level = null + level_manager.reset_coins(current_level) + reset() + ai_controller.reset() + + +func handle_movement(delta): + var movement := Vector3() + + if ai_controller.heuristic == "human": + if Input.is_action_pressed("ui_up"): + movement.x = -1 + if Input.is_action_pressed("ui_down"): + movement.x = 1 + if Input.is_action_pressed("ui_left"): + movement.z = 1 + if Input.is_action_pressed("ui_right"): + movement.z = -1 + movement = movement.normalized() + else: + movement = requested_movement + + apply_acceleration(movement, delta) + apply_gravity(delta) + apply_friction(delta) + apply_conveyor_belt_velocity(delta) + limit_horizontal_speed() + + move_and_slide() + + rotate_toward_movement(delta) + update_wheels_and_visual_rotation(delta) + +func apply_conveyor_belt_velocity(delta): + if conveyor_belt_areas_entered > 0: + velocity += Vector3.LEFT * conveyor_belt_direction * conveyor_belt_speed * delta + + +func limit_horizontal_speed(): + var horizontal_velocity := Vector2(velocity.x, velocity.z).limit_length(max_horizontal_speed) + velocity = Vector3(horizontal_velocity.x, velocity.y, horizontal_velocity.y) + + +func apply_acceleration(direction, delta): + velocity += direction * acceleration * delta + + +func apply_friction(delta): + velocity = velocity.move_toward(Vector3(0, velocity.y, 0), friction * delta) + + +func apply_gravity(delta): + velocity += gravity * delta + + +func rotate_toward_movement(delta): + var movement = Vector3(velocity.x, 0, velocity.z).normalized() + var look_at_target: Vector3 = global_position + movement + + if look_at_target.distance_to(global_position) > 0: + robot_visual.global_transform = ( + robot_visual + . global_transform + . interpolate_with(global_transform.looking_at(look_at_target), rotation_speed * delta) + . orthonormalized() + ) + + +func update_wheels_and_visual_rotation(delta): + var movement := Vector2(velocity.x, velocity.z).length() + for wheel in wheels: + wheel.rotate_object_local(Vector3.LEFT, movement * delta) + robot_visual.rotation.x = -0.01 * movement + + +func _on_area_3d_area_entered(area): + if area.get_collision_layer_value(1): + #print("Level goal reached") + if not level_manager.check_all_coins_collected(current_level): + return + if current_level > max_level_reached: + max_level_reached = current_level + print("max level passed: ", max_level_reached) + next_level = (current_level + 1) % level_manager.levels. size() + end_episode(1.0) + if area.get_collision_layer_value(2): + #print("Coin picked up") + level_manager.deactivate_coin(area, current_level) + ai_controller.reward += 1 + if area.get_collision_layer_value(3): + #print("On conveyor belt") + conveyor_belt_direction = 1 if randi_range(0, 1) == 0 else -1 + conveyor_belt_areas_entered += 1 + pass + if area.get_collision_layer_value(4): + #print("Enemy collision") + end_episode(-1.0) + + +func _on_area_3d_body_entered(body): + if body.get_collision_layer_value(10): + #print("Robot fell down") + end_episode(-1.0) + + +func end_episode(reward: float): + ai_controller.reward += reward + ai_controller.done = true + ai_controller.needs_reset = true + + +func _on_area_3d_area_exited(area): + if area.get_collision_layer_value(3): + conveyor_belt_areas_entered -= 1 diff --git a/scenes/robot/robot.tscn b/scenes/robot/robot.tscn new file mode 100644 index 0000000000000000000000000000000000000000..6cca3430c9117c4a65a63ccb4bc7ad2c1608d542 --- /dev/null +++ b/scenes/robot/robot.tscn @@ -0,0 +1,205 @@ +[gd_scene load_steps=7 format=3 uid="uid://3gt386v3b1ej"] + +[ext_resource type="Script" path="res://scenes/robot/robot.gd" id="1_jpfj0"] +[ext_resource type="PackedScene" uid="uid://dau8w8quwnwpj" path="res://blender/robot.blend" id="1_kysqn"] +[ext_resource type="Script" path="res://addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd" id="3_k05bk"] +[ext_resource type="Script" path="res://scenes/robot/RobotAIController.gd" id="4_l00n2"] + +[sub_resource type="CapsuleShape3D" id="CapsuleShape3D_jp65j"] +radius = 1.23023 +height = 4.205 + +[sub_resource type="BoxShape3D" id="BoxShape3D_3w2uy"] +size = Vector3(3, 3, 3) + +[node name="Robot" type="CharacterBody3D" node_paths=PackedStringArray("wheels")] +collision_layer = 2 +slide_on_ceiling = false +script = ExtResource("1_jpfj0") +wheels = [NodePath("robot/Wheel_001"), NodePath("robot/Wheel")] + +[node name="robot" parent="." instance=ExtResource("1_kysqn")] + +[node name="CollisionShape3D" type="CollisionShape3D" parent="."] +transform = Transform3D(-1, 3.89414e-07, 0, -3.89414e-07, -1, 0, 0, 0, 1, 0, 1.10713, 0) +shape = SubResource("CapsuleShape3D_jp65j") + +[node name="Node3D" type="Node3D" parent="."] +transform = Transform3D(-0.0218088, -0.607985, 0.793649, 0, 0.793838, 0.608129, -0.999762, 0.0132626, -0.0173126, 13.2659, 11.8416, -0.404609) + +[node name="Sensors" type="Node3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -0.00404263, 1.2, 0) + +[node name="WallSensor" type="Node3D" parent="Sensors"] +visible = false +script = ExtResource("3_k05bk") +boolean_class_mask = 0 +n_rays_width = 18.0 +n_rays_height = 1.0 +ray_length = 25.0 +cone_width = 360.0 +cone_height = 0.0 + +[node name="node_0 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-4.3412, 0, -24.6202) + +[node name="node_1 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-12.5, 0, -21.6506) + +[node name="node_2 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-19.1511, 0, -16.0697) + +[node name="node_3 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-23.4923, 0, -8.5505) + +[node name="node_4 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-25, 0, 1.53076e-15) + +[node name="node_5 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-23.4923, 0, 8.5505) + +[node name="node_6 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-19.1511, 0, 16.0697) + +[node name="node_7 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-12.5, 0, 21.6506) + +[node name="node_8 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(-4.3412, 0, 24.6202) + +[node name="@RayCast3D@29154" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(4.3412, 0, 24.6202) + +[node name="@RayCast3D@29155" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(12.5, 0, 21.6506) + +[node name="@RayCast3D@29156" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(19.1511, 0, 16.0697) + +[node name="node_12 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(23.4923, 0, 8.5505) + +[node name="node_13 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(25, 0, 1.53076e-15) + +[node name="node_14 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(23.4923, 0, -8.5505) + +[node name="node_15 0" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(19.1511, 0, -16.0697) + +[node name="@RayCast3D@29157" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(12.5, 0, -21.6506) + +[node name="@RayCast3D@29158" type="RayCast3D" parent="Sensors/WallSensor"] +target_position = Vector3(4.3412, 0, -24.6202) + +[node name="FloorSensor" type="Node3D" parent="Sensors"] +transform = Transform3D(1, 0, 0, 0, -4.37114e-08, -1, 0, 1, -4.37114e-08, 0, 0, 0) +visible = false +script = ExtResource("3_k05bk") +collision_mask = 5 +boolean_class_mask = 4 +n_rays_width = 4.0 +n_rays_height = 4.0 +ray_length = 15.0 +cone_width = 120.0 +cone_height = 120.0 +collide_with_areas = true +class_sensor = true + +[node name="@RayCast3D@29422" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-7.5, -10.6066, 7.5) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29423" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-10.2452, -3.88229, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29424" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-10.2452, 3.88229, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29425" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-7.5, 10.6066, 7.5) +collision_mask = 5 +collide_with_areas = true + +[node name="node_1 0" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-2.74519, -10.6066, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="node_1 1" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-3.75, -3.88229, 13.9952) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29426" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-3.75, 3.88229, 13.9952) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29427" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(-2.74519, 10.6066, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="node_2 0" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(2.74519, -10.6066, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="node_2 1" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(3.75, -3.88229, 13.9952) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29428" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(3.75, 3.88229, 13.9952) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29429" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(2.74519, 10.6066, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="node_3 0" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(7.5, -10.6066, 7.5) +collision_mask = 5 +collide_with_areas = true + +[node name="node_3 1" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(10.2452, -3.88229, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29430" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(10.2452, 3.88229, 10.2452) +collision_mask = 5 +collide_with_areas = true + +[node name="@RayCast3D@29431" type="RayCast3D" parent="Sensors/FloorSensor"] +target_position = Vector3(7.5, 10.6066, 7.5) +collision_mask = 5 +collide_with_areas = true + +[node name="Area3D" type="Area3D" parent="."] +collision_layer = 0 +collision_mask = 527 + +[node name="CollisionShape3D" type="CollisionShape3D" parent="Area3D"] +transform = Transform3D(-1, 3.89414e-07, 0, -3.89414e-07, -1, 0, 0, 0, 1, 0, 1.10713, 0) +shape = SubResource("BoxShape3D_3w2uy") + +[node name="AIController3D" type="Node3D" parent="."] +script = ExtResource("4_l00n2") +reset_after = 3500 + +[connection signal="area_entered" from="Area3D" to="." method="_on_area_3d_area_entered"] +[connection signal="area_exited" from="Area3D" to="." method="_on_area_3d_area_exited"] +[connection signal="body_entered" from="Area3D" to="." method="_on_area_3d_body_entered"] diff --git a/testing_scene/testing_scene.tscn b/testing_scene/testing_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..e2337528fb49451aed001635012354f2d0d8475f --- /dev/null +++ b/testing_scene/testing_scene.tscn @@ -0,0 +1,49 @@ +[gd_scene load_steps=7 format=3 uid="uid://b60wttcr7f5ci"] + +[ext_resource type="PackedScene" uid="uid://bsp37y3hehf5y" path="res://scenes/game_scene/game_scene.tscn" id="1_iyad5"] +[ext_resource type="Script" path="res://training_scene/SyncOverride.gd" id="2_vgdgg"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_ox2c0"] +sky_top_color = Color(0.384314, 0.454902, 0.54902, 1) +sky_horizon_color = Color(0.6, 0.616667, 0.640196, 1) + +[sub_resource type="Sky" id="Sky_t7h1l"] +sky_material = SubResource("ProceduralSkyMaterial_ox2c0") + +[sub_resource type="Environment" id="Environment_ep2c2"] +background_mode = 2 +sky = SubResource("Sky_t7h1l") +tonemap_mode = 2 +sdfgi_enabled = true +glow_enabled = true + +[sub_resource type="WorldBoundaryShape3D" id="WorldBoundaryShape3D_cs0bj"] + +[node name="TestingScene" type="Node3D"] + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_ep2c2") + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(0.707107, -0.642927, 0.294355, 0, 0.416281, 0.909236, -0.707107, -0.642927, 0.294355, 0, 0, 0) +shadow_enabled = true + +[node name="FallDownDetector" type="StaticBody3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -10.437, -143.42) +collision_layer = 512 +collision_mask = 7 + +[node name="CollisionShape3D" type="CollisionShape3D" parent="FallDownDetector"] +shape = SubResource("WorldBoundaryShape3D_cs0bj") + +[node name="GameScene" parent="." instance=ExtResource("1_iyad5")] + +[node name="GameScene2" parent="." instance=ExtResource("1_iyad5")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -90, 0, 0) + +[node name="Sync" type="Node" parent="."] +script = ExtResource("2_vgdgg") +control_mode = 2 +action_repeat = 10 +speed_up = 2 +onnx_model_path = "C:\\Users\\computer\\Documents\\godot_rl_agents\\examples\\robot.onnx" diff --git a/training_scene/SyncOverride.gd b/training_scene/SyncOverride.gd new file mode 100644 index 0000000000000000000000000000000000000000..bab17192b6f512be3cf5a38df274d8c99b717970 --- /dev/null +++ b/training_scene/SyncOverride.gd @@ -0,0 +1,7 @@ +extends "res://addons/godot_rl_agents/sync.gd" + + +func _initialize(): + super._initialize() + Engine.physics_ticks_per_second = _get_speedup() * 30 # Replace with function body. + Engine.time_scale = _get_speedup() * 1.0 diff --git a/training_scene/training_scene.tscn b/training_scene/training_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..ff604dcd275c8191cd7e8e955203f9f43c36f23a --- /dev/null +++ b/training_scene/training_scene.tscn @@ -0,0 +1,77 @@ +[gd_scene load_steps=7 format=3 uid="uid://mwsee7v5ksaq"] + +[ext_resource type="PackedScene" uid="uid://bsp37y3hehf5y" path="res://scenes/game_scene/game_scene.tscn" id="1_0cco7"] +[ext_resource type="Script" path="res://training_scene/SyncOverride.gd" id="2_m5uj8"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_1igdm"] +sky_top_color = Color(0.384314, 0.454902, 0.54902, 1) +sky_horizon_color = Color(0.6, 0.616667, 0.640196, 1) + +[sub_resource type="Sky" id="Sky_smiub"] +sky_material = SubResource("ProceduralSkyMaterial_1igdm") + +[sub_resource type="Environment" id="Environment_ljxuh"] +background_mode = 2 +sky = SubResource("Sky_smiub") +tonemap_mode = 2 + +[sub_resource type="WorldBoundaryShape3D" id="WorldBoundaryShape3D_cs0bj"] + +[node name="TrainingScene" type="Node3D"] + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_ljxuh") + +[node name="FallDownDetector" type="StaticBody3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, -10.437, -143.42) +collision_layer = 512 +collision_mask = 7 + +[node name="CollisionShape3D" type="CollisionShape3D" parent="FallDownDetector"] +shape = SubResource("WorldBoundaryShape3D_cs0bj") + +[node name="GameScene" parent="." instance=ExtResource("1_0cco7")] + +[node name="GameScene2" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -100, 0, 0) +visible = false + +[node name="GameScene3" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -200, 0, 0) +visible = false + +[node name="GameScene4" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -300, 0, 0) +visible = false + +[node name="GameScene5" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -400, 0, 0) +visible = false + +[node name="GameScene6" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -500, 0, 0) +visible = false + +[node name="GameScene7" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -600, 0, 0) +visible = false + +[node name="GameScene8" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -700, 0, 0) +visible = false + +[node name="GameScene9" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -800, 0, 0) +visible = false + +[node name="GameScene10" parent="." instance=ExtResource("1_0cco7")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -900, 0, 0) +visible = false + +[node name="Sync" type="Node" parent="."] +script = ExtResource("2_m5uj8") +action_repeat = 10 +speed_up = 2 + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(-4.37114e-08, -0.707107, 0.707107, 0, 0.707107, 0.707107, -1, 3.09086e-08, -3.09086e-08, 0, 0, 0)