Пример #1
0
        public static void Rewrite(RewriteDesign design, RewrittenValueBridge[] args, InvocationExpressionSyntax invocation)
        {
            var access     = (MemberAccessExpressionSyntax)invocation.Expression;
            var name       = (GenericNameSyntax)access.Name;
            var type       = name.TypeArgumentList.Arguments[0];
            var typeSymbol = design.Semantic.GetTypeInfo(type).Type;

            if (SymbolExtensions.IsSameType(typeSymbol, design.LastValue.Type))
            {
            }
            else if (design.Unchecked || SymbolExtensions.IsDescendantType(typeSymbol, design.LastValue.Type))
            {
                design.LastValue = design.LastValue.Reusable(design);
                design.ForAdd(If(Not(design.LastValue.Is(type)),
                                 Continue()));
                design.LastValue = new TypedValueBridge(type, design.LastValue.Cast(type));
            }
            else
            {
                design.LastValue = design.LastValue.Reusable(design);
                design.ForAdd(If(Not(design.LastValue.Is(type)),
                                 Continue()));
                design.LastValue = new TypedValueBridge(type, design.LastValue.Cast(ParseTypeName("object")).Cast(type));
            }

            design.ResultSize          = null;
            design.ListEnumeration     = false;
            design.ModifiedEnumeration = true;
        }
Пример #2
0
        public static void Rewrite(RewriteDesign design, RewrittenValueBridge[] args, InvocationExpressionSyntax invocation)
        {
            var access     = (MemberAccessExpressionSyntax)invocation.Expression;
            var name       = (GenericNameSyntax)access.Name;
            var type       = name.TypeArgumentList.Arguments[0];
            var typeSymbol = design.Semantic.GetTypeInfo(type).Type;

            if (SymbolExtensions.IsSameType(typeSymbol, design.LastValue.Type))
            {
                ;
            }
            else if (design.Unchecked || SymbolExtensions.IsDescendantType(typeSymbol, design.LastValue.Type))
            {
                design.LastValue = new TypedValueBridge(type, design.LastValue.Cast(type));
                if (!design.Unchecked)
                {
                    design.ListEnumeration = false;
                }
            }
            else
            {
                design.LastValue       = new TypedValueBridge(type, design.LastValue.Cast(ParseTypeName("object")).Cast(type));
                design.ListEnumeration = false;
            }
        }
Пример #3
0
            static IEnumerable <CodeInstruction> Transpiler(MethodBase original, IEnumerable <CodeInstruction> instructions)
            {
                var from = AccessTools.Method(typeof(Time), "get_deltaTime", new Type[0]);
                var to   = SymbolExtensions.GetMethodInfo(() => Main.GetDeltaTime());

                return(instructions.MethodReplacer(from, to));
            }
Пример #4
0
 public void Initialize(Contract.Type bootstrapper, ServerContext context, string[] args)
 {
     Logger.Info("Initializing bootstrapper " + bootstrapper.AssemblyQualifiedName + "...");
     this._bootstrapper = this.CreateInstance(bootstrapper.AssemblyQualifiedName);
     SymbolExtensions.GetMethodInfo <IBootstrapper>(b => b.Initialize(null, null)).Invoke(this._bootstrapper, new object[] { context, args });
     Logger.Info("Initialized");
 }
Пример #5
0
        static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
        {
            var codes = new List <CodeInstruction>(instructions);

            for (int i = 0; i < codes.Count; i++)
            {
                yield return(codes[i]);

                if (codes[i].opcode == OpCodes.Callvirt)
                {
                    if (codes[i].operand.ToString().Contains("IngestedCalculateAmounts"))
                    {
                        MethodInfo m_MyExtraMethod = SymbolExtensions.GetMethodInfo(() => InformWish(null, null, 0, 0));
                        yield return(new CodeInstruction(OpCodes.Ldarg_1));

                        yield return(new CodeInstruction(OpCodes.Ldarg_0));

                        yield return(new CodeInstruction(OpCodes.Ldloc_0));

                        yield return(new CodeInstruction(OpCodes.Ldloc_1));

                        yield return(new CodeInstruction(OpCodes.Call, m_MyExtraMethod));

                        for (int j = i + 1; j < codes.Count; j++)
                        {
                            yield return(codes[j]);
                        }
                        break;
                    }
                }
            }
        }
