Exemplo n.º 1
0
        /*********
        ** Public methods
        *********/

        /// <summary>The mod entry point, called after the mod is first loaded.</summary>
        /// <param name="helper">Provides simplified APIs for writing mods.</param>
        public override void Entry(IModHelper helper)
        {
            HarmonyInstance harmony = HarmonyInstance.Create(this.Helper.DirectoryPath);

            harmony.PatchAll(Assembly.GetExecutingAssembly());
        }
 public override void Patch(HarmonyInstance harmony)
 {
     PatchPrefix(harmony, TARGET_METHOD);
 }
Exemplo n.º 3
0
        public void OnCreated(ILoading loading)
        {
            var harmony = HarmonyInstance.Create("com.pachang.enhanceddistrictservices");

            harmony.PatchAll(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 4
0
 private static bool OnUnload(UnityModManager.ModEntry modEntry)
 {
     HarmonyInstance.Create(modEntry.Info.Id).UnpatchAll();
     return(true);
 }
Exemplo n.º 5
0
        public override void Entry(IModHelper helper)
        {
            config   = Helper.ReadConfig <Config>();
            _helper  = Helper;
            _monitor = Monitor;

            helper.Events.Display.Rendering += (s, e) =>
            {
                if (FixedViewport.HasValue)
                {
                    Game1.viewport = FixedViewport.Value;
                }
            };

            helper.Events.Display.RenderingWorld += (s, e) =>
            {
                if (removeMapLayers)
                {
                    Game1.graphics.GraphicsDevice.Clear(transparentXNA);
                }
            };

            helper.Events.GameLoop.GameLaunched += (s, e) =>
            {
                pixel  = getRectangle(1, 1, Microsoft.Xna.Framework.Color.White);
                tex    = new Texture2D(Game1.graphics.GraphicsDevice, Game1.game1.Window.ClientBounds.Width, Game1.game1.Window.ClientBounds.Height);
                colors = new Microsoft.Xna.Framework.Color[Game1.game1.Window.ClientBounds.Width * Game1.game1.Window.ClientBounds.Height];
                transparentBackground = getRectangle(Game1.game1.Window.ClientBounds.Width, Game1.game1.Window.ClientBounds.Height, transparentXNA);
            };

            helper.Events.GameLoop.UpdateTicked += (s, e) =>
            {
                uint frameM = (uint)(60 / config.FPS);
                frameMet     = e.IsMultipleOf(frameM);
                nextRecFrame = e.IsMultipleOf(30);
            };

            helper.Events.Display.WindowResized += (s, e) =>
            {
                tex.Dispose();
                transparentBackground.Dispose();
                transparentBackground = getRectangle(Game1.game1.Window.ClientBounds.Width, Game1.game1.Window.ClientBounds.Height, transparentXNA);
                colors = null;
                tex    = new Texture2D(Game1.graphics.GraphicsDevice, Game1.game1.Window.ClientBounds.Width, Game1.game1.Window.ClientBounds.Height);
                colors = new Microsoft.Xna.Framework.Color[Game1.game1.Window.ClientBounds.Width * Game1.game1.Window.ClientBounds.Height];
                setupFraming(true);
                if (recording)
                {
                    recording    = false;
                    frameCounter = 0;
                }
            };

            helper.Events.Input.ButtonPressed += (s, e) =>
            {
                if (!config.WithCtrlButton || shouldFrame || Helper.Input.IsDown(SButton.LeftControl) || Helper.Input.IsDown(SButton.RightControl))
                {
                    if (e.Button == config.RecordButton && Helper.Input.IsDown(SButton.LeftControl) || Helper.Input.IsDown(SButton.RightControl))
                    {
                        if (!recording && gifThread == null)
                        {
                            frames       = new ConcurrentQueue <Microsoft.Xna.Framework.Color[]>();
                            frameCounter = 0;
                            recording    = true;
                            startExport();
                        }
                        else if (recording)
                        {
                            recording = false;
                        }
                    }

                    if (recording)
                    {
                        return;
                    }

                    if (e.Button == config.FrameButton && !recording)
                    {
                        if (!shouldFrame && !framing.HasValue)
                        {
                            setupFraming();
                        }
                        else if (!shouldFrame)
                        {
                            shouldFrame = true;
                        }
                        else
                        {
                            shouldFrame = false;
                        }
                    }
                }

                if (recording)
                {
                    return;
                }

                if (shouldFrame && !recording)
                {
                    if (shouldFrame && e.Button == config.FrameUp && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.Y  = Math.Max(rect.Y - 20, 0);
                        framing = rect;
                        setupFraming();
                    }

                    if (shouldFrame && e.Button == config.FrameDown && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.Y  = Math.Min(rect.Y + 20, Game1.game1.Window.ClientBounds.Height - rect.Height);
                        framing = rect;
                        setupFraming();
                    }

                    if (shouldFrame && e.Button == config.FrameRight && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.X  = Math.Min(rect.X + 20, Game1.game1.Window.ClientBounds.Width - rect.Width);
                        framing = rect;
                        setupFraming();
                    }

                    if (shouldFrame && e.Button == config.FrameLeft && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.X  = Math.Max(rect.X - 20, 0);
                        framing = rect;
                        setupFraming();
                    }


                    if (shouldFrame && e.Button == config.FrameWider && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.Width = Math.Min(rect.Width + 20, Game1.game1.Window.ClientBounds.Width - rect.X);
                        rect.X    -= 10;
                        framing    = rect;
                        setupFraming();
                    }

                    if (shouldFrame && e.Button == config.FrameTaller && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.Height = Math.Min(rect.Height + 20, Game1.game1.Window.ClientBounds.Height - rect.Y);
                        rect.Y     -= 10;
                        framing     = rect;
                        setupFraming();
                    }

                    if (shouldFrame && e.Button == config.FrameFlatter && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.Height = Math.Max(rect.Height - 20, 0);
                        rect.Y     += 10;
                        framing     = rect;
                        setupFraming();
                    }

                    if (shouldFrame && e.Button == config.FrameThiner && !recording)
                    {
                        if (!framing.HasValue)
                        {
                            setupFraming();
                        }

                        Rectangle rect = framing.Value;
                        rect.Width = Math.Max(rect.Width - 20, 0);
                        rect.X    += 10;
                        framing    = rect;
                        setupFraming();
                    }
                }

                if (shouldFrame || Helper.Input.IsDown(SButton.LeftControl) || Helper.Input.IsDown(SButton.RightControl))
                {
                    if (e.Button == config.FixViewport)
                    {
                        if (!FixedViewport.HasValue)
                        {
                            FixedViewport = new xTile.Dimensions.Rectangle(Game1.viewport);
                        }
                        else
                        {
                            FixedViewport = null;
                        }
                    }

                    if (e.Button == config.RemoveBackground)
                    {
                        removeMapLayers = !removeMapLayers;
                    }
                }
            };
            HarmonyInstance instance = HarmonyInstance.Create("GifRecorder");

            instance.Patch(typeof(xTile.Layers.Layer).GetMethod("Draw", BindingFlags.Public | BindingFlags.Instance), new HarmonyMethod(this.GetType().GetMethod("PreventMapDraw", BindingFlags.Public | BindingFlags.Static)));
            instance.Patch(typeof(Game1).GetMethod("renderScreenBuffer", BindingFlags.Instance | BindingFlags.NonPublic), new HarmonyMethod(this.GetType().GetMethod("Record", BindingFlags.Public | BindingFlags.Static)));
        }
Exemplo n.º 6
0
 public void OnDisabled()
 {
     harmony.UnpatchAll(harmonyId);
     harmony = null;
 }
Exemplo n.º 7
0
        /// <summary>The mod entry point, called after the mod is first loaded.</summary>
        /// <param name="helper">Provides simplified APIs for writing mods.</param>
        public override void Entry(IModHelper helper)
        {
            context = this;
            Config  = helper.ReadConfig <ModConfig>();
            SHelper = helper;
            if (!Config.EnableMod)
            {
                return;
            }

            api = (MobilePhoneApi)GetApi();

            MobilePhoneApp.Initialize(Helper, Monitor, Config);
            MobilePhoneCall.Initialize(Helper, Monitor, Config);
            ThemeApp.Initialize(Helper, Monitor, Config);
            PhoneVisuals.Initialize(Helper, Monitor, Config);
            PhoneInput.Initialize(Helper, Monitor, Config);
            PhoneGameLoop.Initialize(Helper, Monitor, Config);
            PhoneUtils.Initialize(Helper, Monitor, Config);
            PhonePatches.Initialize(Helper, Monitor, Config);

            var harmony = HarmonyInstance.Create(ModManifest.UniqueID);

            harmony.Patch(
                original: AccessTools.Method(typeof(Game1), nameof(Game1.pressSwitchToolButton)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Game1_pressSwitchToolButton_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.endBehaviors)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_endBehaviors_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Farmer), nameof(Farmer.changeFriendship)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Farmer_changeFriendship_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(GameLocation), "resetLocalState"),
                postfix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.GameLocation_resetLocalState_postfix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_awardFestivalPrize)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_addTool)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_addConversationTopic)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_addCookingRecipe)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_addCraftingRecipe)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_money)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_removeItem)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_friendship)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_dump)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), nameof(Event.command_cutscene)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_command_cutscene_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(Event), "namePet"),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.Event_namePet_prefix))
                );

            harmony.Patch(
                original: AccessTools.Method(typeof(CarpenterMenu), nameof(CarpenterMenu.returnToCarpentryMenu)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.CarpenterMenu_returnToCarpentryMenu_prefix))
                );
            harmony.Patch(
                original: AccessTools.Method(typeof(CarpenterMenu), nameof(CarpenterMenu.returnToCarpentryMenuAfterSuccessfulBuild)),
                prefix: new HarmonyMethod(typeof(PhonePatches), nameof(PhonePatches.CarpenterMenu_returnToCarpentryMenuAfterSuccessfulBuild_prefix))
                );

            Helper.Events.Input.ButtonPressed            += PhoneInput.Input_ButtonPressed;
            Helper.Events.GameLoop.SaveLoaded            += PhoneGameLoop.GameLoop_SaveLoaded;
            Helper.Events.GameLoop.GameLaunched          += PhoneGameLoop.GameLoop_GameLaunched;
            Helper.Events.GameLoop.ReturnedToTitle       += PhoneGameLoop.ReturnedToTitle;
            Helper.Events.GameLoop.TimeChanged           += PhoneGameLoop.GameLoop_TimeChanged;
            Helper.Events.GameLoop.OneSecondUpdateTicked += PhoneGameLoop.GameLoop_OneSecondUpdateTicked;
            Helper.Events.Display.WindowResized          += PhoneVisuals.Display_WindowResized;
        }
 static MethodBase TargetMethod(HarmonyInstance instance)
 {
     return(AccessTools.Property(ClrTypes.TMP_Text, "text").GetSetMethod());
 }
 static bool Prepare(HarmonyInstance instance)
 {
     return(ClrTypes.TMP_Text != null);
 }
 static bool Prepare(HarmonyInstance instance)
 {
     return(ClrTypes.TextMeshPro != null);
 }
 static MethodBase TargetMethod(HarmonyInstance instance)
 {
     return(AccessTools.Method(ClrTypes.TextMeshPro, "OnEnable"));
 }
 static MethodBase TargetMethod(HarmonyInstance instance)
 {
     return(AccessTools.Method(ClrTypes.TMP_Text, "SetCharArray", new[] { typeof(int[]), typeof(int), typeof(int) }));
 }
 static MethodBase TargetMethod(HarmonyInstance instance)
 {
     return(AccessTools.Method(ClrTypes.TMP_Text, "SetText", new[] { typeof(string), typeof(float), typeof(float), typeof(float) }));
 }
