public static string GetModName(UIState prevUi, UIState currUi) { Type uiType = currUi.GetType(); FieldInfo uiLocalmodField = uiType.GetField("localMod", BindingFlags.NonPublic | BindingFlags.Instance); if (uiLocalmodField == null) { LogHelpers.Warn("No 'localMod' field in " + uiType); return(null); } object localmod = uiLocalmodField.GetValue(currUi); if (localmod != null) { return(ModMenuHelpers.GetLocalMod(localmod).name); } else { if (prevUi?.GetType().Name == "UIModBrowser") { return(ModMenuHelpers.GetSelectedModBrowserModName(prevUi)); } } LogHelpers.Alert("No mod loaded."); return(null); }
//////////////// public void BeginResetTimer() { var mymod = ResetModeMod.Instance; if (mymod.Config.DebugModeInfo) { LogHelpers.Alert(); } if (TimeLimitAPI.GetTimersOf("reset").Count > 0) { LogHelpers.Alert("Existing reset timers halted."); Main.NewText("Warning: Existing reset timers removed."); } TimeLimitAPI.TimerStop("reset"); // Stop regardless? API failure perhaps? if (!this.Data.AwaitingNextWorld) { TimeLimitAPI.TimerStart("reset", mymod.Config.SecondsUntilResetInitially, false); } else { TimeLimitAPI.TimerStart("reset", mymod.Config.SecondsUntilResetSubsequently, false); } }
public void ExpireCurrentWorldInSession(ResetModeMod mymod) { if (mymod.Config.DebugModeInfo) { LogHelpers.Alert("Sets AwaitingNextWorld=true, CurrentSessionedWorldId=\"\", PlayersValidated.Clear()"); } this.Data.AwaitingNextWorld = true; this.Data.CurrentSessionedWorldId = ""; this.Data.PlayersValidated.Clear(); if (Main.netMode != 1) { this.Save(); } if (Main.netMode == 2) { SessionProtocol.SyncToClients(); } if (Main.netMode != 1) { this.GoodExit(); } }
//// public override void Unload() { LogHelpers.Alert("Unloading mod..."); this.UnloadFull(); ModHelpersMod.Instance = null; }
//////////////// public void ClearAllWorlds() { if (ResetModeMod.Instance.Config.DebugModeInfo) { LogHelpers.Alert("Deletes all world files, Sets PlayersValidated.Clear(), CurrentSessionedWorldId=\"\", AwaitingNextWorld=true"); } try { Main.LoadWorlds(); while (Main.WorldList.Count > 0) { WorldFileData worldData = Main.WorldList[0]; WorldFileHelpers.EraseWorld(worldData, false); } this.Data.PlayersValidated.Clear(); this.Data.CurrentSessionedWorldId = ""; this.Data.AwaitingNextWorld = true; if (Main.netMode != 1) { this.Save(); } } catch (Exception e) { LogHelpers.Warn(e.ToString()); } }
//////////////// public static void Implant(Chest chest, ChestImplanterItemDefinition info) { int addedAmount = ChestImplanter.GetImplantQuantity(info); if (addedAmount == 0) { return; } int itemType = info.ChestItem.Type; if (itemType == 0) { LogHelpers.Alert("Invalid item key " + info.ChestItem); return; } // Add or remove quantity of item, according to implanter spec if (addedAmount > 0) { ChestImplanter.PrependItemToChest(chest, itemType, addedAmount, info); } else if (addedAmount < 0) { ChestImplanter.ExtractItemFromChest(chest, itemType, -addedAmount); } else { throw new ModHelpersException("Invalid quantity."); } }
public override bool UseItem(Player player) { var mymod = (LicensesMod)this.mod; int savings; int oldStack = this.item.stack; ItemDefinition randItemDef = this.AttemptToLicenseRandomItem(player, out savings); if (randItemDef == null) { Main.NewText("No items of the given tier left to license.", Color.Red); return(false); } int targetRarity = WildcardLicenseItem.ComputeTargetRarityOfLicenseStackSize(oldStack); Color color = ItemRarityAttributeHelpers.RarityColor[targetRarity]; string randItemName = ItemAttributeHelpers.GetQualifiedName(randItemDef.Type); string msg = randItemName + " licensed"; if (savings > 0) { msg += " - " + savings + " discounted"; } PlayerMessages.AddPlayerLabel(player, msg, color, 2 * 60, true); Main.NewText(msg, color); if (LicensesMod.Config.DebugModeInfo) { LogHelpers.Alert(randItemName + " unlocked"); } return(true); }
//////////////// internal bool UpdateForEventsBeginnings(VanillaEventFlag eventFlags) { bool eventsChanged = false; IEnumerable <VanillaEventFlag> eventFlagSet = DotNetHelpers.FlagsToCollection <VanillaEventFlag>((int)eventFlags); foreach (VanillaEventFlag flag in eventFlagSet) { if (this.CurrentEvents.Contains(flag)) { continue; } switch (flag) { case VanillaEventFlag.Sandstorm: case VanillaEventFlag.BloodMoon: case VanillaEventFlag.SlimeRain: case VanillaEventFlag.SolarEclipse: case VanillaEventFlag.LunarApocalypse: break; default: if (RewardsMod.Instance.SettingsConfig.DebugModeInfo) { LogHelpers.Alert("Event added: " + Enum.GetName(typeof(VanillaEventFlag), flag)); } eventsChanged = true; this.CurrentEvents.Add(flag); break; } } return(eventsChanged); }
/// <summary> /// Gets the mod name of a mod-representing menu UI (sometimes needs the previous UI for context). /// </summary> /// <param name="prevUi"></param> /// <param name="currUi"></param> /// <returns></returns> public static string GetModName(UIState prevUi, UIState currUi) { // = uiType.GetField( "_localMod", BindingFlags.NonPublic | BindingFlags.Instance ); object localmod; // <- is a LocalMod class if (!ReflectionHelpers.Get(currUi, "_localMod", out localmod)) { LogHelpers.Warn("No '_localMod' field in " + currUi.GetType()); return(null); } if (localmod != null) { return(ModMenuHelpers.GetLocalMod(localmod).name); } else { if (prevUi?.GetType().Name == "UIModBrowser") { return(ModMenuHelpers.GetSelectedModBrowserModName(prevUi)); } } LogHelpers.Alert("No mod loaded."); return(null); }
/// <summary> /// Reports whether a given mod (by the given internal name) is "properly presented": Has a valid description, /// homepage, and any other needed checks (in future considerations). /// </summary> /// <param name="modName"></param> /// <returns></returns> public static bool IsLoadedModProperlyPresented(string modName) { Mod mod = ModLoader.GetMod(modName); if (mod == null) { LogHelpers.Alert("Invalid mod " + modName); return(false); } IDictionary <string, BuildPropertiesViewer> modInfos = ModListHelpers.GetLoadedModNamesWithBuildProps(); if (!modInfos.ContainsKey(modName)) { LogHelpers.Alert("Missing mod " + modName); return(false); } var modInfo = new BasicModInfo(mod.DisplayName, modInfos[modName].Author.Split(',').SafeSelect(a => a.Trim()), mod.Version, modInfos[modName].Description, modInfos[modName].Homepage ); return(ModIdentityHelpers.IsProperlyPresented(modInfo)); }
//// protected override void Receive(int fromWho) { IList <(ushort TileX, ushort TileY)> innerHouseSpace, fullHouseSpace; int floorX, floorY; HouseViabilityState state = HouseFurnishingKitItem.IsValidHouse( this.TileX, this.TileY, out innerHouseSpace, out fullHouseSpace, out floorX, out floorY ); if (state == HouseViabilityState.Good) { bool aborted = HouseFurnishingKitItem.FurnishHouseFull( Main.player[this.PlayerWho], this.TileX, this.TileY, innerHouseSpace, fullHouseSpace, floorX, floorY ); } else { LogHelpers.Alert("Could not furnish house"); } }
private void HandleFilteredMods(UIState _menuUi, bool isFiltered, IList <string> filteredModNameList, int onTagCount, int offTagCount) { string filterName = "Tags"; if (onTagCount > 0 || offTagCount > 0) { filterName += " "; if (onTagCount > 0) { filterName += "+" + onTagCount; if (offTagCount > 0) { filterName += " "; } } if (offTagCount > 0) { filterName += "-" + offTagCount; } } if (ReflectionHelpers.Set(_menuUi, "UpdateFilterMode", (UpdateFilter)0)) { ModMenuHelpers.ApplyModBrowserFilter(filterName, isFiltered, (List <string>)filteredModNameList); } else { LogHelpers.Alert("Could not set UpdateFilterMode for the mod browser"); } }
private bool ComputeGroupMatch <T>(IList <T> entityPool, string groupName, string[] dependencies, Func <T, IDictionary <string, ISet <int> >, bool> matcherFunc, out ISet <int> entityIdsOfGroup) where T : Entity { entityIdsOfGroup = new HashSet <int>(); IDictionary <string, ISet <int> > deps = this.GetGroups <T>(groupName, dependencies); for (int i = 1; i < entityPool.Count; i++) { try { lock (EntityGroups.MyLock) { if (matcherFunc(entityPool[i], deps)) { entityIdsOfGroup.Add(i); } } } catch (Exception) { LogHelpers.Alert("Compute fail for '" + groupName + "' with ent (" + i + ") " + (entityPool[i] == null ? "null" : entityPool[i].ToString())); } } return(true); }
public void GoodExit() { var mymod = ResetModeMod.Instance; if (Main.netMode == 1) { throw new ModHelpersException("Single or server only."); } if (mymod.Session.IsExiting) { return; } mymod.Session.IsExiting = true; if (mymod.Config.DebugModeInfo) { LogHelpers.Alert(); } string msg = "This world is now expired. Please switch to the next world to continue."; if (Main.netMode == 0) { Main.NewText(msg, Color.Red); TimeLimitAPI.TimerStart("exit", 5, false); } else if (Main.netMode == 2) { NetMessage.BroadcastChatMessage(NetworkText.FromLiteral(msg), Color.Red, -1); TimeLimitAPI.TimerStart("serverclose", 7, false); } }
public void BadExit() { var mymod = ResetModeMod.Instance; if (Main.netMode == 1) { throw new ModHelpersException("Single or server only."); } if (mymod.Session.IsExiting) { return; } mymod.Session.IsExiting = true; if (mymod.Config.DebugModeInfo) { LogHelpers.Alert(); } string msg = "World not valid for reset mode. Exiting..."; if (Main.netMode == 0) { //TmlHelpers.ExitToMenu( false ); TimeLimitAPI.TimerStart("exit", 4, false); Main.NewText(msg, Color.Red); } else { //TmlHelpers.ExitToDesktop( false ); TimeLimitAPI.TimerStart("serverclose", 4, false); NetMessage.BroadcastChatMessage(NetworkText.FromLiteral(msg), Color.Red); } }
private static void RetrieveAllModInfoAsync(Action <IDictionary <string, BasicModInfoEntry>, bool> onSuccess) { Action <Exception, string> onFail = (e, output) => { if (e is JsonReaderException) { LogHelpers.Alert("Bad JSON: " + (output.Length > 256 ? output.Substring(0, 256) : output)); } else if (e is WebException || e is NullReferenceException) { LogHelpers.Alert((output ?? "") + " - " + e.Message); } else { LogHelpers.Alert((output ?? "") + " - " + e.ToString()); } }; Action <IDictionary <string, BasicModInfoEntry>, bool> onCompletion = (responseVal, success) => { if (responseVal == null) { responseVal = new Dictionary <string, BasicModInfoEntry>(); } onSuccess(responseVal, success); }; NetHelpers.MakeGetRequestAsync(GetModInfo.ModInfoUrl, GetModInfo.HandleModInfoReceipt, onFail, onCompletion); }
//////////////// public void OpenPack(Item packItem) { var mymod = (RewardsMod)this.mod; var myitem = packItem.modItem as ShopPackItem; if (myitem == null) { LogHelpers.Warn("Pack item " + packItem.Name + " missing mod data"); ItemHelpers.DestroyItem(packItem); return; } string output; if (!myitem.BuyAndOpenPack_Synced(this.player, out output)) { LogHelpers.Warn(output); } else { if (mymod.SettingsConfig.DebugModeInfo) { LogHelpers.Alert(output); } } if (myitem.IsClone(Main.mouseItem)) { ItemHelpers.DestroyItem(Main.mouseItem); Main.mouseItem = new Item(); } }
//////////////// // Server Senders //////////////// /*public static void SendSettingsFromServer( HonorBoundMod mymod, Player player ) { * if( Main.netMode != 2 ) { return; } // Server only * * ModPacket packet = mymod.GetPacket(); * * packet.Write( (byte)HonorBoundNetProtocolTypes.ModSettingsFromServer ); * packet.Write( (string)mymod.Config.SerializeMe() ); * * packet.Send( (int)player.whoAmI ); * }*/ public static void SendHonorSettingsFromServer(Player player) { if (Main.netMode != 2) { return; } // Server only var mymod = HonorBoundMod.Instance; var modworld = ModContent.GetInstance <HonorBoundWorld>(); var mylogic = modworld.Logic; ModPacket packet = mymod.GetPacket(); packet.Write((byte)NetProtocolTypes.ReceiveHonorSettingsWithClient); packet.Write((bool)mylogic.IsHonorBound); packet.Write((bool)mylogic.IsDishonorable); packet.Write((int)mylogic.CurrentActiveHonorifics.Count); foreach (string honorific in mylogic.CurrentActiveHonorifics) { packet.Write(honorific); } packet.Send((int)player.whoAmI); if (mymod.Config.DebugModeInfo) { LogHelpers.Alert("IsHonorBound:" + mylogic.IsHonorBound + " IsDishonorable:" + mylogic.IsDishonorable + " CurrentActiveHonorifics:" + String.Join(",", mylogic.CurrentActiveHonorifics)); } }
public void SyncToAll() { if (!this.IsInitialized) { //throw new HamstarException( "!ModHelpers.CustomEntity.SyncToAll ("+this.GetType().Name+") - Not initialized." ); throw new HamstarException("Not initialized."); } if (!SaveableEntityComponent.HaveAllEntitiesLoaded) { //LogHelpers.Log( "!ModHelpers.CustomEntity.SyncToAll ("+this.GetType().Name+") - Entities not yet loaded." ); LogHelpers.Alert("Entities not yet loaded."); return; } if (ModHelpersMod.Instance.Config.DebugModeCustomEntityInfo) { LogHelpers.Alert("Syncing..."); } if (Main.netMode == 0) { //throw new HamstarException( "!ModHelpers.CustomEntity.SyncToAll (" + this.GetType().Name + ") - Multiplayer only." ); throw new HamstarException("Multiplayer only."); } if (Main.netMode == 2) { CustomEntityProtocol.SendToClients(this); } else if (Main.netMode == 1) { CustomEntityProtocol.SyncToAll(this); } }
private void RefreshEditMode() { string modName = this.Manager.CurrentModName; ISet <string> onTags = this.Manager.GetTagsWithGivenState(1); if (this.Manager.AllModTagsSnapshot == null) { LogHelpers.Alert("AllModTagsSnapshot == null"); } else if (this.Manager.AllModTagsSnapshot.ContainsKey(modName) == true) { // No changes? if (onTags.SetEquals(this.Manager.AllModTagsSnapshot[modName])) { this.SetEditMode(false); return; } } // Non-zero tags? if (onTags.Count >= 2) { this.EditButton.Enable(); } else { this.EditButton.Disable(); } }
//////////////// public override void Load(TagCompound tag) { var self = this; this.TrialLicensedItems.Clear(); this.LicensedItems.Clear(); if (tag.ContainsKey("trial_license_key_count")) { int count = tag.GetInt("trial_license_key_count"); for (int i = 0; i < count; i++) { string itemKey = tag.GetString("trial_license_key_" + i); this.PendingLoadTrialLicenses.Add(new ItemDefinition(itemKey)); } if (LicensesMod.Config.DebugModeInfo) { LogHelpers.Alert(" Loaded for player " + this.player.name + " (" + this.player.whoAmI + ") " + count + " trial licensed items..."); } } if (tag.ContainsKey("license_key_count")) { int count = tag.GetInt("license_key_count"); for (int i = 0; i < count; i++) { string itemKey = tag.GetString("license_key_" + i); this.PendingLoadLicenses.Add(new ItemDefinition(itemKey)); } if (LicensesMod.Config.DebugModeInfo) { LogHelpers.Alert(" Loaded for player " + this.player.name + " (" + this.player.whoAmI + ") " + count + " licensed items..."); } } }
private void ReceiveMe(Player player) { var mymod = RewardsMod.Instance; var myworld = ModContent.GetInstance <RewardsWorld>(); KillData data = myworld.Logic.GetPlayerData(player); if (data == null) { throw new ModHelpersException("No player data for " + player.name); } if (!data.Spend((int)this.Pack.Price, player)) { LogHelpers.Warn("Not enough PP. PP out of sync."); //return; // TODO: Add validation of purchases } Item[] items = ShopPackDefinition.OpenPack(player, this.Pack); foreach (var hook in RewardsMod.Instance.OnPointsSpentHooks) { hook(player, this.Pack.Name, this.Pack.Price, items); } if (mymod.SettingsConfig.DebugModeInfo) { LogHelpers.Alert("Purchase made for " + player.name + " of " + this.Pack.Name + " (" + this.Pack.Price + ")"); } }
//////////////// public void LoadGameMode() { if( LicensesMod.Config.DebugModeInfo ) { LogHelpers.Alert( "Loading game mode..." ); } NihilismAPI.InstancedFiltersOn(); NihilismAPI.OnSyncOrWorldLoad( ( isSync ) => { if( isSync ) { return; } this.LoadNihilismFilters(); NihilismAPI.NihilateCurrentWorld( true ); }, 0f ); LoadHooks.AddWorldLoadEachHook( () => { if( LicensesMod.Config.RemoveRewardsGrinding ) { RewardsPointsConfig rewConfig = ModContent.GetInstance<RewardsPointsConfig>(); rewConfig.GrindKillMultiplier = 0f; } if( LicensesMod.Config.ForceSpawnWayfarer ) { RewardsAPI.SpawnWayfarer( false ); } this.LoadLicensePacks(); } ); this.PostLoadGameMode(); if( LicensesMod.Config.DebugModeInfo ) { LogHelpers.Alert( "Finished loading game mode" ); } }
public bool StartSession() { var mymod = ResetModeMod.Instance; if (Main.netMode == 1) { throw new Exception("Clients cannot call this."); } //this.IsExiting = false; // Careful! // Already running? if (this.Data.IsRunning) { LogHelpers.Warn("Session already running"); return(false); } if (mymod.Config.DebugModeInfo) { LogHelpers.Alert(); } this.Data.IsRunning = true; this.Save(); if (Main.netMode == 2) { SessionProtocol.SyncToClients(); } return(true); }
public bool EndSession() { var mymod = ResetModeMod.Instance; if (Main.netMode == 1) { throw new Exception("Clients cannot call this."); } // Already ended? if (!this.Data.IsRunning) { LogHelpers.Alert("Already stopped."); return(false); } if (mymod.Config.DebugModeInfo) { string worldId = WorldHelpers.GetUniqueIdForCurrentWorld(true); LogHelpers.Alert("Sets ALL session data to defaults, stops all TimeLimit \"reset\" commands (world id: " + worldId + ")"); } this.IsExiting = false; this.Data.ResetAll(); this.Save(); if (Main.netMode == 2) { SessionProtocol.SyncToClients(); } this.ResetCurrentWorldForSession(); return(true); }
//////////////// public void Load() { var mymod = ResetModeMod.Instance; if (Main.netMode == 1) { LogHelpers.Warn("Clients cannot load config from file"); return; } var data = ModCustomDataFileHelpers.LoadJson <ResetModeSessionData>(mymod, SessionLogic.DataFileNameOnly); if (data != null) { // Very specific failsafe: if (data.IsRunning && !data.AwaitingNextWorld && data.CurrentSessionedWorldId == "" && data.AllPlayedWorlds.Count == 0) { data.IsRunning = false; } this.DataOnLoad = data.Clone(); this.Data = data; } if (mymod.Config.DebugModeInfo) { LogHelpers.Alert("Success? " + (data != null) + ": " + this.Data.ToString()); } }
public override bool ConsumeItem(Player player) { int tileX = (int)player.Center.X >> 4; int tileY = (int)player.position.Y >> 4; ISet <(int, int)> _; bool canErect = HouseFramingKitItem.Validate(ref tileX, ref tileY, out _); if (canErect) { if (Main.netMode == 0) { HouseFramingKitItem.MakeHouseFrame(tileX, tileY); } else if (Main.netMode == 1) { FramingKitProtocol.SendToServer(tileX, tileY); return(true); } else if (Main.netMode == 2) { LogHelpers.Alert("Server?"); } } else { Main.NewText("Not enough open space.", Color.Yellow); } return(canErect); }
//////////////// private static void CacheAllGlobalInboxAsync() { ThreadPool.QueueUserWorkItem(_ => { lock (GetGlobalInbox.MyLock) { var mymod = ModHelpersMod.Instance; var args = new GlobalInboxLoadHookArguments { Found = false }; GetGlobalInbox.RetrieveGlobalInboxAsync((success, globalInbox) => { try { if (success) { args.SetGlobalInbox(globalInbox); } args.Found = success; CustomLoadHooks.TriggerHook(GetGlobalInbox.GlobalInboxReceivedHookValidator, GetGlobalInbox.GlobalInboxReceivedHookValidatorKey, args); } catch (Exception e) { LogHelpers.Alert(e.ToString()); } }); } }); }
//////////////// private static void CacheAllModTagsAsync() { ThreadPool.QueueUserWorkItem(_ => { lock (GetModTags.MyLock) { var mymod = ModHelpersMod.Instance; var args = new ModTagsPromiseArguments { Found = false }; GetModTags.RetrieveAllModTagsAsync((modTags, found) => { try { if (found) { args.SetTagMods(modTags); } args.Found = found; Promises.TriggerValidatedPromise(GetModTags.TagsReceivedPromiseValidator, GetModTags.PromiseValidatorKey, args); } catch (Exception e) { LogHelpers.Alert(e.ToString()); } }); } }); }
public void OnEnterWorldForServer() { if (LicensesMod.Config.DebugModeInfo) { LogHelpers.Alert("Loading player for game mode..."); } this.PostOnEnterWorld(); }