Пример #6
0
        /// <summary>
        /// Registers the Love/Hate Lua functions with the Dialogue System.
        /// </summary>
        public static void RegisterLuaFunctions()
        {
            if (hasRegisteredLuaFunctions)
            {
                return;
            }
            hasRegisteredLuaFunctions = true;
            Lua.RegisterFunction("GetFactionName", null, SymbolExtensions.GetMethodInfo(() => GetFactionName(string.Empty)));

            Lua.RegisterFunction("GetPersonalityTrait", null, SymbolExtensions.GetMethodInfo(() => GetPersonalityTrait(string.Empty, string.Empty)));
            Lua.RegisterFunction("SetPersonalityTrait", null, SymbolExtensions.GetMethodInfo(() => SetPersonalityTrait(string.Empty, string.Empty, (double)0)));

            Lua.RegisterFunction("GetAffinity", null, SymbolExtensions.GetMethodInfo(() => GetAffinity(string.Empty, string.Empty)));
            Lua.RegisterFunction("SetAffinity", null, SymbolExtensions.GetMethodInfo(() => SetAffinity(string.Empty, string.Empty, (double)0)));
            Lua.RegisterFunction("ModifyAffinity", null, SymbolExtensions.GetMethodInfo(() => ModifyAffinity(string.Empty, string.Empty, (double)0)));

            Lua.RegisterFunction("GetRelationshipTrait", null, SymbolExtensions.GetMethodInfo(() => GetRelationshipTrait(string.Empty, string.Empty, string.Empty)));
            Lua.RegisterFunction("SetRelationshipTrait", null, SymbolExtensions.GetMethodInfo(() => SetRelationshipTrait(string.Empty, string.Empty, string.Empty, (double)0)));
            Lua.RegisterFunction("ModifyRelationshipTrait", null, SymbolExtensions.GetMethodInfo(() => ModifyRelationshipTrait(string.Empty, string.Empty, string.Empty, (double)0)));

            Lua.RegisterFunction("SetRelationshipInheritability", null, SymbolExtensions.GetMethodInfo(() => SetRelationshipInheritable(string.Empty, string.Empty, true)));

            Lua.RegisterFunction("GetHappiness", null, SymbolExtensions.GetMethodInfo(() => GetHappiness(string.Empty)));
            Lua.RegisterFunction("GetPleasure", null, SymbolExtensions.GetMethodInfo(() => GetPleasure(string.Empty)));
            Lua.RegisterFunction("GetArousal", null, SymbolExtensions.GetMethodInfo(() => GetArousal(string.Empty)));
            Lua.RegisterFunction("GetDominance", null, SymbolExtensions.GetMethodInfo(() => GetDominance(string.Empty)));
            Lua.RegisterFunction("ModifyPAD", null, SymbolExtensions.GetMethodInfo(() => ModifyPAD(string.Empty, (double)0, (double)0, (double)0, (double)0)));
            Lua.RegisterFunction("GetTemperament", null, SymbolExtensions.GetMethodInfo(() => GetTemperament(string.Empty)));
            Lua.RegisterFunction("GetEmotionalState", null, SymbolExtensions.GetMethodInfo(() => GetEmotionalState(string.Empty)));

            Lua.RegisterFunction("KnowsDeed", null, SymbolExtensions.GetMethodInfo(() => KnowsDeed(string.Empty, string.Empty, string.Empty, string.Empty)));
            Lua.RegisterFunction("ReportDeed", null, SymbolExtensions.GetMethodInfo(() => ReportDeed(string.Empty, string.Empty, string.Empty)));
            Lua.RegisterFunction("ShareRumors", null, SymbolExtensions.GetMethodInfo(() => ShareRumors(string.Empty, string.Empty)));
        }
Пример #7
0
        static CrossPromotion()
        {
            if (Harmony.HasAnyPatches(_crosspromotion))
            {
                return;
            }

            var instance = new Harmony(_crosspromotion);

            _ = instance.Patch(
                SymbolExtensions.GetMethodInfo(() => ModLister.RebuildModList()),
                postfix: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => ModLister_RebuildModList_Postfix()))
                );

            _ = instance.Patch(
                AccessTools.DeclaredMethod(typeof(Page_ModsConfig), nameof(Page_ModsConfig.PostClose)),
                postfix: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => Page_ModsConfig_PostClose_Postfix()))
                );

            _ = instance.Patch(
                AccessTools.DeclaredMethod(typeof(WorkshopItems), "Notify_Subscribed"),
                postfix: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => WorkshopItems_Notify_Subscribed_Postfix(new PublishedFileId_t(0))))
                );

            _ = instance.Patch(
                AccessTools.DeclaredMethod(typeof(Page_ModsConfig), nameof(Page_ModsConfig.DoWindowContents)),
                transpiler: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => Page_ModsConfig_DoWindowContents_Transpiler(null, null)))
                );
        }