Exemplo n.º 14
0
        static HarmonyPatches()
        {
            bool   injected = false;
            string patchLog = "Start injecting PSI to pawns ...";

            foreach (ThingDef def in DefDatabase <ThingDef> .AllDefs.Where(
                         x => x.race != null && x.race.Humanlike &&
                         x.race.IsFlesh))
            {
                patchLog += "\nPSI check: " + def;
                if (def?.comps != null)
                {
                    def.comps.Add(new CompProperties(typeof(CompPSI)));
                    patchLog += " - PSI injected.";
                    injected  = true;
                }
            }

            patchLog += injected ? string.Empty : "\nNo pawns found for PSI :(";
            Log.Message(patchLog);

            HarmonyInstance harmony = HarmonyInstance.Create("com.colonistbarkf.rimworld.mod");

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar), nameof(ColonistBar.ColonistBarOnGUI)),
                new HarmonyMethod(typeof(ColonistBar_KF), nameof(ColonistBar_KF.ColonistBarOnGUI_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar),
                                   nameof(ColonistBar.MapColonistsOrCorpsesInScreenRect)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(MapColonistsOrCorpsesInScreenRect_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar),
                                   nameof(ColonistBar.CaravanMembersCaravansInScreenRect)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(CaravanMembersCaravansInScreenRect_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar), nameof(ColonistBar.ColonistOrCorpseAt)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(ColonistOrCorpseAt_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar), nameof(ColonistBar.CaravanMemberCaravanAt)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(CaravanMemberCaravanAt_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar), nameof(ColonistBar.GetColonistsInOrder)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(GetColonistsInOrder_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(ColonistBar), nameof(ColonistBar.MarkColonistsDirty)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(MarkColonistsDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Caravan), nameof(Caravan.Notify_PawnAdded)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(EntriesDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Caravan), nameof(Caravan.Notify_PawnRemoved)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(EntriesDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Caravan), nameof(Caravan.PostAdd)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(EntriesDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Caravan), nameof(Caravan.PostRemove)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(EntriesDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Game), nameof(Game.AddMap)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(EntriesDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Window), nameof(Window.Notify_ResolutionChanged)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(IsPlayingDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Game), nameof(Game.DeinitAndRemoveMap)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(IsPlayingDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Pawn), nameof(Pawn.SetFaction)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(EntriesDirty_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Pawn), nameof(Pawn.SpawnSetup)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(Pawn_SpawnSetup_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Pawn), nameof(Pawn.Kill)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(Pawn_Kill_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Pawn_HealthTracker), nameof(Pawn_HealthTracker.Notify_Resurrected)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(Pawn_Resurrected_Postfix)));

            // NOT WORKING, FollowMe immediatly cancels if this is active
            // harmony.Patch(
            // AccessTools.Method(typeof(CameraDriver), nameof(CameraDriver.JumpToCurrentMapLoc), new[] { typeof(Vector3) }),
            // new HarmonyMethod(typeof(HarmonyPatches), nameof(StopFollow_Prefix)),
            // null);
            harmony.Patch(
                AccessTools.Method(
                    typeof(WorldCameraDriver),
                    nameof(WorldCameraDriver.JumpTo),
                    new[] { typeof(Vector3) }),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(StopFollow_Prefix)),
                null);

            harmony.Patch(
                AccessTools.Method(
                    typeof(ThingSelectionUtility),
                    nameof(ThingSelectionUtility.SelectNextColonist)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(StartFollowSelectedColonist1)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(StartFollowSelectedColonist2)),
                null);

            harmony.Patch(
                AccessTools.Method(
                    typeof(ThingSelectionUtility),
                    nameof(ThingSelectionUtility.SelectPreviousColonist)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(StartFollowSelectedColonist1)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(StartFollowSelectedColonist2)),
                null);

            harmony.Patch(
                AccessTools.Method(
                    typeof(CameraDriver),
                    nameof(CameraDriver.JumpToCurrentMapLoc),
                    new[] { typeof(Vector3) }),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(StopFollow_Prefix_Vector3)),
                null);

            harmony.Patch(
                AccessTools.Method(typeof(Pawn), nameof(Pawn.PostApplyDamage)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(Pawn_PostApplyDamage_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Corpse), "NotifyColonistBar"),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(NotifyColonistBar_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(MapPawns), "DoListChangedNotifications"),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(IsColonistBarNull_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(ThingOwner), "NotifyColonistBarIfColonistCorpse"),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(NotifyColonistBarIfColonistCorpse_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(Thing), nameof(Thing.DeSpawn)),
                null,
                new HarmonyMethod(typeof(HarmonyPatches), nameof(DeSpawn_Postfix)));

            harmony.Patch(
                AccessTools.Method(typeof(PlaySettings), nameof(PlaySettings.DoPlaySettingsGlobalControls)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(PlaySettingsDirty_Prefix)),
                new HarmonyMethod(typeof(HarmonyPatches), nameof(PlaySettingsDirty_Postfix)));

            Log.Message(
                "Colonistbar KF successfully completed " + harmony.GetPatchedMethods().Count()
                + " patches with harmony.");
        }
