Exemplo n.º 1
0
        /// <summary>Raised after a game menu is opened, closed, or replaced.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnMenuChanged(object sender, MenuChangedEventArgs e)
        {
            var menu = e.NewMenu as ShopMenu;

            if (menu?.portraitPerson == null)
            {
                return;
            }

            if (menu.portraitPerson.Name == "Pierre")
            {
                Log.trace("Adding crops to shop");

                List <Item> forSale = Helper.Reflection.GetField <List <Item> >(menu, "forSale").GetValue();
                Dictionary <Item, int[]> itemPriceAndStock = Helper.Reflection.GetField <Dictionary <Item, int[]> >(menu, "itemPriceAndStock").GetValue();

                IReflectedMethod precondMeth = Helper.Reflection.GetMethod(Game1.currentLocation, "checkEventPrecondition");
                foreach (KeyValuePair <string, CropData> crop in CropData.crops)
                {
                    if (!crop.Value.Seasons.Contains(Game1.currentSeason))
                    {
                        continue;
                    }
                    if (crop.Value.SeedPurchaseRequirements.Count > 0 && precondMeth.Invoke <int>(new object[] { crop.Value.GetSeedPurchaseRequirementString() }) == -1)
                    {
                        continue;
                    }
                    Item item = new StardewValley.Object(Vector2.Zero, crop.Value.GetSeedId(), int.MaxValue);
                    forSale.Add(item);
                    itemPriceAndStock.Add(item, new int[] { crop.Value.SeedPurchasePrice, int.MaxValue });
                }
            }
        }
Exemplo n.º 2
0
 private void OnButtonPressed(object sender, ButtonPressedEventArgs e)
 {
     if (e.Button == this.Config.Monster_Log_Keybind)
     {
         this.Monitor.Log("Detected button press to open monster log", LogLevel.Trace);
         if (Game1.activeClickableMenu == null)
         {
             GameLocation adventureGuild = Game1.getLocationFromName("AdventureGuild");
             if (this.Helper.ModRegistry.IsLoaded("DefenTheNation.CustomGuildChallenges"))
             {
                 IReflectedMethod method = this.Helper.Reflection.GetMethod(adventureGuild, "ShowNewMonsterKillList");
                 if (method == null)
                 {
                     this.Monitor.Log("Cannot access the Custom Guild Challenge log method", LogLevel.Error);
                 }
                 else
                 {
                     this.Monitor.Log("Showing the Custom Guild Challenge monster log", LogLevel.Trace);
                     method.Invoke();
                 }
             }
             else
             {
                 this.Monitor.Log("Showing the vanilla monster log", LogLevel.Trace);
                 (adventureGuild as AdventureGuild).showMonsterKillList();
             }
         }
         else
         {
             this.Monitor.Log("Can't show monster log because a menu is up.", LogLevel.Debug);
         }
     }
 }
        public CachedMessageEmojis(IModHelper helper, int numberVanillaEmojis)
        {
            Reflection = helper.Reflection;

            messagesField             = Reflection.GetField <List <ChatMessage> >(Game1.chatBox, "messages");
            cheatHistoryPositionField = Reflection.GetField <int>(Game1.chatBox, "cheatHistoryPosition");
            choosingEmojiField        = Reflection.GetField <bool>(Game1.chatBox, "choosingEmoji");
            emojiMenuIconField        = Reflection.GetField <ClickableTextureComponent>(Game1.chatBox, "emojiMenuIcon");

            formatMessageMethod = Reflection.GetMethod(Game1.chatBox, "formatMessage");
            messageColorMethod  = Reflection.GetMethod(Game1.chatBox, "messageColor");

            PlayerMessageList = new List <PlayerMessage>();

            NumberVanillaEmoji = numberVanillaEmojis;

            chatCommandsIsLoaded = helper.ModRegistry.IsLoaded("cat.chatcommands");
            if (chatCommandsIsLoaded)
            {
                displayLineIndexField    = Reflection.GetField <int>(Game1.chatBox, "displayLineIndex");
                getEndDisplayIndexMethod = Reflection.GetMethod(Game1.chatBox, "GetEndDisplayIndex");
            }

            SubscribeEvents();
        }
