public override void Unload()
        {
            client?.Dispose();
            client   = null;
            Instance = null;
            _exampleUserInterface?.SetState(null);    // Choose Starter
            _exampleUserInterfaceNew?.SetState(null); // Pokegear Main Menu
            PokegearUserInterfaceNew?.SetState(null); // Pokegear Events Menu
            evolveUserInterfaceNew?.SetState(null);
            summaryUIInterface?.SetState(null);
            _uiSidebar?.SetState(null);
            _partySlots?.SetState(null);
            _moves?.SetState(null);
            _battle?.SetState(null);
            BattleMode.UI            = null;
            PartySlots               = null;
            pokemonStore             = null;
            wildPokemonStore         = null;
            movesStore               = null;
            _exampleUserInterface    = null;
            _exampleUserInterfaceNew = null;
            PokegearUserInterfaceNew = null;
            _uiSidebar               = null;
            _partySlots              = null;
            _moves          = null;
            _battle         = null;
            BaseMove._mrand = null;


            ChooseStarter.Deactivate();
            ChooseStarter = null;
            ChooseStarterBulbasaur.Deactivate();
            ChooseStarterBulbasaur = null;
            ChooseStarterCharmander.Deactivate();
            ChooseStarterCharmander = null;
            ChooseStarterSquirtle.Deactivate();
            ChooseStarterSquirtle = null;
            PokegearUI.Deactivate();
            PokegearUI = null;
            PokegearUIEvents.Deactivate();
            PokegearUIEvents = null;
            evolveUI.Deactivate();
            evolveUI = null;
            UISidebar.Deactivate();
            UISidebar = null;
            Moves.Deactivate();
            Moves = null;

            summaryUI.Deactivate();
            summaryUI = null;

            PartyCycle       = null;
            FirstPKMAbility  = null;
            SecondPKMAbility = null;
            ThirdPKMAbility  = null;
            FourthPKMAbility = null;
            CompressSidebar  = null;

            Localisation = null;
            Textures     = null;
            storage      = null;
            Store.Dispose();
            Store = null;
            Scheduler?.CancelDelayedTasks();
            Scheduler      = null;
            schedulerClock = null;
            ParentPokemonNPC.HighlightTexture = null;
            ParentPokemon.HighlightTexture    = null;
        }