Exemplo n.º 15
0
 static void InitPatches() =>
 HarmonyInstance.Create(Constants.ModName)
 .PatchAll(Assembly.GetExecutingAssembly());
        public static void Init()
        {
            var manifestDirectory = Path.GetDirectoryName(VersionManifestUtilities.MANIFEST_FILEPATH)
                                    ?? throw new InvalidOperationException("Manifest path is invalid.");

            ModDirectory = Path.GetFullPath(
                Path.Combine(manifestDirectory,
                             Path.Combine(Path.Combine(Path.Combine(
                                                           "..", ".."), ".."), "Mods")));

            LogPath = Path.Combine(ModDirectory, "BTModLoader.log");

            // do some simple benchmarking
            var sw = new Stopwatch();

            sw.Start();

            if (!Directory.Exists(ModDirectory))
            {
                Directory.CreateDirectory(ModDirectory);
            }

            // create log file, overwritting if it's already there
            using (var logWriter = File.CreateText(LogPath))
            {
                logWriter.WriteLine($"BTModLoader -- {DateTime.Now}");
            }

            var harmony = HarmonyInstance.Create("io.github.mpstark.BTModLoader");

            // get all dll paths
            var dllPaths = Directory.GetFiles(ModDirectory).Where(x => Path.GetExtension(x).ToLower() == ".dll").ToArray();

            if (dllPaths.Length == 0)
            {
                Log(@"No .dlls loaded. DLLs must be placed in the root of the folder \BATTLETECH\Mods\.");
                return;
            }

            // load the dlls
            foreach (var dllPath in dllPaths)
            {
                Log($"Found DLL: {Path.GetFileName(dllPath)}");
                LoadDLL(dllPath);
            }

            // do some simple benchmarking
            sw.Stop();
            Log("");
            Log($"Took {sw.Elapsed.TotalSeconds} seconds to load mods");

            // print out harmony summary
            var patchedMethods = harmony.GetPatchedMethods().ToArray();

            if (patchedMethods.Length == 0)
            {
                Log("No Harmony Patches loaded.");
                return;
            }

            Log("");
            Log("Harmony Patched Methods (after mod loader startup):");

            foreach (var method in patchedMethods)
            {
                var info = harmony.GetPatchInfo(method);

                if (info == null)
                {
                    continue;
                }

                Log($"{method.ReflectedType.FullName}.{method.Name}:");

                // prefixes
                if (info.Prefixes.Count != 0)
                {
                    Log("\tPrefixes:");
                }
                foreach (var patch in info.Prefixes)
                {
                    Log($"\t\t{patch.owner}");
                }

                // transpilers
                if (info.Transpilers.Count != 0)
                {
                    Log("\tTranspilers:");
                }
                foreach (var patch in info.Transpilers)
                {
                    Log($"\t\t{patch.owner}");
                }

                // postfixes
                if (info.Postfixes.Count != 0)
                {
                    Log("\tPostfixes:");
                }
                foreach (var patch in info.Postfixes)
                {
                    Log($"\t\t{patch.owner}");
                }
            }

            Log("");
        }