Exemplo n.º 4
0
        /// <summary>The method to call instead of the Dialogue constructor.</summary>
        /// <param name="__instance">The instance being patched.</param>
        /// <param name="masterDialogue">The dialogue being parsed.</param>
        /// <param name="speaker">The NPC for which the dialogue is being parsed.</param>
        /// <returns>Returns whether to execute the original method.</returns>
        private static bool Before_Dialogue_Constructor(Dialogue __instance, string masterDialogue, NPC speaker)
        {
            // get private members
            bool             nameArraysTranslated              = DialogueErrorPatch.Reflection.GetField <bool>(typeof(Dialogue), "nameArraysTranslated").GetValue();
            IReflectedMethod translateArraysOfStrings          = DialogueErrorPatch.Reflection.GetMethod(typeof(Dialogue), "TranslateArraysOfStrings");
            IReflectedMethod parseDialogueString               = DialogueErrorPatch.Reflection.GetMethod(__instance, "parseDialogueString");
            IReflectedMethod checkForSpecialDialogueAttributes = DialogueErrorPatch.Reflection.GetMethod(__instance, "checkForSpecialDialogueAttributes");

            // replicate base constructor
            __instance.dialogues ??= new List <string>();

            // duplicate code with try..catch
            try
            {
                if (!nameArraysTranslated)
                {
                    translateArraysOfStrings.Invoke();
                }
                __instance.speaker = speaker;
                parseDialogueString.Invoke(masterDialogue);
                checkForSpecialDialogueAttributes.Invoke();
            }
            catch (Exception baseEx) when(baseEx.InnerException is TargetInvocationException invocationEx && invocationEx.InnerException is Exception ex)
            {
                string name = !string.IsNullOrWhiteSpace(speaker?.Name) ? speaker.Name : null;

                DialogueErrorPatch.MonitorForGame.Log($"Failed parsing dialogue string{(name != null ? $" for {name}" : "")}:\n{masterDialogue}\n{ex}", LogLevel.Error);

                parseDialogueString.Invoke("...");
                checkForSpecialDialogueAttributes.Invoke();
            }

            return(false);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Reflects into the game's event preconditions method to do condition checking
        /// </summary>
        /// <param name="conditions"></param>
        /// <returns>true if all conditions matches, otherwise false</returns>
        internal static bool CheckConditions(string[] conditions)
        {
            VanillaPreconditionsMethod = ModEntry.helper.Reflection.GetMethod(Game1.currentLocation, "checkEventPrecondition");
            //if no conditions are supplied, then conditions are always met
            if (conditions == null)
            {
                return(true);
            }

            //if someone somewhow marked this fake ID as seen,
            //unmark it so condition checking will actually work
            if (Game1.player.eventsSeen.Contains(-5005))
            {
                ModEntry.monitor.Log("STF uses the fake event ID of -5005 in order to use vanilla preconditions." +
                                     " Somehow your save has marked this ID as seen. STF is freeing it back up.", LogLevel.Warn);
                Game1.player.eventsSeen.Remove(-5005);
            }

            //if any of the conditions are met, return true
            foreach (var con in conditions)
            {
                if (CheckIndividualConditions(con.Split('/')))
                {
                    ModEntry.monitor.Log($"Player met the conditions: \"{con}\"");
                    return(true);
                }
            }

            //if no conditions are met, return false
            return(false);
        }
Exemplo n.º 6
0
        private void GetFields()
        {
            AlphaField    = ModEntry.Instance.Helper.Reflection.GetField <float>(this, "alpha");         // TODO: FIX: CustomBush.AlphaField null after SpaceCore deserialise
            ShakeField    = ModEntry.Instance.Helper.Reflection.GetField <float>(this, "shakeRotation");
            MaxShakeField = ModEntry.Instance.Helper.Reflection.GetField <float>(this, "maxShake");

            ShakeMethod = ModEntry.Instance.Helper.Reflection.GetMethod(this, "shake");
        }
Exemplo n.º 7
0
        // Tries to stop a sound cue, but uses reflection and ignores the
        // nonexistence of the method since some players have a version of the
        // game and/or XNA that doesn't like this.
        public static void TryStopCue(ICue cue)
        {
            IReflectedMethod stop =
                Helper.Reflection.GetMethod(cue, "Stop", false);

            if (stop != null)
            {
                stop.Invoke(AudioStopOptions.AsAuthored);
            }
        }
Exemplo n.º 8
0
        /// <summary>Raised after the save file is loaded.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event data.</param>
        private void OnSaveLoaded(object sender, SaveLoadedEventArgs e)
        {
            saveFileCode = Game1.uniqueIDForThisGame;
            Helper.Events.Player.Warped            += OnWarped;
            Helper.Events.GameLoop.DayStarted      += OnDayStarted;
            Helper.Events.GameLoop.ReturnedToTitle += OnReturnedToTitle;

            takeScreenshot = Helper.Reflection.GetMethod(Game1.game1, "takeMapScreenshot");

            Helper.Events.Input.ButtonPressed += OnButtonPressed;
        }
Exemplo n.º 9
0
        /// <summary>Get a static method.</summary>
        /// <param name="type">The type which has the method.</param>
        /// <param name="name">The field name.</param>
        /// <param name="required">Whether to throw an exception if the field is not found.</param>
        public IReflectedMethod GetMethod(Type type, string name, bool required = true)
        {
            // get method from hierarchy
            IReflectedMethod method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);

            if (required && method == null)
            {
                throw new InvalidOperationException($"The {type.FullName} object doesn't have a '{name}' static method.");
            }
            return(method);
        }
Exemplo n.º 10
0
 public CommandEmojiMenu(IReflectionHelper reflection, ChatBox chatBox, Texture2D emojiTexture,
                         Texture2D chatBoxTexture) : base(chatBox, emojiTexture, chatBoxTexture)
 {
     this.bUpArrow               = reflection.GetField <ClickableComponent>(this, "upArrow").GetValue();
     this.bDownArrow             = reflection.GetField <ClickableComponent>(this, "downArrow").GetValue();
     this.bSendArrow             = reflection.GetField <ClickableComponent>(this, "sendArrow").GetValue();
     this.bEmojiSelectionButtons =
         reflection.GetField <List <ClickableComponent> >(this, "emojiSelectionButtons").GetValue();
     this.bPageStartIndex   = reflection.GetField <int>(this, "pageStartIndex");
     this.bUpArrowPressed   = reflection.GetMethod(this, "upArrowPressed");
     this.bDownArrowPressed = reflection.GetMethod(this, "downArrowPressed");
 }
Exemplo n.º 11
0
        /// <summary>Gets a result from a given <see cref="IReflectedMethod"/>.</summary>
        /// <param name="methodInfo">The method to invoke with the value.</param>
        /// <param name="value">The value to pass to the method.</param>
        /// <param name="uniqueId">The unique of the api (Used only for logging).</param>
        /// <returns>The api result from the method with the passed value.</returns>
        private int GetApiResult(IReflectedMethod methodInfo, string value, string uniqueId)
        {
            // ensure the api returned a value
            int apiResult = methodInfo.Invoke <int>(value);

            if (apiResult == -1)
            {
                ModEntry.ModMonitor.Log($"No value was returned from method: {methodInfo} in api provided by: {uniqueId} with a passed value of: {value}", LogLevel.Error);
            }

            return(apiResult);
        }