Example #2
0
        public override void Load()
        {
            base.Load();

            RecentChatters = new List <string>();

#if DEBUG
            //Used for debugging
            RecentChatters.AddRange(new[]
            {
                "Nightbot",
                "KarmikKoalla",
                "Moobot",
                "SomeoneFromChat"
            });
#endif

            Instance = this;

            BossCommands = new Dictionary <string, Action>();

            EventsPool = new List <WorldEvent>();

            LastStatus.Value = $"[c/{TwitchColor}: Client not connected]";

            OldConfig = new TwitchOldConfig(Storage = new ModStorage(@"Twitch"));

            Store = new ResourceStore <byte[]>(new StorageBackedResourceStore(Storage));
            if (ModLoader.version.Major == 10)
            {
                Store.AddStore(new OnlineStore());
            }
            else
            {
                Store.AddStore(new WebStore("image/png"));
            }

            Textures = new Texture2DStore(Store);

            EmoticonHandler.store = new EmoticonsStore(Store);

            if (Storage.Exists("EmoteIDs.json"))
            {
                using (Stream p = Storage.GetStream("EmoteIDs.json"))
                    using (StreamReader s = new StreamReader(p))
                    {
                        try
                        {
                            EmoticonHandler.convertingEmotes =
                                JsonConvert.DeserializeObject <Dictionary <string, int> >(s.ReadToEnd());
                        }
                        catch (Exception e)
                        {
                            Logger.Warn($"Failed to load emotes id:\n{e}");
                        }
                    }
            }

            // Just to create file
            OldConfig.Save();


            Irc = new IrcClient(); // This client used in my twitch bot so class know all info about twitch irc server so we don't need to provide what info here

            //Start migrating to new configs
            //ShowDebug = OldConfig.Get<bool>(TwitchCfg.ShowAllIrc);
            //IgnoreCommands = OldConfig.Get<bool>(TwitchCfg.IgnoreCommands);
            //CommandPrefix = OldConfig.Get<string>(TwitchCfg.IgnoreCommandPrefix);
            Username = OldConfig.Get <string>(TwitchCfg.Username);
            Fun      = OldConfig.Get <bool>(TwitchCfg.EnableFun);
            Channel  = OldConfig.Get <string>(TwitchCfg.Channel);

            if (ShowDebug)
            {
                Razorwing.Framework.Logging.Logger.Storage =
                    Storage; //Thx tML 0.11 for adding "Mod.Logger" <3 Breaking all as all ways
            }
            if (Fun)
            {
                //Since it not work on server (Not affect clients) until i write packets for this Twitch boss is disabled for server
                if (Main.netMode == NetmodeID.Server || Main.netMode == NetmodeID.SinglePlayer)
                {
                    TwitchBoss.InitialiseDefault();
                }


                //Register inner world event invasions
                foreach (Mod mod in ModLoader.Mods)
                {
                    foreach (TypeInfo it in mod.GetType().Assembly.DefinedTypes)
                    {
                        if (!it.IsAbstract && (
                                it.BaseType != typeof(object) && it.BaseType == typeof(WorldEvent) ||
                                it.BaseType?.BaseType != typeof(object) && it.BaseType?.BaseType == typeof(WorldEvent))
                            ) //In case if WorldEvent is second parent
                        {
                            try
                            {
                                EventsPool.Add((WorldEvent)Activator.CreateInstance(it));
                            }
                            catch (Exception e)
                            {
                                Logger.Error(
                                    "Exception caught in Events register loop. Report mod author with related stacktrace: \n" +
                                    $"{e.Message}\n" +
                                    $"{e.StackTrace}\n");
                            }
                        }
                    }
                }
            }


            if (ShowDebug)
            {
                Irc.ServerMessage += (s, m) =>
                {
                    try
                    {
                        Text(m);
                    }
                    catch (Exception)
                    {
                        Logger.Warn("Failed to post message");
                    }
                }
            }
            ;

            Irc.OnConnect += (s, e) =>
            {
                LastStatus.Value = $"[c/{TwitchColor}:Connected]";

                Irc.SendRaw("CAP REQ :twitch.tv/tags");
                Thread.Sleep(500);
                Irc.SendRaw("CAP REQ :twitch.tv/commands");
                Thread.Sleep(500);
                Irc.JoinChannel(Channel);

                inRestoringState = false;
            };

            Irc.ConnectionClosed += (s, e) =>
            {
                if (!inRestoringState)
                {
                    LastStatus.Value = $"[c/{TwitchColor}:Connection lost!]";
                    inRestoringState = true;
                    Thread.Sleep(5000);
                    Irc.Connect();
                }
                else
                {
                    LastStatus.Value = $"[c/{TwitchColor}:Connection terminated! Client now offline]";
                }
            };

            Irc.ChannelMessage += (s, e) =>
            {
                if (Main.netMode != NetmodeID.Server && !Main.gameMenu)
                {
                    //If we ignore commands, we also want ignore bots messages
                    if (IgnoreCommands)
                    {
                        if (e.Message.StartsWith(CommandPrefix))
                        {
                            return;
                        }
                        //In case you self bot, we ignore your own messages
                        if (e.From == Username)
                        {
                            return;
                        }
                        //if message was send by known bot, we ignore it
                        if (KnownBots.Contains(e.From))
                        {
                            return;
                        }
                    }

                    var result = e.Message;

                    var parsed = new List <SEmote>();

                    foreach (var it in e.Badge.emotes)
                    {
                        if (it == string.Empty)
                        {
                            break;
                        }
                        string[] pair = it.Split(':');
                        string[] ind  = pair[1].Split(',');
                        parsed.AddRange(ind.Select(p =>
                        {
                            string[] ip = p.Split('-');
                            return(new SEmote(ip[0], ip[1], pair[0]));
                        }));
                    }

                    if (parsed.Count != 0)
                    {
                        var list = new Dictionary <int, string>();
                        foreach (SEmote it in parsed)
                        {
                            if (list.ContainsKey(it.Emote))
                            {
                                continue;
                            }
                            var st = e.Message.Substring(it.Start, it.End - it.Start + 1);

                            //Not perfect because if Kappa mentioned in msg KappaPride get broken,
                            //but it way faster what per glyph concat
                            result = result.Replace(st, $"[e:{it.Emote}]");

                            list.Add(it.Emote, st);
                        }

                        foreach (KeyValuePair <int, string> em in list)
                        {
                            if (!EmoticonHandler.convertingEmotes.ContainsKey(em.Value))
                            {
                                EmoticonHandler.convertingEmotes.Add(em.Value, em.Key);
                            }
                        }
                    }
                    else
                    {
                        result = e.Message;
                    }


                    var prefix = "";
                    if (e.Badge.sub)
                    {
                        prefix += $"[i:{ItemID.Star}] ";
                    }
                    if (e.Badge.mod)
                    {
                        prefix += $"[i:{ItemID.Arkhalis}]";
                    }

                    //String format
                    Main.NewText($@"{prefix} [c/{TwitchColor}:{e.Badge.DisplayName}]: {result}");

                    if (!RecentChatters.Contains(e.Badge.DisplayName))
                    {
                        RecentChatters.Add(e.Badge.DisplayName);
                    }
                }

                if ((Main.netMode == NetmodeID.Server || Main.netMode == NetmodeID.SinglePlayer) && Fun)
                {
                    if (e.Message.StartsWith(CommandPrefix))
                    {
                        return;
                    }
                    //In case you self bot, we ignore your own messages
#if !DEBUG
                    if (e.From == Username)
                    {
                        return;
                    }
#endif
                    //if message was sent by known bot, we ignore it
                    if (KnownBots.Contains(e.From))
                    {
                        return;
                    }


                    //var word = e.Message.ToLower().Split(' ').First();

                    //if (CurrentPool?.ContainsKey(word) ?? false)
                    //{
                    //    CurrentPool[word]?.Invoke(e);
                    //}
                    if (e.From == TwitchBoss.Boss && TwitchBoss.Cooldown < DateTimeOffset.Now)
                    {
                        TwitchBoss.ProcessCommand(e);
                    }
                }
            };

            if (OldConfig.Get <bool>(TwitchCfg.AutoConnect) && OldConfig.Get <string>(TwitchCfg.OAToken) !=
                "https://twitchapps.com/tmi/" &&
                OldConfig.Get <string>(TwitchCfg.Username) != "missingno")
            {
                Irc.Username  = OldConfig.Get <string>(TwitchCfg.Username);
                Irc.AuthToken = OldConfig.Get <string>(TwitchCfg.OAToken);
                Irc.Connect();
            }

            WorldGen.SpawnTownNPC += SpawnTownNpcHook;
        }
        public override void Load()
        {
            // Load movedb

            BaseMove.LoadMoveDb();

            // Initalize Discord RP on Mod Load
            if (!Main.dedServ)
            {
                client        = new DiscordRpcClient("790364236554829824");
                client.Logger = new ConsoleLogger()
                {
                    Level = LogLevel.Warning
                };
                //

                Logger.Info("Attempting to establish Discord RP connection");

                // Subscribe to events
                client.OnReady += (sender, e) =>
                {
                    Logger.Info("Established connection");
                    Console.WriteLine("Received Ready from user {0}", e.User.Username);
                };

                client.OnPresenceUpdate += (sender, e) =>
                {
                    Console.WriteLine("Received Update! {0}", e.Presence);
                };

                client.OnError += (sender, e) =>
                {
                    Logger.Error("Could not start Discord RP. Reason: " + e.Message);
                };

                //Connect to the RPC
                client.Initialize();

                client.SetPresence(new RichPresence()
                {
                    Details = "In Menu",
                    State   = "Playing v0.4.2",
                    Assets  = new Assets()
                    {
                        LargeImageKey  = "largeimage2",
                        LargeImageText = "Merry Christmas!"
                    }
                });
            }

            BaseMove._mrand = new UnifiedRandom(BaseMove._seed = new Random().Next());
            //Load all mons to a store
            LoadPokemons();

            if (Main.netMode != NetmodeID.Server)
            {
                if (Localisation == null)
                {
                    Localisation = new LocalisationManager(locale);
                }
                locale = new Bindable <string>(Language.ActiveCulture.Name);

                storage = new ModStorage("Terramon");                                                                  //Initialise local resource store
                Store   = new ResourceStore <byte[]>(new EmbeddedStore());                                             //Make new instance of ResourceStore with dependency what loads data from ModStore
                Store.AddStore(new StorageCachableStore(storage, new WebStore()));                                     //Add second dependency what checks if data exist in local store.
                                                                                                                       //If not and provided URL load data from web and save it on drive
                Textures = new Texture2DStore(Store);                                                                  //Initialise cachable texture store in order not creating new texture each call

                Localisation.AddLanguage(GameCulture.English.Name, new LocalisationStore(Store, GameCulture.English)); //Adds en-US.lang file handling
                Localisation.AddLanguage(GameCulture.Russian.Name, new LocalisationStore(Store, GameCulture.Russian)); //Adds ru-RU.lang file handling
#if DEBUG
                UseWebAssets = true;
                var ss = Localisation.GetLocalisedString(new LocalisedString(("title", "Powered by broken code")));//It's terrible checking in ui from phone, so i can ensure everything works from version string
                //Main.versionNumber = ss.Value + "\n" + Main.versionNumber;
#endif
                Ref <Effect> screenRef      = new Ref <Effect>(GetEffect("Effects/ShockwaveEffect")); // The path to the compiled shader file.
                Ref <Effect> whiteShaderRef = new Ref <Effect>(GetEffect("Effects/whiteshader"));     // The path to the compiled shader file.
                Filters.Scene["Shockwave"] = new Filter(new ScreenShaderData(screenRef, "Shockwave"), EffectPriority.VeryHigh);
                Filters.Scene["Shockwave"].Load();
                GameShaders.Misc["WhiteTint"] = new MiscShaderData(whiteShaderRef, "ArmorBasic");

                ChooseStarter = new ChooseStarter();
                ChooseStarter.Activate();
                ChooseStarterBulbasaur = new ChooseStarterBulbasaur();
                ChooseStarterBulbasaur.Activate();
                ChooseStarterCharmander = new ChooseStarterCharmander();
                ChooseStarterCharmander.Activate();
                ChooseStarterSquirtle = new ChooseStarterSquirtle();
                ChooseStarterSquirtle.Activate();
                PokegearUI = new PokegearUI();
                PokegearUI.Activate();
                PokegearUIEvents = new PokegearUIEvents();
                PokegearUIEvents.Activate();
                evolveUI = new EvolveUI();
                evolveUI.Activate();
                UISidebar = new UISidebar();
                UISidebar.Activate();
                Moves = new Moves();
                Moves.Activate();
                PartySlots = new PartySlots();
                PartySlots.Activate();
                _exampleUserInterface    = new UserInterface();
                _exampleUserInterfaceNew = new UserInterface();
                PokegearUserInterfaceNew = new UserInterface();
                evolveUserInterfaceNew   = new UserInterface();
                _uiSidebar  = new UserInterface();
                _moves      = new UserInterface();
                _partySlots = new UserInterface();
                _battle     = new UserInterface();
                ParentPokemonNPC.HighlightTexture = new Dictionary <string, Texture2D>();
                ParentPokemon.HighlightTexture    = new Dictionary <string, Texture2D>();

                //_exampleUserInterface.SetState(ChooseStarter); // Choose Starter
#if DEBUG
                _exampleUserInterface.SetState(new TestState());
#endif
                _exampleUserInterfaceNew.SetState(PokegearUI);       // Pokegear Main Menu
                PokegearUserInterfaceNew.SetState(PokegearUIEvents); // Pokegear Events Menu
                evolveUserInterfaceNew.SetState(evolveUI);
                _uiSidebar.SetState(UISidebar);
                _moves.SetState(Moves);
                _partySlots.SetState(PartySlots);
                _battle.SetState(BattleMode.UI = new BattleUI());// Automatically assign shortcut

                summaryUI = new AnimatorUI();
                summaryUI.Activate();

                summaryUIInterface = new UserInterface();
                summaryUIInterface.SetState(summaryUI);
            }


            if (Main.dedServ)
            {
                return;
            }

            Scheduler = new Scheduler(Thread.CurrentThread, schedulerClock = new GameTimeClock());

            FirstPKMAbility  = RegisterHotKey("First Pokémon Move", Keys.Z.ToString());
            SecondPKMAbility = RegisterHotKey("Second Pokémon Move", Keys.X.ToString());
            ThirdPKMAbility  = RegisterHotKey("Third Pokémon Move", Keys.C.ToString());
            FourthPKMAbility = RegisterHotKey("Fourth Pokémon Move", Keys.V.ToString());

            CompressSidebar = RegisterHotKey("Compress Sidebar", Keys.RightShift.ToString());

            PartyCycle = RegisterHotKey("Quick Spawn First Party Pokémon", Keys.RightAlt.ToString());
        }