Exemplo n.º 17
0
 public void OnEnabled()
 {
     //HarmonyInstance.DEBUG = false;
     harmony = HarmonyInstance.Create(harmonyId);
     harmony.PatchAll(Assembly.GetExecutingAssembly());
 }
        public static void Main()
        {
            //Where the fun begins

            //Initiate the madness
            HarmonyInstance harmonyInstance = HarmonyInstance.Create("Legionite.collidercommand.core");

            harmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
            GUIColliderController.Initiate();
            //ColliderCommander.EarlySubscribe();
            //BlockScanner.GUIBlockGrabber.Initiate();

            if (LookForMod("WaterMod"))
            {
                Debug.Log("COLLIDER CONTROLLER: Found Water Mod!  Will compensate for missing buoyency colliders!");
                isWaterModPresent = true;
                if (LookForMod("ScaleableTechs"))
                {
                    Debug.Log("COLLIDER CONTROLLER: Found ScaleTechs!  Will update post rescale update!");
                    isScaleTechsPresent = true;
                }
            }

            if (LookForMod("Control Block"))
            {
                Debug.Log("COLLIDER CONTROLLER: Found Control blocks!  Will switch no-collider block fetch system to Control-Block Supported!");
                isControlBlocksPresent = true;
            }


            Debug.Log("\nCOLLIDER CONTROLLER: Config Loading");
            ModConfig thisModConfig = new ModConfig();

            Debug.Log("\nCOLLIDER CONTROLLER: Config Loaded.");

            thisModConfig.BindConfig <KickStart>(null, "keyInt");
            hotKey = (KeyCode)keyInt;

            //thisModConfig.BindConfig<KickStart>(null, "colliderGUIActive");

            thisModConfig.BindConfig <KickStart>(null, "KeepBFFaceBlocks");
            thisModConfig.BindConfig <KickStart>(null, "KeepGCArmorPlates");
            thisModConfig.BindConfig <KickStart>(null, "KeepHESlopes");
            thisModConfig.BindConfig <KickStart>(null, "KeepGSOArmorPlates");

            thisModConfig.BindConfig <KickStart>(null, "enableBlockUpdate");
            thisModConfig.BindConfig <KickStart>(null, "ActiveColliders");
            thisModConfig.BindConfig <KickStart>(null, "AutoToggleOnEnemy");
            thisModConfig.BindConfig <KickStart>(null, "AutoToggleOnAlly");
            thisModConfig.BindConfig <KickStart>(null, "noColliderModeMouse");
            _thisModConfig = thisModConfig;

            //Nativeoptions
            var ColliderProperties = ModName + " - Collider Menu Settings";

            GUIMenuHotKey = new OptionKey("GUI Menu button", ColliderProperties, hotKey);
            GUIMenuHotKey.onValueSaved.AddListener(() => { keyInt = (int)(hotKey = GUIMenuHotKey.SavedValue); thisModConfig.WriteConfigJsonFile(); });

            //UIActive = new OptionToggle("Collider GUI Active", ColliderProperties, colliderGUIActive);
            //UIActive.onValueSaved.AddListener(() => {colliderGUIActive = UIActive.SavedValue; });

            KeepBF = new OptionToggle("Keep BF Face Blocks", ColliderProperties, KeepBFFaceBlocks);
            KeepBF.onValueSaved.AddListener(() => { KeepBFFaceBlocks = KeepBF.SavedValue; });
            KeepGC = new OptionToggle("Keep GC Shock Plates", ColliderProperties, KeepGCArmorPlates);
            KeepGC.onValueSaved.AddListener(() => { KeepGCArmorPlates = KeepGC.SavedValue; });
            KeepHE = new OptionToggle("Keep HE Fort Slopes", ColliderProperties, KeepHESlopes);
            KeepHE.onValueSaved.AddListener(() => { KeepHESlopes = KeepHE.SavedValue; });
            KeepGSO = new OptionToggle("Keep GSO Armour Plates and Ploughs", ColliderProperties, KeepGSOArmorPlates);
            KeepGSO.onValueSaved.AddListener(() => { KeepGSOArmorPlates = KeepGSO.SavedValue; });

            mouseModeWithNoColliders = new OptionToggle("Allow Grab of Disabled Colliders", ColliderProperties, noColliderModeMouse);
            mouseModeWithNoColliders.onValueSaved.AddListener(() => { noColliderModeMouse = mouseModeWithNoColliders.SavedValue; });
            autoHandleCombat = new OptionToggle("Toggle Colliders on Combat", ColliderProperties, AutoToggleOnEnemy);
            autoHandleCombat.onValueSaved.AddListener(() => { AutoToggleOnEnemy = autoHandleCombat.SavedValue; });
            autoHandleAlly = new OptionToggle("Toggle Colliders on Allied Collision", ColliderProperties, AutoToggleOnAlly);
            autoHandleAlly.onValueSaved.AddListener(() => { AutoToggleOnAlly = autoHandleAlly.SavedValue; });
            blockUpdate = new OptionToggle("BlockUpdate (INCREASES LAG ON HUGE)", ColliderProperties, enableBlockUpdate);
            blockUpdate.onValueSaved.AddListener(() => { enableBlockUpdate = blockUpdate.SavedValue; });

            activeColliderGrab = new OptionRange("Non-Collider Grabber (More means more lag)", ColliderProperties, ActiveColliders, 20f, 100f, 10f);
            activeColliderGrab.onValueSaved.AddListener(() => { ActiveColliders = (int)activeColliderGrab.SavedValue; });
        }
