mirror of
https://github.com/aharabada/glitchy-engine-beef.git
synced 2026-09-05 13:01:52 +00:00
Start of using CoreCLR and automatic scriptglue generation
This commit is contained in:
+469
-4
@@ -1,8 +1,19 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Linq.Expressions;
|
||||
using System.Numerics;
|
||||
using System.Reflection;
|
||||
using System.Reflection.Emit;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Loader;
|
||||
using GlitchyEngine.Core;
|
||||
using GlitchyEngine.Editor;
|
||||
using GlitchyEngine.Extensions;
|
||||
using GlitchyEngine.Graphics;
|
||||
using GlitchyEngine.Graphics.Text;
|
||||
using GlitchyEngine.Math;
|
||||
@@ -11,16 +22,470 @@ using GlitchyEngine.Serialization;
|
||||
|
||||
namespace GlitchyEngine;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal unsafe partial struct EngineFunctions
|
||||
{
|
||||
public delegate* unmanaged[Cdecl]<Log.LogLevel, char*, char*, int, void> Log_LogMessage;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// All methods in here are glued to the ScriptGlue.bf in the engine.
|
||||
/// TODO: This could be auto-generated fairly easily
|
||||
/// </summary>
|
||||
internal static class ScriptGlue
|
||||
internal static partial class ScriptGlue
|
||||
{
|
||||
#region Script Glueing infrastructure
|
||||
|
||||
static ScriptGlue()
|
||||
{
|
||||
NativeLibrary.SetDllImportResolver(typeof(ScriptGlue).Assembly, ImportResolver);
|
||||
}
|
||||
|
||||
private static IntPtr ImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
|
||||
{
|
||||
if (libraryName == "__Internal")
|
||||
{
|
||||
// Lade die aktuelle exe selbst
|
||||
return NativeLibrary.Load(Process.GetCurrentProcess().MainModule.FileName);
|
||||
}
|
||||
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private static EngineFunctions _engineFunctions;
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static unsafe void SetEngineFunctions(EngineFunctions* engineFunctions)
|
||||
{
|
||||
_engineFunctions = *engineFunctions;
|
||||
|
||||
Log.Info("Yeah");
|
||||
}
|
||||
|
||||
private static AssemblyLoadContext? _scriptAssemblyContext;
|
||||
|
||||
private static Assembly? _appAssembly;
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static unsafe void LoadScriptAssembly(byte* assemblyData, long assemblyLength, byte* pdbData, long pdbLength)
|
||||
{
|
||||
using UnmanagedMemoryStream assemblyStream = new(assemblyData, assemblyLength);
|
||||
|
||||
using UnmanagedMemoryStream? pdbStream = (pdbData != null) ? new UnmanagedMemoryStream(pdbData, pdbLength) : null;
|
||||
|
||||
LoadAssembly(assemblyStream, pdbStream);
|
||||
}
|
||||
|
||||
private static void LoadAssembly(Stream assemblyStream, Stream? pdbStream)
|
||||
{
|
||||
try
|
||||
{
|
||||
_scriptAssemblyContext ??= new AssemblyLoadContext("ScriptContext", true);
|
||||
|
||||
_appAssembly = _scriptAssemblyContext.LoadFromStream(assemblyStream, pdbStream);
|
||||
|
||||
Debug.Assert(_appAssembly != null);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Fehler: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static void UnloadAssemblies()
|
||||
{
|
||||
_scriptAssemblyContext?.Unload();
|
||||
_scriptAssemblyContext = null;
|
||||
}
|
||||
|
||||
struct ScriptClassInfo
|
||||
{
|
||||
public byte[] Name;
|
||||
public Guid Guid;
|
||||
}
|
||||
|
||||
private static NativeScriptClassInfo[]? _unsafeClasses;
|
||||
|
||||
struct NativeScriptClassInfo
|
||||
{
|
||||
public IntPtr Name;
|
||||
public Guid Guid;
|
||||
public ScriptMethods Methods;
|
||||
public bool RunInEditMode;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
public enum ScriptMethods
|
||||
{
|
||||
None = 0,
|
||||
OnCreate = 0x1,
|
||||
OnUpdate = 0x2,
|
||||
OnDestroy = 0x4
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static unsafe void GetScriptClasses(void** outBuffer, long* length)
|
||||
{
|
||||
using var contextualReflection = AssemblyLoadContext.EnterContextualReflection(_appAssembly);
|
||||
|
||||
Debug.Assert(_appAssembly != null);
|
||||
|
||||
Internal_FreeScriptClassNames();
|
||||
|
||||
var types = _appAssembly.GetTypes();
|
||||
|
||||
List<(string Name, Guid Guid, ScriptMethods AvailableMethods, bool runInEditMode)> scriptClasses = new();
|
||||
|
||||
foreach (var type in types)
|
||||
{
|
||||
if (type.IsSubclassOf(typeof(Entity)))
|
||||
{
|
||||
string? name = type.FullName;
|
||||
|
||||
if (name == null)
|
||||
continue;
|
||||
|
||||
Guid guid = type.GUID;
|
||||
|
||||
ScriptMethods methods = ScriptMethods.None;
|
||||
|
||||
static ScriptMethods HasMethod(Type type, string methodName, ScriptMethods methodFlag)
|
||||
{
|
||||
MethodInfo? methodInfo = type.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
|
||||
|
||||
return methodInfo != null ? methodFlag : ScriptMethods.None;
|
||||
}
|
||||
|
||||
methods |= HasMethod(type, nameof(Entity.OnCreate), ScriptMethods.OnCreate);
|
||||
methods |= HasMethod(type, nameof(Entity.OnUpdate), ScriptMethods.OnUpdate);
|
||||
methods |= HasMethod(type, nameof(Entity.OnDestroy), ScriptMethods.OnDestroy);
|
||||
|
||||
bool runInEditMode = type.HasCustomAttribute<RunInEditModeAttribute>();
|
||||
|
||||
scriptClasses.Add((name, guid, methods, runInEditMode));
|
||||
}
|
||||
}
|
||||
|
||||
_unsafeClasses = new NativeScriptClassInfo[scriptClasses.Count];
|
||||
|
||||
for (int i = 0; i < _unsafeClasses.Length; i++)
|
||||
{
|
||||
_unsafeClasses[i] = new NativeScriptClassInfo()
|
||||
{
|
||||
Guid = scriptClasses[i].Guid,
|
||||
Name = Marshal.StringToCoTaskMemUTF8(scriptClasses[i].Name),
|
||||
Methods = scriptClasses[i].AvailableMethods,
|
||||
RunInEditMode = scriptClasses[i].runInEditMode
|
||||
};
|
||||
}
|
||||
|
||||
*outBuffer = (void*)Marshal.UnsafeAddrOfPinnedArrayElement(_unsafeClasses, 0);
|
||||
*length = _unsafeClasses.Length;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static void FreeScriptClassNames()
|
||||
{
|
||||
Internal_FreeScriptClassNames();
|
||||
}
|
||||
|
||||
internal static void Internal_FreeScriptClassNames()
|
||||
{
|
||||
if (_unsafeClasses == null)
|
||||
return;
|
||||
|
||||
foreach (NativeScriptClassInfo info in _unsafeClasses)
|
||||
{
|
||||
Marshal.FreeCoTaskMem(info.Name);
|
||||
}
|
||||
|
||||
_unsafeClasses = null;
|
||||
}
|
||||
|
||||
private static Dictionary<UUID, (Entity Entity, Type Type)> _entityScripts = new();
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static void ShowEntityEditor(UUID entityId)
|
||||
{
|
||||
(Entity entity, Type type) = _entityScripts[entityId];
|
||||
EntityEditor.ShowEntityEditor(entity);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static void InvokeEntityOnCreate(UUID entityId)
|
||||
{
|
||||
try
|
||||
{
|
||||
(Entity entity, Type type) = _entityScripts[entityId];
|
||||
entity.OnCreate();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
// TODO: Log exceptions to console
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static void InvokeEntityOnUpdate(UUID entityId, float deltaTime)
|
||||
{
|
||||
// using var _ = AssemblyLoadContext.EnterContextualReflection(_appAssembly); // TODO: Check if reflection works correctly in entities
|
||||
|
||||
(Entity entity, Type type) = _entityScripts[entityId];
|
||||
entity.OnUpdate(deltaTime);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static void InvokeEntityOnDestroy(UUID entityId, float deltaTime)
|
||||
{
|
||||
(Entity entity, Type type) = _entityScripts[entityId];
|
||||
entity.OnDestroy();
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly]
|
||||
public static unsafe void CreateScriptInstance(UUID entityId, byte* scriptClassName)
|
||||
{
|
||||
using var _ = AssemblyLoadContext.EnterContextualReflection(_appAssembly);
|
||||
|
||||
Debug.Assert(_appAssembly != null);
|
||||
|
||||
string? typeName = Marshal.PtrToStringUTF8((IntPtr)scriptClassName);
|
||||
|
||||
Debug.Assert(typeName != null);
|
||||
|
||||
Type? scriptType = _appAssembly.GetType(typeName);
|
||||
|
||||
Debug.Assert(scriptType != null, "Script class Type not found.");
|
||||
|
||||
Entity? scriptInstance = ActivatorExtension.CreateEngineObject(scriptType, entityId) as Entity;
|
||||
|
||||
//
|
||||
// // Get the constructor
|
||||
// ConstructorInfo? constructor = scriptType.GetConstructor(
|
||||
// BindingFlags.Instance | BindingFlags.Public,
|
||||
// null,
|
||||
// [],
|
||||
// null);
|
||||
//
|
||||
// Debug.Assert(constructor != null, "Script class constructor not found.");
|
||||
//
|
||||
// // Call the constructor to create an instance
|
||||
// Entity? scriptInstance = constructor?.Invoke(null) as Entity;
|
||||
Debug.Assert(scriptInstance != null, "Failed to create script instance.");
|
||||
//
|
||||
// if (scriptInstance != null)
|
||||
// scriptInstance._uuid = entityId;
|
||||
|
||||
//ScriptFunctions functions = new();
|
||||
|
||||
_entityScripts.Add(entityId, (scriptInstance!, scriptType));
|
||||
|
||||
//MethodInfo? onCreateMethod = scriptType.GetMethod("OnCreate", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
//if (onCreateMethod != null)
|
||||
//{
|
||||
// var v = MethodHelpers.GetFunctionPointerForNativeCode(onCreateMethod, null);
|
||||
//}
|
||||
//if (onCreateMethod != null)
|
||||
//{
|
||||
// //Delegate del = CreateDelegateWithTarget(onCreateMethod, scriptInstance);
|
||||
|
||||
// //var createDelegate = onCreateMethod.CreateDelegate<Action>(scriptInstance);
|
||||
// //var createDelegate = onCreateMethod.CreateDelegate(typeof(OnCreateMethodDelegate), scriptInstance);
|
||||
// //onCreateMethod.CreateDelegate(scriptInstance);
|
||||
|
||||
// //functions.OnCreateMethod = Marshal.GetFunctionPointerForDelegate(createDelegate);
|
||||
//}
|
||||
//
|
||||
// MethodInfo? onUpdateMethod = scriptType.GetMethod("OnUpdate", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
// if (onUpdateMethod != null)
|
||||
// {
|
||||
// // Create the delegate from your method and instance
|
||||
// OnUpdateMethodDelegate onUpdateDelegate = (OnUpdateMethodDelegate)Delegate.CreateDelegate(typeof(OnUpdateMethodDelegate), scriptInstance, onUpdateMethod);
|
||||
//
|
||||
// // Get the function pointer from your delegate
|
||||
// functions.OnUpdateMethod = Marshal.GetFunctionPointerForDelegate(onUpdateDelegate);
|
||||
// }
|
||||
|
||||
|
||||
//functions.OnUpdateMethod = Marshal.GetFunctionPointerForDelegate((float deltaTime) => onUpdateMethod.Invoke(scriptInstance, new object?[]{ deltaTime }));
|
||||
|
||||
//MethodInfo? onDestroyMethod = scriptType.GetMethod("OnUpdate", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
//if (onDestroyMethod != null)
|
||||
// functions.OnDestroyMethod = Marshal.GetFunctionPointerForDelegate(() => onDestroyMethod.Invoke(scriptInstance, null));
|
||||
|
||||
//return functions;
|
||||
}
|
||||
|
||||
static Delegate CreateDelegate(MethodInfo method)
|
||||
{
|
||||
if (method == null)
|
||||
{
|
||||
throw new ArgumentNullException(nameof(method));
|
||||
}
|
||||
|
||||
if (!method.IsStatic)
|
||||
{
|
||||
throw new ArgumentException("The provided method must be static.", nameof(method));
|
||||
}
|
||||
|
||||
if (method.IsGenericMethod)
|
||||
{
|
||||
throw new ArgumentException("The provided method must not be generic.", nameof(method));
|
||||
}
|
||||
|
||||
return method.CreateDelegate(Expression.GetDelegateType(
|
||||
(from parameter in method.GetParameters() select parameter.ParameterType)
|
||||
.Concat(new[] { method.ReturnType })
|
||||
.ToArray()));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Create delegate by methodinfo in target
|
||||
/// </summary>
|
||||
/// <param name="method">method info</param>
|
||||
/// <param name="target">A instance of the object which contains the method where will be execute</param>
|
||||
/// <returns>delegate or null</returns>
|
||||
public static Delegate? CreateDelegateWithTarget(MethodInfo? method, object? target)
|
||||
{
|
||||
if (method is null ||
|
||||
target is null)
|
||||
return null;
|
||||
|
||||
//if (method.IsStatic)
|
||||
// return null;
|
||||
|
||||
if (method.IsGenericMethod)
|
||||
return null;
|
||||
|
||||
return method.CreateDelegate(Expression.GetDelegateType(
|
||||
(from parameter in method.GetParameters() select parameter.ParameterType)
|
||||
.Concat(new[] { method.ReturnType })
|
||||
.ToArray()), target);
|
||||
}
|
||||
|
||||
internal static class MethodHelpers
|
||||
{
|
||||
private const string DelegateTypesAssemblyName = "JitDelegateTypes";
|
||||
|
||||
private static ModuleBuilder _modBuilder;
|
||||
|
||||
private static ConcurrentDictionary<(string, object), Delegate> _delegatesCache;
|
||||
private static ConcurrentDictionary<string, Type> _delegateTypesCache;
|
||||
|
||||
static MethodHelpers()
|
||||
{
|
||||
AssemblyBuilder asmBuilder = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName(DelegateTypesAssemblyName), AssemblyBuilderAccess.Run);
|
||||
|
||||
_modBuilder = asmBuilder.DefineDynamicModule(DelegateTypesAssemblyName);
|
||||
|
||||
_delegatesCache = new ConcurrentDictionary<(string, object), Delegate>();
|
||||
_delegateTypesCache = new ConcurrentDictionary<string, Type>();
|
||||
}
|
||||
|
||||
public static IntPtr GetFunctionPointerForNativeCode(MethodInfo meth, object instance = null)
|
||||
{
|
||||
string funcName = GetFullName(meth);
|
||||
|
||||
Delegate dlg = _delegatesCache.GetOrAdd((funcName, instance), (_) =>
|
||||
{
|
||||
Type[] parameters = meth.GetParameters().Select(x => x.ParameterType).ToArray();
|
||||
|
||||
Type delegateType = GetDelegateType(parameters, meth.ReturnType);
|
||||
|
||||
return Delegate.CreateDelegate(delegateType, instance, meth);
|
||||
});
|
||||
|
||||
return Marshal.GetFunctionPointerForDelegate<Delegate>(dlg);
|
||||
}
|
||||
|
||||
private static string GetFullName(MethodInfo meth)
|
||||
{
|
||||
return $"{meth.DeclaringType.FullName}.{meth.Name}";
|
||||
}
|
||||
|
||||
private static Type GetDelegateType(Type[] parameters, Type returnType)
|
||||
{
|
||||
string key = GetFunctionSignatureKey(parameters, returnType);
|
||||
|
||||
return _delegateTypesCache.GetOrAdd(key, (_) => MakeDelegateType(parameters, returnType, key));
|
||||
}
|
||||
|
||||
private const MethodAttributes CtorAttributes =
|
||||
MethodAttributes.RTSpecialName |
|
||||
MethodAttributes.HideBySig |
|
||||
MethodAttributes.Public;
|
||||
|
||||
private const MethodImplAttributes ImplAttributes =
|
||||
MethodImplAttributes.Runtime |
|
||||
MethodImplAttributes.Managed;
|
||||
|
||||
private const MethodAttributes InvokeAttributes =
|
||||
MethodAttributes.Public |
|
||||
MethodAttributes.HideBySig |
|
||||
MethodAttributes.NewSlot |
|
||||
MethodAttributes.Virtual;
|
||||
|
||||
private const TypeAttributes DelegateTypeAttributes =
|
||||
TypeAttributes.Class |
|
||||
TypeAttributes.Public |
|
||||
TypeAttributes.Sealed |
|
||||
TypeAttributes.AnsiClass |
|
||||
TypeAttributes.AutoClass;
|
||||
|
||||
private static readonly Type[] _delegateCtorSignature = { typeof(object), typeof(IntPtr) };
|
||||
|
||||
private static Type MakeDelegateType(Type[] parameters, Type returnType, string name)
|
||||
{
|
||||
TypeBuilder builder = _modBuilder.DefineType(name, DelegateTypeAttributes, typeof(MulticastDelegate));
|
||||
|
||||
builder.DefineConstructor(CtorAttributes, CallingConventions.Standard, _delegateCtorSignature).SetImplementationFlags(ImplAttributes);
|
||||
|
||||
builder.DefineMethod("Invoke", InvokeAttributes, returnType, parameters).SetImplementationFlags(ImplAttributes);
|
||||
|
||||
return builder.CreateTypeInfo();
|
||||
}
|
||||
|
||||
private static string GetFunctionSignatureKey(Type[] parameters, Type returnType)
|
||||
{
|
||||
string sig = GetTypeName(returnType);
|
||||
|
||||
foreach (Type type in parameters)
|
||||
{
|
||||
sig += '_' + GetTypeName(type);
|
||||
}
|
||||
|
||||
return sig;
|
||||
}
|
||||
|
||||
private static string GetTypeName(Type type)
|
||||
{
|
||||
return type.FullName.Replace(".", string.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region Log
|
||||
|
||||
[MethodImpl(MethodImplOptions.InternalCall)]
|
||||
internal static extern void Log_LogMessage(Log.LogLevel logLevel, string message, string filePath, int line);
|
||||
|
||||
internal static unsafe void Log_LogMessage(Log.LogLevel logLevel, string message, string filePath, int line)
|
||||
{
|
||||
// unsafe
|
||||
// {
|
||||
// byte* mess = (byte*)Marshal.StringToCoTaskMemUTF8(message);
|
||||
//
|
||||
// fixed (char* messagePtr = message)
|
||||
// fixed (char* filePathPtr = filePath)
|
||||
// {
|
||||
// _engineFunctions.Log_LogMessage(logLevel, messagePtr, filePathPtr, line);
|
||||
// }
|
||||
//
|
||||
// Marshal.FreeCoTaskMem((IntPtr)mess);
|
||||
// }
|
||||
}
|
||||
|
||||
|
||||
[MethodImpl(MethodImplOptions.InternalCall)]
|
||||
|
||||
Reference in New Issue
Block a user