base structure
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Godot;
|
||||
|
||||
namespace GodotHostTest.addons.godot_di;
|
||||
|
||||
/// <summary>
|
||||
/// Taken from https://github.com/godotengine/godot-proposals/issues/12294
|
||||
/// </summary>
|
||||
public static class GodotScriptPathCache
|
||||
{
|
||||
private static readonly ConcurrentDictionary<Type, string> TypeToPath = new();
|
||||
private static readonly ConcurrentDictionary<string, Type> PathToType = new();
|
||||
private static readonly Type GodotObject = typeof(GodotObject);
|
||||
private static readonly Type ScriptPathAttribute = typeof(ScriptPathAttribute);
|
||||
|
||||
private static AssemblyLoadEventHandler? _assemblyLoadEventHandler;
|
||||
|
||||
private static void InitializeIfNeeded()
|
||||
{
|
||||
if (_assemblyLoadEventHandler != null) return;
|
||||
Initialize();
|
||||
System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly())!
|
||||
.Unloading += _ => { Deinitialize(); };
|
||||
}
|
||||
|
||||
private static void Initialize()
|
||||
{
|
||||
GD.Print($"Initializing {nameof(GodotScriptPathCache)}");
|
||||
TypeToPath.Clear();
|
||||
PathToType.Clear();
|
||||
_assemblyLoadEventHandler = (sender, args) => CacheScriptsInAssembly(args.LoadedAssembly);
|
||||
AppDomain.CurrentDomain.AssemblyLoad += _assemblyLoadEventHandler;
|
||||
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||||
CacheScriptsInAssembly(assembly);
|
||||
return;
|
||||
|
||||
void CacheScriptsInAssembly(Assembly assembly)
|
||||
{
|
||||
foreach (var type in assembly.GetTypes()
|
||||
.Where(t => t.IsClass)
|
||||
.Where(t => t.IsSubclassOf(GodotObject)))
|
||||
// get script path attribute
|
||||
if (type.GetCustomAttributes(ScriptPathAttribute, false).FirstOrDefault() is ScriptPathAttribute
|
||||
scriptPath)
|
||||
{
|
||||
TypeToPath[type] = scriptPath.Path;
|
||||
PathToType[scriptPath.Path] = type;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Deinitialize()
|
||||
{
|
||||
GD.Print($"Deinitializing {nameof(GodotScriptPathCache)}");
|
||||
AppDomain.CurrentDomain.AssemblyLoad -= _assemblyLoadEventHandler;
|
||||
_assemblyLoadEventHandler = null;
|
||||
TypeToPath.Clear();
|
||||
PathToType.Clear();
|
||||
}
|
||||
|
||||
public static bool TryGetScriptPath(Type type, [MaybeNullWhen(false)] out string path)
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return TypeToPath.TryGetValue(type, out path);
|
||||
}
|
||||
|
||||
public static Script GetScriptFromType(Type type)
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return TryGetScriptPath(type, out string path)
|
||||
? GD.Load<Script>(path)
|
||||
: throw new InvalidOperationException("Script path not found in cache.");
|
||||
}
|
||||
|
||||
public static Script GetScriptFromType<T>()
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return GetScriptFromType(typeof(T));
|
||||
}
|
||||
|
||||
public static bool TryGetTypeFromPath(string path, [MaybeNullWhen(false)] out Type type)
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return PathToType.TryGetValue(path, out type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using Godot;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
public interface ISceneInstantiator
|
||||
{
|
||||
/// <summary>
|
||||
/// Instantiate a packed scene, just like <see cref="PackedScene.Instantiate"/>, but also looks for a scope between the top level children and triggers the dependency injection mechanism when found.
|
||||
/// </summary>
|
||||
/// <param name="packedScene">The packed scene to instantiate.</param>
|
||||
/// <returns>The created node, with its dependencies satisfied.</returns>
|
||||
Node Instantiate(PackedScene packedScene);
|
||||
|
||||
/// <summary>
|
||||
/// Instantiate a packed scene, just like <see cref="PackedScene.Instantiate{T}"/>, but also looks for a scope between the top level children and triggers the dependency injection mechanism when found.
|
||||
/// </summary>
|
||||
/// <param name="packedScene">The packed scene to instantiate.</param>
|
||||
/// <returns>The created node, with its dependencies satisfied.</returns>
|
||||
T Instantiate<T>(PackedScene packedScene) where T : Node;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
uid://bv7aut87rpm5u
|
||||
@@ -0,0 +1,6 @@
|
||||
using System;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method)]
|
||||
public class InjectAttribute: Attribute;
|
||||
@@ -0,0 +1 @@
|
||||
uid://mshffj1jlgi7
|
||||
@@ -0,0 +1,64 @@
|
||||
namespace GodotHostTest.addons.godot_di;
|
||||
|
||||
// RandomIntEditor.cs
|
||||
#if TOOLS
|
||||
using Godot;
|
||||
|
||||
public partial class RandomIntEditor : EditorProperty
|
||||
{
|
||||
// The main control for editing the property.
|
||||
private Button _propertyControl = new Button();
|
||||
|
||||
// An internal value of the property.
|
||||
private int _currentValue = 0;
|
||||
|
||||
// A guard against internal changes when the property is updated.
|
||||
private bool _updating = false;
|
||||
|
||||
public RandomIntEditor()
|
||||
{
|
||||
// Add the control as a direct child of EditorProperty node.
|
||||
AddChild(_propertyControl);
|
||||
// Make sure the control is able to retain the focus.
|
||||
AddFocusable(_propertyControl);
|
||||
// Setup the initial state and connect to the signal to track changes.
|
||||
RefreshControlText();
|
||||
_propertyControl.Pressed += OnButtonPressed;
|
||||
}
|
||||
|
||||
private void OnButtonPressed()
|
||||
{
|
||||
// Ignore the signal if the property is currently being updated.
|
||||
if (_updating)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Generate a new random integer between 0 and 99.
|
||||
_currentValue = (int)GD.Randi() % 100;
|
||||
RefreshControlText();
|
||||
EmitChanged(GetEditedProperty(), _currentValue);
|
||||
}
|
||||
|
||||
public override void _UpdateProperty()
|
||||
{
|
||||
// Read the current value from the property.
|
||||
var newValue = (int)GetEditedObject().Get(GetEditedProperty());
|
||||
if (newValue == _currentValue)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Update the control with the new value.
|
||||
_updating = true;
|
||||
_currentValue = newValue;
|
||||
RefreshControlText();
|
||||
_updating = false;
|
||||
}
|
||||
|
||||
private void RefreshControlText()
|
||||
{
|
||||
_propertyControl.Text = $"Value: {_currentValue}";
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,79 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Godot;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OwofGames.GodotHost;
|
||||
using OwofGames.GodotLume.Microsoft.DependencyInjection;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
/// <summary>
|
||||
/// The base class for a root scope. Implement this class and its abstract methods to kick off the DI system.
|
||||
/// </summary>
|
||||
public abstract partial class RootServiceSource : ServiceSource, ISceneInstantiator
|
||||
{
|
||||
private Host? _host;
|
||||
|
||||
private Host Host
|
||||
{
|
||||
get => _host ??
|
||||
throw new InvalidOperationException(
|
||||
"Some method of RootScope has been invoked before it entered the tree");
|
||||
set => _host = value;
|
||||
}
|
||||
|
||||
private ILogger<RootServiceSource>? _logger;
|
||||
|
||||
private ILogger<RootServiceSource> Logger => _logger ??= Host.GetLogger<RootServiceSource>();
|
||||
|
||||
public override void _EnterTree()
|
||||
{
|
||||
// create the host
|
||||
Host = new HostBuilder()
|
||||
.SetServiceCollectionBuilder(InnerConfigure)
|
||||
.SetServiceProviderFactory(new LumeServiceProviderFactory())
|
||||
.Build();
|
||||
|
||||
// resolve nodes
|
||||
ResolveInjectedNodes(Host.ServiceProvider);
|
||||
}
|
||||
|
||||
private void InnerConfigure(IServiceCollection serviceCollection)
|
||||
{
|
||||
serviceCollection.AddSingleton<ISceneInstantiator>(this);
|
||||
Configure(serviceCollection);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Configure the service collection by adding the registrations your game needs.
|
||||
/// </summary>
|
||||
/// <param name="serviceCollection">The service collection to enrich.</param>
|
||||
protected abstract void Configure(IServiceCollection serviceCollection);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public Node Instantiate(PackedScene packedScene)
|
||||
{
|
||||
var node = packedScene.Instantiate();
|
||||
var scope = node.GetChildren().OfType<ServiceSource>().SingleOrDefault();
|
||||
if (scope == null)
|
||||
{
|
||||
Logger.LogDebug(
|
||||
"Instantiated the scene {PackedSceneName} through ISceneInstantiator.Instantiate, but no scope found.",
|
||||
packedScene.GetName());
|
||||
}
|
||||
else
|
||||
{
|
||||
scope.ResolveInjectedNodes(Host.ServiceProvider);
|
||||
}
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public T Instantiate<T>(PackedScene packedScene)
|
||||
where T : Node
|
||||
{
|
||||
return (T)Instantiate(packedScene);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
uid://fr0c6wwras8c
|
||||
@@ -0,0 +1,31 @@
|
||||
#if TOOLS
|
||||
using Godot;
|
||||
using GodotHostTest.addons.godot_di;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
public partial class ScopeInspectorPlugin : EditorInspectorPlugin
|
||||
{
|
||||
public override bool _CanHandle(GodotObject @object)
|
||||
{
|
||||
var result = @object.GetScript().AsGodotObject() is CSharpScript script &&
|
||||
GodotScriptPathCache.TryGetTypeFromPath(script.ResourcePath, out var type) &&
|
||||
type.IsAssignableTo(typeof(ServiceSource));
|
||||
return result;
|
||||
}
|
||||
|
||||
public override bool _ParseProperty(GodotObject @object, Variant.Type type, string name, PropertyHint hintType,
|
||||
string hintString,
|
||||
PropertyUsageFlags usageFlags, bool wide)
|
||||
{
|
||||
// We handle properties of type integer.
|
||||
if (name != "_serviceScope") return false;
|
||||
// Create an instance of the custom property editor and register
|
||||
// it to a specific property path.
|
||||
AddPropertyEditor(name, new ScopePickerEditor());
|
||||
// Inform the editor to remove the default property editor for
|
||||
// this property type.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,95 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using Godot;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
public partial class ScopePickerEditor : EditorProperty
|
||||
{
|
||||
/// <summary>
|
||||
/// The "combo box" that picks a choice from the scopes.
|
||||
/// </summary>
|
||||
private OptionButton _optionButton = new();
|
||||
|
||||
/// <summary>
|
||||
/// The currently chosen type.
|
||||
/// </summary>
|
||||
private string _currentType;
|
||||
|
||||
/// <summary>
|
||||
/// All the known fully qualified names for scopes.
|
||||
/// </summary>
|
||||
private string[] _fullyQualifiedNames;
|
||||
|
||||
/// <summary>
|
||||
/// A guard against internal changes while the property is being updated.
|
||||
/// </summary>
|
||||
private bool _updating;
|
||||
|
||||
public ScopePickerEditor()
|
||||
{
|
||||
// save all the known fully qualified names
|
||||
_fullyQualifiedNames = ScopeTypesAndNames.GetQualifiedNames().ToArray();
|
||||
|
||||
// fill the options button
|
||||
for (var i = 0; i < _fullyQualifiedNames.Length; i++)
|
||||
{
|
||||
// root scope is always the first, and root scope = not scoped
|
||||
_optionButton.AddItem(
|
||||
i == 0
|
||||
? "not a scope boundary"
|
||||
: ScopeTypesAndNames.GetSimpleNameFromQualifiedName(_fullyQualifiedNames[i]), i);
|
||||
}
|
||||
|
||||
// add the control as a direct child of EditorProperty node.
|
||||
AddChild(_optionButton);
|
||||
|
||||
// make sure the control is able to retain the focus.
|
||||
AddFocusable(_optionButton);
|
||||
|
||||
// initialize the starting value
|
||||
_currentType = _fullyQualifiedNames[0];
|
||||
|
||||
// update the property when the button value changes
|
||||
_optionButton.ItemSelected += OnOptionButtonItemSelected;
|
||||
}
|
||||
|
||||
public override void _UpdateProperty()
|
||||
{
|
||||
// get the new value and immediately return if it's already the selected one.
|
||||
var newValue = GetEditedObject().Get(GetEditedProperty()).AsString();
|
||||
if (newValue == _currentType) return;
|
||||
|
||||
_updating = true;
|
||||
try
|
||||
{
|
||||
var nameIndex = Array.IndexOf(_fullyQualifiedNames, newValue);
|
||||
if (nameIndex < 0)
|
||||
{
|
||||
GD.PushWarning($"Could not find name {newValue} in the list of scope names, resetting to root scope");
|
||||
_currentType = _fullyQualifiedNames[0];
|
||||
EmitChanged(GetEditedProperty(), _currentType);
|
||||
return;
|
||||
}
|
||||
|
||||
_currentType = newValue;
|
||||
UpdateControl();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_updating = false;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnOptionButtonItemSelected(long index)
|
||||
{
|
||||
_currentType = _fullyQualifiedNames[index];
|
||||
UpdateControl();
|
||||
EmitChanged(GetEditedProperty(), _currentType);
|
||||
}
|
||||
|
||||
private void UpdateControl()
|
||||
{
|
||||
_optionButton.Selected = Array.IndexOf(_fullyQualifiedNames, _currentType);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using Godot;
|
||||
using OwofGames.GodotLume;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
public static class ScopeTypesAndNames
|
||||
{
|
||||
private static readonly ConcurrentDictionary<Type, string> TypeToQualifiedName = new();
|
||||
private static readonly ConcurrentDictionary<string, Type> QualifiedNameToType = new();
|
||||
private static readonly ConcurrentDictionary<string, string> QualifiedNameToSimpleName = new();
|
||||
private static readonly Type RootScopeType = typeof(RootScope);
|
||||
|
||||
private static AssemblyLoadEventHandler? _assemblyLoadEventHandler;
|
||||
|
||||
private static void InitializeIfNeeded()
|
||||
{
|
||||
if (_assemblyLoadEventHandler != null) return;
|
||||
Initialize();
|
||||
System.Runtime.Loader.AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly())!
|
||||
.Unloading += _ => { Deinitialize(); };
|
||||
}
|
||||
|
||||
private static void Initialize()
|
||||
{
|
||||
GD.Print($"Initializing {nameof(ScopeTypesAndNames)}");
|
||||
TypeToQualifiedName.Clear();
|
||||
QualifiedNameToType.Clear();
|
||||
QualifiedNameToSimpleName.Clear();
|
||||
_assemblyLoadEventHandler = (sender, args) => CacheScriptsInAssembly(args.LoadedAssembly);
|
||||
AppDomain.CurrentDomain.AssemblyLoad += _assemblyLoadEventHandler;
|
||||
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
|
||||
CacheScriptsInAssembly(assembly);
|
||||
return;
|
||||
|
||||
void CacheScriptsInAssembly(Assembly assembly)
|
||||
{
|
||||
foreach (var type in assembly.GetTypes()
|
||||
.Where(t => t.IsClass)
|
||||
.Where(t => t == RootScopeType || t.IsSubclassOf(RootScopeType)))
|
||||
{
|
||||
if (type.AssemblyQualifiedName == null)
|
||||
{
|
||||
GD.PrintErr("Assembly qualified name of {type} is null");
|
||||
continue;
|
||||
}
|
||||
|
||||
TypeToQualifiedName[type] = type.AssemblyQualifiedName;
|
||||
QualifiedNameToType[type.AssemblyQualifiedName] = type;
|
||||
QualifiedNameToSimpleName[type.AssemblyQualifiedName] = type.Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Deinitialize()
|
||||
{
|
||||
GD.Print($"Deinitializing {nameof(ScopeTypesAndNames)}");
|
||||
AppDomain.CurrentDomain.AssemblyLoad -= _assemblyLoadEventHandler;
|
||||
_assemblyLoadEventHandler = null;
|
||||
TypeToQualifiedName.Clear();
|
||||
QualifiedNameToType.Clear();
|
||||
QualifiedNameToSimpleName.Clear();
|
||||
}
|
||||
|
||||
public static IEnumerable<string> GetQualifiedNames()
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return from p in TypeToQualifiedName
|
||||
orderby p.Key == RootScopeType ? 0 : 1
|
||||
select p.Value;
|
||||
}
|
||||
|
||||
public static Type GetType(string qualifiedName)
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return QualifiedNameToType[qualifiedName];
|
||||
}
|
||||
|
||||
public static string GetSimpleNameFromQualifiedName(string qualifiedName)
|
||||
{
|
||||
InitializeIfNeeded();
|
||||
return QualifiedNameToSimpleName[qualifiedName];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using Godot;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using OwofGames.GodotLume;
|
||||
|
||||
namespace GodotHostTest.GodotDI;
|
||||
|
||||
[Icon("res://addons/GodotDI/ServiceSource.svg")]
|
||||
public partial class ServiceSource : Node
|
||||
{
|
||||
[Export] private string _serviceScope = typeof(RootScope).AssemblyQualifiedName!;
|
||||
[Export] protected Node?[] InjectedNodes = [];
|
||||
|
||||
internal void ResolveInjectedNodes(IServiceProvider serviceProvider)
|
||||
{
|
||||
// if this service source must also act as a scope, create the scope and use its service provider
|
||||
if (_serviceScope != "")
|
||||
{
|
||||
serviceProvider = serviceProvider
|
||||
.CreateScope()
|
||||
.ServiceProvider;
|
||||
}
|
||||
|
||||
// resolve the injected nodes against the chosen service provider
|
||||
// TODO: move to source generator, make it the only way for injection
|
||||
foreach (var node in InjectedNodes)
|
||||
{
|
||||
if (node == null) continue;
|
||||
var nodeType = node.GetType();
|
||||
foreach (var field in nodeType
|
||||
.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
|
||||
{
|
||||
if (field.GetCustomAttribute<InjectAttribute>() == null) continue;
|
||||
var fieldType = field.FieldType;
|
||||
var service = serviceProvider.GetRequiredService(fieldType);
|
||||
field.SetValue(node, service);
|
||||
}
|
||||
|
||||
foreach (var method in nodeType.GetMethods(BindingFlags.Instance | BindingFlags.Public |
|
||||
BindingFlags.NonPublic))
|
||||
{
|
||||
if (method.GetCustomAttribute<InjectAttribute>() == null) continue;
|
||||
var parameters = method.GetParameters();
|
||||
var values = new object?[parameters.Length];
|
||||
var i = 0;
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
var parameterType = parameter.ParameterType;
|
||||
var service = serviceProvider.GetRequiredService(parameterType);
|
||||
values[i++] = service;
|
||||
}
|
||||
|
||||
method.Invoke(node, values);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
uid://qjonl8stia46
|
||||
Reference in New Issue
Block a user