Exemplo n.º 19
0
        /// <summary>
        /// Applies all patches.
        /// </summary>
        /// <param name="instance">The Harmony instance to use when patching.</param>
        private static void PatchAll(HarmonyInstance instance)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            // ColonyAchievementStatus
            if (ACHIEVEMENT_SERIALIZE != null)
            {
                // TODO Vanilla/DLC code
                instance.Patch(typeof(ColonyAchievementStatus), nameof(ColonyAchievementStatus.
                                                                       Serialize), PatchMethod(nameof(Serialize_Prefix)), null);
            }

            // Db
            instance.Patch(typeof(Db), nameof(Db.Initialize), PatchMethod(nameof(
                                                                              Initialize_Prefix)), PatchMethod(nameof(Initialize_Postfix)));

            // Game
            instance.Patch(typeof(Game), "DestroyInstances", null, PatchMethod(nameof(
                                                                                   Game_DestroyInstances_Postfix)));
            instance.Patch(typeof(Game), "OnPrefabInit", null, PatchMethod(nameof(
                                                                               Game_OnPrefabInit_Postfix)));

            // GameInputMapping
            instance.Patch(typeof(GameInputMapping), nameof(GameInputMapping.
                                                            SetDefaultKeyBindings), null, PatchMethod(nameof(
                                                                                                          SetDefaultKeyBindings_Postfix)));

            // GameUtil
            instance.Patch(typeof(GameUtil), nameof(GameUtil.GetKeycodeLocalized),
                           PatchMethod(nameof(GetKeycodeLocalized_Prefix)), null);

            // KInputController
            instance.PatchConstructor(typeof(KInputController.KeyDef), new Type[] {
                typeof(KKeyCode), typeof(Modifier)
            }, null, PatchMethod(nameof(CKeyDef_Postfix)));
            instance.Patch(typeof(KInputController), nameof(KInputController.IsActive),
                           PatchMethod(nameof(IsActive_Prefix)), null);
            instance.Patch(typeof(KInputController), nameof(KInputController.QueueButtonEvent),
                           PatchMethod(nameof(QueueButtonEvent_Prefix)), null);

            if (PLightManager.InitInstance())
            {
                // DiscreteShadowCaster
                instance.Patch(typeof(DiscreteShadowCaster), nameof(DiscreteShadowCaster.
                                                                    GetVisibleCells), PatchMethod(nameof(GetVisibleCells_Prefix)), null);

                // Light2D
                instance.Patch(typeof(Light2D), "AddToScenePartitioner",
                               PatchMethod(nameof(AddToScenePartitioner_Prefix)), null);
                instance.Patch(typeof(Light2D), nameof(Light2D.RefreshShapeAndPosition), null,
                               PatchMethod(nameof(RefreshShapeAndPosition_Postfix)));

                // LightGridEmitter
                instance.Patch(typeof(LightGridEmitter), nameof(LightGridEmitter.AddToGrid),
                               null, PatchMethod(nameof(AddToGrid_Postfix)));
                instance.Patch(typeof(LightGridEmitter), "ComputeLux",
                               PatchMethod(nameof(ComputeLux_Prefix)), null);
                instance.Patch(typeof(LightGridEmitter), nameof(LightGridEmitter.
                                                                RemoveFromGrid), null, PatchMethod(nameof(RemoveFromGrid_Postfix)));
                instance.Patch(typeof(LightGridEmitter), nameof(LightGridEmitter.
                                                                UpdateLitCells), PatchMethod(nameof(UpdateLitCells_Prefix)), null);

                // LightGridManager
                instance.Patch(typeof(LightGridManager), nameof(LightGridManager.
                                                                CreatePreview), PatchMethod(nameof(CreatePreview_Prefix)), null);

                // LightShapePreview
                instance.Patch(typeof(LightShapePreview), "Update",
                               PatchMethod(nameof(LightShapePreview_Update_Prefix)), null);

                // Rotatable
                instance.Patch(typeof(Rotatable), "OrientVisualizer", null,
                               PatchMethod(nameof(OrientVisualizer_Postfix)));
            }

            // MainMenu
            instance.Patch(typeof(MainMenu), "OnSpawn", null, PatchMethod(
                               nameof(MainMenu_OnSpawn_Postfix)));

            // PBuilding
            instance.Patch(typeof(BuildingTemplates), nameof(BuildingTemplates.
                                                             CreateBuildingDef), null, PatchMethod(nameof(CreateBuildingDef_Postfix)));
            instance.Patch(typeof(EquipmentTemplates), nameof(EquipmentTemplates.
                                                              CreateEquipmentDef), null, PatchMethod(nameof(CreateEquipmentDef_Postfix)));
            if (PBuilding.CheckBuildings())
            {
                instance.Patch(typeof(GeneratedBuildings), nameof(GeneratedBuildings.
                                                                  LoadGeneratedBuildings), PatchMethod(nameof(
                                                                                                           LoadGeneratedBuildings_Prefix)), null);
            }

            // PCodex
            instance.Patch(typeof(CodexCache), nameof(CodexCache.CollectEntries), null,
                           PatchMethod(nameof(CollectEntries_Postfix)));
            instance.Patch(typeof(CodexCache), nameof(CodexCache.CollectSubEntries), null,
                           PatchMethod(nameof(CollectSubEntries_Postfix)));

            // PLocalization
            var locale = Localization.GetLocale();

            if (locale != null)
            {
                PLocalization.LocalizeAll(locale);
                PLocalizationItself.LocalizeItself(locale);
            }

            // ModsScreen
            POptions.Init();
            instance.Patch(typeof(ModsScreen), "BuildDisplay", null, PatchMethod(nameof(
                                                                                     BuildDisplay_Postfix)));

            // SteamUGCService
            var ugc = PPatchTools.GetTypeSafe("SteamUGCService", "Assembly-CSharp");

            if (ugc != null)
            {
                try {
                    instance.PatchTranspile(ugc, "LoadPreviewImage", PatchMethod(nameof(
                                                                                     LoadPreviewImage_Transpile)));
                } catch (Exception e) {
                    PUtil.LogExcWarn(e);
                }
            }

            // TMPro.TMP_InputField
            var tmpType = PPatchTools.GetTypeSafe("TMPro.TMP_InputField");

            if (tmpType != null)
            {
                try {
                    instance.Patch(tmpType, "AssignPositioningIfNeeded",
                                   PatchMethod(nameof(AssignPositioningIfNeeded_Prefix)), null);
                    instance.Patch(tmpType, "OnEnable", null, PatchMethod(
                                       nameof(OnEnable_Postfix)));
                } catch (Exception) {
                    PUtil.LogWarning("Unable to patch TextMeshPro bug, text fields may " +
                                     "display improperly inside scroll areas");
                }
            }

            // Postload, legacy and normal
            PPatchManager.ExecuteLegacyPostload();
            PPatchManager.RunAll(RunAt.AfterModsLoad);
        }
