diff --git a/Completed/.gitattributes b/Completed/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..8ad74f78d9c9b9b8f3d68772c6d5aa0cb3fe47e9 --- /dev/null +++ b/Completed/.gitattributes @@ -0,0 +1,2 @@ +# Normalize EOL for all files that Git considers text files. +* text=auto eol=lf diff --git a/Completed/.gitignore b/Completed/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7de8ea58b7054d16d554ddea743ca5255256b122 --- /dev/null +++ b/Completed/.gitignore @@ -0,0 +1,3 @@ +# Godot 4+ specific ignores +.godot/ +android/ diff --git a/Completed/GridRobot.csproj b/Completed/GridRobot.csproj new file mode 100644 index 0000000000000000000000000000000000000000..da3d05b0eb84d4069194eccca0237091d177450a --- /dev/null +++ b/Completed/GridRobot.csproj @@ -0,0 +1,11 @@ + + + net6.0 + net7.0 + net8.0 + true + + + + + \ No newline at end of file diff --git a/Completed/GridRobot.sln b/Completed/GridRobot.sln new file mode 100644 index 0000000000000000000000000000000000000000..c0373f32b80dd37a7e7b32e8a78f17f372fd8e63 --- /dev/null +++ b/Completed/GridRobot.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GridRobot", "GridRobot.csproj", "{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}" +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 + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU + EndGlobalSection +EndGlobal diff --git a/Completed/addons/godot_rl_agents/controller/ai_controller_2d.gd b/Completed/addons/godot_rl_agents/controller/ai_controller_2d.gd new file mode 100644 index 0000000000000000000000000000000000000000..6b8615d9de6058069ad945a4592449b705086015 --- /dev/null +++ b/Completed/addons/godot_rl_agents/controller/ai_controller_2d.gd @@ -0,0 +1,127 @@ +extends Node2D +class_name AIController2D + +enum ControlModes { + INHERIT_FROM_SYNC, ## Inherit setting from sync node + HUMAN, ## Test the environment manually + TRAINING, ## Train a model + ONNX_INFERENCE, ## Load a pretrained model using an .onnx file + RECORD_EXPERT_DEMOS ## Record observations and actions for expert demonstrations +} +@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC +## The path to a trained .onnx model file to use for inference (overrides the path set in sync node). +@export var onnx_model_path := "" +## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance. +@export var reset_after := 1000 + +@export_group("Record expert demos mode options") +## Path where the demos will be saved. The file can later be used for imitation learning. +@export var expert_demo_save_path: String +## The action that erases the last recorded episode from the currently recorded data. +@export var remove_last_episode_key: InputEvent +## Action will be repeated for n frames. Will introduce control lag if larger than 1. +## Can be used to ensure that action_repeat on inference and training matches +## the recorded demonstrations. +@export var action_repeat: int = 1 + +@export_group("Multi-policy mode options") +## Allows you to set certain agents to use different policies. +## Changing has no effect with default SB3 training. Works with Rllib example. +## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md +@export var policy_name: String = "shared_policy" + +var onnx_model: ONNXModel + +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 set_action method is not implemented when extending from ai_controller") + + +#-----------------------------------------------------------------------------# + + +#-- Methods that sometimes need implementing using the "extend script" option in Godot --# +# Only needed if you are recording expert demos with this AIController +func get_action() -> Array: + assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used") + return [] + +# -----------------------------------------------------------------------------# + +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/Completed/addons/godot_rl_agents/controller/ai_controller_3d.gd b/Completed/addons/godot_rl_agents/controller/ai_controller_3d.gd new file mode 100644 index 0000000000000000000000000000000000000000..f36d4dc01bc74aacd3e115c079c55e53edfe1e5d --- /dev/null +++ b/Completed/addons/godot_rl_agents/controller/ai_controller_3d.gd @@ -0,0 +1,128 @@ +extends Node3D +class_name AIController3D + +enum ControlModes { + INHERIT_FROM_SYNC, ## Inherit setting from sync node + HUMAN, ## Test the environment manually + TRAINING, ## Train a model + ONNX_INFERENCE, ## Load a pretrained model using an .onnx file + RECORD_EXPERT_DEMOS ## Record observations and actions for expert demonstrations +} +@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC +## The path to a trained .onnx model file to use for inference (overrides the path set in sync node). +@export var onnx_model_path := "" +## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance. +@export var reset_after := 1000 + +@export_group("Record expert demos mode options") +## Path where the demos will be saved. The file can later be used for imitation learning. +@export var expert_demo_save_path: String +## The action that erases the last recorded episode from the currently recorded data. +@export var remove_last_episode_key: InputEvent +## Action will be repeated for n frames. Will introduce control lag if larger than 1. +## Can be used to ensure that action_repeat on inference and training matches +## the recorded demonstrations. +@export var action_repeat: int = 1 + +@export_group("Multi-policy mode options") +## Allows you to set certain agents to use different policies. +## Changing has no effect with default SB3 training. Works with Rllib example. +## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md +@export var policy_name: String = "shared_policy" + +var onnx_model: ONNXModel + +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_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 set_action method is not implemented when extending from ai_controller") + + +#-----------------------------------------------------------------------------# + + +#-- Methods that sometimes need implementing using the "extend script" option in Godot --# +# Only needed if you are recording expert demos with this AIController +func get_action() -> Array: + assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used") + return [] + +# -----------------------------------------------------------------------------# + + +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/Completed/addons/godot_rl_agents/godot_rl_agents.gd b/Completed/addons/godot_rl_agents/godot_rl_agents.gd new file mode 100644 index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296 --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/icon.png b/Completed/addons/godot_rl_agents/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/Completed/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs new file mode 100644 index 0000000000000000000000000000000000000000..58d4dc253f6c8fad9dc42f881c22f0efb37c765a --- /dev/null +++ b/Completed/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs @@ -0,0 +1,109 @@ +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 + /// + /// + /// + /// Returns the output size of the model + public int Initialize(string Path, int BatchSize) + { + modelPath = Path; + batchSize = BatchSize; + SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions(); + session = LoadModel(modelPath); + return session.OutputMetadata["output"].Dimensions[1]; + } + + + /// + 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/Completed/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/Completed/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs new file mode 100644 index 0000000000000000000000000000000000000000..ad7a41cfee0dc3d497d9c1d03bd0752b09d49f3a --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/Completed/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml new file mode 100644 index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8 --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/Completed/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml new file mode 100644 index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2 --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/Completed/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd new file mode 100644 index 0000000000000000000000000000000000000000..e27f2c3ac0d139d023f09485d4dc5d1d77d94ecf --- /dev/null +++ b/Completed/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd @@ -0,0 +1,51 @@ +extends Resource +class_name ONNXModel +var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs") + +var inferencer = null + +## How many action values the model outputs +var action_output_size: int + +## Used to differentiate models +## that only output continuous action mean (e.g. sb3, cleanrl export) +## versus models that output mean and logstd (e.g. rllib export) +var action_means_only: bool + +## Whether action_means_value has been set already for this model +var action_means_only_set: bool + +# Must provide the path to the model and the batch size +func _init(model_path, batch_size): + inferencer = inferencer_script.new() + action_output_size = 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() + +# Check whether agent uses a continuous actions model with only action means or not +func set_action_means_only(agent_action_space): + action_means_only_set = true + var continuous_only: bool = true + var continuous_actions: int + for action in agent_action_space: + if not agent_action_space[action]["action_type"] == "continuous": + continuous_only = false + break + else: + continuous_actions += agent_action_space[action]["size"] + if continuous_only: + if continuous_actions == action_output_size: + action_means_only = true diff --git a/Completed/addons/godot_rl_agents/plugin.cfg b/Completed/addons/godot_rl_agents/plugin.cfg new file mode 100644 index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/Completed/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5 --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..da170ba93919a8f28510ea8fc1ab876fe5876d34 --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd @@ -0,0 +1,235 @@ +@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/Completed/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..67669a1d71a3e37d780b396633951d7d1ac79edb --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd @@ -0,0 +1,25 @@ +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/Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..9bb54ede90a6f6ffd5e65d89bf1bd561bc0832ed --- /dev/null +++ b/Completed/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, 3000, 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 = false + 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 get_observation() -> Array: + return self.calculate_raycasts() + + +func calculate_raycasts() -> Array: + var result = [] + for ray in rays: + ray.enabled = true + ray.force_raycast_update() + var distance = _get_raycast_distance(ray) + result.append(distance) + ray.enabled = false + 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/Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/Completed/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/Completed/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..476b886bb61ff69c599369a529d4399747bf4638 --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd @@ -0,0 +1,258 @@ +@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_z * _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_z * _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/Completed/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..aca3c2db480c5f61058d565ae4652916af4c51ad --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd @@ -0,0 +1,25 @@ +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/Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..96dfb6a5be126711f531cf2b9b05f87d207e306f --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd @@ -0,0 +1,63 @@ +extends Node3D +class_name RGBCameraSensor3D +var camera_pixels = null + +@onready var camera_texture := $Control/CameraTexture as Sprite2D +@onready var processed_texture := $Control/ProcessedTexture as Sprite2D +@onready var sub_viewport := $SubViewport as SubViewport +@onready var displayed_image: ImageTexture + +@export var render_image_resolution := Vector2(36, 36) +## Display size does not affect rendered or sent image resolution. +## Scale is relative to either render image or downscale image resolution +## depending on which mode is set. +@export var displayed_image_scale_factor := Vector2(8, 8) + +@export_group("Downscale image options") +## Enable to downscale the rendered image before sending the obs. +@export var downscale_image: bool = false +## If downscale_image is true, will display the downscaled image instead of rendered image. +@export var display_downscaled_image: bool = true +## This is the resolution of the image that will be sent after downscaling +@export var resized_image_resolution := Vector2(36, 36) + + +func _ready(): + sub_viewport.size = render_image_resolution + camera_texture.scale = displayed_image_scale_factor + + if downscale_image and display_downscaled_image: + camera_texture.visible = false + processed_texture.scale = displayed_image_scale_factor + else: + processed_texture.visible = false + + +func get_camera_pixel_encoding(): + var image := camera_texture.get_texture().get_image() as Image + + if downscale_image: + image.resize( + resized_image_resolution.x, resized_image_resolution.y, Image.INTERPOLATE_NEAREST + ) + if display_downscaled_image: + if not processed_texture.texture: + displayed_image = ImageTexture.create_from_image(image) + processed_texture.texture = displayed_image + else: + displayed_image.update(image) + + return image.get_data().hex_encode() + + +func get_camera_shape() -> Array: + var size = resized_image_resolution if downscale_image else render_image_resolution + + assert( + size.x >= 36 and size.y >= 36, + "Camera sensor sent image resolution must be 36x36 or larger." + ) + if sub_viewport.transparent_bg: + return [4, size.y, size.x] + else: + return [3, size.y, size.x] diff --git a/Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..d58649ca06ae2aec39a88125901537d24a9eeb43 --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn @@ -0,0 +1,35 @@ +[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="ViewportTexture_y72s3"] +viewport_path = NodePath("SubViewport") + +[node name="RGBCameraSensor3D" type="Node3D"] +script = ExtResource("1") + +[node name="RemoteTransform" type="RemoteTransform3D" parent="."] +remote_path = NodePath("../SubViewport/Camera") + +[node name="SubViewport" type="SubViewport" parent="."] +size = Vector2i(36, 36) +render_target_update_mode = 3 + +[node name="Camera" 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 +metadata/_edit_use_anchors_ = true + +[node name="CameraTexture" type="Sprite2D" parent="Control"] +texture = SubResource("ViewportTexture_y72s3") +centered = false + +[node name="ProcessedTexture" type="Sprite2D" parent="Control"] +centered = false diff --git a/Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..8fe294469678787d9e85cadae3c2f8b02eac6740 --- /dev/null +++ b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd @@ -0,0 +1,185 @@ +@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 = false + 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/Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/Completed/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55 --- /dev/null +++ b/Completed/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/Completed/addons/godot_rl_agents/sync.gd b/Completed/addons/godot_rl_agents/sync.gd new file mode 100644 index 0000000000000000000000000000000000000000..23fc629123c316e71e338837778080742d8d086f --- /dev/null +++ b/Completed/addons/godot_rl_agents/sync.gd @@ -0,0 +1,587 @@ +extends Node +class_name Sync + +# --fixed-fps 2000 --disable-render-loop + +enum ControlModes { + HUMAN, ## Test the environment manually + TRAINING, ## Train a model + ONNX_INFERENCE ## Load a pretrained model using an .onnx file +} +@export var control_mode: ControlModes = ControlModes.TRAINING +## Action will be repeated for n frames (Godot physics steps). +@export_range(1, 10, 1, "or_greater") var action_repeat := 8 +## Speeds up the physics in the environment to enable faster training. +@export_range(0, 10, 0.01, "or_greater") var speed_up := 1.0 +## The path to a trained .onnx model file to use for inference (only needed for the 'Onnx Inference' control mode). +@export var onnx_model_path := "" + +# Onnx model stored for each requested path +var onnx_models: Dictionary + +@onready var start_time = Time.get_ticks_msec() + +const MAJOR_VERSION := "0" +const MINOR_VERSION := "7" +const DEFAULT_PORT := "11008" +const DEFAULT_SEED := "1" +var stream: StreamPeerTCP = null +var connected = false +var message_center +var should_connect = true + +var all_agents: Array +var agents_training: Array +## Policy name of each agent, for use with multi-policy multi-agent RL cases +var agents_training_policy_names: Array[String] = ["shared_policy"] +var agents_inference: Array +var agents_heuristic: Array + +## For recording expert demos +var agent_demo_record: Node +## File path for writing recorded trajectories +var expert_demo_save_path: String +## Stores recorded trajectories +var demo_trajectories: Array +## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead) +var current_demo_trajectory: Array + +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_training: Array[Dictionary] = [] +var _action_space_inference: Array[Dictionary] = [] +var _obs_space_training: Array[Dictionary] = [] + +# Called when the node enters the scene tree for the first time. +func _ready(): + await get_parent().ready + get_tree().set_pause(true) + _initialize() + #await get_tree().create_timer(1.0).timeout + get_tree().set_pause(false) + + +func _initialize(): + _get_agents() + 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", all_agents) + + _initialize_training_agents() + _initialize_inference_agents() + _initialize_demo_recording() + + _set_seed() + _set_action_repeat() + initialized = true + + +func _initialize_training_agents(): + if agents_training.size() > 0: + _obs_space_training.resize(agents_training.size()) + _action_space_training.resize(agents_training.size()) + for agent_idx in range(0, agents_training.size()): + _obs_space_training[agent_idx] = agents_training[agent_idx].get_obs_space() + _action_space_training[agent_idx] = agents_training[agent_idx].get_action_space() + connected = connect_to_server() + if connected: + _set_heuristic("model", agents_training) + _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?" + ) + + +func _initialize_inference_agents(): + if agents_inference.size() > 0: + if control_mode == 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_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1) + + for agent in agents_inference: + var action_space = agent.get_action_space() + _action_space_inference.append(action_space) + + var agent_onnx_model: ONNXModel + if agent.onnx_model_path.is_empty(): + assert( + onnx_models.has(onnx_model_path), + ( + "Node %s has no onnx model path set " % agent.get_path() + + "and sync node's control mode is not set to OnnxInference. " + + "Either add the path to the AIController, " + + "or if you want to use the path set on sync node instead, " + + "set control mode to OnnxInference." + ) + ) + prints( + "Info: AIController %s" % agent.get_path(), + "has no onnx model path set.", + "Using path set on the sync node instead." + ) + agent_onnx_model = onnx_models[onnx_model_path] + else: + if not onnx_models.has(agent.onnx_model_path): + assert( + FileAccess.file_exists(agent.onnx_model_path), + ( + "Onnx Model Path set on %s node does not exist: %s" + % [agent.get_path(), agent.onnx_model_path] + ) + ) + onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1) + agent_onnx_model = onnx_models[agent.onnx_model_path] + + agent.onnx_model = agent_onnx_model + if not agent_onnx_model.action_means_only_set: + agent_onnx_model.set_action_means_only(action_space) + + _set_heuristic("model", agents_inference) + + +func _initialize_demo_recording(): + if agent_demo_record: + expert_demo_save_path = agent_demo_record.expert_demo_save_path + assert( + not expert_demo_save_path.is_empty(), + "Expert demo save path set in %s is empty." % agent_demo_record.get_path() + ) + + InputMap.add_action("RemoveLastDemoEpisode") + InputMap.action_add_event( + "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key + ) + current_demo_trajectory.resize(2) + current_demo_trajectory[0] = [] + current_demo_trajectory[1] = [] + agent_demo_record.heuristic = "demo_record" + + +func _physics_process(_delta): + # two modes, human control, agent control + # pause tree, send obs, get actions, set actions, unpause tree + + _demo_record_process() + + if n_action_steps % action_repeat != 0: + n_action_steps += 1 + return + + n_action_steps += 1 + + _training_process() + _inference_process() + _heuristic_process() + + +func _training_process(): + if connected: + get_tree().set_pause(true) + + if just_reset: + just_reset = false + var obs = _get_obs_from_agents(agents_training) + + 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(agents_training) + + var reply = {"type": "step", "obs": obs, "reward": reward, "done": done} + _send_dict_as_json_message(reply) + + var handled = handle_message() + + +func _inference_process(): + if agents_inference.size() > 0: + var obs: Array = _get_obs_from_agents(agents_inference) + var actions = [] + + for agent_id in range(0, agents_inference.size()): + var model: ONNXModel = agents_inference[agent_id].onnx_model + var action = model.run_inference( + obs[agent_id]["obs"], 1.0 + ) + var action_dict = _extract_action_dict( + action["output"], _action_space_inference[agent_id], model.action_means_only + ) + actions.append(action_dict) + + _set_agent_actions(actions, agents_inference) + _reset_agents_if_done(agents_inference) + get_tree().set_pause(false) + + +func _demo_record_process(): + if not agent_demo_record: + return + + if Input.is_action_just_pressed("RemoveLastDemoEpisode"): + print("[Sync script][Demo recorder] Removing last recorded episode.") + demo_trajectories.remove_at(demo_trajectories.size() - 1) + print("Remaining episode count: %d" % demo_trajectories.size()) + + if n_action_steps % agent_demo_record.action_repeat != 0: + return + + var obs_dict: Dictionary = agent_demo_record.get_obs() + + # Get the current obs from the agent + assert( + obs_dict.has("obs"), + "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from." + ) + current_demo_trajectory[0].append(obs_dict.obs) + + # Get the action applied for the current obs from the agent + agent_demo_record.set_action() + var acts = agent_demo_record.get_action() + + var terminal = agent_demo_record.get_done() + # Record actions only for non-terminal states + if terminal: + agent_demo_record.set_done_false() + else: + current_demo_trajectory[1].append(acts) + + if terminal: + #current_demo_trajectory[2].append(true) + demo_trajectories.append(current_demo_trajectory.duplicate(true)) + print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size()) + current_demo_trajectory[0].clear() + current_demo_trajectory[1].clear() + + +func _heuristic_process(): + for agent in agents_heuristic: + _reset_agents_if_done(agents_heuristic) + + +func _extract_action_dict(action_array: Array, action_space: Dictionary, action_means_only: bool): + var index = 0 + var result = {} + for key in action_space.keys(): + var size = action_space[key]["size"] + var action_type = action_space[key]["action_type"] + if action_type == "discrete": + var largest_logit: float # Value of the largest logit for this action in the actions array + var largest_logit_idx: int # Index of the largest logit for this action in the actions array + for logit_idx in range(0, size): + var logit_value = action_array[index + logit_idx] + if logit_value > largest_logit: + largest_logit = logit_value + largest_logit_idx = logit_idx + result[key] = largest_logit_idx # Index of the largest logit is the discrete action value + index += size + elif action_type == "continuous": + # For continous actions, we only take the action mean values + result[key] = clamp_array(action_array.slice(index, index + size), -1.0, 1.0) + if action_means_only: + index += size # model only outputs action means, so we move index by size + else: + index += size * 2 # model outputs logstd after action mean, we skip the logstd part + + else: + assert(false, 'Only "discrete" and "continuous" action types supported. Found: %s action type set.' % action_type) + + + return result + + +## For AIControllers that inherit mode from sync, sets the correct mode. +func _set_agent_mode(agent: Node): + var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC + + if agent_inherits_mode: + match control_mode: + ControlModes.HUMAN: + agent.control_mode = agent.ControlModes.HUMAN + ControlModes.TRAINING: + agent.control_mode = agent.ControlModes.TRAINING + ControlModes.ONNX_INFERENCE: + agent.control_mode = agent.ControlModes.ONNX_INFERENCE + + +func _get_agents(): + all_agents = get_tree().get_nodes_in_group("AGENT") + for agent in all_agents: + _set_agent_mode(agent) + + if agent.control_mode == agent.ControlModes.TRAINING: + agents_training.append(agent) + elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE: + agents_inference.append(agent) + elif agent.control_mode == agent.ControlModes.HUMAN: + agents_heuristic.append(agent) + elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS: + assert( + not agent_demo_record, + "Currently only a single AIController can be used for recording expert demos." + ) + agent_demo_record = agent + + var training_agent_count = agents_training.size() + agents_training_policy_names.resize(training_agent_count) + for i in range(0, training_agent_count): + agents_training_policy_names[i] = agents_training[i].policy_name + + +func _set_heuristic(heuristic, agents: Array): + 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, "", false)) + + +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_training, + "action_space": _action_space_training, + "n_agents": len(agents_training), + "agent_policy_names": agents_training_policy_names + } + _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_float() + + +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_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, agents_training) + 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 all_agents: + returns.append(agent.call(method)) + + return returns + + +func _reset_agents_if_done(agents = all_agents): + for agent in agents: + if agent.get_done(): + agent.set_done_false() + + +func _reset_agents(agents = all_agents): + for agent in agents: + agent.needs_reset = true + #agent.reset() + + +func _get_obs_from_agents(agents: Array = all_agents): + var obs = [] + for agent in agents: + obs.append(agent.get_obs()) + return obs + + +func _get_reward_from_agents(agents: Array = agents_training): + var rewards = [] + for agent in agents: + rewards.append(agent.get_reward()) + agent.zero_reward() + return rewards + + +func _get_done_from_agents(agents: Array = agents_training): + 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, agents: Array = all_agents): + 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 + + +## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor) +func _notification(what): + if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty(): + return + + if what == NOTIFICATION_PREDELETE: + var json_string = JSON.stringify(demo_trajectories, "", false) + var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE) + + if not file: + var error: Error = FileAccess.get_open_error() + assert(not error, "There was an error opening the file: %d" % error) + + file.store_line(json_string) + var error = file.get_error() + assert(not error, "There was an error after trying to write to the file: %d" % error) diff --git a/Completed/assets/car.glb b/Completed/assets/car.glb new file mode 100644 index 0000000000000000000000000000000000000000..c52ef0113e1c19afb8f94a9c84497738510d7909 Binary files /dev/null and b/Completed/assets/car.glb differ diff --git a/Completed/assets/goal_tile.glb b/Completed/assets/goal_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..c3cf428c57bdd269573df94d4c4e350a8014bf16 Binary files /dev/null and b/Completed/assets/goal_tile.glb differ diff --git a/Completed/assets/orange_tile.glb b/Completed/assets/orange_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..54e2bb94780f4f4734fc807d6e96ca199a8fc22d Binary files /dev/null and b/Completed/assets/orange_tile.glb differ diff --git a/Completed/assets/road_tile.glb b/Completed/assets/road_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..1e794d818859536e431362160a80fff491c1a004 Binary files /dev/null and b/Completed/assets/road_tile.glb differ diff --git a/Completed/assets/robot.glb b/Completed/assets/robot.glb new file mode 100644 index 0000000000000000000000000000000000000000..f14e0b7b5745356247a5d453520a772f795d90bd Binary files /dev/null and b/Completed/assets/robot.glb differ diff --git a/Completed/assets/tree_tile.glb b/Completed/assets/tree_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..30d1a8480f03028d272411270dca9177d31e5590 Binary files /dev/null and b/Completed/assets/tree_tile.glb differ diff --git a/Completed/icon.svg b/Completed/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..3fe4f4ae8c2985fa888004c01af65739669cd443 --- /dev/null +++ b/Completed/icon.svg @@ -0,0 +1 @@ + diff --git a/Completed/license.md b/Completed/license.md new file mode 100644 index 0000000000000000000000000000000000000000..bcb8621e930c3c568e012f46a1411fc51d289027 --- /dev/null +++ b/Completed/license.md @@ -0,0 +1,5 @@ +CrossTheRoad Environment made by Ivan Dodic (https://github.com/Ivan-267) + +The following license is only for the graphical assets in the folder "assets", specifically .glb files: +Author: Ivan Dodic (https://github.com/Ivan-267), +License: https://creativecommons.org/licenses/by/4.0/ \ No newline at end of file diff --git a/Completed/model.onnx b/Completed/model.onnx new file mode 100644 index 0000000000000000000000000000000000000000..8c315271d02f47fb01f1129942f2e5919f2c6d08 --- /dev/null +++ b/Completed/model.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6d2345651e25fb09773faa5fc1ee47f74e27de57b52b8dbc3a818bb9b6b76c3 +size 39900 diff --git a/Completed/project.godot b/Completed/project.godot new file mode 100644 index 0000000000000000000000000000000000000000..640acded0527e40fb8add7ae1cc82264fbed9b78 --- /dev/null +++ b/Completed/project.godot @@ -0,0 +1,55 @@ +; 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="CrossTheRoadEnv" +run/main_scene="res://scenes/training_scene.tscn" +config/features=PackedStringArray("4.3", "C#", "Forward Plus") +config/icon="res://icon.svg" + +[dotnet] + +project/assembly_name="GridRobot" + +[editor_plugins] + +enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg") + +[input] + +move_left={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":97,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194319,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} +move_right={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":100,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194321,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} +move_up={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":119,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194320,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} +move_down={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":115,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194322,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} + +[rendering] + +anti_aliasing/name="CrossTheRoad" diff --git a/Completed/scenes/car.tscn b/Completed/scenes/car.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a0c5260e5fb503eb40e875d8a7e1cc4c21cf1502 --- /dev/null +++ b/Completed/scenes/car.tscn @@ -0,0 +1,10 @@ +[gd_scene load_steps=3 format=3 uid="uid://bhk60xl5s8pmm"] + +[ext_resource type="Script" path="res://scripts/car.gd" id="1_psb6d"] +[ext_resource type="PackedScene" uid="uid://b2n1vy10th4qo" path="res://assets/car.glb" id="2_fqh82"] + +[node name="Car" type="Node3D"] +transform = Transform3D(-4.37114e-08, 0, 1, 0, 1, 0, -1, 0, -4.37114e-08, 0, 0.75, 0) +script = ExtResource("1_psb6d") + +[node name="car" parent="." instance=ExtResource("2_fqh82")] diff --git a/Completed/scenes/game_scene.tscn b/Completed/scenes/game_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..b8d5a08abb0394fa4d30c94a8463233d39c391fa --- /dev/null +++ b/Completed/scenes/game_scene.tscn @@ -0,0 +1,28 @@ +[gd_scene load_steps=6 format=3 uid="uid://dn2auvcty4aoe"] + +[ext_resource type="PackedScene" uid="uid://bsuw6dqwq2e3v" path="res://scenes/robot.tscn" id="1_2k47m"] +[ext_resource type="PackedScene" uid="uid://crui8soua8lj2" path="res://scenes/tile.tscn" id="2_ltmsi"] +[ext_resource type="Script" path="res://scripts/car_manager.gd" id="4_jfcfq"] +[ext_resource type="Script" path="res://scripts/grid_map.gd" id="4_lrlqi"] +[ext_resource type="PackedScene" uid="uid://bhk60xl5s8pmm" path="res://scenes/car.tscn" id="4_nsbp8"] + +[node name="GameScene" type="Node3D"] + +[node name="Camera3D" type="Camera3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 0.615661, 0.788011, 0, -0.788011, 0.615661, 5, 10, 15.95) +size = 12.748 + +[node name="Map" type="Node3D" parent="."] +script = ExtResource("4_lrlqi") +tile = ExtResource("2_ltmsi") + +[node name="Tiles" type="Node3D" parent="Map"] + +[node name="Cars" type="Node3D" parent="." node_paths=PackedStringArray("map")] +script = ExtResource("4_jfcfq") +map = NodePath("../Map") +car_scene = ExtResource("4_nsbp8") + +[node name="Robot" parent="." node_paths=PackedStringArray("map", "car_manager") instance=ExtResource("1_2k47m")] +map = NodePath("../Map") +car_manager = NodePath("../Cars") diff --git a/Completed/scenes/onnx_inference_scene.tscn b/Completed/scenes/onnx_inference_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..f390722621546e801f84c2a7ae6c7702acc575a6 --- /dev/null +++ b/Completed/scenes/onnx_inference_scene.tscn @@ -0,0 +1,35 @@ +[gd_scene load_steps=6 format=3 uid="uid://qnxlq4cwno4t"] + +[ext_resource type="PackedScene" uid="uid://dn2auvcty4aoe" path="res://scenes/game_scene.tscn" id="1_0y8h2"] +[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_5kbv3"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_bdk3k"] +sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) +ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) + +[sub_resource type="Sky" id="Sky_uw47m"] +sky_material = SubResource("ProceduralSkyMaterial_bdk3k") + +[sub_resource type="Environment" id="Environment_iamhl"] +background_mode = 2 +sky = SubResource("Sky_uw47m") +tonemap_mode = 2 +glow_enabled = true + +[node name="OnnxInferenceScene" type="Node3D"] + +[node name="GameScene" parent="." instance=ExtResource("1_0y8h2")] + +[node name="Sync" type="Node" parent="."] +script = ExtResource("2_5kbv3") +control_mode = 2 +action_repeat = 1 +speed_up = 0.1 +onnx_model_path = "model.onnx" + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_iamhl") + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(-0.866025, -0.433013, 0.25, 0, 0.5, 0.866025, -0.5, 0.75, -0.433013, 0, 0, 0) +shadow_enabled = true diff --git a/Completed/scenes/robot.tscn b/Completed/scenes/robot.tscn new file mode 100644 index 0000000000000000000000000000000000000000..774d29089e1a55f0be88691b8880b36f5ebf1cc1 --- /dev/null +++ b/Completed/scenes/robot.tscn @@ -0,0 +1,207 @@ +[gd_scene load_steps=8 format=3 uid="uid://bsuw6dqwq2e3v"] + +[ext_resource type="PackedScene" uid="uid://bb2je1c8jc1qr" path="res://assets/robot.glb" id="1_n7jto"] +[ext_resource type="Script" path="res://scripts/robot.gd" id="1_vywkg"] +[ext_resource type="Script" path="res://scripts/robot_ai_controller.gd" id="5_sx7mj"] + +[sub_resource type="Animation" id="Animation_2kfmf"] +length = 0.001 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Robot/Arm:rotation") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Robot/Arm_001:rotation") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Robot/Torso:position") +tracks/2/interp = 1 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/3/type = "value" +tracks/3/imported = false +tracks/3/enabled = true +tracks/3/path = NodePath("Robot/Head:position") +tracks/3/interp = 1 +tracks/3/loop_wrap = true +tracks/3/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/4/type = "value" +tracks/4/imported = false +tracks/4/enabled = true +tracks/4/path = NodePath("Robot/Head:rotation") +tracks/4/interp = 1 +tracks/4/loop_wrap = true +tracks/4/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} + +[sub_resource type="Animation" id="Animation_ly00x"] +resource_name = "idle" +length = 4.0 +loop_mode = 1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Robot/Arm:rotation") +tracks/0/interp = 2 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0, 2), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0.349066, 0, 0.0610865)] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Robot/Arm_001:rotation") +tracks/1/interp = 2 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0, 2), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(-0.349066, 0, -0.148353)] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Robot/Head:rotation") +tracks/2/interp = 2 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0, 1, 2, 3), +"transitions": PackedFloat32Array(1, 1, 1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, 0.162316, 0.0488692), Vector3(0, 0, 0), Vector3(0.139626, -0.178024, 0.0226893)] +} + +[sub_resource type="Animation" id="Animation_6jb0l"] +resource_name = "idle" +loop_mode = 1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Robot/Arm:rotation") +tracks/0/interp = 2 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0, 0.5), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, -0.174533, 0)] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Robot/Arm_001:rotation") +tracks/1/interp = 2 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0, 0.5), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, 0.174533, 0)] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Robot/Torso:position") +tracks/2/interp = 2 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0, 0.25, 0.5), +"transitions": PackedFloat32Array(1, 1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, -0.01, 0), Vector3(0, 0, 0)] +} +tracks/3/type = "value" +tracks/3/imported = false +tracks/3/enabled = true +tracks/3/path = NodePath("Robot/Head:position") +tracks/3/interp = 1 +tracks/3/loop_wrap = true +tracks/3/keys = { +"times": PackedFloat32Array(0, 0.5), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, -0.02, 0)] +} +tracks/4/type = "value" +tracks/4/imported = false +tracks/4/enabled = true +tracks/4/path = NodePath("Robot/Head:rotation") +tracks/4/interp = 1 +tracks/4/loop_wrap = true +tracks/4/keys = { +"times": PackedFloat32Array(0, 0.25, 0.5), +"transitions": PackedFloat32Array(1, 1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(-0.0349066, 0, 0), Vector3(0, 0, 0)] +} + +[sub_resource type="AnimationLibrary" id="AnimationLibrary_g7kmm"] +_data = { +"RESET": SubResource("Animation_2kfmf"), +"idle": SubResource("Animation_ly00x"), +"walking": SubResource("Animation_6jb0l") +} + +[node name="Robot" type="Node3D" groups=["resetable"]] +script = ExtResource("1_vywkg") +print_game_status_enabled = true +metadata/_edit_lock_ = true + +[node name="AIController3D" type="Node3D" parent="."] +script = ExtResource("5_sx7mj") +reset_after = 40 + +[node name="robot" parent="." instance=ExtResource("1_n7jto")] +transform = Transform3D(2, 0, 0, 0, 2, 0, 0, 0, 2, 0, -0.1, 0) + +[node name="Robot" parent="robot" index="0"] +transform = Transform3D(-4.37114e-08, 0, 1, 0, 1, 0, -1, 0, -4.37114e-08, 0, 0, 0) + +[node name="Arm_001" parent="robot/Robot" index="1"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.00394951, 0, -0.18) + +[node name="AnimationPlayer" type="AnimationPlayer" parent="robot"] +libraries = { +"": SubResource("AnimationLibrary_g7kmm") +} +autoplay = "idle" +speed_scale = 16.0 + +[editable path="robot"] diff --git a/Completed/scenes/tile.tscn b/Completed/scenes/tile.tscn new file mode 100644 index 0000000000000000000000000000000000000000..6c056ea0c5cbb163b88c15bad57741b2d4aff1bc --- /dev/null +++ b/Completed/scenes/tile.tscn @@ -0,0 +1,18 @@ +[gd_scene load_steps=6 format=3 uid="uid://crui8soua8lj2"] + +[ext_resource type="Script" path="res://scripts/tile.gd" id="1_xode2"] +[ext_resource type="PackedScene" uid="uid://bfb0o41scdp70" path="res://assets/road_tile.glb" id="2_c5l1q"] +[ext_resource type="PackedScene" uid="uid://bn7tu2v2dgfuc" path="res://assets/orange_tile.glb" id="3_rlmbm"] +[ext_resource type="PackedScene" uid="uid://dtq61doicjsbq" path="res://assets/tree_tile.glb" id="4_p4mpm"] +[ext_resource type="PackedScene" uid="uid://6wdk5i0xsijn" path="res://assets/goal_tile.glb" id="5_p4gbw"] + +[node name="Tile" type="Node3D"] +script = ExtResource("1_xode2") + +[node name="orange_tile" parent="." instance=ExtResource("3_rlmbm")] + +[node name="road_tile" parent="." instance=ExtResource("2_c5l1q")] + +[node name="tree_tile" parent="." instance=ExtResource("4_p4mpm")] + +[node name="goal_tile" parent="." instance=ExtResource("5_p4gbw")] diff --git a/Completed/scenes/training_scene.tscn b/Completed/scenes/training_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..97766d19bb0b9ef66caaef13fa81fca3e22c8498 --- /dev/null +++ b/Completed/scenes/training_scene.tscn @@ -0,0 +1,42 @@ +[gd_scene load_steps=6 format=3 uid="uid://cl152s178wgm5"] + +[ext_resource type="PackedScene" uid="uid://dn2auvcty4aoe" path="res://scenes/game_scene.tscn" id="1_ft0b8"] +[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_sk0r2"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_bdk3k"] +sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) +ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) + +[sub_resource type="Sky" id="Sky_uw47m"] +sky_material = SubResource("ProceduralSkyMaterial_bdk3k") + +[sub_resource type="Environment" id="Environment_iamhl"] +background_mode = 2 +sky = SubResource("Sky_uw47m") +tonemap_mode = 2 +glow_enabled = true + +[node name="TrainingScene" type="Node3D"] + +[node name="GameScene" parent="." instance=ExtResource("1_ft0b8")] + +[node name="GameScene2" parent="." instance=ExtResource("1_ft0b8")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -30, 0, 0) + +[node name="GameScene3" parent="." instance=ExtResource("1_ft0b8")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 30, 0, 0) + +[node name="GameScene4" parent="." instance=ExtResource("1_ft0b8")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -400) + +[node name="Sync" type="Node" parent="."] +script = ExtResource("2_sk0r2") +action_repeat = 1 +speed_up = 8.0 + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_iamhl") + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(-0.866025, -0.433013, 0.25, 0, 0.5, 0.866025, -0.5, 0.75, -0.433013, 0, 0, 0) +shadow_enabled = true diff --git a/Completed/scripts/car.gd b/Completed/scripts/car.gd new file mode 100644 index 0000000000000000000000000000000000000000..37fd8e959f6040e2c3dd4566d3cebceb924e8fb2 --- /dev/null +++ b/Completed/scripts/car.gd @@ -0,0 +1,18 @@ +extends Node3D +class_name Car + +## Car, moves along x axis, +## and changes direction once left or right edge is reached + +#region Initialized by car manager +var step_size: int +var left_edge_x: int +var right_edge_x: int +var current_direction: int = 1 +#endregion + +func _physics_process(_delta: float) -> void: + if not (position.x > left_edge_x and position.x < right_edge_x): + current_direction = -current_direction + rotation.y = current_direction / 2.0 * PI + position.x += step_size * current_direction diff --git a/Completed/scripts/car_manager.gd b/Completed/scripts/car_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..8d86ce8b5296251f3167cdd2c0a2e93e0d807fa7 --- /dev/null +++ b/Completed/scripts/car_manager.gd @@ -0,0 +1,48 @@ +extends Node3D +class_name CarManager + +@export var map: Map +@export var car_scene: PackedScene + +var car_left_edge_x: int +var car_right_edge_x: int + +@onready var cars: Array[Node] = get_children() + +# Called when the node enters the scene tree for the first time. +func _ready() -> void: + for road_row_idx in map.road_rows.size(): + create_car() + reset() + + +func create_car(): + var new_car = car_scene.instantiate() + add_child(new_car) + cars.append(new_car) + + +func reset(): + # If there are more cars than the current map layout road rows, remove + # the extra cars + while cars.size() > map.road_rows.size(): + cars[cars.size() - 1].queue_free() + cars.remove_at(cars.size() - 1) + + # If there are less cars than the current map layout road rows, + # add more cars + while cars.size() < map.road_rows.size(): + create_car() + + # Set car edge positions (at which they turn), position and other properties + for car_id in cars.size(): + var car = cars[car_id] + car.left_edge_x = 0 + car.right_edge_x = (map.grid_size_x - 1) * map.tile_size + car.step_size = map.tile_size + + car.position.x = range(car.left_edge_x + 2, car.right_edge_x - 2, 2).pick_random() + car.position.y = map.tile_size / 2 + 0.75 # 0.75 is to make the bottom of the car be at road height + car.position.z = map.road_rows[car_id] * 2 + + car.current_direction = 1 if randi_range(0, 1) == 0 else -1 diff --git a/Completed/scripts/grid_map.gd b/Completed/scripts/grid_map.gd new file mode 100644 index 0000000000000000000000000000000000000000..e1f4270ae9e736c12a86e7a9339aa7ecf263222e --- /dev/null +++ b/Completed/scripts/grid_map.gd @@ -0,0 +1,122 @@ +extends Node3D +class_name Map + +@export var tile: PackedScene + +# Grid positions +var instantiated_tiles: Dictionary +var tile_positions: Array[Vector3i] + +var player_start_position: Vector3i +var goal_position: Vector3i + +## Size of each tile, adjust manually if using larger or smaller tiles +var tile_size: int = 2 + +## Determines the width of the grid, tested with 6 +## may need adjustments for the AIController obs as it captures +## 6 cells from the left and right of the player +var grid_size_x = 6 + +## Number of rows in the grid +var grid_size_z = 0 + +var road_rows: Array[int] + +var tiles_instantiated: bool = false + +## Removes all tile nodes on first launch (if any are added in the editor) +## and on subsequent calls, it hides all tiles +func remove_all_tiles(): + for tile in $Tiles.get_children(): + if not tiles_instantiated: + tile.queue_free() + else: + tile.hide_all() + + tile_positions.clear() + road_rows.clear() + grid_size_z = 0 + +## Adds a tile to the grid, takes a scene containing the tile and grid position +func create_tile(tile_name: Tile.TileNames, grid_position: Vector3i): + if instantiated_tiles.has(grid_position): + instantiated_tiles[grid_position].set_tile(tile_name) + tile_positions.append(grid_position) + return + + var new_tile = tile.instantiate() as Tile + new_tile.position = grid_position * tile_size + $Tiles.add_child(new_tile) + instantiated_tiles[grid_position] = new_tile + new_tile.set_tile(tile_name) + tile_positions.append(grid_position) + +func _ready(): + set_cells() + +## You can set the layout by adjusting each row with set_row_cells() +## Note: Changing size after initial start is not supported +## you can change the order or rows or how many of the second tiles to add +## as long as the total size (number of rows, width) remains the same + +func set_cells(): + remove_all_tiles() + + add_row(Tile.TileNames.orange, Tile.TileNames.goal, 1) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) + add_row(Tile.TileNames.road) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange) + + set_player_position_to_last_row() + + tiles_instantiated = true + +func reset(): + if not is_node_ready(): + await ready + set_cells() + +func get_tile(grid_pos: Vector3i): + if not grid_pos in tile_positions: + return null + return instantiated_tiles[grid_pos] + + +func get_grid_position(global_pos: Vector3i): + var grid_pos = Vector3i(to_local(global_pos) / 2.0) + return grid_pos + +func set_row_tiles(row: int, tile: Tile.TileNames, second_tile: Tile.TileNames = Tile.TileNames.orange, second_tile_count: int = 0): + var first_tile_columns: Array = range(grid_size_x) + + if second_tile_count: + for i in second_tile_count: + first_tile_columns.remove_at(randi_range(0, first_tile_columns.size() - 1)) + + for column in range(grid_size_x): + var tile_to_create: Tile.TileNames + if column in first_tile_columns: + tile_to_create = tile + else: + tile_to_create = second_tile + var tile_grid_coords := Vector3i(column, 0, row) + create_tile(tile_to_create, tile_grid_coords) + if tile_to_create == Tile.TileNames.goal: + goal_position = tile_grid_coords + + if tile == Tile.TileNames.road: + road_rows.append(row) + +func add_row(tile: Tile.TileNames, second_tile: Tile.TileNames = Tile.TileNames.orange, second_tile_count: int = 0): + set_row_tiles(grid_size_z, tile, second_tile, second_tile_count) + grid_size_z += 1 + +func set_player_position_to_grid_row(row: int): + player_start_position = to_global(Vector3i(range(0, grid_size_x - 1, 2).pick_random(), 0, row * tile_size)) + +func set_player_position_to_last_row(): + set_player_position_to_grid_row(grid_size_z - 1) diff --git a/Completed/scripts/robot.gd b/Completed/scripts/robot.gd new file mode 100644 index 0000000000000000000000000000000000000000..5201429169d3e3152c036b7b22fb26f3d3f88875 --- /dev/null +++ b/Completed/scripts/robot.gd @@ -0,0 +1,111 @@ +extends Node3D +class_name Player + +## Whether to print the game success/failed messsages to console +@export var print_game_status_enabled: bool + +## How far the robot can move per step +@export var movement_step := 2.0 + +@export var map: Map +@export var car_manager: CarManager + +@onready var _ai_controller := $AIController3D +@onready var visual_robot: Node3D = $robot + +var last_dist_to_goal + +#region Set by AIController +var requested_movement: Vector3 +#endregion + + +func _ready(): + reset() + + +func _physics_process(delta): + # Set to true by the sync node when reset is requested from Python (starting training, evaluation, etc.) + if _ai_controller.needs_reset: + game_over() + _process_movement(delta) + + +func _process_movement(_delta): + for car in car_manager.cars: + if get_grid_position() == map.get_grid_position(car.global_position): + # If a car has moved to the current player position, end episode + game_over(0) + print_game_status("Failed, hit car while standing") + + if requested_movement: + # Move the robot to the requested position + global_position += (requested_movement * movement_step) + # Update the visual rotation of the robot to look toward the direction of last requested movement + visual_robot.global_rotation_degrees.y = rad_to_deg(atan2(-requested_movement.x, -requested_movement.z)) + + var grid_position: Vector3i = get_grid_position() + var tile: Tile = map.get_tile(grid_position) + + if not tile: + # Push the robot back if there's no tile to move to (out of map boundary) + global_position -= (requested_movement * movement_step) + elif tile.id == tile.TileNames.tree: + # Push the robot back if it has moved to a tree tile + global_position -= (requested_movement * movement_step) + elif tile.id == tile.TileNames.goal: + # If a goal tile is reached, end episode with reward +1 + game_over(1) + print_game_status("Success, reached goal") + else: + for car in car_manager.cars: + if get_grid_position() == map.get_grid_position(car.global_position): + # If the robot moved to a car's current position, end episode + game_over(0) + print_game_status("Failed, hit car while walking") + + # After processing the move, zero the movement for the next step + # (only in case of human control) + if _ai_controller.control_mode == AIController3D.ControlModes.HUMAN: + requested_movement = Vector3.ZERO + + reward_approaching_goal() + + +## Adds a positive reward if the robot approaches the goal +func reward_approaching_goal(): + var grid_pos: Vector3i = get_grid_position() + var dist_to_goal = grid_pos.distance_to(map.goal_position) + if last_dist_to_goal == null: last_dist_to_goal = dist_to_goal + + if dist_to_goal < last_dist_to_goal: + _ai_controller.reward += (last_dist_to_goal - dist_to_goal) / 10.0 + last_dist_to_goal = dist_to_goal + + +func get_grid_position() -> Vector3i: + return map.get_grid_position(global_position) + + +func game_over(reward = 0.0): + _ai_controller.done = true + _ai_controller.reward += reward + _ai_controller.reset() + reset() + + +func reset(): + last_dist_to_goal = null + # Order of resetting is important: + # We reset the map first, which sets a new player start position + # and the road segments (needed to know where to spawn the cars) + map.reset() + # after that, we can set the player position + global_position = Vector3(map.player_start_position) + Vector3.UP * 1.5 + # and also reset or create (on first start) the cars + car_manager.reset() + + +func print_game_status(message: String): + if print_game_status_enabled: + print(message) diff --git a/Completed/scripts/robot_ai_controller.gd b/Completed/scripts/robot_ai_controller.gd new file mode 100644 index 0000000000000000000000000000000000000000..0340202eac33334c674e477f8e801559006d35a1 --- /dev/null +++ b/Completed/scripts/robot_ai_controller.gd @@ -0,0 +1,121 @@ +extends AIController3D +class_name RobotAIController + +@onready var player := get_parent() as Player + + +func get_obs() -> Dictionary: + var observations := Array() + var player_pos = player.get_grid_position() + + # Determines how many grid cells the AI can observe + # e.g. front refers to "up" looking from above, + # and does not rotate with the robot, same with others. + # Set to observe all cells from two rows in front of player, + # 0 behind + var visible_rows_in_front_of_player: int = 2 + var visible_rows_behind_the_player: int = 0 + + # Set to observe the entire width of the grid on both sides + # so it will always see all cells up to 2 rows in front. + var visible_columns_left_of_player: int = player.map.grid_size_x + var visible_columns_right_of_player: int = player.map.grid_size_x + + # For tiles near player we provide [direction, id] (e.g: [-1, 0]) + # direction is -1 or 1 for cars, 0 for static tiles + # if a car is in a tile, we override the id of tile underneath + + # Car ID is the ID of the last tile + 1 + var car_id = Tile.TileNames.size() + + # If there is no tile placed at the grid coord, we use -1 as id + var no_tile_id: int = -1 + + # Note: We don't need to include the player position directly in obs + # as we are always including data for cells "around" the player, + # so the player location relative to those cells is implicitly included + + for z in range( + player_pos.z - visible_rows_in_front_of_player, + player_pos.z + visible_rows_behind_the_player + 1 + ): + for x in range( + player_pos.x - visible_columns_left_of_player, + player_pos.x + visible_columns_right_of_player + 1 + ): + var grid_pos := Vector3i(x, 0, z) + var tile: Tile = player.map.get_tile(grid_pos) + + if not tile: + observations.append_array([0, no_tile_id]) + else: + var is_car: bool + for car in player.car_manager.cars: + if grid_pos == player.map.get_grid_position(car.global_position): + is_car = true + observations.append(car.current_direction) + if is_car: + observations.append(car_id) + else: + observations.append_array([0, tile.id]) + + return {"obs": observations} + + +func get_reward() -> float: + return reward + + +func _process(_delta: float) -> void: + # In case of human control, we get the user input + if control_mode == ControlModes.HUMAN: + get_user_input() + + +func _physics_process(_delta: float) -> void: + # Reset on timeout, this is implemented in parent class to set needs_reset to true, + # we are re-implementing here to call player.game_over() that handles the game reset. + n_steps += 1 + if n_steps > reset_after: + player.game_over(0) + player.print_game_status("Episode timed out.") + + +## Defines the actions for the AI agent +func get_action_space() -> Dictionary: + return { + "movement": {"size": 5, "action_type": "discrete"}, + } + + +## Applies AI control actions to the robot +func set_action(action = null) -> void: + # We have specified discrete action type with size 5, + # which means there are 5 possible values that the agent can output + # for each step, i.e. one of: 0, 1, 2, 3, 4, + # we use those to allow the agent to move in 4 directions, + # + there is a 'no movement' action. + # First convert to int to use match as action value is of float type. + match int(action.movement): + 0: + player.requested_movement = Vector3.LEFT + 1: + player.requested_movement = Vector3.RIGHT + 2: + player.requested_movement = Vector3.FORWARD + 3: + player.requested_movement = Vector3.BACK + 4: + player.requested_movement = Vector3.ZERO + + +## Applies user input actions to the robot +func get_user_input() -> void: + if Input.is_action_just_pressed("move_up"): + player.requested_movement = Vector3.FORWARD + elif Input.is_action_just_pressed("move_right"): + player.requested_movement = Vector3.RIGHT + elif Input.is_action_just_pressed("move_down"): + player.requested_movement = Vector3.BACK + elif Input.is_action_just_pressed("move_left"): + player.requested_movement = Vector3.LEFT diff --git a/Completed/scripts/tile.gd b/Completed/scripts/tile.gd new file mode 100644 index 0000000000000000000000000000000000000000..264742f5a67ab2d1682e49a430fef1497385c30f --- /dev/null +++ b/Completed/scripts/tile.gd @@ -0,0 +1,30 @@ +extends Node3D +class_name Tile + +## Tile class it allows setting the visible tile design by +## hiding the nodes with not currently used tile designs. +## (Intended to be used with tile.tscn) + +## Tile names, must be in the same order as child nodes +enum TileNames { + orange, + road, + tree, + goal +} + +## ID of the current set tile +var id: int + +@onready var tiles: Array = get_children() + +## Sets the specified tile mesh to be visible, and hides others +func set_tile(tile_name: TileNames): + hide_all() + id = int(tile_name) + tiles[id].visible = true + +## Hides all tiles +func hide_all(): + for tile in tiles: + tile.visible = false diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0059fc55a8dc1f0325ff771a3083c3b63fc2f491 --- /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 CrossTheRoad 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 jtatman/godot_rl_CrossTheRoad +``` + + + diff --git a/Starter/.gitattributes b/Starter/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..8ad74f78d9c9b9b8f3d68772c6d5aa0cb3fe47e9 --- /dev/null +++ b/Starter/.gitattributes @@ -0,0 +1,2 @@ +# Normalize EOL for all files that Git considers text files. +* text=auto eol=lf diff --git a/Starter/.gitignore b/Starter/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..7de8ea58b7054d16d554ddea743ca5255256b122 --- /dev/null +++ b/Starter/.gitignore @@ -0,0 +1,3 @@ +# Godot 4+ specific ignores +.godot/ +android/ diff --git a/Starter/GridRobot.csproj b/Starter/GridRobot.csproj new file mode 100644 index 0000000000000000000000000000000000000000..da3d05b0eb84d4069194eccca0237091d177450a --- /dev/null +++ b/Starter/GridRobot.csproj @@ -0,0 +1,11 @@ + + + net6.0 + net7.0 + net8.0 + true + + + + + \ No newline at end of file diff --git a/Starter/GridRobot.sln b/Starter/GridRobot.sln new file mode 100644 index 0000000000000000000000000000000000000000..c0373f32b80dd37a7e7b32e8a78f17f372fd8e63 --- /dev/null +++ b/Starter/GridRobot.sln @@ -0,0 +1,19 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GridRobot", "GridRobot.csproj", "{A5E8FC07-E73E-476D-93D5-2EA7814E2E23}" +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 + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportDebug|Any CPU.ActiveCfg = ExportDebug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportDebug|Any CPU.Build.0 = ExportDebug|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportRelease|Any CPU.ActiveCfg = ExportRelease|Any CPU + {A5E8FC07-E73E-476D-93D5-2EA7814E2E23}.ExportRelease|Any CPU.Build.0 = ExportRelease|Any CPU + EndGlobalSection +EndGlobal diff --git a/Starter/addons/godot_rl_agents/controller/ai_controller_2d.gd b/Starter/addons/godot_rl_agents/controller/ai_controller_2d.gd new file mode 100644 index 0000000000000000000000000000000000000000..6b8615d9de6058069ad945a4592449b705086015 --- /dev/null +++ b/Starter/addons/godot_rl_agents/controller/ai_controller_2d.gd @@ -0,0 +1,127 @@ +extends Node2D +class_name AIController2D + +enum ControlModes { + INHERIT_FROM_SYNC, ## Inherit setting from sync node + HUMAN, ## Test the environment manually + TRAINING, ## Train a model + ONNX_INFERENCE, ## Load a pretrained model using an .onnx file + RECORD_EXPERT_DEMOS ## Record observations and actions for expert demonstrations +} +@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC +## The path to a trained .onnx model file to use for inference (overrides the path set in sync node). +@export var onnx_model_path := "" +## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance. +@export var reset_after := 1000 + +@export_group("Record expert demos mode options") +## Path where the demos will be saved. The file can later be used for imitation learning. +@export var expert_demo_save_path: String +## The action that erases the last recorded episode from the currently recorded data. +@export var remove_last_episode_key: InputEvent +## Action will be repeated for n frames. Will introduce control lag if larger than 1. +## Can be used to ensure that action_repeat on inference and training matches +## the recorded demonstrations. +@export var action_repeat: int = 1 + +@export_group("Multi-policy mode options") +## Allows you to set certain agents to use different policies. +## Changing has no effect with default SB3 training. Works with Rllib example. +## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md +@export var policy_name: String = "shared_policy" + +var onnx_model: ONNXModel + +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 set_action method is not implemented when extending from ai_controller") + + +#-----------------------------------------------------------------------------# + + +#-- Methods that sometimes need implementing using the "extend script" option in Godot --# +# Only needed if you are recording expert demos with this AIController +func get_action() -> Array: + assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used") + return [] + +# -----------------------------------------------------------------------------# + +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/Starter/addons/godot_rl_agents/controller/ai_controller_3d.gd b/Starter/addons/godot_rl_agents/controller/ai_controller_3d.gd new file mode 100644 index 0000000000000000000000000000000000000000..f36d4dc01bc74aacd3e115c079c55e53edfe1e5d --- /dev/null +++ b/Starter/addons/godot_rl_agents/controller/ai_controller_3d.gd @@ -0,0 +1,128 @@ +extends Node3D +class_name AIController3D + +enum ControlModes { + INHERIT_FROM_SYNC, ## Inherit setting from sync node + HUMAN, ## Test the environment manually + TRAINING, ## Train a model + ONNX_INFERENCE, ## Load a pretrained model using an .onnx file + RECORD_EXPERT_DEMOS ## Record observations and actions for expert demonstrations +} +@export var control_mode: ControlModes = ControlModes.INHERIT_FROM_SYNC +## The path to a trained .onnx model file to use for inference (overrides the path set in sync node). +@export var onnx_model_path := "" +## Once the number of steps has passed, the flag 'needs_reset' will be set to 'true' for this instance. +@export var reset_after := 1000 + +@export_group("Record expert demos mode options") +## Path where the demos will be saved. The file can later be used for imitation learning. +@export var expert_demo_save_path: String +## The action that erases the last recorded episode from the currently recorded data. +@export var remove_last_episode_key: InputEvent +## Action will be repeated for n frames. Will introduce control lag if larger than 1. +## Can be used to ensure that action_repeat on inference and training matches +## the recorded demonstrations. +@export var action_repeat: int = 1 + +@export_group("Multi-policy mode options") +## Allows you to set certain agents to use different policies. +## Changing has no effect with default SB3 training. Works with Rllib example. +## Tutorial: https://github.com/edbeeching/godot_rl_agents/blob/main/docs/TRAINING_MULTIPLE_POLICIES.md +@export var policy_name: String = "shared_policy" + +var onnx_model: ONNXModel + +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_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 set_action method is not implemented when extending from ai_controller") + + +#-----------------------------------------------------------------------------# + + +#-- Methods that sometimes need implementing using the "extend script" option in Godot --# +# Only needed if you are recording expert demos with this AIController +func get_action() -> Array: + assert(false, "the get_action method is not implemented in extended AIController but demo_recorder is used") + return [] + +# -----------------------------------------------------------------------------# + + +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/Starter/addons/godot_rl_agents/godot_rl_agents.gd b/Starter/addons/godot_rl_agents/godot_rl_agents.gd new file mode 100644 index 0000000000000000000000000000000000000000..e4fe13693a598c808aca1b64051d1c0c70783296 --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/icon.png b/Starter/addons/godot_rl_agents/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ccb4ca000e3e1cf659fe367ab5bff67c1eb3467d --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs b/Starter/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs new file mode 100644 index 0000000000000000000000000000000000000000..58d4dc253f6c8fad9dc42f881c22f0efb37c765a --- /dev/null +++ b/Starter/addons/godot_rl_agents/onnx/csharp/ONNXInference.cs @@ -0,0 +1,109 @@ +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 + /// + /// + /// + /// Returns the output size of the model + public int Initialize(string Path, int BatchSize) + { + modelPath = Path; + batchSize = BatchSize; + SessionOpt = SessionConfigurator.MakeConfiguredSessionOptions(); + session = LoadModel(modelPath); + return session.OutputMetadata["output"].Dimensions[1]; + } + + + /// + 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/Starter/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs b/Starter/addons/godot_rl_agents/onnx/csharp/SessionConfigurator.cs new file mode 100644 index 0000000000000000000000000000000000000000..ad7a41cfee0dc3d497d9c1d03bd0752b09d49f3a --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml b/Starter/addons/godot_rl_agents/onnx/csharp/docs/ONNXInference.xml new file mode 100644 index 0000000000000000000000000000000000000000..91b07d607dc89f11e957e13758d8c0ee4fb72be8 --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml b/Starter/addons/godot_rl_agents/onnx/csharp/docs/SessionConfigurator.xml new file mode 100644 index 0000000000000000000000000000000000000000..f160c02f0d4cab92e10f799b6f4c5a71d4d6c0f2 --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd b/Starter/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd new file mode 100644 index 0000000000000000000000000000000000000000..e27f2c3ac0d139d023f09485d4dc5d1d77d94ecf --- /dev/null +++ b/Starter/addons/godot_rl_agents/onnx/wrapper/ONNX_wrapper.gd @@ -0,0 +1,51 @@ +extends Resource +class_name ONNXModel +var inferencer_script = load("res://addons/godot_rl_agents/onnx/csharp/ONNXInference.cs") + +var inferencer = null + +## How many action values the model outputs +var action_output_size: int + +## Used to differentiate models +## that only output continuous action mean (e.g. sb3, cleanrl export) +## versus models that output mean and logstd (e.g. rllib export) +var action_means_only: bool + +## Whether action_means_value has been set already for this model +var action_means_only_set: bool + +# Must provide the path to the model and the batch size +func _init(model_path, batch_size): + inferencer = inferencer_script.new() + action_output_size = 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() + +# Check whether agent uses a continuous actions model with only action means or not +func set_action_means_only(agent_action_space): + action_means_only_set = true + var continuous_only: bool = true + var continuous_actions: int + for action in agent_action_space: + if not agent_action_space[action]["action_type"] == "continuous": + continuous_only = false + break + else: + continuous_actions += agent_action_space[action]["size"] + if continuous_only: + if continuous_actions == action_output_size: + action_means_only = true diff --git a/Starter/addons/godot_rl_agents/plugin.cfg b/Starter/addons/godot_rl_agents/plugin.cfg new file mode 100644 index 0000000000000000000000000000000000000000..b1bc988c80e3fe68e6d4279691fd5892e5ef323d --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn b/Starter/addons/godot_rl_agents/sensors/sensors_2d/ExampleRaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5edb6c7fc9da56e625d57185bdbafdbcc3fc67c5 --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..da170ba93919a8f28510ea8fc1ab876fe5876d34 --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_2d/GridSensor2D.gd @@ -0,0 +1,235 @@ +@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/Starter/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..67669a1d71a3e37d780b396633951d7d1ac79edb --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_2d/ISensor2D.gd @@ -0,0 +1,25 @@ +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/Starter/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.gd new file mode 100644 index 0000000000000000000000000000000000000000..9bb54ede90a6f6ffd5e65d89bf1bd561bc0832ed --- /dev/null +++ b/Starter/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, 3000, 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 = false + 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 get_observation() -> Array: + return self.calculate_raycasts() + + +func calculate_raycasts() -> Array: + var result = [] + for ray in rays: + ray.enabled = true + ray.force_raycast_update() + var distance = _get_raycast_distance(ray) + result.append(distance) + ray.enabled = false + 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/Starter/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn b/Starter/addons/godot_rl_agents/sensors/sensors_2d/RaycastSensor2D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..5ca402c08305efedbfc6afd0a1893a0ca2e11cfd --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn b/Starter/addons/godot_rl_agents/sensors/sensors_3d/ExampleRaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a8057c7619cbb835709d2704074b0d5ebfa00a0c --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..476b886bb61ff69c599369a529d4399747bf4638 --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_3d/GridSensor3D.gd @@ -0,0 +1,258 @@ +@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_z * _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_z * _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/Starter/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..aca3c2db480c5f61058d565ae4652916af4c51ad --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_3d/ISensor3D.gd @@ -0,0 +1,25 @@ +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/Starter/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..96dfb6a5be126711f531cf2b9b05f87d207e306f --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.gd @@ -0,0 +1,63 @@ +extends Node3D +class_name RGBCameraSensor3D +var camera_pixels = null + +@onready var camera_texture := $Control/CameraTexture as Sprite2D +@onready var processed_texture := $Control/ProcessedTexture as Sprite2D +@onready var sub_viewport := $SubViewport as SubViewport +@onready var displayed_image: ImageTexture + +@export var render_image_resolution := Vector2(36, 36) +## Display size does not affect rendered or sent image resolution. +## Scale is relative to either render image or downscale image resolution +## depending on which mode is set. +@export var displayed_image_scale_factor := Vector2(8, 8) + +@export_group("Downscale image options") +## Enable to downscale the rendered image before sending the obs. +@export var downscale_image: bool = false +## If downscale_image is true, will display the downscaled image instead of rendered image. +@export var display_downscaled_image: bool = true +## This is the resolution of the image that will be sent after downscaling +@export var resized_image_resolution := Vector2(36, 36) + + +func _ready(): + sub_viewport.size = render_image_resolution + camera_texture.scale = displayed_image_scale_factor + + if downscale_image and display_downscaled_image: + camera_texture.visible = false + processed_texture.scale = displayed_image_scale_factor + else: + processed_texture.visible = false + + +func get_camera_pixel_encoding(): + var image := camera_texture.get_texture().get_image() as Image + + if downscale_image: + image.resize( + resized_image_resolution.x, resized_image_resolution.y, Image.INTERPOLATE_NEAREST + ) + if display_downscaled_image: + if not processed_texture.texture: + displayed_image = ImageTexture.create_from_image(image) + processed_texture.texture = displayed_image + else: + displayed_image.update(image) + + return image.get_data().hex_encode() + + +func get_camera_shape() -> Array: + var size = resized_image_resolution if downscale_image else render_image_resolution + + assert( + size.x >= 36 and size.y >= 36, + "Camera sensor sent image resolution must be 36x36 or larger." + ) + if sub_viewport.transparent_bg: + return [4, size.y, size.x] + else: + return [3, size.y, size.x] diff --git a/Starter/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..d58649ca06ae2aec39a88125901537d24a9eeb43 --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RGBCameraSensor3D.tscn @@ -0,0 +1,35 @@ +[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="ViewportTexture_y72s3"] +viewport_path = NodePath("SubViewport") + +[node name="RGBCameraSensor3D" type="Node3D"] +script = ExtResource("1") + +[node name="RemoteTransform" type="RemoteTransform3D" parent="."] +remote_path = NodePath("../SubViewport/Camera") + +[node name="SubViewport" type="SubViewport" parent="."] +size = Vector2i(36, 36) +render_target_update_mode = 3 + +[node name="Camera" 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 +metadata/_edit_use_anchors_ = true + +[node name="CameraTexture" type="Sprite2D" parent="Control"] +texture = SubResource("ViewportTexture_y72s3") +centered = false + +[node name="ProcessedTexture" type="Sprite2D" parent="Control"] +centered = false diff --git a/Starter/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd new file mode 100644 index 0000000000000000000000000000000000000000..8fe294469678787d9e85cadae3c2f8b02eac6740 --- /dev/null +++ b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.gd @@ -0,0 +1,185 @@ +@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 = false + 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/Starter/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn b/Starter/addons/godot_rl_agents/sensors/sensors_3d/RaycastSensor3D.tscn new file mode 100644 index 0000000000000000000000000000000000000000..35f9796596b2fb79bfcfe31e3d3a9637d9008e55 --- /dev/null +++ b/Starter/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/Starter/addons/godot_rl_agents/sync.gd b/Starter/addons/godot_rl_agents/sync.gd new file mode 100644 index 0000000000000000000000000000000000000000..23fc629123c316e71e338837778080742d8d086f --- /dev/null +++ b/Starter/addons/godot_rl_agents/sync.gd @@ -0,0 +1,587 @@ +extends Node +class_name Sync + +# --fixed-fps 2000 --disable-render-loop + +enum ControlModes { + HUMAN, ## Test the environment manually + TRAINING, ## Train a model + ONNX_INFERENCE ## Load a pretrained model using an .onnx file +} +@export var control_mode: ControlModes = ControlModes.TRAINING +## Action will be repeated for n frames (Godot physics steps). +@export_range(1, 10, 1, "or_greater") var action_repeat := 8 +## Speeds up the physics in the environment to enable faster training. +@export_range(0, 10, 0.01, "or_greater") var speed_up := 1.0 +## The path to a trained .onnx model file to use for inference (only needed for the 'Onnx Inference' control mode). +@export var onnx_model_path := "" + +# Onnx model stored for each requested path +var onnx_models: Dictionary + +@onready var start_time = Time.get_ticks_msec() + +const MAJOR_VERSION := "0" +const MINOR_VERSION := "7" +const DEFAULT_PORT := "11008" +const DEFAULT_SEED := "1" +var stream: StreamPeerTCP = null +var connected = false +var message_center +var should_connect = true + +var all_agents: Array +var agents_training: Array +## Policy name of each agent, for use with multi-policy multi-agent RL cases +var agents_training_policy_names: Array[String] = ["shared_policy"] +var agents_inference: Array +var agents_heuristic: Array + +## For recording expert demos +var agent_demo_record: Node +## File path for writing recorded trajectories +var expert_demo_save_path: String +## Stores recorded trajectories +var demo_trajectories: Array +## A trajectory includes obs: Array, acts: Array, terminal (set in Python env instead) +var current_demo_trajectory: Array + +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_training: Array[Dictionary] = [] +var _action_space_inference: Array[Dictionary] = [] +var _obs_space_training: Array[Dictionary] = [] + +# Called when the node enters the scene tree for the first time. +func _ready(): + await get_parent().ready + get_tree().set_pause(true) + _initialize() + #await get_tree().create_timer(1.0).timeout + get_tree().set_pause(false) + + +func _initialize(): + _get_agents() + 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", all_agents) + + _initialize_training_agents() + _initialize_inference_agents() + _initialize_demo_recording() + + _set_seed() + _set_action_repeat() + initialized = true + + +func _initialize_training_agents(): + if agents_training.size() > 0: + _obs_space_training.resize(agents_training.size()) + _action_space_training.resize(agents_training.size()) + for agent_idx in range(0, agents_training.size()): + _obs_space_training[agent_idx] = agents_training[agent_idx].get_obs_space() + _action_space_training[agent_idx] = agents_training[agent_idx].get_action_space() + connected = connect_to_server() + if connected: + _set_heuristic("model", agents_training) + _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?" + ) + + +func _initialize_inference_agents(): + if agents_inference.size() > 0: + if control_mode == 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_models[onnx_model_path] = ONNXModel.new(onnx_model_path, 1) + + for agent in agents_inference: + var action_space = agent.get_action_space() + _action_space_inference.append(action_space) + + var agent_onnx_model: ONNXModel + if agent.onnx_model_path.is_empty(): + assert( + onnx_models.has(onnx_model_path), + ( + "Node %s has no onnx model path set " % agent.get_path() + + "and sync node's control mode is not set to OnnxInference. " + + "Either add the path to the AIController, " + + "or if you want to use the path set on sync node instead, " + + "set control mode to OnnxInference." + ) + ) + prints( + "Info: AIController %s" % agent.get_path(), + "has no onnx model path set.", + "Using path set on the sync node instead." + ) + agent_onnx_model = onnx_models[onnx_model_path] + else: + if not onnx_models.has(agent.onnx_model_path): + assert( + FileAccess.file_exists(agent.onnx_model_path), + ( + "Onnx Model Path set on %s node does not exist: %s" + % [agent.get_path(), agent.onnx_model_path] + ) + ) + onnx_models[agent.onnx_model_path] = ONNXModel.new(agent.onnx_model_path, 1) + agent_onnx_model = onnx_models[agent.onnx_model_path] + + agent.onnx_model = agent_onnx_model + if not agent_onnx_model.action_means_only_set: + agent_onnx_model.set_action_means_only(action_space) + + _set_heuristic("model", agents_inference) + + +func _initialize_demo_recording(): + if agent_demo_record: + expert_demo_save_path = agent_demo_record.expert_demo_save_path + assert( + not expert_demo_save_path.is_empty(), + "Expert demo save path set in %s is empty." % agent_demo_record.get_path() + ) + + InputMap.add_action("RemoveLastDemoEpisode") + InputMap.action_add_event( + "RemoveLastDemoEpisode", agent_demo_record.remove_last_episode_key + ) + current_demo_trajectory.resize(2) + current_demo_trajectory[0] = [] + current_demo_trajectory[1] = [] + agent_demo_record.heuristic = "demo_record" + + +func _physics_process(_delta): + # two modes, human control, agent control + # pause tree, send obs, get actions, set actions, unpause tree + + _demo_record_process() + + if n_action_steps % action_repeat != 0: + n_action_steps += 1 + return + + n_action_steps += 1 + + _training_process() + _inference_process() + _heuristic_process() + + +func _training_process(): + if connected: + get_tree().set_pause(true) + + if just_reset: + just_reset = false + var obs = _get_obs_from_agents(agents_training) + + 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(agents_training) + + var reply = {"type": "step", "obs": obs, "reward": reward, "done": done} + _send_dict_as_json_message(reply) + + var handled = handle_message() + + +func _inference_process(): + if agents_inference.size() > 0: + var obs: Array = _get_obs_from_agents(agents_inference) + var actions = [] + + for agent_id in range(0, agents_inference.size()): + var model: ONNXModel = agents_inference[agent_id].onnx_model + var action = model.run_inference( + obs[agent_id]["obs"], 1.0 + ) + var action_dict = _extract_action_dict( + action["output"], _action_space_inference[agent_id], model.action_means_only + ) + actions.append(action_dict) + + _set_agent_actions(actions, agents_inference) + _reset_agents_if_done(agents_inference) + get_tree().set_pause(false) + + +func _demo_record_process(): + if not agent_demo_record: + return + + if Input.is_action_just_pressed("RemoveLastDemoEpisode"): + print("[Sync script][Demo recorder] Removing last recorded episode.") + demo_trajectories.remove_at(demo_trajectories.size() - 1) + print("Remaining episode count: %d" % demo_trajectories.size()) + + if n_action_steps % agent_demo_record.action_repeat != 0: + return + + var obs_dict: Dictionary = agent_demo_record.get_obs() + + # Get the current obs from the agent + assert( + obs_dict.has("obs"), + "Demo recorder needs an 'obs' key in get_obs() returned dictionary to record obs from." + ) + current_demo_trajectory[0].append(obs_dict.obs) + + # Get the action applied for the current obs from the agent + agent_demo_record.set_action() + var acts = agent_demo_record.get_action() + + var terminal = agent_demo_record.get_done() + # Record actions only for non-terminal states + if terminal: + agent_demo_record.set_done_false() + else: + current_demo_trajectory[1].append(acts) + + if terminal: + #current_demo_trajectory[2].append(true) + demo_trajectories.append(current_demo_trajectory.duplicate(true)) + print("[Sync script][Demo recorder] Recorded episode count: %d" % demo_trajectories.size()) + current_demo_trajectory[0].clear() + current_demo_trajectory[1].clear() + + +func _heuristic_process(): + for agent in agents_heuristic: + _reset_agents_if_done(agents_heuristic) + + +func _extract_action_dict(action_array: Array, action_space: Dictionary, action_means_only: bool): + var index = 0 + var result = {} + for key in action_space.keys(): + var size = action_space[key]["size"] + var action_type = action_space[key]["action_type"] + if action_type == "discrete": + var largest_logit: float # Value of the largest logit for this action in the actions array + var largest_logit_idx: int # Index of the largest logit for this action in the actions array + for logit_idx in range(0, size): + var logit_value = action_array[index + logit_idx] + if logit_value > largest_logit: + largest_logit = logit_value + largest_logit_idx = logit_idx + result[key] = largest_logit_idx # Index of the largest logit is the discrete action value + index += size + elif action_type == "continuous": + # For continous actions, we only take the action mean values + result[key] = clamp_array(action_array.slice(index, index + size), -1.0, 1.0) + if action_means_only: + index += size # model only outputs action means, so we move index by size + else: + index += size * 2 # model outputs logstd after action mean, we skip the logstd part + + else: + assert(false, 'Only "discrete" and "continuous" action types supported. Found: %s action type set.' % action_type) + + + return result + + +## For AIControllers that inherit mode from sync, sets the correct mode. +func _set_agent_mode(agent: Node): + var agent_inherits_mode: bool = agent.control_mode == agent.ControlModes.INHERIT_FROM_SYNC + + if agent_inherits_mode: + match control_mode: + ControlModes.HUMAN: + agent.control_mode = agent.ControlModes.HUMAN + ControlModes.TRAINING: + agent.control_mode = agent.ControlModes.TRAINING + ControlModes.ONNX_INFERENCE: + agent.control_mode = agent.ControlModes.ONNX_INFERENCE + + +func _get_agents(): + all_agents = get_tree().get_nodes_in_group("AGENT") + for agent in all_agents: + _set_agent_mode(agent) + + if agent.control_mode == agent.ControlModes.TRAINING: + agents_training.append(agent) + elif agent.control_mode == agent.ControlModes.ONNX_INFERENCE: + agents_inference.append(agent) + elif agent.control_mode == agent.ControlModes.HUMAN: + agents_heuristic.append(agent) + elif agent.control_mode == agent.ControlModes.RECORD_EXPERT_DEMOS: + assert( + not agent_demo_record, + "Currently only a single AIController can be used for recording expert demos." + ) + agent_demo_record = agent + + var training_agent_count = agents_training.size() + agents_training_policy_names.resize(training_agent_count) + for i in range(0, training_agent_count): + agents_training_policy_names[i] = agents_training[i].policy_name + + +func _set_heuristic(heuristic, agents: Array): + 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, "", false)) + + +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_training, + "action_space": _action_space_training, + "n_agents": len(agents_training), + "agent_policy_names": agents_training_policy_names + } + _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_float() + + +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_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, agents_training) + 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 all_agents: + returns.append(agent.call(method)) + + return returns + + +func _reset_agents_if_done(agents = all_agents): + for agent in agents: + if agent.get_done(): + agent.set_done_false() + + +func _reset_agents(agents = all_agents): + for agent in agents: + agent.needs_reset = true + #agent.reset() + + +func _get_obs_from_agents(agents: Array = all_agents): + var obs = [] + for agent in agents: + obs.append(agent.get_obs()) + return obs + + +func _get_reward_from_agents(agents: Array = agents_training): + var rewards = [] + for agent in agents: + rewards.append(agent.get_reward()) + agent.zero_reward() + return rewards + + +func _get_done_from_agents(agents: Array = agents_training): + 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, agents: Array = all_agents): + 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 + + +## Save recorded export demos on window exit (Close game window instead of "Stop" button in Godot Editor) +func _notification(what): + if demo_trajectories.size() == 0 or expert_demo_save_path.is_empty(): + return + + if what == NOTIFICATION_PREDELETE: + var json_string = JSON.stringify(demo_trajectories, "", false) + var file = FileAccess.open(expert_demo_save_path, FileAccess.WRITE) + + if not file: + var error: Error = FileAccess.get_open_error() + assert(not error, "There was an error opening the file: %d" % error) + + file.store_line(json_string) + var error = file.get_error() + assert(not error, "There was an error after trying to write to the file: %d" % error) diff --git a/Starter/assets/car.glb b/Starter/assets/car.glb new file mode 100644 index 0000000000000000000000000000000000000000..c52ef0113e1c19afb8f94a9c84497738510d7909 Binary files /dev/null and b/Starter/assets/car.glb differ diff --git a/Starter/assets/goal_tile.glb b/Starter/assets/goal_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..c3cf428c57bdd269573df94d4c4e350a8014bf16 Binary files /dev/null and b/Starter/assets/goal_tile.glb differ diff --git a/Starter/assets/orange_tile.glb b/Starter/assets/orange_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..54e2bb94780f4f4734fc807d6e96ca199a8fc22d Binary files /dev/null and b/Starter/assets/orange_tile.glb differ diff --git a/Starter/assets/road_tile.glb b/Starter/assets/road_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..1e794d818859536e431362160a80fff491c1a004 Binary files /dev/null and b/Starter/assets/road_tile.glb differ diff --git a/Starter/assets/robot.glb b/Starter/assets/robot.glb new file mode 100644 index 0000000000000000000000000000000000000000..f14e0b7b5745356247a5d453520a772f795d90bd Binary files /dev/null and b/Starter/assets/robot.glb differ diff --git a/Starter/assets/tree_tile.glb b/Starter/assets/tree_tile.glb new file mode 100644 index 0000000000000000000000000000000000000000..30d1a8480f03028d272411270dca9177d31e5590 Binary files /dev/null and b/Starter/assets/tree_tile.glb differ diff --git a/Starter/icon.svg b/Starter/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..3fe4f4ae8c2985fa888004c01af65739669cd443 --- /dev/null +++ b/Starter/icon.svg @@ -0,0 +1 @@ + diff --git a/Starter/license.md b/Starter/license.md new file mode 100644 index 0000000000000000000000000000000000000000..bcb8621e930c3c568e012f46a1411fc51d289027 --- /dev/null +++ b/Starter/license.md @@ -0,0 +1,5 @@ +CrossTheRoad Environment made by Ivan Dodic (https://github.com/Ivan-267) + +The following license is only for the graphical assets in the folder "assets", specifically .glb files: +Author: Ivan Dodic (https://github.com/Ivan-267), +License: https://creativecommons.org/licenses/by/4.0/ \ No newline at end of file diff --git a/Starter/project.godot b/Starter/project.godot new file mode 100644 index 0000000000000000000000000000000000000000..640acded0527e40fb8add7ae1cc82264fbed9b78 --- /dev/null +++ b/Starter/project.godot @@ -0,0 +1,55 @@ +; 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="CrossTheRoadEnv" +run/main_scene="res://scenes/training_scene.tscn" +config/features=PackedStringArray("4.3", "C#", "Forward Plus") +config/icon="res://icon.svg" + +[dotnet] + +project/assembly_name="GridRobot" + +[editor_plugins] + +enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg") + +[input] + +move_left={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":97,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194319,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} +move_right={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":100,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194321,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} +move_up={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":119,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194320,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} +move_down={ +"deadzone": 0.5, +"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":115,"location":0,"echo":false,"script":null) +, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194322,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null) +] +} + +[rendering] + +anti_aliasing/name="CrossTheRoad" diff --git a/Starter/scenes/car.tscn b/Starter/scenes/car.tscn new file mode 100644 index 0000000000000000000000000000000000000000..a0c5260e5fb503eb40e875d8a7e1cc4c21cf1502 --- /dev/null +++ b/Starter/scenes/car.tscn @@ -0,0 +1,10 @@ +[gd_scene load_steps=3 format=3 uid="uid://bhk60xl5s8pmm"] + +[ext_resource type="Script" path="res://scripts/car.gd" id="1_psb6d"] +[ext_resource type="PackedScene" uid="uid://b2n1vy10th4qo" path="res://assets/car.glb" id="2_fqh82"] + +[node name="Car" type="Node3D"] +transform = Transform3D(-4.37114e-08, 0, 1, 0, 1, 0, -1, 0, -4.37114e-08, 0, 0.75, 0) +script = ExtResource("1_psb6d") + +[node name="car" parent="." instance=ExtResource("2_fqh82")] diff --git a/Starter/scenes/game_scene.tscn b/Starter/scenes/game_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..b8d5a08abb0394fa4d30c94a8463233d39c391fa --- /dev/null +++ b/Starter/scenes/game_scene.tscn @@ -0,0 +1,28 @@ +[gd_scene load_steps=6 format=3 uid="uid://dn2auvcty4aoe"] + +[ext_resource type="PackedScene" uid="uid://bsuw6dqwq2e3v" path="res://scenes/robot.tscn" id="1_2k47m"] +[ext_resource type="PackedScene" uid="uid://crui8soua8lj2" path="res://scenes/tile.tscn" id="2_ltmsi"] +[ext_resource type="Script" path="res://scripts/car_manager.gd" id="4_jfcfq"] +[ext_resource type="Script" path="res://scripts/grid_map.gd" id="4_lrlqi"] +[ext_resource type="PackedScene" uid="uid://bhk60xl5s8pmm" path="res://scenes/car.tscn" id="4_nsbp8"] + +[node name="GameScene" type="Node3D"] + +[node name="Camera3D" type="Camera3D" parent="."] +transform = Transform3D(1, 0, 0, 0, 0.615661, 0.788011, 0, -0.788011, 0.615661, 5, 10, 15.95) +size = 12.748 + +[node name="Map" type="Node3D" parent="."] +script = ExtResource("4_lrlqi") +tile = ExtResource("2_ltmsi") + +[node name="Tiles" type="Node3D" parent="Map"] + +[node name="Cars" type="Node3D" parent="." node_paths=PackedStringArray("map")] +script = ExtResource("4_jfcfq") +map = NodePath("../Map") +car_scene = ExtResource("4_nsbp8") + +[node name="Robot" parent="." node_paths=PackedStringArray("map", "car_manager") instance=ExtResource("1_2k47m")] +map = NodePath("../Map") +car_manager = NodePath("../Cars") diff --git a/Starter/scenes/onnx_inference_scene.tscn b/Starter/scenes/onnx_inference_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..f390722621546e801f84c2a7ae6c7702acc575a6 --- /dev/null +++ b/Starter/scenes/onnx_inference_scene.tscn @@ -0,0 +1,35 @@ +[gd_scene load_steps=6 format=3 uid="uid://qnxlq4cwno4t"] + +[ext_resource type="PackedScene" uid="uid://dn2auvcty4aoe" path="res://scenes/game_scene.tscn" id="1_0y8h2"] +[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_5kbv3"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_bdk3k"] +sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) +ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) + +[sub_resource type="Sky" id="Sky_uw47m"] +sky_material = SubResource("ProceduralSkyMaterial_bdk3k") + +[sub_resource type="Environment" id="Environment_iamhl"] +background_mode = 2 +sky = SubResource("Sky_uw47m") +tonemap_mode = 2 +glow_enabled = true + +[node name="OnnxInferenceScene" type="Node3D"] + +[node name="GameScene" parent="." instance=ExtResource("1_0y8h2")] + +[node name="Sync" type="Node" parent="."] +script = ExtResource("2_5kbv3") +control_mode = 2 +action_repeat = 1 +speed_up = 0.1 +onnx_model_path = "model.onnx" + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_iamhl") + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(-0.866025, -0.433013, 0.25, 0, 0.5, 0.866025, -0.5, 0.75, -0.433013, 0, 0, 0) +shadow_enabled = true diff --git a/Starter/scenes/robot.tscn b/Starter/scenes/robot.tscn new file mode 100644 index 0000000000000000000000000000000000000000..835aa164737241ef0fdfe360956444c47bcf1ac2 --- /dev/null +++ b/Starter/scenes/robot.tscn @@ -0,0 +1,206 @@ +[gd_scene load_steps=8 format=3 uid="uid://bsuw6dqwq2e3v"] + +[ext_resource type="PackedScene" uid="uid://bb2je1c8jc1qr" path="res://assets/robot.glb" id="1_n7jto"] +[ext_resource type="Script" path="res://scripts/robot.gd" id="1_vywkg"] +[ext_resource type="Script" path="res://scripts/robot_ai_controller.gd" id="5_sx7mj"] + +[sub_resource type="Animation" id="Animation_2kfmf"] +length = 0.001 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Robot/Arm:rotation") +tracks/0/interp = 1 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Robot/Arm_001:rotation") +tracks/1/interp = 1 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Robot/Torso:position") +tracks/2/interp = 1 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/3/type = "value" +tracks/3/imported = false +tracks/3/enabled = true +tracks/3/path = NodePath("Robot/Head:position") +tracks/3/interp = 1 +tracks/3/loop_wrap = true +tracks/3/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} +tracks/4/type = "value" +tracks/4/imported = false +tracks/4/enabled = true +tracks/4/path = NodePath("Robot/Head:rotation") +tracks/4/interp = 1 +tracks/4/loop_wrap = true +tracks/4/keys = { +"times": PackedFloat32Array(0), +"transitions": PackedFloat32Array(1), +"update": 0, +"values": [Vector3(0, 0, 0)] +} + +[sub_resource type="Animation" id="Animation_ly00x"] +resource_name = "idle" +length = 4.0 +loop_mode = 1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Robot/Arm:rotation") +tracks/0/interp = 2 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0, 2), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0.349066, 0, 0.0610865)] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Robot/Arm_001:rotation") +tracks/1/interp = 2 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0, 2), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(-0.349066, 0, -0.148353)] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Robot/Head:rotation") +tracks/2/interp = 2 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0, 1, 2, 3), +"transitions": PackedFloat32Array(1, 1, 1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, 0.162316, 0.0488692), Vector3(0, 0, 0), Vector3(0.139626, -0.178024, 0.0226893)] +} + +[sub_resource type="Animation" id="Animation_6jb0l"] +resource_name = "idle" +loop_mode = 1 +tracks/0/type = "value" +tracks/0/imported = false +tracks/0/enabled = true +tracks/0/path = NodePath("Robot/Arm:rotation") +tracks/0/interp = 2 +tracks/0/loop_wrap = true +tracks/0/keys = { +"times": PackedFloat32Array(0, 0.5), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, -0.174533, 0)] +} +tracks/1/type = "value" +tracks/1/imported = false +tracks/1/enabled = true +tracks/1/path = NodePath("Robot/Arm_001:rotation") +tracks/1/interp = 2 +tracks/1/loop_wrap = true +tracks/1/keys = { +"times": PackedFloat32Array(0, 0.5), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, 0.174533, 0)] +} +tracks/2/type = "value" +tracks/2/imported = false +tracks/2/enabled = true +tracks/2/path = NodePath("Robot/Torso:position") +tracks/2/interp = 2 +tracks/2/loop_wrap = true +tracks/2/keys = { +"times": PackedFloat32Array(0, 0.25, 0.5), +"transitions": PackedFloat32Array(1, 1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, -0.01, 0), Vector3(0, 0, 0)] +} +tracks/3/type = "value" +tracks/3/imported = false +tracks/3/enabled = true +tracks/3/path = NodePath("Robot/Head:position") +tracks/3/interp = 1 +tracks/3/loop_wrap = true +tracks/3/keys = { +"times": PackedFloat32Array(0, 0.5), +"transitions": PackedFloat32Array(1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(0, -0.02, 0)] +} +tracks/4/type = "value" +tracks/4/imported = false +tracks/4/enabled = true +tracks/4/path = NodePath("Robot/Head:rotation") +tracks/4/interp = 1 +tracks/4/loop_wrap = true +tracks/4/keys = { +"times": PackedFloat32Array(0, 0.25, 0.5), +"transitions": PackedFloat32Array(1, 1, 1), +"update": 0, +"values": [Vector3(0, 0, 0), Vector3(-0.0349066, 0, 0), Vector3(0, 0, 0)] +} + +[sub_resource type="AnimationLibrary" id="AnimationLibrary_g7kmm"] +_data = { +"RESET": SubResource("Animation_2kfmf"), +"idle": SubResource("Animation_ly00x"), +"walking": SubResource("Animation_6jb0l") +} + +[node name="Robot" type="Node3D" groups=["resetable"]] +script = ExtResource("1_vywkg") +metadata/_edit_lock_ = true + +[node name="AIController3D" type="Node3D" parent="."] +script = ExtResource("5_sx7mj") +reset_after = 40 + +[node name="robot" parent="." instance=ExtResource("1_n7jto")] +transform = Transform3D(2, 0, 0, 0, 2, 0, 0, 0, 2, 0, -0.1, 0) + +[node name="Robot" parent="robot" index="0"] +transform = Transform3D(-4.37114e-08, 0, 1, 0, 1, 0, -1, 0, -4.37114e-08, 0, 0, 0) + +[node name="Arm_001" parent="robot/Robot" index="1"] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0.00394951, 0, -0.18) + +[node name="AnimationPlayer" type="AnimationPlayer" parent="robot"] +libraries = { +"": SubResource("AnimationLibrary_g7kmm") +} +autoplay = "idle" +speed_scale = 16.0 + +[editable path="robot"] diff --git a/Starter/scenes/tile.tscn b/Starter/scenes/tile.tscn new file mode 100644 index 0000000000000000000000000000000000000000..6c056ea0c5cbb163b88c15bad57741b2d4aff1bc --- /dev/null +++ b/Starter/scenes/tile.tscn @@ -0,0 +1,18 @@ +[gd_scene load_steps=6 format=3 uid="uid://crui8soua8lj2"] + +[ext_resource type="Script" path="res://scripts/tile.gd" id="1_xode2"] +[ext_resource type="PackedScene" uid="uid://bfb0o41scdp70" path="res://assets/road_tile.glb" id="2_c5l1q"] +[ext_resource type="PackedScene" uid="uid://bn7tu2v2dgfuc" path="res://assets/orange_tile.glb" id="3_rlmbm"] +[ext_resource type="PackedScene" uid="uid://dtq61doicjsbq" path="res://assets/tree_tile.glb" id="4_p4mpm"] +[ext_resource type="PackedScene" uid="uid://6wdk5i0xsijn" path="res://assets/goal_tile.glb" id="5_p4gbw"] + +[node name="Tile" type="Node3D"] +script = ExtResource("1_xode2") + +[node name="orange_tile" parent="." instance=ExtResource("3_rlmbm")] + +[node name="road_tile" parent="." instance=ExtResource("2_c5l1q")] + +[node name="tree_tile" parent="." instance=ExtResource("4_p4mpm")] + +[node name="goal_tile" parent="." instance=ExtResource("5_p4gbw")] diff --git a/Starter/scenes/training_scene.tscn b/Starter/scenes/training_scene.tscn new file mode 100644 index 0000000000000000000000000000000000000000..97766d19bb0b9ef66caaef13fa81fca3e22c8498 --- /dev/null +++ b/Starter/scenes/training_scene.tscn @@ -0,0 +1,42 @@ +[gd_scene load_steps=6 format=3 uid="uid://cl152s178wgm5"] + +[ext_resource type="PackedScene" uid="uid://dn2auvcty4aoe" path="res://scenes/game_scene.tscn" id="1_ft0b8"] +[ext_resource type="Script" path="res://addons/godot_rl_agents/sync.gd" id="2_sk0r2"] + +[sub_resource type="ProceduralSkyMaterial" id="ProceduralSkyMaterial_bdk3k"] +sky_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) +ground_horizon_color = Color(0.64625, 0.65575, 0.67075, 1) + +[sub_resource type="Sky" id="Sky_uw47m"] +sky_material = SubResource("ProceduralSkyMaterial_bdk3k") + +[sub_resource type="Environment" id="Environment_iamhl"] +background_mode = 2 +sky = SubResource("Sky_uw47m") +tonemap_mode = 2 +glow_enabled = true + +[node name="TrainingScene" type="Node3D"] + +[node name="GameScene" parent="." instance=ExtResource("1_ft0b8")] + +[node name="GameScene2" parent="." instance=ExtResource("1_ft0b8")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, -30, 0, 0) + +[node name="GameScene3" parent="." instance=ExtResource("1_ft0b8")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 30, 0, 0) + +[node name="GameScene4" parent="." instance=ExtResource("1_ft0b8")] +transform = Transform3D(1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -400) + +[node name="Sync" type="Node" parent="."] +script = ExtResource("2_sk0r2") +action_repeat = 1 +speed_up = 8.0 + +[node name="WorldEnvironment" type="WorldEnvironment" parent="."] +environment = SubResource("Environment_iamhl") + +[node name="DirectionalLight3D" type="DirectionalLight3D" parent="."] +transform = Transform3D(-0.866025, -0.433013, 0.25, 0, 0.5, 0.866025, -0.5, 0.75, -0.433013, 0, 0, 0) +shadow_enabled = true diff --git a/Starter/scripts/car.gd b/Starter/scripts/car.gd new file mode 100644 index 0000000000000000000000000000000000000000..37fd8e959f6040e2c3dd4566d3cebceb924e8fb2 --- /dev/null +++ b/Starter/scripts/car.gd @@ -0,0 +1,18 @@ +extends Node3D +class_name Car + +## Car, moves along x axis, +## and changes direction once left or right edge is reached + +#region Initialized by car manager +var step_size: int +var left_edge_x: int +var right_edge_x: int +var current_direction: int = 1 +#endregion + +func _physics_process(_delta: float) -> void: + if not (position.x > left_edge_x and position.x < right_edge_x): + current_direction = -current_direction + rotation.y = current_direction / 2.0 * PI + position.x += step_size * current_direction diff --git a/Starter/scripts/car_manager.gd b/Starter/scripts/car_manager.gd new file mode 100644 index 0000000000000000000000000000000000000000..8d86ce8b5296251f3167cdd2c0a2e93e0d807fa7 --- /dev/null +++ b/Starter/scripts/car_manager.gd @@ -0,0 +1,48 @@ +extends Node3D +class_name CarManager + +@export var map: Map +@export var car_scene: PackedScene + +var car_left_edge_x: int +var car_right_edge_x: int + +@onready var cars: Array[Node] = get_children() + +# Called when the node enters the scene tree for the first time. +func _ready() -> void: + for road_row_idx in map.road_rows.size(): + create_car() + reset() + + +func create_car(): + var new_car = car_scene.instantiate() + add_child(new_car) + cars.append(new_car) + + +func reset(): + # If there are more cars than the current map layout road rows, remove + # the extra cars + while cars.size() > map.road_rows.size(): + cars[cars.size() - 1].queue_free() + cars.remove_at(cars.size() - 1) + + # If there are less cars than the current map layout road rows, + # add more cars + while cars.size() < map.road_rows.size(): + create_car() + + # Set car edge positions (at which they turn), position and other properties + for car_id in cars.size(): + var car = cars[car_id] + car.left_edge_x = 0 + car.right_edge_x = (map.grid_size_x - 1) * map.tile_size + car.step_size = map.tile_size + + car.position.x = range(car.left_edge_x + 2, car.right_edge_x - 2, 2).pick_random() + car.position.y = map.tile_size / 2 + 0.75 # 0.75 is to make the bottom of the car be at road height + car.position.z = map.road_rows[car_id] * 2 + + car.current_direction = 1 if randi_range(0, 1) == 0 else -1 diff --git a/Starter/scripts/grid_map.gd b/Starter/scripts/grid_map.gd new file mode 100644 index 0000000000000000000000000000000000000000..e1f4270ae9e736c12a86e7a9339aa7ecf263222e --- /dev/null +++ b/Starter/scripts/grid_map.gd @@ -0,0 +1,122 @@ +extends Node3D +class_name Map + +@export var tile: PackedScene + +# Grid positions +var instantiated_tiles: Dictionary +var tile_positions: Array[Vector3i] + +var player_start_position: Vector3i +var goal_position: Vector3i + +## Size of each tile, adjust manually if using larger or smaller tiles +var tile_size: int = 2 + +## Determines the width of the grid, tested with 6 +## may need adjustments for the AIController obs as it captures +## 6 cells from the left and right of the player +var grid_size_x = 6 + +## Number of rows in the grid +var grid_size_z = 0 + +var road_rows: Array[int] + +var tiles_instantiated: bool = false + +## Removes all tile nodes on first launch (if any are added in the editor) +## and on subsequent calls, it hides all tiles +func remove_all_tiles(): + for tile in $Tiles.get_children(): + if not tiles_instantiated: + tile.queue_free() + else: + tile.hide_all() + + tile_positions.clear() + road_rows.clear() + grid_size_z = 0 + +## Adds a tile to the grid, takes a scene containing the tile and grid position +func create_tile(tile_name: Tile.TileNames, grid_position: Vector3i): + if instantiated_tiles.has(grid_position): + instantiated_tiles[grid_position].set_tile(tile_name) + tile_positions.append(grid_position) + return + + var new_tile = tile.instantiate() as Tile + new_tile.position = grid_position * tile_size + $Tiles.add_child(new_tile) + instantiated_tiles[grid_position] = new_tile + new_tile.set_tile(tile_name) + tile_positions.append(grid_position) + +func _ready(): + set_cells() + +## You can set the layout by adjusting each row with set_row_cells() +## Note: Changing size after initial start is not supported +## you can change the order or rows or how many of the second tiles to add +## as long as the total size (number of rows, width) remains the same + +func set_cells(): + remove_all_tiles() + + add_row(Tile.TileNames.orange, Tile.TileNames.goal, 1) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) + add_row(Tile.TileNames.road) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange) + + set_player_position_to_last_row() + + tiles_instantiated = true + +func reset(): + if not is_node_ready(): + await ready + set_cells() + +func get_tile(grid_pos: Vector3i): + if not grid_pos in tile_positions: + return null + return instantiated_tiles[grid_pos] + + +func get_grid_position(global_pos: Vector3i): + var grid_pos = Vector3i(to_local(global_pos) / 2.0) + return grid_pos + +func set_row_tiles(row: int, tile: Tile.TileNames, second_tile: Tile.TileNames = Tile.TileNames.orange, second_tile_count: int = 0): + var first_tile_columns: Array = range(grid_size_x) + + if second_tile_count: + for i in second_tile_count: + first_tile_columns.remove_at(randi_range(0, first_tile_columns.size() - 1)) + + for column in range(grid_size_x): + var tile_to_create: Tile.TileNames + if column in first_tile_columns: + tile_to_create = tile + else: + tile_to_create = second_tile + var tile_grid_coords := Vector3i(column, 0, row) + create_tile(tile_to_create, tile_grid_coords) + if tile_to_create == Tile.TileNames.goal: + goal_position = tile_grid_coords + + if tile == Tile.TileNames.road: + road_rows.append(row) + +func add_row(tile: Tile.TileNames, second_tile: Tile.TileNames = Tile.TileNames.orange, second_tile_count: int = 0): + set_row_tiles(grid_size_z, tile, second_tile, second_tile_count) + grid_size_z += 1 + +func set_player_position_to_grid_row(row: int): + player_start_position = to_global(Vector3i(range(0, grid_size_x - 1, 2).pick_random(), 0, row * tile_size)) + +func set_player_position_to_last_row(): + set_player_position_to_grid_row(grid_size_z - 1) diff --git a/Starter/scripts/robot.gd b/Starter/scripts/robot.gd new file mode 100644 index 0000000000000000000000000000000000000000..f61257f963a105f5ba23d2faf1702a6dae66940f --- /dev/null +++ b/Starter/scripts/robot.gd @@ -0,0 +1,44 @@ +extends Node3D +class_name Player + +## Whether to print the game success/failed messsages to console +@export var print_game_status_enabled: bool + +## How far the robot can move per step +@export var movement_step := 2.0 + +@export var map: Map +@export var car_manager: CarManager + +@onready var _ai_controller := $AIController3D +@onready var visual_robot: Node3D = $robot + +var last_dist_to_goal + +#region Set by AIController +var requested_movement: Vector3 +#endregion + + +#func _ready(): + + +#func _physics_process(delta): + + +#func _process_movement(_delta): + + +#func reward_approaching_goal(): + + +#func get_grid_position() -> Vector3i: + + +#func game_over(reward = 0.0): + + +#func reset(): + + +#func print_game_status(message: String): diff --git a/Starter/scripts/robot_ai_controller.gd b/Starter/scripts/robot_ai_controller.gd new file mode 100644 index 0000000000000000000000000000000000000000..d870a757f7864aaf305395c102f34581031b6e51 --- /dev/null +++ b/Starter/scripts/robot_ai_controller.gd @@ -0,0 +1,25 @@ +extends AIController3D +class_name RobotAIController + +@onready var player := get_parent() as Player + + +#func get_obs() -> Dictionary: + + +#func get_reward() -> float: + + +#func _process(_delta: float) -> void: + + +#func _physics_process(_delta: float) -> void: + + +#func get_action_space() -> Dictionary: + + +#func set_action(action = null) -> void: + + +#func get_user_input() -> void: diff --git a/Starter/scripts/tile.gd b/Starter/scripts/tile.gd new file mode 100644 index 0000000000000000000000000000000000000000..264742f5a67ab2d1682e49a430fef1497385c30f --- /dev/null +++ b/Starter/scripts/tile.gd @@ -0,0 +1,30 @@ +extends Node3D +class_name Tile + +## Tile class it allows setting the visible tile design by +## hiding the nodes with not currently used tile designs. +## (Intended to be used with tile.tscn) + +## Tile names, must be in the same order as child nodes +enum TileNames { + orange, + road, + tree, + goal +} + +## ID of the current set tile +var id: int + +@onready var tiles: Array = get_children() + +## Sets the specified tile mesh to be visible, and hides others +func set_tile(tile_name: TileNames): + hide_all() + id = int(tile_name) + tiles[id].visible = true + +## Hides all tiles +func hide_all(): + for tile in tiles: + tile.visible = false diff --git a/Tutorial/tutorial.md b/Tutorial/tutorial.md new file mode 100644 index 0000000000000000000000000000000000000000..1d10b37b1762365a7b99d22c9025cc93920a6647 --- /dev/null +++ b/Tutorial/tutorial.md @@ -0,0 +1,500 @@ +# Cross The Road Env Tutorial + +Learn how to use Godot RL Agents by building a grid-like cross-the-road mini-game that will be trained using Deep Reinforcement Learning! + +## **Introduction:** + +Welcome to this tutorial, where you will train a robot to reach the goal while navigating around trees and avoiding cars. + +At the end, you will have a trained agent that can complete the game like in the video: + +https://github.com/user-attachments/assets/17fb94e6-771e-42ea-a530-cea028545a67 + +## Objectives: + +- Learn how to use Godot RL Agents by training an agent to complete a grid-like mini-game environment. + +## Prerequisites and requirements: + +- Recommended: Complete [Godot RL Agents](https://huggingface.co/learn/deep-rl-course/unitbonus3/godotrl) before starting this tutorial, +- Some familiarity with Godot is also recommended, +- Godot 4.3 with .NET support (tested on Beta 3, should work with newer versions), +- Godot RL Agents (you can use `pip install godot-rl` in the venv/conda env) + +# The environment + +![the_environment](https://github.com/user-attachments/assets/b47aec6c-0112-4ec1-898c-209ec2652cf6) + +- In the environment, the robot needs to navigate around trees and cars in order to reach the goal tile successfully within the time limit. +- The positions of goal, trees and car starting position/orientation are randomized within their own grid row. The env layout can be further customized in the code (we’ll cover this in the later sections), and you can e.g. add more cars and trees to make the game more challenging. +- As it is a grid-like env, all movements are done by 1 grid coordinate at a time, and the episode lengths are relatively short. + +# Getting started: + +To get started, download the project by cloning [this](https://github.com/edbeeching/godot_rl_agents_examples/tree/main) repository. + +We will work on the starter project, focusing on: + +- Implementing the code for the `Robot` and `AIController` nodes, +- We will briefly go over how to adjust the map size, +- Finally we will train the agent and export an .onnx file of the trained agent, so that we can run inference directly from Godot. + +### Open the starter project in Godot + +Open Godot, click “Import” and navigate to the `Starter` folder `godot_rl_agents_examples/examples/CrossTheRoad +/Starter/`. + +On first import, you may get an error message such as: + +> Unable to load addon script from path: 'res://addons/godot_rl_agents/godot_rl_agents.gd'. This might be due to a code error in that script. +Disabling the addon at 'res://addons/godot_rl_agents/plugin.cfg' to prevent further errors. + +Just re-open the project in the editor, the error should not appear again. + +### Open the `robot.tscn` scene + +> [!TIP] +> You can search for “robot” in the FileSystem search. + +robot_scene + +This scene contains a few nodes: +- `Robot` is the main node that controls the robot +- `AIController3D` handles observations, rewards, and setting actions, +- `robot` contains the visual geometry and animation. + +### Open the `Robot.gd` script for editing: + +> [!TIP] +> To open the script, click on the scroll next to the `Robot` node. + +You will find there are commented method names in the script that need to be implemented. Most of the provided code will contain comments explaining the implementation, but we will also provide an additional overview of the methods. + +**Replace `_ready()`, `_physics_process(delta)`, `_process_movement(_delta)` and `reward_approaching_goal()` with the following implementation:** + +```gdscript +func _ready(): + reset() + +func _physics_process(delta): + # Set to true by the sync node when reset is requested from Python (starting training, evaluation, etc.) + if _ai_controller.needs_reset: + game_over() + _process_movement(delta) + +func _process_movement(_delta): + for car in car_manager.cars: + if get_grid_position() == map.get_grid_position(car.global_position): + # If a car has moved to the current player position, end episode + game_over(0) + print_game_status("Failed, hit car while standing") + + if requested_movement: + # Move the robot to the requested position + global_position += (requested_movement * movement_step) + # Update the visual rotation of the robot to look toward the direction of last requested movement + visual_robot.global_rotation_degrees.y = rad_to_deg(atan2(-requested_movement.x, -requested_movement.z)) + + var grid_position: Vector3i = get_grid_position() + var tile: Tile = map.get_tile(grid_position) + + if not tile: + # Push the robot back if there's no tile to move to (out of map boundary) + global_position -= (requested_movement * movement_step) + elif tile.id == tile.TileNames.tree: + # Push the robot back if it has moved to a tree tile + global_position -= (requested_movement * movement_step) + elif tile.id == tile.TileNames.goal: + # If a goal tile is reached, end episode with reward +1 + game_over(1) + print_game_status("Success, reached goal") + else: + for car in car_manager.cars: + if get_grid_position() == map.get_grid_position(car.global_position): + # If the robot moved to a car's current position, end episode + game_over(0) + print_game_status("Failed, hit car while walking") + + # After processing the move, zero the movement for the next step + # (only in case of human control) + if _ai_controller.control_mode == AIController3D.ControlModes.HUMAN: + requested_movement = Vector3.ZERO + + reward_approaching_goal() + +## Adds a positive reward if the robot approaches the goal +func reward_approaching_goal(): + var grid_pos: Vector3i = get_grid_position() + var dist_to_goal = grid_pos.distance_to(map.goal_position) + if last_dist_to_goal == null: last_dist_to_goal = dist_to_goal + + if dist_to_goal < last_dist_to_goal: + _ai_controller.reward += (last_dist_to_goal - dist_to_goal) / 10.0 + last_dist_to_goal = dist_to_goal +``` + +A brief overview of the methods: + +- In `_ready()` we reset the game on start. +- In `_process_movement()` we move the Robot, handle collision with tree tiles, goal (in this case we add a positive reward and end the episode), and cars (if a car is hit, we add 0 to the reward and end the episode). +- In `reward_approaching_goal()` we give a positive reward when the robot approaches the goal, based on best/smallest distance to the goal, which is reset for each episode/game. + +**Replace `get_grid_position()`, `game_over()`, `reset()`, and `print_game_status()` with the following implementation:** + +```gdscript +func get_grid_position() -> Vector3i: + return map.get_grid_position(global_position) + +func game_over(reward = 0.0): + _ai_controller.done = true + _ai_controller.reward += reward + _ai_controller.reset() + reset() + +func reset(): + last_dist_to_goal = null + # Order of resetting is important: + # We reset the map first, which sets a new player start position + # and the road segments (needed to know where to spawn the cars) + map.reset() + # after that, we can set the player position + global_position = Vector3(map.player_start_position) + Vector3.UP * 1.5 + # and also reset or create (on first start) the cars + car_manager.reset() + +func print_game_status(message: String): + if print_game_status_enabled: + print(message) +``` + +A brief overview of the methods: + +- `get_grid_position()` tells us where the car is on the grid. +- `game_over()` takes care of resetting the player, but also ending the episode for the RL agent and resetting the AIController, and the environment (e.g. generating a new map for the next episode) as well. +- `print_game_status()` prints out game status messages (e.g. game successfully completed) in the console when this flag is enabled on the Player node in the inspector. This is disabled by default. + +That’s it for the Player node. Press `CTRL + S` to save the changes, and let’s implement the AIController code. + +### Open the `robot_ai_controller.gd` script for editing: + +> [!TIP] +> To open the script, click on the scroll next to the `AIController3D` node. + +**Replace `get_obs()` with the following implementation:** + +```gdscript +func get_obs() -> Dictionary: + var observations := Array() + var player_pos = player.get_grid_position() + + # Determines how many grid cells the AI can observe + # e.g. front refers to "up" looking from above, + # and does not rotate with the robot, same with others. + # Set to observe all cells from two rows in front of player, + # 0 behind + var visible_rows_in_front_of_player: int = 2 + var visible_rows_behind_the_player: int = 0 + + # Set to observe the entire width of the grid on both sides + # so it will always see all cells up to 2 rows in front. + var visible_columns_left_of_player: int = player.map.grid_size_x + var visible_columns_right_of_player: int = player.map.grid_size_x + + # For tiles near player we provide [direction, id] (e.g: [-1, 0]) + # direction is -1 or 1 for cars, 0 for static tiles + # if a car is in a tile, we override the id of tile underneath + + # Car ID is the ID of the last tile + 1 + var car_id = Tile.TileNames.size() + + # If there is no tile placed at the grid coord, we use -1 as id + var no_tile_id: int = -1 + + # Note: We don't need to include the player position directly in obs + # as we are always including data for cells "around" the player, + # so the player location relative to those cells is implicitly included + + for z in range( + player_pos.z - visible_rows_in_front_of_player, + player_pos.z + visible_rows_behind_the_player + 1 + ): + for x in range( + player_pos.x - visible_columns_left_of_player, + player_pos.x + visible_columns_right_of_player + 1 + ): + var grid_pos := Vector3i(x, 0, z) + var tile: Tile = player.map.get_tile(grid_pos) + + if not tile: + observations.append_array([0, no_tile_id]) + else: + var is_car: bool + for car in player.car_manager.cars: + if grid_pos == player.map.get_grid_position(car.global_position): + is_car = true + observations.append(car.current_direction) + if is_car: + observations.append(car_id) + else: + observations.append_array([0, tile.id]) + + return {"obs": observations} +``` + +In this method, we provide observations to the RL agent about the grid tiles (or cars) that are near the player. As info from grid cells near the player is provided, we don’t need to include the player position in the grid directly in the obs. + +With the implementation above, the agent can “see" up to two rows in front of it (toward the goal), zero rows behind, and all of the cells left/right from the player are visible. You can adjust this as needed if you change the map size, or to experiment. + +For each cell, we provide a `tile id` (e.g. 0, 1, 2, 3) so that the agent can differentiate between different tiles. If there’s a car above a specific tile, we provide the `car id` instead of the tile id, so that the agent knows there’s a car to avoid there. As cars can move and change direction, we also provide the direction (-1 or 1 for cars, 0 for tiles). We also provide `-1` as id if there’s nothing at that coordinate (out of grid boundaries). + +**Replace `get_reward()`, `_process()`, `_physics_process()`, and `get_action_space()` with the following implementation:** + +```gdscript +func get_reward() -> float: + return reward + +func _process(_delta: float) -> void: + # In case of human control, we get the user input + if control_mode == ControlModes.HUMAN: + get_user_input() + +func _physics_process(_delta: float) -> void: + # Reset on timeout, this is implemented in parent class to set needs_reset to true, + # we are re-implementing here to call player.game_over() that handles the game reset. + n_steps += 1 + if n_steps > reset_after: + player.game_over(0) + player.print_game_status("Episode timed out.") + +## Defines the actions for the AI agent +func get_action_space() -> Dictionary: + return { + "movement": {"size": 5, "action_type": "discrete"}, + } +``` + +- `get_reward()` just returns the current reward value, this is used by the Godot RL Agents `sync` node to send the reward the data to the training algorithm, +- `_process()` handles user input if human control mode is selected, +- `_physics_process()` handles restarting the game on episode time out, +- `get_action_space()` defines the actions we need to receive from the RL agent to control the robot. In this case that is a discrete action with size 5 (allowing the robot to move in any of 4 directions, or stand still). + +**Replace `set_action()`, and `get_user_input()` with the following implementation:** + +```gdscript +## Applies AI control actions to the robot +func set_action(action = null) -> void: + # We have specified discrete action type with size 5, + # which means there are 5 possible values that the agent can output + # for each step, i.e. one of: 0, 1, 2, 3, 4, + # we use those to allow the agent to move in 4 directions, + # + there is a 'no movement' action. + # First convert to int to use match as action value is of float type. + match int(action.movement): + 0: + player.requested_movement = Vector3.LEFT + 1: + player.requested_movement = Vector3.RIGHT + 2: + player.requested_movement = Vector3.FORWARD + 3: + player.requested_movement = Vector3.BACK + 4: + player.requested_movement = Vector3.ZERO + +## Applies user input actions to the robot +func get_user_input() -> void: + if Input.is_action_just_pressed("move_up"): + player.requested_movement = Vector3.FORWARD + elif Input.is_action_just_pressed("move_right"): + player.requested_movement = Vector3.RIGHT + elif Input.is_action_just_pressed("move_down"): + player.requested_movement = Vector3.BACK + elif Input.is_action_just_pressed("move_left"): + player.requested_movement = Vector3.LEFT +``` + +- `set_action()` converts the action received from the RL agent to a movement direction for the robot. +- `get_user_input()` converts user input into a movement direction for the robot (if human control mode is selected). + +Now the implementation is done and we’re ready to export the game and start training! + +### Export the game for training: + +You can export the game from Godot using `Project > Export`. + +# Training: + +### **Download a copy of the [SB3 Example script](https://github.com/edbeeching/godot_rl_agents/blob/main/examples/stable_baselines3_example.py) from the Godot RL Repository.** + +### **Run training using the arguments below:** + +```gdscript +stable_baselines3_example.py --timesteps=250_000 --onnx_export_path=model.onnx --env_path="PathToExportedExecutable" --n_parallel=4 --speedup=32 +``` + +**Set the env path to the exported game and start training.** + +Training time may take a while, depending on the hardware and settings. + +The `ep_rew_mean` after the 250 000 training steps should be `1.5+` for the preconfigured map layout. + +In case you’d like to tweak the settings, you could change `n_parallel` to get more FPS on some computers, note this could affect the number of timesteps needed to train successfully as well. If you’re familiar with Stable Baselines 3, you can also adjust the [PPO hyperparameters](https://stable-baselines3.readthedocs.io/en/master/modules/ppo.html) by modifying the Python script. + +### **Copy the onnx file or the path to the exported onnx file.** + +After training completes, you will get a message in the console such as `Exporting onnx to: ...`. You can copy or move the `.onnx` file from there to the Godot project folder, or you can just copy the full path to the file. + +### Open the `onnx_inference_scene.tscn` scene: + +> [!TIP] +> You can search for “onnx_inference” in the FileSystem search. + +Click on the Sync node, then paste the path to the onnx model file from the previous step into the `Onnx Model Path` property. You can adjust the `speed_up` optionally to make the env run faster, recommended for preview is the `0.1` default. + +![onnx_scene](https://github.com/user-attachments/assets/38c25d91-6846-45de-9411-728212482628) + +### Start the game and watch the agent play: + +With the `onnx_inference_scene` open, press `F6` to start the game from this scene. + +> [!TIP] +> You can also open `robot.tscn`, click on the `Robot` node, and enable `Print Game Status Enabled` in inspector to see the debug info printed in the console (whether an episode was successful or not), then get back to the `onnx_inference_scene` before pressing `F6`. + +The trained agent should behave similarly as in the video below: + +https://github.com/user-attachments/assets/82858efb-1af0-41c5-a211-0d5a85665bf0 + +If so, 🎉 congratulations! 🌟 You’ve completed the tutorial successfully! + +If there are issues with the performance of the agent, you could try retraining with some more time-steps. + +If there are some errors when trying to run the onnx file, check if there is an error message. You could also try importing and running the `Completed` Godot project to see if it works well, then compare for any differences. + +# Customizing the map layout: + +If you’d like to change the layout of the map, open the `scripts/grid_map.gd` script (you can find it in the FileSystem). + +You will find the relevant code section in the `set_cells()` method: + +```gdscript +## You can set the layout by adjusting each row with set_row_cells() +## Note: Changing size after initial start is not supported +## you can change the order or rows or how many of the second tiles to add +## as long as the total size (number of rows, width) remains the same + +func set_cells(): + remove_all_tiles() + + add_row(Tile.TileNames.orange, Tile.TileNames.goal, 1) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) + add_row(Tile.TileNames.road) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange) + + set_player_position_to_last_row() + + tiles_instantiated = true +``` + +In the code above, each `add_row()` method call adds another row to the map. The method takes 3 arguments: + +- The name of the tile to use for the first/main tile of that row +- The name of the tile to use for the second tile of that row (the second tile gets randomly positioned along grid x coordinate) +- How many of the second tiles to place in that row. + +For instance, a call to: + +```gdscript +add_row(Tile.TileNames.orange, Tile.TileNames.tree, 2) +``` + +will add a grid row with mostly orange (walkable) tiles, and 2 randomly positioned trees (along the x axis). + +Note that for any road segment that you add using: + +```gdscript +add_row(Tile.TileNames.road) +``` + +a car will also be added automatically that will move along the road. When using road tiles, you shouldn’t add a second tile as this wasn’t intended by the current design. + +Here’s a more complex layout example you can try: + +```gdscript +## You can set the layout by adjusting each row with set_row_cells() +## Note: Changing size after initial start is not supported +## you can change the order or rows or how many of the second tiles to add +## as long as the total size (number of rows, width) remains the same + +func set_cells(): + remove_all_tiles() + + add_row(Tile.TileNames.orange, Tile.TileNames.goal, 1) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 3) + add_row(Tile.TileNames.road) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 3) + add_row(Tile.TileNames.road) + add_row(Tile.TileNames.orange, Tile.TileNames.tree, 3) + add_row(Tile.TileNames.road) + add_row(Tile.TileNames.orange) + add_row(Tile.TileNames.orange) + + set_player_position_to_last_row() + + tiles_instantiated = true +``` + +That would generate maps that looks similar to below: + +![larger_map](https://github.com/user-attachments/assets/b638f4e8-d2f2-4ee4-a18c-5bac7f8b3aec) + +If you’d like to shuffle the rows to create a more randomized map layout, you can try something similar to below: + +```gdscript +## You can set the layout by adjusting each row with set_row_cells() +## Note: Changing size after initial start is not supported +## you can change the order or rows or how many of the second tiles to add +## as long as the total size (number of rows, width) remains the same + +func set_cells(): + remove_all_tiles() + + # Keeps the goal row fixed + set_row_tiles(0, Tile.TileNames.orange, Tile.TileNames.goal, 1) + + var row_ids = range(1, 5) + row_ids.shuffle() + set_row_tiles(row_ids[0], Tile.TileNames.orange, Tile.TileNames.tree, 2) + set_row_tiles(row_ids[1], Tile.TileNames.orange, Tile.TileNames.tree, 2) + set_row_tiles(row_ids[2], Tile.TileNames.road) + set_row_tiles(row_ids[3], Tile.TileNames.road) + + # Keeps the player starting row fixed + set_row_tiles(5, Tile.TileNames.orange) + grid_size_z = 6 + + set_player_position_to_last_row() + + tiles_instantiated = true +``` + +Note that these layouts can take longer to train. For example, I tried training the “shuffle” variant above with `n_steps=32,batch_size=256` set in the Python training script, `n_parallel=6` set as CL argument, and I've also increased the observation settings so that the agent can see more rows in front of the player, and one row behind. I’ve trained it for a couple of hours on my PC (I stopped manually, it’s possible the behavior was learned earlier). It resulted in a high success rate during onnx inference. + +Some notes: + +- During training, you could randomize/shuffle the row order, the number of cars (automatically set based on number of rows with road) can also change, but changing the map size (number of rows or grid width) between episodes is not supported (it’s possible to extend the script to support this case). +- While you can run inference using the same onnx you previously trained on a different map, the results may not be good (might be a bit better if training a shuffled variant to learn a more generalized behavior). Retraining might be needed. +- To see a different map layout properly, you may need to adjust the camera position in Godot editor (found in `res://scenes/game_scene.tscn`). +- Training may take longer for more complex maps. Tuning the Python script hyperparameters might help. +- When the map is larger and takes longer to complete, you may need to increase the timeout steps, this is adjustable from Godot editor as the `reset after` property of AIController3D (check screenshot below): + +![reset_after](https://github.com/user-attachments/assets/bf09bb10-c4b0-4942-a04c-c2ea59c3632c) + +# Conclusion: + +Congrats! You’ve learned how to train a RL agent to successfully complete a grid-like env using Godot, Godot RL Agents, and Stable Baselines 3. + +For more inspiration, feel free to check out our other [example environments](https://github.com/edbeeching/godot_rl_agents_examples/tree/main/examples), and our two tutorials on the HF Deep RL Course (https://huggingface.co/learn/deep-rl-course/unitbonus3/godotrl, https://huggingface.co/learn/deep-rl-course/unitbonus5/introduction). diff --git a/readme.md b/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..8ba3ddf30755a7e177047cf7ab1ef79811421c26 --- /dev/null +++ b/readme.md @@ -0,0 +1,5 @@ +# Cross The Road Environment + +https://github.com/user-attachments/assets/c74f9711-9912-43aa-9af4-bd5a614cf674 + +This environment comes with a [tutorial](Tutorial/tutorial.md).