Пример #8
0
        public void Setup()
        {
            var harmony = new Harmony($"{nameof(ApplicationVersionUtilsTests)}.{nameof(Setup)}");

            harmony.Patch(SymbolExtensions.GetMethodInfo(() => ApplicationVersionHelper.GameVersionStr()),
                          prefix: new HarmonyMethod(DelegateHelper.GetMethodInfo(MockedGetVersionStr)));
        }
Пример #9
0
        public void Start(GameDataModder gameDataMod)
        {
            try
            {
                int dummy = 0;

                var harmony = new Harmony("Hp2LadyJizzMod.Hp2BaseMod");

                var femaleJizzToggleCode = new CodeDataMod(10001,
                                                           "509B82A2A4E16DF3774EA93B133F840F",
                                                           CodeType.TOGGLE,
                                                           false,
                                                           "Female j**z off.",
                                                           "Female j**z on.");
                gameDataMod.AddData(femaleJizzToggleCode);

                var mInit        = AccessTools.Method(typeof(UiWindowPhotos), "GetDefaultPhotoViewMode");
                var mInitPostfix = SymbolExtensions.GetMethodInfo(() => InitPostfix(ref dummy));

                harmony.Patch(mInit, null, new HarmonyMethod(mInitPostfix));

                var mRefresh     = AccessTools.Method(typeof(UiWindowPhotos), "Refresh");
                var mfreshPrefix = SymbolExtensions.GetMethodInfo(() => RefreshPrefix(null));

                harmony.Patch(mRefresh, null, new HarmonyMethod(mfreshPrefix));
            }
            catch (Exception e)
            {
                Harmony.DEBUG = true;
                FileLog.Log("EXCEPTION Hp2LadyJizzMod: " + e.Message);
            }
        }
        public void Setup()
        {
            var harmony = new Harmony($"{nameof(DependencyInjectionTests)}.{nameof(Setup)}");

            harmony.Patch(SymbolExtensions.GetMethodInfo(() => FSIOHelper.GetConfigPath()),
                          prefix: new HarmonyMethod(DelegateHelper.GetMethodInfo(MockedGetConfigPath)));
            harmony.Patch(SymbolExtensions2.GetPropertyInfo(() => TWCommon.ConfigName).GetMethod,
                          prefix: new HarmonyMethod(DelegateHelper.GetMethodInfo(MockedGetConfigName)));
            var engineUtilitiesType = Type.GetType("TaleWorlds.Engine.Utilities, TaleWorlds.Engine", false);

            harmony.Patch(engineUtilitiesType?.GetMethod("GetModulesNames", BindingFlags.Public | BindingFlags.Static),
                          prefix: new HarmonyMethod(DelegateHelper.GetMethodInfo(MockedGetModuleNames)));

            var subModule        = new ButterLibSubModule();
            var subModuleWrapper = new MBSubModuleBaseWrapper(subModule);

            subModuleWrapper.SubModuleLoad();
            ExceptionHandlerSubSystem.Instance?.Disable();

            var services = ButterLibSubModule.Instance !.GetServices() !;

            services.AddScoped <CampaignDescriptor, CampaignDescriptorImplementation>();
            services.AddSingleton <ICampaignDescriptorStatic, CampaignDescriptorStaticImplementation>();
            services.AddScoped(typeof(DistanceMatrix <>), typeof(DistanceMatrixImplementation <>));
            services.AddSingleton <IDistanceMatrixStatic, DistanceMatrixStaticImplementation>();
            services.AddSingleton <ICampaignExtensions, CampaignExtensionsImplementation>();
            subModuleWrapper.BeforeInitialModuleScreenSetAsRoot();
        }
Пример #11
0
            public static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
            {
                var from = AccessTools.PropertyGetter(typeof(SteamManager), nameof(SteamManager.Initialized));
                var to   = SymbolExtensions.GetMethodInfo(() => TrueReturner());

                return(Transpilers.MethodReplacer(instructions, from, to));
            }