Exemplo n.º 20
0
        static HarmonyPatches()
        {
            HarmonyInstance harmony = HarmonyInstance.Create(id: "rimworld.jecrell.doorsexpanded");

            // What?: Reduce movement penalty for moving through expanded doors.
            // Why?: Movement penalty while crossing bulky doors is frustrating to players.
            // How? Patches Verse.CostToMoveIntoCell(Pawn pawn, IntVec3 c)
            harmony.Patch(original:
                          AccessTools.Method(
                              type: typeof(Pawn_PathFollower),
                              name: "CostToMoveIntoCell",
                              parameters: new Type[] { typeof(Pawn), typeof(IntVec3) }),
                          prefix: null,
                          postfix:
                          new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(CostToMoveIntoCell_PostFix_ChangeDoorPathCost)
                              )
                          );

            harmony.Patch(original: AccessTools.Method(type: typeof(EdificeGrid), name: "Register"),
                          prefix: new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(RegisterDoorExpanded)), postfix: null);
            harmony.Patch(original: AccessTools.Method(type: typeof(Building_Door), name: "DoorOpen"),
                          prefix: new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(InvisDoorOpen)), postfix: null);
            harmony.Patch(original: AccessTools.Method(type: typeof(Building_Door), name: "DoorTryClose"),
                          prefix: new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(InvisDoorTryClose)), postfix: null);
            harmony.Patch(original: AccessTools.Method(type: typeof(Building_Door), name: "Notify_PawnApproaching"),
                          prefix: null, postfix: new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(InvisDoorNotifyApproaching)), transpiler: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(Building_Door),
                                             name: nameof(Building_Door.StartManualCloseBy)),
                prefix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                          name: nameof(InvisDoorManualClose)), postfix: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(Building_Door),
                                             name: nameof(Building_Door.StartManualOpenBy)), prefix: null,
                postfix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                           name: nameof(InvisDoorManualOpen)), transpiler: null);
            harmony.Patch(
                original: AccessTools.Property(type: typeof(Building_Door), name: nameof(Building_Door.FreePassage))
                .GetGetMethod(),
                prefix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                          name: nameof(get_FreePassage)), postfix: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(GhostDrawer), name: nameof(GhostDrawer.DrawGhostThing)),
                prefix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                          name: nameof(HeronDoorGhostHandler)), postfix: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(GenSpawn), name: nameof(GenSpawn.SpawnBuildingAsPossible)),
                prefix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                          name: nameof(HeronSpawnBuildingAsPossible)), postfix: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(GenSpawn), name: nameof(GenSpawn.WipeExistingThings)),
                prefix: new HarmonyMethod(
                    type: typeof(HarmonyPatches),
                    name: nameof(WipeExistingThings)), postfix: null);
            harmony.Patch(original: AccessTools.Method(type: typeof(GenSpawn), name: nameof(GenSpawn.SpawningWipes)),
                          prefix: null, postfix: new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(InvisDoorsDontWipe)), transpiler: null);
            harmony.Patch(original: AccessTools.Method(type: typeof(GenPath), name: "ShouldNotEnterCell"), prefix: null,
                          postfix: new HarmonyMethod(
                              type: typeof(HarmonyPatches),
                              name: nameof(ShouldNotEnterCellInvisDoors)), transpiler: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(CompForbiddable), name: nameof(CompForbiddable.PostDraw)),
                prefix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                          name: nameof(DontDrawInvisDoorForbiddenIcons)), postfix: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(PawnPathUtility),
                                             name: nameof(PawnPathUtility.TryFindLastCellBeforeBlockingDoor)),
                prefix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                          name: nameof(ManhunterJobGiverFix)), postfix: null);
            harmony.Patch(
                original: AccessTools.Method(type: typeof(ForbidUtility),
                                             name: nameof(ForbidUtility.IsForbiddenToPass)),
                prefix: null, postfix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                                         name: nameof(IsForbiddenToPass_PostFix)));

            harmony.Patch(
                original: AccessTools.Method(type: typeof(PathFinder), name: nameof(PathFinder.GetBuildingCost)),
                prefix: null, postfix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                                         name: nameof(GetBuildingCost_PostFix)));
            harmony.Patch(
                original: AccessTools.Method(type: typeof(PawnPathUtility),
                                             name: nameof(PawnPathUtility.FirstBlockingBuilding)),
                prefix: null, postfix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                                         name: nameof(FirstBlockingBuilding_PostFix)));
            harmony.Patch(
                original: AccessTools.Method(typeof(GenGrid), "CanBeSeenOver", new[] { typeof(Building) }),
                prefix: null, postfix: new HarmonyMethod(type: typeof(HarmonyPatches),
                                                         name: nameof(CanBeSeenOver)));

            harmony.Patch(
                AccessTools.Method(typeof(JobGiver_Manhunter), "TryGiveJob"),
                null, null, new HarmonyMethod(type: typeof(HarmonyPatches),
                                              name: nameof(JobGiver_Manhunter_TryGiveJob_Transpiler)));
            //harmony.Patch(
            //    AccessTools.Method(typeof(JobGiver_SeekAllowedArea), "TryGiveJob"),
            //    new HarmonyMethod(type: typeof(HarmonyPatches),
            //        name: nameof(SeekAllowedArea_TryGiveJob)), null);
            harmony.Patch(
                AccessTools.Method(typeof(Building_Door), "CanPhysicallyPass"),
                new HarmonyMethod(type: typeof(HarmonyPatches),
                                  name: nameof(CanPhysicallyPass)), null);
            //harmony.Patch(
            //    original: AccessTools.Method(typeof(Region), "Allows"),
            //    prefix: null, postfix: new HarmonyMethod(type: typeof(HarmonyPatches),
            //        name: nameof(RegionAllows)));
        }
        public void setUpConfig()
        {
            HarmonyInstance instance = HarmonyInstance.Create("PelicanTTS.GMCM");

            // instance.Patch(typeof(ChatBox).GetMethod("receiveChatMessage"), prefix: new HarmonyMethod(typeof(PelicanTTSMod).GetMethod("receiveChatMessage")));

            if (!Helper.ModRegistry.IsLoaded("spacechase0.GenericModConfigMenu"))
            {
                return;
            }

            var cVoices = voices[LocalizedContentManager.CurrentLanguageCode];
            var eVoices = new List <string>();

            foreach (var lang in voices.Where(v => v.Key != LocalizedContentManager.CurrentLanguageCode))
            {
                foreach (var voice in lang.Value.Where(v => !cVoices.Contains(v)))
                {
                    eVoices.Add(voice + "*");
                }
            }

            foreach (var voice in others.Where(v => !cVoices.Contains(v) && !eVoices.Contains(v + "*")))
            {
                eVoices.Add(voice + "*");
            }

            cVoices.AddRange(eVoices.OrderBy(v => v).Where(v => !cVoices.Contains(v)));

            maxValues = Math.Min(cVoices.Count + 1, 7);

            activeVoiceSetup = new Dictionary <string, MenuVoiceSetup>();
            var api = Helper.ModRegistry.GetApi <IGMCMAPI>("spacechase0.GenericModConfigMenu");

            api.RegisterModConfig(ModManifest, () =>
            {
                config.Greeting                 = true;
                config.MumbleDialogues          = false;
                config.Pitch                    = 0;
                config.Volume                   = 1;
                config.Rate                     = 100;
                config.ReadDialogues            = true;
                config.ReadHudMessages          = true;
                config.ReadLetters              = true;
                config.ReadNonCharacterMessages = true;
                config.ReadScreenKey            = SButton.N;
                config.LanguageCode             = SpeechHandlerPolly.getLanguageCode(true);
                //config.ReadChatMessages = true;

                var npcs = Helper.Content.Load <Dictionary <string, string> >("Data//NPCDispositions", ContentSource.GameContent);

                foreach (var voice in config.Voices.Keys)
                {
                    config.Voices[voice].Pitch = 0;
                    if (npcs.ContainsKey(voice))
                    {
                        config.Voices[voice].Voice = SpeechHandlerPolly.getVoice(voice, npcs[voice].Contains("female"));
                    }
                }
            }, () => Helper.WriteConfig <ModConfig>(config));
            api.RegisterLabel(ModManifest, MainLabelText, "");

            api.RegisterSimpleOption(ModManifest, "Mumbling", "Should all NPCs mumble", () => config.MumbleDialogues, (s) => config.MumbleDialogues = s);
            api.RegisterSimpleOption(ModManifest, "Greeting", "Enables the morning greeting", () => config.Greeting, (s) => config.Greeting         = s);
            api.RegisterSimpleOption(ModManifest, "Read Character Dialogues", "", () => config.ReadDialogues, (s) => config.ReadDialogues           = s);
            api.RegisterSimpleOption(ModManifest, "Read Non-Character Messages", "", () => config.ReadNonCharacterMessages, (s) => config.ReadNonCharacterMessages = s);
            api.RegisterSimpleOption(ModManifest, "Read Letters", "", () => config.ReadLetters, (s) => config.ReadLetters = s);
            api.RegisterSimpleOption(ModManifest, "Read Hud Messages", "", () => config.ReadHudMessages, (s) => config.ReadHudMessages = s);
            api.RegisterSimpleOption(ModManifest, "Read Screen Key", "", () => config.ReadScreenKey, (s) => config.ReadScreenKey       = s);
            api.RegisterSimpleOption(ModManifest, "Language Code", "", () => config.LanguageCode, (s) => config.LanguageCode           = s);
            //  api.RegisterSimpleOption(ModManifest, "Read Chat Messages", "", () => config.ReadChatMessages, (s) => config.ReadChatMessages = s);
            api.RegisterSimpleOption(ModManifest, "Neural Voices", "", () => config.UseNeuralVoices, (s) => config.UseNeuralVoices = s);

            api.RegisterChoiceOption(ModManifest, "Server", "", () => config.Server, (s) =>
            {
                config.Server         = s;
                activeEndpoint        = endPoints[s];
                SpeechHandlerPolly.pc = null;
            }, endPoints.Keys.ToArray());

            api.RegisterClampedOption(ModManifest, "Volume", "Set Volume", () =>
            {
                activeVolume = config.Volume;
                return(config.Volume);
            }, (s) =>
            {
                config.Volume = (float)Math.Ceiling((double)(s * 100)) / 100f;
            }, 0, 1);

            api.RegisterClampedOption(ModManifest, "Rate", "Set Rate (20-200%)", () =>
            {
                activeRate = config.Rate;
                return(config.Rate);
            }, (s) =>
            {
                config.Rate = (int)s;
            }, 50, 200);

            /*    instance.Patch(Type.GetType("GenericModConfigMenu.UI.Dropdown, GenericModConfigMenu").GetMethod("Update"), new HarmonyMethod(typeof(PelicanTTSMod).GetMethod("UpdateGMCM")));
             *  instance.Patch(Type.GetType("GenericModConfigMenu.UI.Dropdown, GenericModConfigMenu").GetMethod("Draw"), new HarmonyMethod(typeof(PelicanTTSMod).GetMethod("DrawGMCM")));
             *  instance.Patch(Type.GetType("GenericModConfigMenu.UI.Table, GenericModConfigMenu").GetMethod("Update"), new HarmonyMethod(typeof(PelicanTTSMod).GetMethod("UpdateTableGMCM")));
             *  instance.Patch(Type.GetType("GenericModConfigMenu.UI.Scrollbar, GenericModConfigMenu").GetMethod("Scroll"), new HarmonyMethod(typeof(PelicanTTSMod).GetMethod("ScrollGMCM")));
             */

            Helper.Events.Input.MouseWheelScrolled += (s, e) =>
            {
                List <object> obj = new List <object>();
                foreach (var dropDown in currentIndex.Keys.Where(k => ((bool)k.GetType().GetField("dropped").GetValue(k))))
                {
                    obj.Add(dropDown);
                    currentIndex[dropDown] -= e.Delta / 120;
                    currentIndex[dropDown]  = Math.Max(currentIndex[dropDown], 0);
                    break;
                }
            };

            api.RegisterLabel(ModManifest, "Voices", "Set the voices for each NPC");
            int index = 2;

            foreach (var npc in config.Voices.Keys.OrderBy(k => k))
            {
                if (!activeVoiceSetup.ContainsKey(npc))
                {
                    activeVoiceSetup.Add(npc, new MenuVoiceSetup());
                }
                activeVoiceSetup[npc].Index = index;
                activeVoiceSetup[npc].Name  = npc;

                List <string> npcVoices = new List <string>()
                {
                    npc + ":default"
                };
                npcVoices.AddRange(cVoices);
                api.RegisterChoiceOption(ModManifest, npc + " Voice", "Choose a voice", () =>
                {
                    Game1.stopMusicTrack(Game1.MusicContext.Default);
                    if (config.Voices[npc].Voice.Contains("default"))
                    {
                        return(npc + ":default");
                    }

                    activeVoiceSetup[npc].Voice = config.Voices[npc].Voice;
                    string voice = config.Voices[npc].Voice;

                    if (!voices[LocalizedContentManager.CurrentLanguageCode].Contains(voice))
                    {
                        return(voice + "*");
                    }
                    return(voice);
                }, (s) =>
                {
                    config.Voices[npc].Voice    = s.Replace(npc + ":", "").Replace("*", "");
                    activeVoiceSetup[npc].Voice = config.Voices[npc].Voice;
                    currentName = npc;
                }, npcVoices.ToArray());

                api.RegisterClampedOption(ModManifest, npc + " Pitch", "Choose a Pitch", () => config.Voices[npc].Pitch, (s) =>
                {
                    config.Voices[npc].Pitch    = (float)Math.Ceiling((double)(s * 100)) / 100f;
                    activeVoiceSetup[npc].Pitch = config.Voices[npc].Pitch;
                }, -1, 1);

                index++;
            }

            for (int i = 0; i < 12; i++)
            {
                api.RegisterLabel(ModManifest, " ", " ");
            }

            api.SubscribeToChange(ModManifest, new Action <string, string>((key, value) =>
            {
                if (key.EndsWith("Voice"))
                {
                    string character = key.Split(' ')[0];

                    if (value == "Default")
                    {
                        value = SpeechHandlerPolly.getVoice(character);
                    }
                    var mvs   = activeVoiceSetup.Values.FirstOrDefault(avs => avs.Name == character);
                    value     = value.Replace("*", "");
                    var intro = character;
                    if (intro == "Default")
                    {
                        intro = i18n.Get("FestivalGreeting");
                    }
                    else
                    {
                        var dialogues = _helper.Content.Load <Dictionary <string, string> >(@"Characters/Dialogue/" + character, ContentSource.GameContent);
                        if (dialogues != null && dialogues.ContainsKey("Introduction"))
                        {
                            intro = dialogues["Introduction"].Split('^')[0].Split('#')[0].Replace("@", "");
                            if (intro.Length < 7)
                            {
                                intro = dialogues["Mon"].Split('^')[0].Split('#')[0].Replace("@", "");
                            }
                        }
                    }
                    SpeechHandlerPolly.configSay(character, value, intro, activeRate, mvs is MenuVoiceSetup ? mvs.Pitch : -1, activeVolume);
                }
            }));

            api.SubscribeToChange(ModManifest, new Action <string, int>((key, value) =>
            {
                if (key.Contains("Rate"))
                {
                    activeRate = value;
                }
            }));

            api.SubscribeToChange(ModManifest, new Action <string, float>((key, value) =>
            {
                if (key.EndsWith("Pitch"))
                {
                    string character = key.Split(' ')[0];
                    var mvs          = activeVoiceSetup.Values.First(avs => avs.Name == character);
                    mvs.Pitch        = (float)Math.Ceiling((double)(value * 100)) / 100f;
                }
                else if (key.Contains("Volume"))
                {
                    activeVolume = (float)Math.Ceiling((double)(value * 100)) / 100f;
                }
            }));
        }