Exemplo n.º 12
0
        /*********
        ** Public methods
        *********/
        /****
        ** Constructor
        ****/
        /// <summary>Construct an instance.</summary>
        /// <param name="serviceProvider">The service provider to use to locate services.</param>
        /// <param name="rootDirectory">The root directory to search for content.</param>
        /// <param name="currentCulture">The current culture for which to localise content.</param>
        /// <param name="languageCodeOverride">The current language code for which to localise content.</param>
        /// <param name="monitor">Encapsulates monitoring and logging.</param>
        /// <param name="reflection">Simplifies access to private code.</param>
        public SContentManager(IServiceProvider serviceProvider, string rootDirectory, CultureInfo currentCulture, string languageCodeOverride, IMonitor monitor, Reflector reflection)
            : base(serviceProvider, rootDirectory, currentCulture, languageCodeOverride)
        {
            // init
            this.Monitor          = monitor ?? throw new ArgumentNullException(nameof(monitor));
            this.Cache            = new ContentCache(this, reflection);
            this.GetKeyLocale     = reflection.GetMethod(this, "languageCode");
            this.ModContentPrefix = this.GetAssetNameFromFilePath(Constants.ModPath);

            // get asset data
            this.CoreAssets = new CoreAssets(this.NormaliseAssetName);
            this.KeyLocales = this.GetKeyLocales(reflection);
        }
Exemplo n.º 13
0
 private static void Update()
 {
     if (!(Game1.activeClickableMenu is TitleMenu menu))
     {
         return;
     }
     _isTransitioningButtons             = Helper.GetReflectedField <bool>(menu, "isTransitioningButtons");
     _titleInPosition                    = Helper.GetReflectedField <bool>(menu, "titleInPosition");
     _transitioningCharacterCreationMenu =
         Helper.GetReflectedField <bool>(menu, "transitioningCharacterCreationMenu");
     _quitTimer        = Helper.GetReflectedField <int>(menu, "quitTimer");
     _shouldDrawCursor = Helper.GetReflectedMethod(menu, "ShouldDrawCursor");
     Helper.Events.Input.CursorMoved          += PerformHoverAction;
     Helper.Events.Display.RenderedActiveMenu += Draw;
     Helper.Events.Display.WindowResized      += WindowResized;
     Helper.Events.Input.ButtonPressed        += ReceiveLeftClick;
 }
Exemplo n.º 14
0
        /****
        ** Methods
        ****/
        /// <summary>Get a instance method.</summary>
        /// <param name="obj">The object which has the method.</param>
        /// <param name="name">The field name.</param>
        /// <param name="required">Whether to throw an exception if the field is not found.</param>
        public IReflectedMethod GetMethod(object obj, string name, bool required = true)
        {
            // validate
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj), "Can't get a instance method from a null object.");
            }

            // get method from hierarchy
            IReflectedMethod method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

            if (required && method == null)
            {
                throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a '{name}' instance method.");
            }
            return(method);
        }