Пример #12
0
        static CrossPromotion()
        {
            var instance = HarmonyInstance.Create(_crosspromotion);

            if (instance.HasAnyPatches(_crosspromotion))
            {
                return;
            }

            instance.Patch(
                SymbolExtensions.GetMethodInfo(() => MainMenuDrawer.Init()),
                postfix: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => MainMenuDrawer_Init_Postfix()))
                );

            instance.Patch(
                AccessTools.DeclaredMethod(typeof(Page_ModsConfig), nameof(Page_ModsConfig.PostClose)),
                postfix: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => Page_ModsConfig_PostClose_Postfix()))
                );

            instance.Patch(
                AccessTools.DeclaredMethod(typeof(WorkshopItems), "Notify_Subscribed"),
                postfix: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => WorkshopItems_Notify_Subscribed_Postfix(new PublishedFileId_t(0))))
                );

            instance.Patch(
                AccessTools.DeclaredMethod(typeof(Page_ModsConfig), nameof(Page_ModsConfig.DoWindowContents)),
                transpiler: new HarmonyMethod(SymbolExtensions.GetMethodInfo(() => Page_ModsConfig_DoWindowContents_Transpiler(null, null)))
                );
        }
        public static void DoPatching()
        {
            var harmony = new Harmony("com.example.patch");

            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var dll   = assemblies?.FirstOrDefault(x => x.FullName.Contains("RemotePlay"));
            var types = dll?.GetTypes();

            // Show toolbar patch
            var type = types?.FirstOrDefault(x => x.Name.Equals("StreamingToolBar"));

            var showToolBarMethod  = AccessTools.Method(type, "ShowToolBar");
            var showToolBarPrefix  = SymbolExtensions.GetMethodInfo(() => ShowToolBarPrefix());
            var showToolBarPostfix = SymbolExtensions.GetMethodInfo(() => ShowToolBarPostfix());

            // in general, add null checks here (new HarmonyMethod() does it for you too)

            harmony.Patch(showToolBarMethod, new HarmonyMethod(showToolBarPrefix), new HarmonyMethod(showToolBarPostfix));

            // Hide toolbar patch
            var hideToolBarMethod  = AccessTools.Method(type, "HideToolBar");
            var hideToolBarPrefix  = SymbolExtensions.GetMethodInfo(() => HideToolBarPrefix());
            var hideToolBarPostfix = SymbolExtensions.GetMethodInfo(() => HideToolBarPostfix());

            harmony.Patch(hideToolBarMethod, new HarmonyMethod(hideToolBarPrefix), new HarmonyMethod(hideToolBarPostfix));
        }
Пример #14
0
        public void Deserialize()
        {
            PatchInfoSerialization.useBinaryFormatter = false;

            var data      = Encoding.UTF8.GetBytes(ExpectedJSON());
            var patchInfo = PatchInfoSerialization.Deserialize(data);

            var n     = 0;
            var names = new[] { "prefixes", "postfixes", "transpilers", "finalizers" };

            new[] { patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers }
            .Do(fixes =>
            {
                Assert.AreEqual(1, fixes.Length);

                Assert.AreEqual(names[n++], fixes[0].owner);
                Assert.AreEqual(Priority.High, fixes[0].priority);
                Assert.AreEqual(new[] { "p1", null, "p2" }, fixes[0].before);
                Assert.AreEqual(0, fixes[0].after.Length);
                Assert.True(fixes[0].debug);

                var method = SymbolExtensions.GetMethodInfo(() => ExpectedJSON());
                Assert.AreEqual(method, fixes[0].PatchMethod);
            });
        }
        public void RegisterPatch_FileName_InsertAsLastChild()
        {
            var harmony = new Harmony($"{nameof(PrefabComponentPrefabs2Tests)}.{nameof(RegisterPatch_FileName_InsertAsLastChild)}");

            harmony.Patch(SymbolExtensions.GetMethodInfo(() => TaleWorlds.Engine.Utilities.GetBasePath()),
                          prefix: new HarmonyMethod(AccessTools.Method(typeof(PrefabComponentPrefabs2Tests), nameof(MockedGetBasePathPath))));

            // Arrange
            const string MovieName = "TestMovieName";
            const string XPath     = "descendant::OptionsScreenWidget[@Id='Options']/Children";
            var          patch     = PatchCreator.ConstructInsertPatchPath(InsertType.Child, "Prefab", 10);

            PrefabComponent prefabComponent = new("TestModule");
            var             movieDocument   = GetBaseDocument();

            // Act
            prefabComponent.RegisterPatch(MovieName, XPath, patch);
            prefabComponent.ProcessMovieIfNeeded(MovieName, movieDocument);

            // Assert
            var validRootNode = movieDocument.SelectSingleNode("descendant::ValidRoot");

            Assert.IsNotNull(validRootNode);
            Assert.AreEqual("Children", validRootNode !.ParentNode !.Name);
            Assert.AreEqual("SomeChild", validRootNode.FirstChild.Name);
            Assert.AreEqual(validRootNode, validRootNode.ParentNode.ChildNodes[validRootNode.ParentNode.ChildNodes.Count - 1], $"Last child should be ValidRoot. Was {validRootNode.ParentNode.FirstChild.Name}");
        }