Exemplo n.º 22
0
 static MethodInfo CalculateMethod(HarmonyInstance harmony)
 {
     return(AccessTools.Method(AccessTools.TypeByName(TypeName), MethodName));
 }
Exemplo n.º 23
0
 public override void Patch(HarmonyInstance harmony)
 {
     PatchMultiple(harmony, TARGET_METHOD, true, true, false);
 }
 public override void Patch(HarmonyInstance harmony)
 {
     PatchTranspiler(harmony, TARGET_METHOD);
 }
        static HarmonyPatches()
        {
            var harmony = HarmonyInstance.Create("net.whniwwd.rimworld.mountainminermultiplayerfix");

            harmony.PatchAll(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 26
0
        public static void InstallHooks()
        {
            var harmony = HarmonyInstance.Create("com.bepis.bepinex.resourceredirector");

            harmony.PatchAll(typeof(Hooks));
        }
Exemplo n.º 27
0
 public void OnApplicationQuit()
 {
     Logger.log.Debug("OnApplicationQuit");
     HarmonyInstance.UnpatchAll("com.wakamu.questSpectator");
 }
        public Better_Pawn_Textures(ModContentPack content) : base(content)
        {
            var harmony = HarmonyInstance.Create("com.fyarn.better_pawn_textures");

            harmony.PatchAll(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 29
0
        public static void Patch()
        {
            var harmonyInstance = HarmonyInstance.Create("holly.eazfixer");

            harmonyInstance.PatchAll(Assembly.GetExecutingAssembly());
        }
Exemplo n.º 30
0
Arquivo: OwO.cs Projeto: VRCMG/OwO-Mod
        public void Start()
        {
            HarmonyInstance harmonyInstance = HarmonyInstance.Create("OwO");

            harmonyInstance.Patch(typeof(Text).GetProperty("text").GetGetMethod(), null, new HarmonyMethod(typeof(OwO).GetMethod("GetText", BindingFlags.Static | BindingFlags.NonPublic)));
        }