From 9a5406fa849071a96b286747911530c43929a8e3 Mon Sep 17 00:00:00 2001 From: Eddio0141 Date: Thu, 15 Aug 2024 07:12:10 +0100 Subject: [PATCH] automatically allow UniTAS types to be used in moonsharp scripts --- .../Patcher/Implementations/LiveScripting.cs | 48 ++++++++----------- 1 file changed, 20 insertions(+), 28 deletions(-) diff --git a/UniTAS/Patcher/Implementations/LiveScripting.cs b/UniTAS/Patcher/Implementations/LiveScripting.cs index 8ec1ea4c..3b0717a1 100644 --- a/UniTAS/Patcher/Implementations/LiveScripting.cs +++ b/UniTAS/Patcher/Implementations/LiveScripting.cs @@ -1,13 +1,11 @@ using System; -using System.Threading; -using HarmonyLib; using MoonSharp.Interpreter; +using MoonSharp.Interpreter.Interop; +using MoonSharp.Interpreter.Interop.RegistrationPolicies; using MoonSharp.Interpreter.Loaders; -using UniTAS.Patcher.Extensions; using UniTAS.Patcher.Interfaces.DependencyInjection; using UniTAS.Patcher.Services; using UniTAS.Patcher.Services.Logging; -using UnityEngine; namespace UniTAS.Patcher.Implementations; @@ -16,39 +14,33 @@ namespace UniTAS.Patcher.Implementations; [ExcludeRegisterIfTesting] public class LiveScripting : ILiveScripting { - private readonly Thread _setupThread; private readonly ILogger _logger; - public LiveScripting(ILogger logger) + private class CustomInteropRegistrationPolicy : IRegistrationPolicy { - _logger = logger; - _setupThread = new(() => + private static readonly IRegistrationPolicy Default = new DefaultRegistrationPolicy(); + + public IUserDataDescriptor HandleRegistration(IUserDataDescriptor newDescriptor, + IUserDataDescriptor oldDescriptor) { - var allTypes = AccessTools.GetTypesFromAssembly(typeof(LiveScripting).Assembly); - foreach (var type in allTypes) - { - try - { - UserData.RegisterType(type); - } - catch (Exception e) - { - logger.LogWarning($"failed to register type {type.SaneFullName()}, {e}"); - } - } + return Default.HandleRegistration(newDescriptor, oldDescriptor); + } + + public bool AllowTypeAutoRegistration(Type type) + { + var unitasAssembly = typeof(LiveScripting).Assembly; + return Equals(type.Assembly, unitasAssembly); + } + } - UserData.RegisterType(); - UserData.RegisterType(); - UserData.RegisterType(); - }); - _setupThread.Start(); + public LiveScripting(ILogger logger) + { + UserData.RegistrationPolicy = new CustomInteropRegistrationPolicy(); + _logger = logger; } public Script NewScript() { - if (_setupThread.ThreadState == ThreadState.Running) - _setupThread.Join(); - var script = new Script(CoreModules.Preset_Complete) { Options =