Пример #16
0
        public static string StringOperation(string original)
        {
            // This inner transpiler will be applied to the original and
            // the result will replace this method
            //
            // That will allow this method to have a different signature
            // than the original and it must match the transpiled result
            //
            IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
            {
                var list = Transpilers.Manipulator(instructions,
                                                   item => item.opcode == OpCodes.Ldarg_1,
                                                   item => item.opcode = OpCodes.Ldarg_0
                                                   ).ToList();
                var mJoin = SymbolExtensions.GetMethodInfo(() => string.Join(null, null));
                var idx   = list.FindIndex(item => item.opcode == OpCodes.Call && item.operand as MethodInfo == mJoin);

                list.RemoveRange(idx + 1, list.Count - (idx + 1));
                list.Add(new CodeInstruction(OpCodes.Ret));
                return(list.AsEnumerable());
            }

            // make compiler happy
            _ = Transpiler(null);
            return(original);
        }
Пример #17
0
        public void Test_Class22()
        {
            var instance = new Harmony("test");

            Assert.NotNull(instance, "instance");

            var original = SymbolExtensions.GetMethodInfo(() => Class22.Method22());

            Assert.NotNull(original, "original");
            var prefix1 = SymbolExtensions.GetMethodInfo(() => Class22.Prefix1(false));

            Assert.NotNull(original, "prefix1");
            var prefix2 = SymbolExtensions.GetMethodInfo(() => Class22.Prefix2(false));

            Assert.NotNull(original, "prefix2");

            var patched1 = instance.Patch(original, new HarmonyMethod(prefix1));

            Assert.NotNull(patched1, "patched1");

            var patched2 = instance.Patch(original, new HarmonyMethod(prefix2));

            Assert.NotNull(patched2, "patched2");

            Class22.bool1 = null;
            Class22.bool2 = null;
            Class22.Method22();

            Assert.NotNull(Class22.bool1, "Class22.bool1");
            Assert.NotNull(Class22.bool2, "Class22.bool2");
            Assert.IsTrue(Class22.bool1.Value, "Class22.bool1.Value");
            Assert.IsFalse(Class22.bool2.Value, "Class22.bool2.Value");
        }
Пример #18
0
        private static void ImplementEsMain(MethodDefinition newMethod, MethodDefinition[] originalTests, ModuleDefinition moduleToImport)
        {
            var il = newMethod.Body.GetILProcessor();

            il.Emit(OpCodes.Ldc_I4_0);

            foreach (var originalTest in originalTests)
            {
                // obtain reference to ctor
                var testClass = moduleToImport.ImportReference(originalTest.DeclaringType);
                var testCtor  = moduleToImport.ImportReference(originalTest.DeclaringType.Methods.First(x => x.Name == ".ctor"));

                il.Emit(OpCodes.Nop);

                // create Test fixture
                il.Emit(OpCodes.Newobj, testCtor);

                // create action
                il.Emit(OpCodes.Ldftn, moduleToImport.ImportReference(originalTest));
                il.Emit(OpCodes.Newobj, GetCtor(typeof(ECSharp.Action), moduleToImport));

                var testname = originalTest.Name;
                il.Emit(OpCodes.Ldstr, testname);

                // run test
                il.Emit(OpCodes.Call, moduleToImport.ImportReference(SymbolExtensions.GetMethodInfo(() => TargetTestRunner.Run(null, ""))));

                // add results
                il.Emit(OpCodes.Add);
            }

            il.Emit(OpCodes.Ret);

            IlHelper.UpdateIlOffsets(il.Body);
        }
