54 lines
2.6 KiB
C#
54 lines
2.6 KiB
C#
using System.Text;
|
|
using Microsoft.CodeAnalysis;
|
|
|
|
namespace Hangman.SDK.Generators;
|
|
[Generator]
|
|
public class GlobalRegistryGenerator : ISourceGenerator
|
|
{
|
|
public void Initialize(GeneratorInitializationContext context)
|
|
{
|
|
}
|
|
|
|
public void Execute(GeneratorExecutionContext context)
|
|
{
|
|
StringBuilder sb = new();
|
|
sb
|
|
.AppendLine("using Godot;")
|
|
.AppendLine("using System;")
|
|
.AppendLine("using System.Collections.Generic;")
|
|
.AppendLine("using System.Linq;")
|
|
.AppendLine("using System.Reflection;")
|
|
.AppendLine("using Hangman.SDK.Attributes;")
|
|
.AppendLine("using Hangman.SDK;")
|
|
.AppendLine("public static partial class GlobalRegistry")
|
|
.AppendLine("{")
|
|
.AppendLine(" public static void Register()")
|
|
.AppendLine(" {")
|
|
.AppendLine(" Assembly assembly = Assembly.GetExecutingAssembly();")
|
|
.AppendLine(" IEnumerable<Type> registerTypes = Utils.GetLoadableTypes(assembly);")
|
|
.AppendLine(" registerTypes = registerTypes.Where(t => t.IsClass && t.GetCustomAttributes(typeof(AutoRegister), false).Any());")
|
|
.AppendLine(" foreach(Type t in registerTypes)")
|
|
.AppendLine(" {")
|
|
.AppendLine(" MethodInfo registerMethod = t.GetMethod(\"Register\", BindingFlags.Static | BindingFlags.Public);")
|
|
.AppendLine(" if (registerMethod != null)")
|
|
.AppendLine(" registerMethod.Invoke(null, null);")
|
|
.AppendLine(" }")
|
|
.AppendLine(" }")
|
|
.AppendLine(" public static class Asset<T> where T : Node")
|
|
.AppendLine(" {")
|
|
.AppendLine(" private static readonly Queue<T> Pool = new();")
|
|
.AppendLine(" public static PackedScene Scene { get; set; }")
|
|
.AppendLine(" public static T Instance => Scene.Instantiate<T>();")
|
|
.AppendLine(" public static T Get() => Pool.Count > 0 ? Pool.Dequeue() : Instance;")
|
|
.AppendLine(" public static void Return(T obj)")
|
|
.AppendLine(" {")
|
|
.AppendLine(" if(Pool.Count < 10)")
|
|
.AppendLine(" Pool.Enqueue(obj);")
|
|
.AppendLine(" else")
|
|
.AppendLine(" obj.QueueFree();")
|
|
.AppendLine(" }")
|
|
.AppendLine(" }")
|
|
.AppendLine("}");
|
|
context.AddSource("GlobalRegistry.g.cs", sb.ToString());
|
|
}
|
|
} |