Exemplo n.º 15
0
        /*********
        ** Private methods
        *********/
        /// <summary>The method to call when the Dialogue constructor throws an exception.</summary>
        /// <param name="__instance">The instance being patched.</param>
        /// <param name="masterDialogue">The dialogue being parsed.</param>
        /// <param name="speaker">The NPC for which the dialogue is being parsed.</param>
        /// <param name="__exception">The exception thrown by the wrapped method, if any.</param>
        /// <returns>Returns the exception to throw, if any.</returns>
        private static Exception Finalize_Constructor(Dialogue __instance, string masterDialogue, NPC speaker, Exception __exception)
        {
            if (__exception != null)
            {
                // log message
                string name = !string.IsNullOrWhiteSpace(speaker?.Name) ? speaker.Name : null;
                DialoguePatcher.MonitorForGame.Log($"Failed parsing dialogue string{(name != null ? $" for {name}" : "")}:\n{masterDialogue}\n{__exception.GetLogSummary()}", LogLevel.Error);

                // set default dialogue
                IReflectedMethod parseDialogueString = DialoguePatcher.Reflection.GetMethod(__instance, "parseDialogueString");
                IReflectedMethod checkForSpecialDialogueAttributes = DialoguePatcher.Reflection.GetMethod(__instance, "checkForSpecialDialogueAttributes");
                parseDialogueString.Invoke("...");
                checkForSpecialDialogueAttributes.Invoke();
            }

            return(null);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Each string in the array can have multiple conditions separated by the character '/'
        /// and each string is evaluated as true if all of the conditions are met
        /// The method returns true if any of the strings are true
        /// </summary>
        /// <returns>true if all conditions matches, otherwise false</returns>
        internal bool CheckConditions(string[] conditions)
        {
            //if no conditions are supplied, then conditions are always met
            if (conditions == null)
            {
                return(true);
            }

            //using the farm because it should be available for every player at any point in the game. Current location sometimes doesn't exist for farmhands
            VanillaPreconditionsMethod = _helper.Reflection.GetMethod(Game1.getFarm(), "checkEventPrecondition");

            //if someone somewhow marked this fake ID as seen,
            //unmark it so condition checking will actually work
            if (Game1.player.eventsSeen.Contains(-6529))
            {
                _monitor.Log($"{_uniqueId} / Expanded Preconditions Utility uses the fake event ID of -6529 in order to use vanilla preconditions." +
                             " Somehow your save has marked this ID as seen. Expanded Preconditions is freeing it back up.", LogLevel.Warn);
                Game1.player.eventsSeen.Remove(-6529);
            }

            //if any of the conditions are met, return true
            foreach (var con in conditions)
            {
                if (_verboseLogging)
                {
                    _monitor.Log($"{_uniqueId}: Checking condition string: \"{con}\"", LogLevel.Debug);
                }

                if (CheckIndividualConditions(con.Split('/')))
                {
                    if (_verboseLogging)
                    {
                        _monitor.Log($"-{_uniqueId}: Player met the conditions: \"{con}\"", LogLevel.Debug);
                    }
                    return(true);
                }
            }

            if (_verboseLogging)
            {
                _monitor.Log($"-{_uniqueId}: No conditions were met", LogLevel.Debug);
            }

            //if no conditions are met, return false
            return(false);
        }
Exemplo n.º 17
0
        /// <summary>Construct an instance.</summary>
        /// <remarks>Reassigns the enter handler, replaces <see cref="ChatTextBox" /> and <see cref="EmojiMenu" />.</remarks>
        public CommandChatBox(IModHelper helper, ICommandHandler handler, ChatCommandsConfig config)
        {
            this.handler = handler;
            this.bCheatHistoryPosition = helper.Reflection.GetField <int>(this, "cheatHistoryPosition");
            this.bFormatMessage        = helper.Reflection.GetMethod(this, "formatMessage");
            this.bMessages             = helper.Reflection.GetField <List <ChatMessage> >(this, "messages").GetValue();
            this.bEmojiMenuIcon        =
                helper.Reflection.GetField <ClickableTextureComponent>(this, "emojiMenuIcon").GetValue();
            this.bChoosingEmoji = helper.Reflection.GetField <bool>(this, "choosingEmoji");
            Texture2D chatBoxTexture = Game1.content.Load <Texture2D>("LooseSprites\\chatBox");

            this.chatBox.OnEnterPressed -= helper.Reflection.GetField <TextBoxEvent>(this, "e").GetValue();
            this.chatBox = this.commandChatTextBox = new CommandChatTextBox(chatBoxTexture,
                                                                            null, Game1.smallFont, Color.White);
            Game1.keyboardDispatcher.Subscriber = this.chatBox;
            this.chatBox.Selected        = false;
            this.chatBox.OnEnterPressed += this.EnterPressed;

            this.multiplayer = helper.Reflection.GetField <Multiplayer>(typeof(Game1), "multiplayer").GetValue();
            this.inputState  = helper.Reflection.GetField <InputState>(typeof(Game1), "input").GetValue();

            ConsoleChatMessage.Init(LocalizedContentManager.CurrentLanguageCode);

            this.emojiMenu = new CommandEmojiMenu(helper.Reflection, this, emojiTexture, chatBoxTexture);

            helper.Reflection.GetMethod(this, "updatePosition").Invoke();

            this.displayLineIndex = -1;
            this.config           = config;
            this.config.UseMonospacedFontForCommandOutput = this.config.UseMonospacedFontForCommandOutput && !(
                LocalizedContentManager.CurrentLanguageCode ==
                LocalizedContentManager.LanguageCode.ja ||
                LocalizedContentManager.CurrentLanguageCode ==
                LocalizedContentManager.LanguageCode.zh ||
                LocalizedContentManager.CurrentLanguageCode ==
                LocalizedContentManager.LanguageCode.th);
            this.DetermineNumberOfMaxMessages();
        }
Exemplo n.º 18
0
        private string getTodaysTip()
        {
            IReflectedMethod method = CustomTVMod.Modhelper.Reflection.GetMethod(tv, "getTodaysTip");

            return(method.Invoke <string>());
        }
Exemplo n.º 19
0
        /// <summary>When a menu is open (<see cref="Game1.activeClickableMenu"/> isn't null), raised after that menu is drawn to the sprite batch but before it's rendered to the screen.</summary>
/// <param name="sender">The event sender.</param>
/// <param name="e">The event arguments.</param>
        private void OnRenderedActiveMenu(object sender, RenderedActiveMenuEventArgs e)
        {
            // draw shop harvest prices
            if (Game1.activeClickableMenu is ShopMenu menu)
            {
                if (typeof(ShopMenu).GetField("hoveredItem", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(menu) is Item hoverItem)
                {
                    String text             = string.Empty;
                    bool   itemHasPriceInfo = Tools.GetTruePrice(hoverItem) > 0;

                    if (hoverItem is StardewValley.Object &&
                        (hoverItem as StardewValley.Object).Type == "Seeds" &&
                        itemHasPriceInfo &&
                        hoverItem.Name != "Mixed Seeds" &&
                        hoverItem.Name != "Winter Seeds")
                    {
                        StardewValley.Object temp =
                            new StardewValley.Object(
                                new Debris(
                                    new Crop(
                                        hoverItem.ParentSheetIndex,
                                        0,
                                        0)
                                    .indexOfHarvest.Value,
                                    Game1.player.position,
                                    Game1.player.position).chunkType.Value,
                                1);
                        text = "    " + temp.Price;
                    }

                    Item heldItem = typeof(ShopMenu).GetField("heldItem", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(menu) as Item;
                    if (heldItem == null)
                    {
                        int value = 0;
                        switch (hoverItem.ParentSheetIndex)
                        {
                        case 628: value = 50; break;

                        case 629: value = 80; break;

                        case 630:
                        case 633: value = 100; break;

                        case 631:
                        case 632: value = 140; break;
                        }

                        if (value > 0)
                        {
                            text = "    " + value;
                        }

                        if (text != "" &&
                            (hoverItem as StardewValley.Object).Type == "Seeds")
                        {
                            String textToRender = _helper.SafeGetString(
                                LanguageKeys.HarvestPrice);
                            int xPosition = menu.xPositionOnScreen - 30;
                            int yPosition = menu.yPositionOnScreen + 580;
                            IClickableMenu.drawTextureBox(
                                Game1.spriteBatch,
                                xPosition + 20,
                                yPosition - 52,
                                264,
                                108,
                                Color.White);
                            Game1.spriteBatch.DrawString(
                                Game1.dialogueFont,
                                textToRender,
                                new Vector2(xPosition + 30, yPosition - 38),
                                Color.Black * 0.2f);
                            Game1.spriteBatch.DrawString(
                                Game1.dialogueFont,
                                textToRender,
                                new Vector2(xPosition + 32, yPosition - 40),
                                Color.Black * 0.8f);
                            xPosition += 80;

                            Game1.spriteBatch.Draw(
                                Game1.mouseCursors,
                                new Vector2(xPosition, yPosition),
                                new Rectangle(60, 428, 10, 10),
                                Color.White,
                                0,
                                Vector2.Zero,
                                Game1.pixelZoom,
                                SpriteEffects.None,
                                0.85f);

                            Game1.spriteBatch.Draw(
                                Game1.debrisSpriteSheet,
                                new Vector2(xPosition + 32, yPosition + 10),
                                Game1.getSourceRectForStandardTileSheet(Game1.debrisSpriteSheet, 8, 16, 16),
                                Color.White,
                                0,
                                new Vector2(8, 8),
                                4,
                                SpriteEffects.None,
                                0.95f);

                            Game1.spriteBatch.DrawString(
                                Game1.dialogueFont,
                                text,
                                new Vector2(xPosition - 2, yPosition + 6),
                                Color.Black * 0.2f);

                            Game1.spriteBatch.DrawString(
                                Game1.dialogueFont,
                                text,
                                new Vector2(xPosition, yPosition + 4),
                                Color.Black * 0.8f);

                            String           hoverText  = _helper.Reflection.GetField <String>(menu, "hoverText").GetValue();
                            String           hoverTitle = _helper.Reflection.GetField <String>(menu, "boldTitleText").GetValue();
                            Item             hoverItem2 = _helper.Reflection.GetField <Item>(menu, "hoveredItem").GetValue();
                            int              currency   = _helper.Reflection.GetField <int>(menu, "currency").GetValue();
                            int              hoverPrice = _helper.Reflection.GetField <int>(menu, "hoverPrice").GetValue();
                            IReflectedMethod getHoveredItemExtraItemIndex  = _helper.Reflection.GetMethod(menu, "getHoveredItemExtraItemIndex");
                            IReflectedMethod getHoveredItemExtraItemAmount = _helper.Reflection.GetMethod(menu, "getHoveredItemExtraItemAmount");

                            IClickableMenu.drawToolTip(
                                Game1.spriteBatch,
                                hoverText,
                                hoverTitle,
                                hoverItem2,
                                heldItem != null,
                                -1,
                                currency,
                                getHoveredItemExtraItemIndex.Invoke <int>(new object[0]),
                                getHoveredItemExtraItemAmount.Invoke <int>(new object[0]),
                                null,
                                hoverPrice);
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        private string getFortuneTellerOpening()
        {
            IReflectedMethod method = CustomTVMod.Modhelper.Reflection.GetMethod(tv, "getFortuneTellerOpening");

            return(method.Invoke <string>());
        }
Exemplo n.º 21
0
        internal static void Explode(GameLocation location, ModConfig config, Vector2 tileLocation, int radius, Farmer who)
        {
            if (config.LargerRadius)
            {
                int oRadius = radius;
                radius = (int)(radius * (1 + config.RadiusIncreaseRatio));
                ModEntry.Mon.Log($"Radius changed from {oRadius} to {radius}", LogLevel.Trace);
            }
            bool             flag          = false;
            IReflectedMethod rumbleAndFade = ModEntry.Reflection.GetMethod(location, "rumbleAndFade");
            IReflectedMethod damagePlayers = ModEntry.Reflection.GetMethod(location, "damagePlayers");
            Multiplayer      multiplayer   = ModEntry.Reflection.GetField <Multiplayer>(typeof(Game1), "multiplayer").GetValue();

            location.updateMap();
            Vector2 vector = new Vector2(Math.Min(location.map.Layers[0].LayerWidth - 1, Math.Max(0f, tileLocation.X - radius)), Math.Min(location.Map.Layers[0].LayerHeight - 1, Math.Max(0f, tileLocation.Y - radius)));

            bool[,] circleOutlineGrid = Game1.getCircleOutlineGrid(radius);
            Rectangle rectangle = new Rectangle((int)(tileLocation.X - radius - 1f) * 64, (int)(tileLocation.Y - radius - 1f) * 64, (radius * 2 + 1) * 64, (radius * 2 + 1) * 64);
            float     minDamage = radius * 6, maxDamage = radius * 8;

            if (config.ModifyDamagesToEnemies)
            {
                minDamage *= config.DamageMultiplier;
                maxDamage *= config.DamageMultiplier;
            }
            location.damageMonster(rectangle, (int)minDamage, (int)maxDamage, true, who);
            List <TemporaryAnimatedSprite> list1 = new List <TemporaryAnimatedSprite>
            {
                new TemporaryAnimatedSprite(23, 9999f, 6, 1, new Vector2(vector.X * 64f, vector.Y * 64f), false,
                                            Game1.random.NextDouble() < 0.5)
                {
                    light       = true,
                    lightRadius = radius,
                    lightcolor  = Color.Black,
                    alphaFade   = 0.03f - radius * 0.003f
                }
            };
            List <TemporaryAnimatedSprite> list = list1;

            rumbleAndFade?.Invoke(300 + radius * 100);
            damagePlayers?.Invoke(rectangle, radius * 3);

            for (int num = location.terrainFeatures.Count() - 1; num >= 0; num--)
            {
                KeyValuePair <Vector2, TerrainFeature> keyValuePair = location.terrainFeatures.Pairs.ElementAt(num);
                if (keyValuePair.Value.getBoundingBox(keyValuePair.Key).Intersects(rectangle) && keyValuePair.Value.performToolAction(null, radius / 2, keyValuePair.Key, location))
                {
                    location.terrainFeatures.Remove(keyValuePair.Key);
                }
            }

            if (config.BreakBoulders && location is MineShaft shaft)
            {
                for (int num = shaft.resourceClumps.Count - 1; num >= 0; num--)
                {
                    ResourceClump terrain = shaft.resourceClumps[num];
                    switch (terrain.parentSheetIndex.Value)
                    {
                    case 672:
                    case 752:
                    case 754:
                    case 756:
                    case 758: break;

                    default:   continue;
                    }
                    Vector2 vec = terrain.tile.Value;
                    if (terrain.getBoundingBox(vec).Intersects(rectangle))
                    {
                        int number = (terrain.parentSheetIndex.Value == 672) ? 15 : 10;
                        if (Game1.IsMultiplayer)
                        {
                            Game1.createMultipleObjectDebris(390, (int)vec.X, (int)vec.Y, number, Game1.player.UniqueMultiplayerID);
                        }
                        else
                        {
                            Game1.createRadialDebris(Game1.currentLocation, 390, (int)vec.X, (int)vec.Y, number, false, -1, true);
                        }
                        location.playSound("boulderBreak");
                        Game1.createRadialDebris(Game1.currentLocation, 32, (int)vec.X, (int)vec.Y, Game1.random.Next(6, 12), false);
                        shaft.resourceClumps.RemoveAt(num);
                    }
                }
            }
            for (int i = 0; i < radius * 2 + 1; i++)
            {
                for (int j = 0; j < radius * 2 + 1; j++)
                {
                    if (i == 0 || j == 0 || i == radius * 2 || j == radius * 2)
                    {
                        flag = circleOutlineGrid[i, j];
                    }
                    else if (circleOutlineGrid[i, j])
                    {
                        flag = !flag;
                        if (!flag)
                        {
                            if (location.Objects.ContainsKey(vector) && location.Objects[vector].onExplosion(who, location))
                            {
                                if (config.CollectCrystals && location.Objects[vector].CanBeGrabbed)
                                {
                                    Game1.createObjectDebris(location.Objects[vector].ParentSheetIndex, (int)vector.X, (int)vector.Y);
                                }
                                location.destroyObject(vector, who);
                            }
                            if (Game1.random.NextDouble() < 0.45)
                            {
                                if (Game1.random.NextDouble() < 0.5)
                                {
                                    list.Add(new TemporaryAnimatedSprite(362, Game1.random.Next(30, 90), 6, 1, new Vector2(vector.X * 64f, vector.Y * 64f), false, Game1.random.NextDouble() < 0.5)
                                    {
                                        delayBeforeAnimationStart = Game1.random.Next(700)
                                    });
                                }
                                else
                                {
                                    list.Add(new TemporaryAnimatedSprite(5, new Vector2(vector.X * 64f, vector.Y * 64f), Color.White, 8, false, 50f)
                                    {
                                        delayBeforeAnimationStart = Game1.random.Next(200),
                                        scale = Game1.random.Next(5, 15) / 10f
                                    });
                                }
                            }
                        }
                    }
                    if (flag)
                    {
                        if (location.Objects.ContainsKey(vector) && location.Objects[vector].onExplosion(who, location))
                        {
                            if (config.CollectCrystals && location.Objects.ContainsKey(vector) && location.Objects[vector].CanBeGrabbed)
                            {
                                Game1.createObjectDebris(location.Objects[vector].ParentSheetIndex, (int)vector.X, (int)vector.Y);
                            }
                            location.destroyObject(vector, who);
                        }
                        if (Game1.random.NextDouble() < 0.45)
                        {
                            if (Game1.random.NextDouble() < 0.5)
                            {
                                list.Add(new TemporaryAnimatedSprite(362, Game1.random.Next(30, 90), 6, 1, new Vector2(vector.X * 64f, vector.Y * 64f), false, Game1.random.NextDouble() < 0.5)
                                {
                                    delayBeforeAnimationStart = Game1.random.Next(700)
                                });
                            }
                            else
                            {
                                list.Add(new TemporaryAnimatedSprite(5, new Vector2(vector.X * 64f, vector.Y * 64f), Color.White, 8, false, 50f)
                                {
                                    delayBeforeAnimationStart = Game1.random.Next(200),
                                    scale = Game1.random.Next(5, 15) / 10f
                                });
                            }
                        }
                        list.Add(new TemporaryAnimatedSprite(6, new Vector2(vector.X * 64f, vector.Y * 64f), Color.White, 8, Game1.random.NextDouble() < 0.5, Vector2.Distance(vector, tileLocation) * 20f));
                    }
                    vector.Y += 1f;
                    vector.Y  = Math.Min(location.Map.Layers[0].LayerHeight - 1, Math.Max(0f, vector.Y));
                }
                vector.X += 1f;
                vector.Y  = Math.Min(location.Map.Layers[0].LayerWidth - 1, Math.Max(0f, vector.X));
                vector.Y  = tileLocation.Y - radius;
                vector.Y  = Math.Min(location.Map.Layers[0].LayerHeight - 1, Math.Max(0f, vector.Y));
            }
            multiplayer.broadcastSprites(location, list);
            radius           /= 2;
            circleOutlineGrid = Game1.getCircleOutlineGrid(radius);
            vector            = new Vector2((int)(tileLocation.X - radius), (int)(tileLocation.Y - radius));
            for (int k = 0; k < radius * 2 + 1; k++)
            {
                for (int l = 0; l < radius * 2 + 1; l++)
                {
                    if (k == 0 || l == 0 || k == radius * 2 || l == radius * 2)
                    {
                        flag = circleOutlineGrid[k, l];
                    }
                    else if (circleOutlineGrid[k, l])
                    {
                        flag = !flag;
                        if (!flag && !location.Objects.ContainsKey(vector) && Game1.random.NextDouble() < 0.9 && location.doesTileHaveProperty((int)vector.X, (int)vector.Y, "Diggable", "Back") != null && !location.isTileHoeDirt(vector))
                        {
                            location.checkForBuriedItem((int)vector.X, (int)vector.Y, true, false);
                            location.makeHoeDirt(vector);
                        }
                    }
                    if (flag && !location.Objects.ContainsKey(vector) && Game1.random.NextDouble() < 0.9 && location.doesTileHaveProperty((int)vector.X, (int)vector.Y, "Diggable", "Back") != null && !location.isTileHoeDirt(vector))
                    {
                        location.checkForBuriedItem((int)vector.X, (int)vector.Y, true, false);
                        location.makeHoeDirt(vector);
                    }
                    vector.Y += 1f;
                    vector.Y  = Math.Min(location.Map.Layers[0].LayerHeight - 1, Math.Max(0f, vector.Y));
                }
                vector.X += 1f;
                vector.Y  = Math.Min(location.Map.Layers[0].LayerWidth - 1, Math.Max(0f, vector.X));
                vector.Y  = tileLocation.Y - radius;
                vector.Y  = Math.Min(location.Map.Layers[0].LayerHeight - 1, Math.Max(0f, vector.Y));
            }
        }
Exemplo n.º 22
0
        /// <summary>When a menu is open (<see cref="Game1.activeClickableMenu"/> isn't null), raised after that menu is drawn to the sprite batch but before it's rendered to the screen.</summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        private void OnRenderedActiveMenu(object sender, RenderedActiveMenuEventArgs e)
        {
            if (!(Game1.activeClickableMenu is ShopMenu menu))
            {
                return;
            }
            if (!(menu.hoveredItem is Item hoverItem))
            {
                return;
            }

            // draw shop harvest prices
            bool isSeeds   = hoverItem is StardewValley.Object hoverObject && hoverObject.Type == "Seeds";
            bool isSapling = hoverItem.Name.EndsWith("Sapling");
            int  value     = 0;

            if (isSeeds &&
                hoverItem.Name != "Mixed Seeds" &&
                hoverItem.Name != "Winter Seeds")
            {
                bool itemHasPriceInfo = Tools.GetTruePrice(hoverItem) > 0;
                if (itemHasPriceInfo)
                {
                    StardewValley.Object temp =
                        new StardewValley.Object(
                            new Debris(
                                new Crop(
                                    hoverItem.ParentSheetIndex,
                                    0,
                                    0)
                                .indexOfHarvest.Value,
                                Game1.player.position,
                                Game1.player.position).chunkType.Value,
                            1);
                    value = temp.Price;
                }
                else
                {
                    switch (hoverItem.ParentSheetIndex)
                    {
                    case 802: value = 75; break;        // Cactus
                    }
                }
            }
            else if (isSapling)
            {
                switch (hoverItem.ParentSheetIndex)
                {
                case 628: value = 50; break;        // Cherry

                case 629: value = 80; break;        // Apricot

                case 630:                           // Orange
                case 633: value = 100; break;       // Apple

                case 631:                           // Peach
                case 632: value = 140; break;       // Pomegranate
                }
            }

            if (value > 0)
            {
                int xPosition = menu.xPositionOnScreen - 30;
                int yPosition = menu.yPositionOnScreen + 580;
                int height    = isSapling ? 258 : 208;
                IClickableMenu.drawTextureBox(
                    Game1.spriteBatch,
                    xPosition + 20,
                    yPosition - 52,
                    264,
                    height,
                    Color.White);
                // Title "Harvest Price"
                String textToRender = _helper.SafeGetString(LanguageKeys.HarvestPrice);
                Utility.drawTextWithShadow(
                    Game1.spriteBatch,
                    textToRender,
                    Game1.dialogueFont,
                    new Vector2(xPosition + 32, yPosition - 40),
                    Game1.textColor
                    );

                //Calculate price with skill
                if (Game1.player.professions.Contains(Farmer.tiller))
                {
                    value = (int)(value * 1.1f);
                }

                // Draw normal price
                xPosition += 80;
                yPosition += 6;
                DrawPrice(value, xPosition, yPosition, Tools.Quality.Normal);
                // Draw silver price
                yPosition += 46;
                DrawPrice(value, xPosition, yPosition, Tools.Quality.Silver);
                // Draw gold price
                yPosition += 46;
                DrawPrice(value, xPosition, yPosition, Tools.Quality.Gold);
                // Draw iridium price
                if (isSapling)
                {
                    yPosition += 48;
                    DrawPrice(value, xPosition, yPosition, Tools.Quality.Iridium);
                }


                // Found out what this was for: Redraw the tooltip so it doesn't get overlapped by harvest price
                String           hoverText  = _helper.Reflection.GetField <String>(menu, "hoverText").GetValue();
                String           hoverTitle = _helper.Reflection.GetField <String>(menu, "boldTitleText").GetValue();
                IReflectedMethod getHoveredItemExtraItemIndex  = _helper.Reflection.GetMethod(menu, "getHoveredItemExtraItemIndex");
                IReflectedMethod getHoveredItemExtraItemAmount = _helper.Reflection.GetMethod(menu, "getHoveredItemExtraItemAmount");
                IClickableMenu.drawToolTip(
                    Game1.spriteBatch,
                    hoverText,
                    hoverTitle,
                    hoverItem,
                    menu.heldItem != null,
                    -1,
                    menu.currency,
                    getHoveredItemExtraItemIndex.Invoke <int>(new object[0]),
                    getHoveredItemExtraItemAmount.Invoke <int>(new object[0]),
                    null,
                    menu.hoverPrice);
            }
        }
Exemplo n.º 23
0
 /// <summary>Assert that mods can use the reflection helper to access the given member.</summary>
 /// <param name="method">The method being accessed.</param>
 /// <returns>Returns the same method instance for convenience.</returns>
 private IReflectedMethod AssertAccessAllowed(IReflectedMethod method)
 {
     this.AssertAccessAllowed(method?.MethodInfo.GetBaseDefinition());
     return(method);
 }
Exemplo n.º 24
0
        private void setFortuneOverlay()
        {
            IReflectedMethod method = CustomTVMod.Modhelper.Reflection.GetMethod(tv, "setFortuneOverlay");

            method.Invoke();
        }
Exemplo n.º 25
0
        private string[] getWeeklyRecipe()
        {
            IReflectedMethod method = CustomTVMod.Modhelper.Reflection.GetMethod(tv, "getWeeklyRecipe");

            return(method.Invoke <string[]>());
        }
Exemplo n.º 26
0
 private void GameLoop_SaveLoaded(object sender, SaveLoadedEventArgs e)
 {
     takeMapscreenshot = Helper.Reflection.GetMethod(Game1.game1, "takeMapScreenshot");
     addMessage        = Helper.Reflection.GetMethod(Game1.chatBox, "addMessage");
 }
Exemplo n.º 27
0
        private string getWeatherChannelOpening()
        {
            IReflectedMethod method = CustomTVMod.Modhelper.Reflection.GetMethod(tv, "getWeatherChannelOpening");

            return(method.Invoke <string>());
        }
Exemplo n.º 28
0
 /// <summary>Assert that mods can use the reflection helper to access the given member.</summary>
 /// <param name="method">The method being accessed.</param>
 /// <returns>Returns the same method instance for convenience.</returns>
 private IReflectedMethod AssertAccessAllowed(IReflectedMethod method)
 {
     this.AssertAccessAllowed(method?.MethodInfo);
     return(method);
 }
Exemplo n.º 29
0
        private void GoToBed(Farmer who, string whichAnswer)
        {
            if (whichAnswer.Equals("Yes"))
            {
                this.Monitor.Log($"Farmer {Game1.player.Name} goes to bed", LogLevel.Debug);

                FarmHouse farmHouse = Game1.player.currentLocation as FarmHouse;

                // Check SDV version: SMAPI 3.8 is not usable with SDV 1.4 .
                bool isSDV14 = StardewModdingAPI.Constants.ApiVersion.IsOlderThan("3.8.0");
                // Compatibility with SDV 1.4: Access old and new API via reflection.
                IReflectedMethod getBed = isSDV14
                                        ? this.Helper.Reflection.GetMethod(farmHouse, nameof(FarmHouse.getBedSpot))
                                        : this.Helper.Reflection.GetMethod(farmHouse, "GetPlayerBedSpot");
                Game1.player.position.Y = getBed.Invoke <Point>().Y * 64f + 24f;

                // Take hat off. We could check for a hat and store it in the inventory
                // overnight but this requires a free inventory slot and causes its own
                // problems (you always have to put your hat on if you load a game...)
                // so we move the farmer under the blanket and change into swimsuit.
                // Simple and reliable.
                Game1.player.changeIntoSwimsuit();

                // Player is not married.
                if (!Game1.player.isMarried() || Game1.timeOfDay > config_.SpouseGoToBedTime)
                {
                    FarmerSleep();

                    return;
                }

                // If spouse isn't in the farm house player has to sleep alone.
                NPC spouse = Game1.player.getSpouse();
                if (spouse.currentLocation != farmHouse)
                {
                    this.Monitor.Log($"Spouse {spouse.Name} isn't in the farm house", LogLevel.Info);

                    FarmerSleep();

                    return;
                }

                // Disable player movement so spouse can finish his/her path to bed.
                this.Helper.Events.Input.ButtonPressed += OnButtonPressedDisableInput;

                // Spouse goes to bed.
                this.Monitor.Log($"Spouse {spouse.Name} goes to bed", LogLevel.Debug);

                spouse.controller =
                    new PathFindController(
                        spouse,
                        farmHouse,
                        farmHouse.getSpouseBedSpot(spouse.Name),
                        0,
                        (c, location) => {
                    c.doEmote(Character.sleepEmote);
                    FarmHouse.spouseSleepEndFunction(c, location);

                    // Player can rest assured.
                    FarmerSleep();
                });

                if (spouse.controller.pathToEndPoint == null)
                {
                    this.Monitor.Log($"Spouse {spouse.Name} can't reach bed", LogLevel.Warn);

                    FarmerSleep();
                }
            }
        }
Exemplo n.º 30
0
        private string getFortuneForecast()
        {
            IReflectedMethod method = CustomTVMod.Modhelper.Reflection.GetMethod(tv, "getFortuneForecast");

            return(method.Invoke <string>());
        }