Пример #19
0
            static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
            {
                var m_DrawOptionListing = SymbolExtensions.GetMethodInfo(() => OptionListingUtility.DrawOptionListing(Rect.zero, null));

                var instructionsList = instructions.ToList();
                var patched          = false;

                for (var i = 0; i < instructionsList.Count; i++)
                {
                    var instruction = instructionsList[i];
                    if (i + 2 < instructionsList.Count)
                    {
                        var checkingIns = instructionsList[i + 2];
                        if (!patched && checkingIns != null && checkingIns.Calls(m_DrawOptionListing))
                        {
                            yield return(new CodeInstruction(OpCodes.Ldloc_2));

                            yield return(new CodeInstruction(OpCodes.Call, ListingOption));

                            patched = true;
                        }
                    }
                    yield return(instruction);
                }
            }
Пример #20
0
        static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
        {
            var codes = new List <CodeInstruction>(instructions);

            bool mindstatefound = false;

            for (int i = 0; i < codes.Count; i++)
            {
                yield return(codes[i]);

                if (codes[i].opcode == OpCodes.Ldstr && (codes[i].operand as string) == "mindState")
                {
                    mindstatefound = true;
                }
                if (mindstatefound && codes[i].opcode == OpCodes.Call)
                {
                    MethodInfo m_MyExtraMethod = SymbolExtensions.GetMethodInfo(() => ExposeData(null));
                    yield return(new CodeInstruction(OpCodes.Ldarg_0));

                    yield return(new CodeInstruction(OpCodes.Call, m_MyExtraMethod));

                    for (int j = i + 1; j < codes.Count; j++)
                    {
                        yield return(codes[j]);
                    }
                    break;
                }
            }
        }
Пример #21
0
 private void OnEnable()
 {
     Lua.RegisterFunction("getObj", this, SymbolExtensions.GetMethodInfo(() => getObj(string.Empty)));
     Lua.RegisterFunction("getObject", this, SymbolExtensions.GetMethodInfo(() => getObj(string.Empty)));
     Lua.RegisterFunction("getProp", this, SymbolExtensions.GetMethodInfo(() => getProp(string.Empty, string.Empty)));
     Lua.RegisterFunction("setProp", this, SymbolExtensions.GetMethodInfo(() => setProp(string.Empty, string.Empty, default(object))));
 }
Пример #22
0
        private static void ModLoad(Harmony harmony)
        {
            var mOrigional = AccessTools.Method(typeof(GamePersistence), "Load");
            var mLoadPre   = SymbolExtensions.GetMethodInfo(() => LoadPre(null));

            harmony.Patch(mOrigional, new HarmonyMethod(mLoadPre));
        }
Пример #23
0
 private void RegisterLuaFunctions()
 {
     Lua.RegisterFunction("vGetHealth", this, SymbolExtensions.GetMethodInfo(() => vGetHealth()));
     Lua.RegisterFunction("vGetMaxHealth", this, SymbolExtensions.GetMethodInfo(() => vGetMaxHealth()));
     Lua.RegisterFunction("vAddHealth", this, SymbolExtensions.GetMethodInfo(() => vAddHealth((double)0)));
     Lua.RegisterFunction("vAddMaxHealth", this, SymbolExtensions.GetMethodInfo(() => vAddMaxHealth((double)0)));
 }
 void OnEnable()
 {
     // Make the functions available to Lua: (Replace these lines with your own.)
     Lua.RegisterFunction("DebugLog", this, SymbolExtensions.GetMethodInfo(() => DebugLog(string.Empty)));
     Lua.RegisterFunction("AddOne", this, SymbolExtensions.GetMethodInfo(() => AddOne((double)0)));
     Lua.RegisterFunction("BlowItUp", this, typeof(testDialogueFunctionScript).GetMethod("BlowItUp"));
 }
Пример #25
0
        static IEnumerable <CodeInstruction> Transpiler(IEnumerable <CodeInstruction> instructions)
        {
            var    methodContains  = SymbolExtensions.GetMethodInfo(() => PDAScanner.complete.Contains(TechType.None));
            object operandContains = null;
            var    instructionList = new List <CodeInstruction>(instructions);

            for (int i = 0; i < instructionList.Count - 2; i++)
            {
                if (operandContains == null &&
                    instructionList[i].opcode == OpCodes.Callvirt &&
                    instructionList[i].operand as MethodInfo == methodContains &&
                    instructionList[i + 1].opcode == OpCodes.Stloc_S)
                {
                    operandContains = instructionList[i + 1].operand;
                }
                else if (instructionList[i].opcode == OpCodes.Ldloc_S &&
                         instructionList[i].operand == operandContains &&
                         instructionList[i + 1].opcode == OpCodes.Brfalse &&
                         instructionList[i + 2].opcode == OpCodes.Ldc_R4)
                {
                    instructionList[i + 2].operand = knownScanTime;
                    Console.WriteLine("[Rm_FastKnownScan] Changed scan speed to: {0}", knownScanTime);
                    break;
                }
            }
            return(instructionList);
        }
        private IEnumerable <IParameterParser> Parse(MethodCallExpression expression)
        {
            foreach (var argument in expression.Arguments)
            {
                if (argument is ConstantExpression)
                {
                    var constant = argument as ConstantExpression;
                    yield return(new ConstantParser(constant.Value));
                }
                else if (argument is MethodCallExpression)
                {
                    var call            = argument as MethodCallExpression;
                    var parserSelectors = new Func <IParameterParser>[]
                    {
                        () => AnyValueParser(call),
                        () => BetweenParser(call),
                        () => new ConstantParser(SymbolExtensions.GetExpressionValue(call))
                    };

                    var parser = parserSelectors.Select(a => a()).FirstOrDefault(a => a != null);
                    yield return(parser);
                }
                else
                {
                    yield return(new ConstantParser(SymbolExtensions.GetExpressionValue(argument)));
                }
            }
        }
Пример #27
0
        public void SerializeAndDeserialize()
        {
            var method  = SymbolExtensions.GetMethodInfo(() => ExpectedJSON());
            var hMethod = new HarmonyMethod(method, Priority.High, new[] { "p1", null, "p2" }, new string[0], true);

            var originalPatchInfo = new PatchInfo();

            originalPatchInfo.AddPrefixes("prefixes", new[] { hMethod });
            originalPatchInfo.AddPostfixes("postfixes", new[] { hMethod });
            originalPatchInfo.AddTranspilers("transpilers", new[] { hMethod });
            originalPatchInfo.AddFinalizers("finalizers", new[] { hMethod });

            var data      = PatchInfoSerialization.Serialize(originalPatchInfo);
            var patchInfo = PatchInfoSerialization.Deserialize(data);

            var n     = 0;
            var names = new[] { "prefixes", "postfixes", "transpilers", "finalizers" };

            new[] { patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers }
            .Do(fixes =>
            {
                Assert.AreEqual(1, fixes.Length);

                Assert.AreEqual(names[n++], fixes[0].owner);
                Assert.AreEqual(Priority.High, fixes[0].priority);
                Assert.AreEqual(new[] { "p1", null, "p2" }, fixes[0].before);
                Assert.AreEqual(0, fixes[0].after.Length);
                Assert.True(fixes[0].debug);

                var method = SymbolExtensions.GetMethodInfo(() => ExpectedJSON());
                Assert.AreEqual(method, fixes[0].PatchMethod);
            });
        }
Пример #28
0
        public MethodReference GetConstructorReferenceInternal(Expression <Action> expression)
        {
            var info = SymbolExtensions.GetCtorInfo(expression);

            var m = ModuleDefinition.CreateModule("t", ModuleKind.Dll).Import(info);

            return(m);
        }
Пример #29
0
        public static void RegisterOriginalsPatch(Harmony harmony)
        {
            var t_PatchFunctions = AccessTools.TypeByName("HarmonyLib.PatchFunctions");
            var m_UpdateWrapper  = AccessTools.Method(t_PatchFunctions, "UpdateWrapper");
            var m_PatchPostfix   = SymbolExtensions.GetMethodInfo(() => PatchPostfix(null, null));

            _ = harmony.Patch(m_UpdateWrapper, postfix: new HarmonyMethod(m_PatchPostfix));
        }
Пример #30
0
        public MethodReference GetMethodReference(Expression <Action> expression)
        {
            var info   = SymbolExtensions.GetMethodInfo(expression);
            var type   = m_usedTypes.Single(x => info.DeclaringType.Name == x.Name);
            var method = type.Methods.Single(x => x.Name.Contains(info.Name));

            return(method);
        }