Пример #1
0
        /// <summary>
        /// Loads all necessary components and starts the server.
        /// </summary>
        public void Run()
        {
            if (_running)
            {
                throw new Exception("Server is already running.");
            }

            int x, y, width, height;

            GetWindowPosition(out x, out y, out width, out height);
            SetWindowPosition(width + 5, height + 5, width, height);

            ConsoleUtil.WriteHeader("Area Server", ConsoleColor.DarkGreen);
            ConsoleUtil.LoadingTitle();

            NavigateToRoot();

            // Conf
            LoadConf(Config = new AreaConf());

            // Database
            InitDatabase(Database = new AreaDatabase(), Config);

            // Start
            Server = new DefaultServer(Config.Area.Port, false);
            Server.Start();

            var Server2 = new DefaultServer(11041, false);

            Server2.Start();

            ConsoleUtil.RunningTitle();
            _running = true;

            // Commands
            var commands = new AreaConsoleCommands();

            commands.Wait();
        }
Пример #2
0
        private static void BTMMMenu()
        {
            var userChoice = 0;

            while (true)
            {
                userChoice = GetUserChoice(
                    "BTMM Menu", new[]
                {
                    "<- Back",
                    BTMMAlgorithm.IsModelReady() ? "* Status: READY" : "* Status: NOT READY!!",
                    "Train",
                    "Load",
                    "Read Log"
                }, userChoice);

                if (userChoice == 0)
                {
                    return;
                }
                if (userChoice == 1)
                {
                    CheckModelReady();
                }
                else if (userChoice == 2)
                {
                    TrainMenu();
                }
                else if (userChoice == 3)
                {
                    LoadMenu();
                }
                else
                {
                    ConsoleUtil.WriteAndWaitKey(GameLogger.ReadLog());
                }
            }
        }
Пример #3
0
        /// <summary>
        ///     Loads all necessary components and starts the server.
        /// </summary>
        public void Run()
        {
            if (_running)
            {
                throw new Exception("Server is already running.");
            }

            int x, y, width, height;

            Win32.GetWindowPosition(out x, out y, out width, out height);
            Win32.SetWindowPosition(0, 0, width, height);

            ConsoleUtil.WriteHeader($"Auth Server ({Shared.Util.Version.GetVersion()})", ConsoleColor.DarkGreen);
            ConsoleUtil.LoadingTitle();

            Log.Info("Server startup requested");
            Log.Info($"Server Version {Shared.Util.Version.GetVersion()}");

            NavigateToRoot();

            // Conf
            LoadConf(Config = new AuthConf());

            // Database
            InitDatabase(Database = new AuthDatabase(), Config);

            // Start
            Server = new DefaultServer(Config.Auth.Port);
            Server.Start();

            ConsoleUtil.RunningTitle();
            _running = true;

            // Commands
            var commands = new AuthConsoleCommands();

            commands.Wait();
        }
Пример #4
0
        void DisplayProgress(object s, ElapsedEventArgs e)
        {
            int    files, dirs;
            long   bytesThisInterval;
            long   elapsedMs;
            long   msInterval;
            string fileName;

            lock (_lockStats)
            {
                files = numFilesScanned;

                // Currently not using dirs completed, but keep them in case we want them later
                dirs = numDirectoriesScanned;

                // Currently not using interval times or interval bytes, but keep them in case we want them later
                bytesThisInterval = totalBytesScanned - lastBytesScanned;
                lastBytesScanned  = totalBytesScanned;

                elapsedMs = progressStopwatch.ElapsedMilliseconds;
                fileName  = lastFileScanned;
            }

            // Currently not using interval times or interval bytes, but keep them in case we want them later
            msInterval    = elapsedMs - lastElapsedMs;
            lastElapsedMs = elapsedMs;

            double readSpeedBytesPerMin = ((double)lastBytesScanned) / (elapsedMs / (MillisecondsPerSecond * SecondsPerMinute));

            lock (ConsoleUtil._lockGlobalConsole)
            {
                ConsoleColor color = (lastFileWasUnique) ? ConsoleColor.White : ConsoleColor.Yellow;

                ConsoleUtil.WriteColor(String.Format(ProgressFormat, backspaces, spaces, files, FileUtil.FormatByteSize(lastBytesScanned), TimerUtil.FormatMilliseconds(lastElapsedMs),
                                                     FileUtil.FormatByteSize((long)readSpeedBytesPerMin), FileUtil.TrimFileName(fileName, ConsoleMaxFileNameLength)),
                                       color);
            }
        }
Пример #5
0
        public static List <CPet> LoadPetShell(string name)
        {
            for (int i = 0; i < 5; i++)
            {
                try
                {
                    var    path         = Path(name);
                    Stream ws           = new FileStream(path, FileMode.OpenOrCreate);
                    var    deserializer = new BinaryFormatter();

                    var result = (List <CPet>)deserializer.Deserialize(ws);
                    ws.Close();

                    return(result);
                }
                catch (Exception)
                {
                    ConsoleUtil.WriteColor("Retrying...");
                }
            }

            return(null);
        }
Пример #6
0
        private void init()
        {
            Random      = new Random();
            renderer    = new Renderer(50, 25);
            PlayHandler = new MusicPlayHandler(musicFolder);
            Me          = this;
            IsEnabled   = true;

            // Console Settings
            Console.OutputEncoding = Encoding.UTF8;
            Console.CursorVisible  = false;
            ConsoleUtil.FixConsoleWindowSize();

            // Keyboard
            keyBoardHandler = new KeyBoardHandler();
            // 可以非硬编码,由配置文件决定
            keyBoardHandler.Register(ConsoleKey.Q, () => { Exit(); });
            keyBoardHandler.Register(ConsoleKey.N, () => { PlayHandler.SwitchNextSong(); });
            keyBoardHandler.Register(ConsoleKey.M, () => { PlayHandler.SwitchPrevSong(); });
            keyBoardHandler.Register(ConsoleKey.S, () => { PlayHandler.Stop(); });
            keyBoardHandler.Register(ConsoleKey.A, () => { PlayHandler.Play(); });
            keyBoardHandler.Register(ConsoleKey.P, () => { PlayHandler.Pause(); });
        }
Пример #7
0
 public static void Start()
 {
     Directory.CreateDirectory("Dependencies");
     new System.Threading.Thread(async() =>
     {
         if (!File.Exists("Dependencies/discord-rpc.dll"))
         {
             await DownloadDiscordDLL();
         }
         else
         {
             if (File.ReadAllBytes("Dependencies/discord-rpc.dll").Length <= 0)
             {
                 await DownloadDiscordDLL();
             }
         }
         ConsoleUtil.Info("[DEBUG] Started Rich Presence.");
         eventHandlers           = default;
         presence.details        = "A very cool public free cheat";
         presence.state          = "Starting Game...";
         presence.largeImageKey  = "MClient_logo"; // YAEKITH STOP TOUCHING DISCORD RPC
         presence.smallImageKey  = "small_MClient";
         presence.largeImageText = "MClient Client By Yaekith/404";
         presence.joinSecret     = "MTI4NzM0OjFpMmhuZToxMjMxMjM=";
         presence.spectateSecret = "MTIzNDV8MTIzNDV8MTMyNDU0";
         presence.smallImageText = GeneralUtils.Version;
         presence.partyId        = "ae488379-351d-4a4f-ad32 2b9b01c91657";
         presence.partySize      = 0;
         presence.partyMax       = 0;
         presence.startTimestamp = (long)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
         StartClient();
         Timer timer     = new Timer(15000.0);
         timer.Elapsed  += Update;
         timer.AutoReset = true;
         timer.Enabled   = true;
     }).Start();
 }
Пример #8
0
        private IEnumerable <object> recurseImpl(BigInteger taken, int x, int y)
        {
            _debugCounter++;
            if (_debugCounter == 100000)
            {
                var len = (_max + 1).ToString().Length;
                Console.Clear();
                ConsoleUtil.WriteLine(Enumerable.Range(0, _max).Select(row => _grid.Subarray(_max * row, _max).Select((i, col) => i.ToString().PadLeft(len).Color(row < y || (row == y && col < x) ? ConsoleColor.White : ConsoleColor.Red)).JoinColoredString(" ")).JoinColoredString("\n"));
                _debugCounter = 0;
            }

            var ix     = y * _height + x;
            var offset = _grid[ix];

            for (int i = 0; i < _max; i++)
            {
                var j = (i + offset) % _max;
                if ((taken & (BigInteger.One << (j + _maxPlusOne * (x + _width * y)))) != 0)
                {
                    continue;
                }
                var newTaken = taken | (_adders[x][y] << j);
                if (_extraTaken != null)
                {
                    newTaken |= _extraTaken(_grid, y * _width + x, j);
                }
                if (((newTaken + _oneOfEach) & _overhang & (BigInteger.MinusOne << (_maxPlusOne * (x + 1 + _width * y)))) != 0)
                {
                    continue;
                }
                _grid[ix] = j;
                foreach (var result in recurse(newTaken, x + 1, y))
                {
                    yield return(result);
                }
            }
        }
Пример #9
0
        private void HandleShowUser(string module, string[] cmd)
        {
            if (cmd.Length < 3)
            {
                MainConsole.Instance.OutputFormat("Usage: show name <uuid>");
                return;
            }

            UUID userId;

            if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, cmd[2], out userId))
            {
                return;
            }

            string[] names;

            UserData ud;

            lock (m_UserCache)
            {
                if (!m_UserCache.TryGetValue(userId, out ud))
                {
                    MainConsole.Instance.OutputFormat("No name known for user with id {0}", userId);
                    return;
                }
            }

            ConsoleDisplayTable cdt = new ConsoleDisplayTable();

            cdt.AddColumn("UUID", 36);
            cdt.AddColumn("Name", 30);
            cdt.AddColumn("HomeURL", 40);
            cdt.AddRow(userId, string.Format("{0} {1}", ud.FirstName, ud.LastName), ud.HomeURL);

            MainConsole.Instance.Output(cdt.ToString());
        }
Пример #10
0
 private static void RetrievePatches()
 {
     try
     {
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("KickUserRPC"), GetLocalPatch("AntiKick"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("Method_Public_Boolean_String_String_String_1"), GetLocalPatch("CanEnterPublicWorldsPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("Method_Public_Boolean_String_String_String_0"), GetLocalPatch("IsKickedFromWorldPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("Method_Public_Boolean_String_8"), GetLocalPatch("IsBlockedEitherWayPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("BlockStateChangeRPC"), GetLocalPatch("AntiBlock"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("ForceLogoutRPC"), GetLocalPatch("AntiLogout"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("BanPublicOnlyRPC"), GetLocalPatch("AntiPublicBan"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("FriendStateChangeRPC"), GetLocalPatch("FriendPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("BanRPC"), GetLocalPatch("BanPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("MuteChangeRPC"), GetLocalPatch("MutePatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("ShowUserAvatarChangedRPC"), GetLocalPatch("AvatarShownPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("WarnUserRPC"), GetLocalPatch("WarnPatch"), null);
         new Patch("Ethos_Moderation", typeof(ModerationManager).GetMethod("ModForceOffMicRPC"), GetLocalPatch("ModForceOffMicPatch"), null);
         new Patch("Ethos_Moderation", typeof(VRC_TriggerInternal).GetMethod("OnPlayerJoined"), GetLocalPatch("OnPlayerJoin"), null);
         new Patch("Ethos_Moderation", typeof(VRC_TriggerInternal).GetMethod("OnPlayerLeft"), GetLocalPatch("OnPlayerLeave"), null);
         new Patch("Ethos_Extras", typeof(UserInteractMenu).GetMethod("Update"), GetLocalPatch("CloneAvatarPrefix"), null);
         new Patch("Ethos_Extras", AccessTools.Method(typeof(Il2CppSystem.Console), "WriteLine", new Type[] { typeof(string) }), GetLocalPatch("IL2CPPConsoleWriteLine"), null);
         new Patch("Ethos_Extras", typeof(ImageDownloader).GetMethod("DownloadImage"), GetLocalPatch("AntiIpLogImage"), null);
         new Patch("Ethos_Extras", typeof(VRCSDK2.VRC_SyncVideoPlayer).GetMethod("AddURL"), GetLocalPatch("AntiVideoPlayerHijacking"), null);
         new Patch("Ethos_Extras", typeof(VRCSDK2.VRC_SyncVideoPlayer).GetMethods().FirstOrDefault(x => x.Name == "Play" && x.GetParameters().Count() == 0), GetLocalPatch("VideoPlayerPatch"), null);
         new Patch("Ethos_Extras", typeof(PortalInternal).GetMethod("Method_Public_Void_3"), GetLocalPatch("EnterPortalPatch"), null);
         new Patch("Ethos_Extras", typeof(VRC_EventHandler).GetMethod("InternalTriggerEvent"), GetLocalPatch("TriggerEvent"), null);
         new Patch("Ethos_Poggers", typeof(VRC.SDKBase.Networking).GetProperty("IsNetworkSettled").GetGetMethod(), GetLocalPatch("SettledPatch"), null);
         new Patch("Ethos_Extras", typeof(ObjectPublicIPhotonPeerListenerObStBoStObCoDiBo2ObUnique).GetMethod("Method_Public_Virtual_New_Boolean_Byte_Object_ObjectPublicObByObInByObObUnique_SendOptions_0"), GetLocalPatch("OpRaiseEventPrefix"), null);
     }
     catch (Exception e) { if (GeneralUtils.IsDevBranch)
                           {
                               Console.WriteLine(e.ToString());
                           }
     }
     finally { ConsoleUtil.Info("All Patches have been applied successfully."); }
 }
            ///<summary>
            ///get the minimum and maximum values for rooms available query
            ///</summary>
            ///<parameter name = minimumvertical>minimum rooms available</parameter>
            ///<parameter name = maximumvertical>maximum rooms available</parameter>

            public static void GetRoomsAvailableQueryMinMaxValues(out int minimumRoomsAvailable, out int maximumRoomsAvailable)
            {
                minimumRoomsAvailable = 0;
                maximumRoomsAvailable = 0;
                string userResponse = "";

                DisplayReset();

                DisplayMessage("");
                Console.WriteLine(ConsoleUtil.Center("Please Query The Hotels By Rooms Available", WINDOW_WIDTH));
                DisplayMessage("");

                DisplayPromptMessage("Please Enter The Minimum Rooms Available: ");
                userResponse = Console.ReadLine();
                if (userResponse != "")
                {
                    minimumRoomsAvailable = ConsoleUtil.ValidateIntegerResponse("Please Enter the New Minimum Rooms Available.", userResponse);

                }
                DisplayMessage("");

                DisplayPromptMessage("Please Enter The Maximum Rooms Available: ");
                userResponse = Console.ReadLine();
                if (userResponse != "")
                {
                    maximumRoomsAvailable = ConsoleUtil.ValidateIntegerResponse("Please Enter The New Maximum RoomsAvailable.", userResponse);

                }
                DisplayMessage("");

                DisplayMessage(String.Format("You Have Entered {0} Rooms As The Minimum Value and {1} As The Maximum Value.", minimumRoomsAvailable, maximumRoomsAvailable));

                DisplayMessage("");
                DisplayContinuePrompt();

            }
Пример #12
0
        public void LoadingTitle()
        {
            // Currently failing on Travis for some reason o.o
            if (ConsoleUtil.CheckMono())
            {
                return;
            }

            var sw   = new StringWriter();
            var cout = Console.Out;

            Console.SetOut(sw);

            ConsoleUtil.WriteHeader("Yggdrasil", "Tests", Logo, ConsoleColor.Blue, Credits);
            Assert.Equal("Yggdrasil : Tests", Console.Title);

            ConsoleUtil.LoadingTitle();
            Assert.Equal("* Yggdrasil : Tests", Console.Title);

            ConsoleUtil.RunningTitle();
            Assert.Equal("Yggdrasil : Tests", Console.Title);

            Console.SetOut(cout);
        }
Пример #13
0
        private static void LoadMenu()
        {
            var userChoice = 0;

            while (true)
            {
                userChoice = GetUserChoice(
                    "Load BTMM Menu", new[]
                {
                    "<- Back",
                    $"Trained file: {_saveTrainedFilePath}",
                    "Load now!"
                }, userChoice);

                if (userChoice == 0)
                {
                    return;
                }
                if (userChoice == 1)
                {
                    _saveTrainedFilePath = (string)ConsoleUtil.Prompt("Trained data file", _saveTrainedFilePath);
                }
                else
                {
                    try
                    {
                        BTMMAlgorithm.LoadTrainedData(_saveTrainedFilePath);
                        ConsoleUtil.WriteAndWaitKey("> Load Done.");
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteAndWaitKey($"[!] ERROR: {e}");
                    }
                }
            }
        }
Пример #14
0
        public void Execute(CommandLine commandLine, CommandExecutionContext context)
        {
            if (commandLine.Parameters.Count != 2)
            {
                ConsoleUtil.ErrorLine("Invalid request. Please check syntax: " + Usage);
                return;
            }

            var hostFile = context.Hosts;

            var host = commandLine.Parameters[1];
            var ip   = commandLine.Parameters[0];

            if (!hostFile.Contains(host))
            {
                ConsoleUtil.ErrorLine(host + " was not found");
            }
            else
            {
                hostFile.Set(ip, host);
                hostFile.Save();
                Console.WriteLine("1 entry updated: " + ip + " " + host);
            }
        }
            ///<summary>
            ///update the hotel's information
            ///</summary>

            public static Hotel UpdateHotels(Hotel hotel)
            {
                string userResponse = "";
                //int hotelID = 0;
                //int hotelID = 1;
                DisplayReset();

                DisplayMessage("");
                Console.WriteLine(ConsoleUtil.Center("Please Edit A Hotel's Information",
                    WINDOW_WIDTH));
                DisplayMessage("");

                  
                DisplayMessage(String.Format("Current Name: {0}", hotel.Name));
                
                DisplayPromptMessage("Please Enter A New Hotel Name or Just Hit Enter To Keep The Current One: ");
                userResponse = Console.ReadLine();
                if (userResponse != "")
                {
                    hotel.Name = userResponse;
                }

                DisplayMessage("");

                DisplayMessage(String.Format("Current Rooms Available: {0}", hotel.RoomsAvailable.ToString()));
                DisplayPromptMessage("Please Enter The New Number Of Rooms Available Or Just Hit Enter To Keep The Current Rooms Available: ");
                userResponse = Console.ReadLine();

                if (userResponse != "")
                {
                    hotel.RoomsAvailable = ConsoleUtil.ValidateIntegerResponse("Please Enter the New Number Of Rooms Available.", userResponse);
                    DisplayContinuePrompt();

                }
                return hotel;
            }
Пример #16
0
        private void HandleRemoveBehaviour(string module, string[] cmd)
        {
            if (cmd.Length < 3 || cmd.Length > 4)
            {
                MainConsole.Instance.Output("Usage: remove behaviour <abbreviated-behaviour> [<bot-number>]");
                return;
            }

            string rawBehaviours = cmd[2];

            List <Bot> botsToEffect = new List <Bot>();

            if (cmd.Length == 3)
            {
                lock (m_bots)
                    botsToEffect.AddRange(m_bots);
            }
            else
            {
                int botNumber;
                if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, cmd[3], out botNumber))
                {
                    return;
                }

                Bot bot = GetBotFromNumber(botNumber);

                if (bot == null)
                {
                    MainConsole.Instance.Output("Error: No bot found with number {0}", null, botNumber);
                    return;
                }

                botsToEffect.Add(bot);
            }

            HashSet <string> abbreviatedBehavioursToRemove = new HashSet <string>();

            Array.ForEach <string>(rawBehaviours.Split(new char[] { ',' }), b => abbreviatedBehavioursToRemove.Add(b));

            foreach (Bot bot in botsToEffect)
            {
                List <IBehaviour> behavioursRemoved = new List <IBehaviour>();

                foreach (string b in abbreviatedBehavioursToRemove)
                {
                    IBehaviour behaviour;

                    if (bot.TryGetBehaviour(b, out behaviour))
                    {
                        bot.RemoveBehaviour(b);
                        behavioursRemoved.Add(behaviour);
                    }
                }

                MainConsole.Instance.Output(
                    "Removed behaviours {0} from bot {1}",
                    null,
                    string.Join(", ", behavioursRemoved.ConvertAll <string>(b => b.Name).ToArray()), bot.Name);
            }
        }
Пример #17
0
        public override void OnPlayerJoin(VRCPlayerApi player)
        {
            var _player = GeneralWrappers.GetPlayerManager().GetPlayer(player);

            if (_player == null)
            {
                return;
            }

            var apiuser = _player.GetAPIUser();

            if (apiuser == null)
            {
                return;
            }

            if (GeneralUtils.Authorities.TryGetValue(apiuser.id, out string what))
            {
                //im gonna use the what for later ok
                player.SetNamePlateColor(Color.cyan);
                ConsoleUtil.Info($"A Client admin || {apiuser.displayName} has joined.");
            }

            if (GeneralUtils.CantHearOnNonFriends)
            {
                if (!APIUser.IsFriendsWith(apiuser.id))
                {
                    _player.GetVRCPlayer().field_Internal_Boolean_3 = false;
                }
            }

            if (Configuration.GetConfig().LogModerations)
            {
                GeneralUtils.InformHudText(Color.green, $"{apiuser.displayName} has joined.");
            }

            if (Configuration.GetConfig().AntiPhotonBot)
            {
                if (_player.GetAPIUser().statusIsSetToOffline&& _player.GetVRCPlayer().prop_Int16_0 == 0)
                {
                    //most likely photon bot lol, they're offline on the api and their ping is spoofed to 0, this is suspicious as f**k ok
                    GeneralUtils.InformHudText(Color.red, $"{_player.GetAPIUser().displayName} is detected as a photon bot\n User is now removed !");
                    UnityEngine.Object.Destroy(_player.GetVRCPlayer().gameObject);
                    UnityEngine.Object.Destroy(_player.gameObject);
                }
            }

            if (GeneralUtils.DestroyUSpeakOnPlayerJoin)
            {
                UnityEngine.Object.Destroy(_player.GetVRCPlayer().GetUSpeaker().gameObject);
            }

            if (GeneralUtils.ESP)
            {
                GameObject[] array = GameObject.FindGameObjectsWithTag("Player");
                for (int i = 0; i < array.Length; i++)
                {
                    if (array[i].transform.Find("SelectRegion"))
                    {
                        array[i].transform.Find("SelectRegion").GetComponent <Renderer>().material.SetColor("_Color", Color.red);
                        array[i].transform.Find("SelectRegion").GetComponent <Renderer>().sharedMaterial.SetColor("_Color", Color.magenta);
                        GeneralWrappers.GetHighlightsFX().EnableOutline(array[i].transform.Find("SelectRegion").GetComponent <Renderer>(), GeneralUtils.ESP);
                    }
                }
            }
        }
Пример #18
0
        private void HandleThrottleSetCommand(string module, string[] args)
        {
            if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene)
            {
                return;
            }

            bool all = args.Length == 6;
            bool one = args.Length == 8;

            if (!all && !one)
            {
                MainConsole.Instance.Output(
                    "Usage: debug lludp throttles set <param> <value> [<avatar-first-name> <avatar-last-name>]");
                return;
            }

            string param    = args[4];
            string rawValue = args[5];

            string firstName = null;
            string lastName  = null;

            if (one)
            {
                firstName = args[6];
                lastName  = args[7];
            }

            if (param == "adaptive")
            {
                bool newValue;
                if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newValue))
                {
                    return;
                }

                m_udpServer.Scene.ForEachScenePresence(sp =>
                {
                    if (all || (sp.Firstname == firstName && sp.Lastname == lastName))
                    {
                        MainConsole.Instance.Output(
                            "Setting param {0} to {1} for {2} ({3}) in {4}",
                            param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name);

                        LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient;
                        udpClient.FlowThrottle.AdaptiveEnabled = newValue;
                        //                        udpClient.FlowThrottle.MaxDripRate = 0;
                        //                        udpClient.FlowThrottle.AdjustedDripRate = 0;
                    }
                });
            }
            else if (param == "request")
            {
                int newValue;
                if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue))
                {
                    return;
                }

                int newCurrentThrottleKbps = newValue * 1000 / 8;

                m_udpServer.Scene.ForEachScenePresence(sp =>
                {
                    if (all || (sp.Firstname == firstName && sp.Lastname == lastName))
                    {
                        MainConsole.Instance.Output(
                            "Setting param {0} to {1} for {2} ({3}) in {4}",
                            param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name);

                        LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient;
                        udpClient.FlowThrottle.RequestedDripRate = newCurrentThrottleKbps;
                    }
                });
            }
            else if (param == "max")
            {
                int newValue;
                if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue))
                {
                    return;
                }

                int newThrottleMaxKbps = newValue * 1000 / 8;

                m_udpServer.Scene.ForEachScenePresence(sp =>
                {
                    if (all || (sp.Firstname == firstName && sp.Lastname == lastName))
                    {
                        MainConsole.Instance.Output(
                            "Setting param {0} to {1} for {2} ({3}) in {4}",
                            param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name);

                        LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient;
                        udpClient.FlowThrottle.MaxDripRate = newThrottleMaxKbps;
                    }
                });
            }
        }
Пример #19
0
        public static void Main()
        {
            try
            {
                Console.Title = $"LMP {LmpVersioning.CurrentVersion}";

                Console.OutputEncoding  = Encoding.Unicode;
                ServerContext.StartTime = LunaNetworkTime.UtcNow.Ticks;

                LunaLog.Info("Remember! Quit the server by using 'Control + C' so a backup is properly made before closing!");

                if (Common.PlatformIsWindows())
                {
                    ExitSignal.Exit += (sender, args) => Exit();
                }
                else
                {
                    //Register the ctrl+c event and exit signal if we are on linux
                    Console.CancelKeyPress += (sender, args) => Exit();
                }

                //We disable quick edit as otherwise when you select some text for copy/paste then you can't write to the console and server freezes
                //This just happens on windows....
                if (Common.PlatformIsWindows())
                {
                    ConsoleUtil.DisableConsoleQuickEdit();
                }

                //We cannot run more than 6 instances ofd servers + clients as otherwise the sync time will fail (30 seconds / 5 seconds = 6) but we use 3 for safety
                if (GetRunningInstances() > 3)
                {
                    throw new HandledException("Cannot run more than 3 servers at a time!");
                }

                //Start the server clock
                ServerContext.ServerClock.Start();

                ServerContext.ServerStarting = true;

                //Set day for log change
                ServerContext.Day = LunaNetworkTime.Now.Day;

                LunaLog.Normal($"Luna Server version: {LmpVersioning.CurrentVersion} ({Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)})");

                Universe.CheckUniverse();
                LoadSettingsAndGroups();
                VesselStoreSystem.LoadExistingVessels();
                var scenariosCreated = ScenarioSystem.GenerateDefaultScenarios();
                ScenarioStoreSystem.LoadExistingScenarios(scenariosCreated);
                LmpPluginHandler.LoadPlugins();
                WarpSystem.Reset();

                LunaLog.Normal($"Starting '{GeneralSettings.SettingsStore.ServerName}' on Port {ConnectionSettings.SettingsStore.Port}... ");

                LidgrenServer.SetupLidgrenServer();
                LmpPortMapper.OpenLmpPort().Wait();
                LmpPortMapper.OpenWebPort().Wait();
                ServerContext.ServerRunning = true;
                WebServer.StartWebServer();

                //Do not add the command handler thread to the TaskContainer as it's a blocking task
                LongRunTaskFactory.StartNew(CommandHandler.ThreadMain, CancellationTokenSrc.Token);

                TaskContainer.Add(LongRunTaskFactory.StartNew(WebServer.RefreshWebServerInformation, CancellationTokenSrc.Token));

                TaskContainer.Add(LongRunTaskFactory.StartNew(LmpPortMapper.RefreshUpnpPort, CancellationTokenSrc.Token));
                TaskContainer.Add(LongRunTaskFactory.StartNew(LogThread.RunLogThread, CancellationTokenSrc.Token));
                TaskContainer.Add(LongRunTaskFactory.StartNew(ClientMainThread.ThreadMain, CancellationTokenSrc.Token));

                TaskContainer.Add(LongRunTaskFactory.StartNew(() => BackupSystem.PerformBackups(CancellationTokenSrc.Token), CancellationTokenSrc.Token));
                TaskContainer.Add(LongRunTaskFactory.StartNew(LidgrenServer.StartReceivingMessages, CancellationTokenSrc.Token));
                TaskContainer.Add(LongRunTaskFactory.StartNew(LidgrenMasterServer.RegisterWithMasterServer, CancellationTokenSrc.Token));

                TaskContainer.Add(LongRunTaskFactory.StartNew(VersionChecker.RefreshLatestVersion, CancellationTokenSrc.Token));
                TaskContainer.Add(LongRunTaskFactory.StartNew(VersionChecker.DisplayNewVersionMsg, CancellationTokenSrc.Token));

                while (ServerContext.ServerStarting)
                {
                    Thread.Sleep(500);
                }

                LunaLog.Normal("All systems up and running. Поехали!");
                LmpPluginHandler.FireOnServerStart();

                QuitEvent.WaitOne();

                LmpPluginHandler.FireOnServerStop();

                LunaLog.Normal("So long and thanks for all the fish!");
            }
            catch (Exception e)
            {
                LunaLog.Fatal(e is HandledException ? e.Message : $"Error in main server thread, Exception: {e}");
                Console.ReadLine(); //Avoid closing automatically
            }
        }
Пример #20
0
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Green;
            ConsoleUtil.SetConsoleCtrlHandler(new ConsoleUtil.ControlCtrlDelegate(HandlerRoutine), true);
            bool success = true;

            Console.WriteLine("正在初始化服务程序......");
            IObjectBuilder builder = new TypeCreator();

            _serverFactory = new ServerFactory();
            try
            {
                GlobalConfig gc = GlobalConfigTool.Load();
                foreach (ServerSuperIO.Config.Server serverCfg in gc.Servers)
                {
                    IServer server = _serverFactory.CreateServer(serverCfg.ServerConfig);
                    server.AddDeviceCompleted    += server_AddDeviceCompleted;
                    server.DeleteDeviceCompleted += server_DeleteDeviceCompleted;
                    server.Start();
                    _serverFactory.AddServer(server);

                    foreach (Config.Device devCfg in serverCfg.Devices)
                    {
                        try
                        {
                            IRunDevice runDev = builder.BuildUp <IRunDevice>(devCfg.AssemblyFile, devCfg.Instance);

                            runDev.DeviceParameter.DeviceID = devCfg.DeviceID;
                            runDev.DeviceDynamic.DeviceID   = devCfg.DeviceID;
                            runDev.CommunicateType          = devCfg.CommunicateType;
                            runDev.Initialize(devCfg.DeviceID);

                            if (server.AddDevice(runDev) != devCfg.DeviceID)
                            {
                                Console.WriteLine("增加设备:" + devCfg.DeviceID + " 失败!");
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            continue;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                success = false;
                Console.WriteLine(ex.Message);
            }

            if (success)
            {
                Console.WriteLine("初始化服务程序完成");
            }

            while ("exit" == Console.ReadLine())
            {
                _serverFactory.RemoveAllServer();
                break;
            }
        }
Пример #21
0
        public override void Init(LoggerBase log)
        {
#if DEBUG
            if (string.IsNullOrWhiteSpace(Settings.ConfigFile))
            {
                var config = new KtaneWebConfig();
                Console.WriteLine();
                ConsoleUtil.WriteLine("It appears that you are running KtaneWeb for the first time.".Color(ConsoleColor.White));
tryAgain1:
                ConsoleUtil.WriteLine(@"Please provide a location for the JSON settings file (for example: {0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(@"C:\Path\KtaneWeb.settings.json"));
                var path = Console.ReadLine();
                try
                {
                    ClassifyJson.SerializeToFile(config, path);
                }
                catch (Exception e)
                {
                    ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                    goto tryAgain1;
                }

                Console.WriteLine();
tryAgain2:
                ConsoleUtil.WriteLine("Do you already have a local clone of the KtaneContent repository that you want the website to use?".Color(ConsoleColor.White));
                Console.WriteLine("If yes, please type the full path to that repository. If no, just press Enter.");
                var ktaneContent       = Console.ReadLine();
                var expectedSubfolders = "HTML,More,JSON,Icons".Split(',');
                if (string.IsNullOrWhiteSpace(ktaneContent))
                {
                    ConsoleUtil.WriteLine(@"In that case we will create a new clone. I can do that automatically if you have git installed (if you don’t, please abort now).".Color(ConsoleColor.White));
                    ConsoleUtil.WriteLine("This will take a long time as the repository is large.".Color(ConsoleColor.White));
                    Console.WriteLine();
tryAgain3:
                    ConsoleUtil.WriteLine("Please choose a path where you would like all the data stored (for example: {0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(@"C:\Path\KtaneContent"));
                    var cloneFolder = Console.ReadLine();
                    try
                    {
                        Directory.CreateDirectory(cloneFolder);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain3;
                    }
                    try
                    {
                        config.BaseDir = Path.Combine(cloneFolder, "Public");
                        CommandRunner.Run("git", "clone", "https://github.com/Timwi/KtaneContent.git", config.BaseDir).Go();
                        config.MergedPdfsDir = Path.Combine(cloneFolder, "MergedPdfs");
                        Directory.CreateDirectory(config.MergedPdfsDir);
                        config.LogfilesDir = Path.Combine(cloneFolder, "Logfiles");
                        Directory.CreateDirectory(config.LogfilesDir);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain2;
                    }
                }
                else if (expectedSubfolders.Any(s => !Directory.Exists(Path.Combine(ktaneContent, s))))
                {
                    ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {"That folder does not appear to contain KtaneContent.".Color(ConsoleColor.Red)}", null);
                    ConsoleUtil.WriteLine("(We’re looking for a folder that contains subfolders named: {0/DarkMagenta})".Color(ConsoleColor.Magenta).Fmt(expectedSubfolders.JoinString(", ")));
                    goto tryAgain2;
                }
                else
                {
                    var p = ktaneContent;
                    while (p.EndsWith("\""))
                    {
                        p = Path.GetDirectoryName(p);
                    }
                    config.BaseDir = p;
                    p = Path.GetDirectoryName(p);

                    Console.WriteLine();
tryAgain4:
                    var logfiles = Path.Combine(p, "Logfiles");
                    ConsoleUtil.WriteLine("Please choose a path where you would like KtaneWeb to store logfiles uploaded through the Logfile Analyzer, or just press Enter to use the default ({0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(logfiles));
                    config.LogfilesDir = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(config.LogfilesDir))
                    {
                        ConsoleUtil.WriteLine("Using default: {0/DarkCyan}".Color(ConsoleColor.Gray).Fmt(logfiles));
                        config.LogfilesDir = logfiles;
                    }
                    try
                    {
                        Directory.CreateDirectory(config.LogfilesDir);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain4;
                    }

                    Console.WriteLine();
tryAgain5:
                    var mergedPdfs = Path.Combine(p, "MergedPdfs");
                    ConsoleUtil.WriteLine("Please choose a path where you would like KtaneWeb to store merged PDFs, or just press Enter to use the default ({0/DarkCyan}):".Color(ConsoleColor.Gray).Fmt(mergedPdfs));

                    config.MergedPdfsDir = Console.ReadLine();
                    if (string.IsNullOrWhiteSpace(config.MergedPdfsDir))
                    {
                        ConsoleUtil.WriteLine("Using default: {0/DarkCyan}".Color(ConsoleColor.Gray).Fmt(mergedPdfs));
                        config.MergedPdfsDir = mergedPdfs;
                    }
                    try
                    {
                        Directory.CreateDirectory(config.MergedPdfsDir);
                    }
                    catch (Exception e)
                    {
                        ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                        goto tryAgain5;
                    }

                    var appPath = PathUtil.AppPathCombine(@"..\..");
                    config.JavaScriptFile = Path.Combine(appPath, @"Src\Resources\KtaneWeb.js");
                    config.CssFile        = Path.Combine(appPath, @"Src\Resources\KtaneWeb.css");
                    if (!File.Exists(config.JavaScriptFile) || !File.Exists(config.CssFile))
                    {
                        Console.WriteLine();
tryAgain6:
                        ConsoleUtil.WriteLine("Finally, please let me know where you placed the KtaneWeb source code (what you’re running right now):".Color(ConsoleColor.Gray));
                        appPath = Console.ReadLine();
                        config.JavaScriptFile = Path.Combine(appPath, @"Src\Resources\KtaneWeb.js");
                        config.CssFile        = Path.Combine(appPath, @"Src\Resources\KtaneWeb.css");
                        if (!File.Exists(config.JavaScriptFile) || !File.Exists(config.CssFile))
                        {
                            ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {"That does not look like the KtaneWeb source code folder.".Color(ConsoleColor.Red)}", null);
                            goto tryAgain6;
                        }
                    }
                }

                try
                {
                    ClassifyJson.SerializeToFile(config, path);
                    Settings.ConfigFile = path;
                    SaveSettings();
                }
                catch (Exception e)
                {
                    ConsoleUtil.WriteLine($"{"Problem:".Color(ConsoleColor.Magenta)} {e.Message.Color(ConsoleColor.Red)} {$"({e.GetType().FullName})".Color(ConsoleColor.DarkRed)}", null);
                    goto tryAgain1;
                }

                Console.WriteLine();
                ConsoleUtil.WriteLine("That should be all set up for you now!".Color(ConsoleColor.Green));
                ConsoleUtil.WriteLine("Feel free to browse the settings file we just created if you’re curious.".Color(ConsoleColor.DarkGreen));
                ConsoleUtil.WriteLine(@"For automatic PDF generation, we are assuming that Google Chrome is at its default location; if not, please change it manually in the JSON file.".Color(ConsoleColor.DarkGreen));
                Console.WriteLine();
                Console.WriteLine();
            }
#endif
            var original = File.ReadAllText(Settings.ConfigFile);
            _config = ClassifyJson.Deserialize <KtaneWebConfig>(JsonValue.Parse(original));
            var rewrite = serializeConfig();
            if (rewrite != original)
            {
                File.WriteAllText(Settings.ConfigFile, rewrite);
            }
            base.Init(log);
            _logger = log;
        }
Пример #22
0
        /// <summary>
        /// Handles exist command, closing the application immediately.
        /// </summary>
        /// <param name="command"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        protected virtual CommandResult HandleExit(string command, Arguments args)
        {
            ConsoleUtil.Exit(0, false);

            return(CommandResult.Okay);
        }
Пример #23
0
 static void Main(string[] args)
 {
     ConsoleUtil.WriteLine(SystemUtil.ScreenWidth);
     ConsoleUtil.WriteLine(SystemUtil.ScreenHeight);
     ConsoleUtil.Pause();
 }
Пример #24
0
        private void HandleRegionSet(string module, string[] args)
        {
            if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene))
            {
                return;
            }

            if (args.Length != 4)
            {
                MainConsole.Instance.OutputFormat("Usage: region set <param> <value>");
                return;
            }

            string param    = args[2];
            string rawValue = args[3];

            if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene))
            {
                return;
            }

            RegionInfo     ri = m_scene.RegionInfo;
            RegionSettings rs = ri.RegionSettings;

            if (param == "agent-limit")
            {
                int newValue;

                if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, rawValue, out newValue))
                {
                    return;
                }

                if (newValue > ri.AgentCapacity)
                {
                    MainConsole.Instance.OutputFormat(
                        "Cannot set {0} to {1} in {2} as max-agent-limit is {3}", "agent-limit",
                        newValue, m_scene.Name, ri.AgentCapacity);
                }
                else
                {
                    rs.AgentLimit = newValue;

                    MainConsole.Instance.OutputFormat(
                        "{0} set to {1} in {2}", "agent-limit", newValue, m_scene.Name);
                }

                rs.Save();
            }
            else if (param == "max-agent-limit")
            {
                int newValue;

                if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, rawValue, out newValue))
                {
                    return;
                }

                ri.AgentCapacity = newValue;

                MainConsole.Instance.OutputFormat(
                    "{0} set to {1} in {2}", "max-agent-limit", newValue, m_scene.Name);

                if (ri.AgentCapacity < rs.AgentLimit)
                {
                    rs.AgentLimit = ri.AgentCapacity;

                    MainConsole.Instance.OutputFormat(
                        "Reducing {0} to {1} in {2}", "agent-limit", rs.AgentLimit, m_scene.Name);
                }

                rs.Save();
            }
        }
        private void HandleDeleteObject(string module, string[] cmd)
        {
            if (!(m_console.ConsoleScene == null || m_console.ConsoleScene == m_scene))
            {
                return;
            }

            if (cmd.Length < 3)
            {
                return;
            }

            string mode = cmd[2];
            string o    = "";

            if (mode != "outside")
            {
                if (cmd.Length < 4)
                {
                    return;
                }

                o = cmd[3];
            }

            List <SceneObjectGroup> deletes = null;
            UUID match;
            bool requireConfirmation = true;

            switch (mode)
            {
            case "owner":
                if (!UUID.TryParse(o, out match))
                {
                    return;
                }

                deletes = new List <SceneObjectGroup>();

                m_scene.ForEachSOG(delegate(SceneObjectGroup g)
                {
                    if (g.OwnerID == match && !g.IsAttachment)
                    {
                        deletes.Add(g);
                    }
                });

                //                if (deletes.Count == 0)
                //                    m_console.OutputFormat("No objects were found with owner {0}", match);

                break;

            case "creator":
                if (!UUID.TryParse(o, out match))
                {
                    return;
                }

                deletes = new List <SceneObjectGroup>();

                m_scene.ForEachSOG(delegate(SceneObjectGroup g)
                {
                    if (g.RootPart.CreatorID == match && !g.IsAttachment)
                    {
                        deletes.Add(g);
                    }
                });

                //                if (deletes.Count == 0)
                //                    m_console.OutputFormat("No objects were found with creator {0}", match);

                break;

            case "id":
                UUID uuid;
                uint localId;
                if (!ConsoleUtil.TryParseConsoleId(m_console, o, out uuid, out localId))
                {
                    return;
                }

                requireConfirmation = false;
                deletes             = new List <SceneObjectGroup>();

                SceneObjectGroup so;
                if (localId == ConsoleUtil.LocalIdNotFound)
                {
                    so = m_scene.GetSceneObjectGroup(uuid);
                }
                else
                {
                    so = m_scene.GetSceneObjectGroup(localId);
                }

                if (!so.IsAttachment)
                {
                    deletes.Add(so);
                }

                //                if (deletes.Count == 0)
                //                    m_console.OutputFormat("No objects were found with uuid {0}", match);

                break;

            case "name":
                deletes = GetDeleteCandidatesByName(module, cmd);
                break;

            case "outside":
                deletes = new List <SceneObjectGroup>();

                m_scene.ForEachSOG(delegate(SceneObjectGroup g)
                {
                    SceneObjectPart rootPart = g.RootPart;
                    bool delete = false;

                    if (rootPart.GroupPosition.Z < 0.0 || rootPart.GroupPosition.Z > 10000.0)
                    {
                        delete = true;
                    }
                    else
                    {
                        ILandObject parcel
                            = m_scene.LandChannel.GetLandObject(rootPart.GroupPosition.X, rootPart.GroupPosition.Y);

                        if (parcel == null || parcel.LandData.Name == "NO LAND")
                        {
                            delete = true;
                        }
                    }

                    if (delete && !g.IsAttachment && !deletes.Contains(g))
                    {
                        deletes.Add(g);
                    }
                });

                if (deletes.Count == 0)
                {
                    m_console.OutputFormat("No objects were found outside region bounds");
                }

                break;

            case "pos":
                deletes = GetDeleteCandidatesByPos(module, cmd);
                break;

            default:
                m_console.OutputFormat("Unrecognized mode {0}", mode);
                return;
            }

            if (deletes == null || deletes.Count <= 0)
            {
                return;
            }

            if (requireConfirmation)
            {
                string response = MainConsole.Instance.CmdPrompt(
                    string.Format(
                        "Are you sure that you want to delete {0} objects from {1}",
                        deletes.Count, m_scene.RegionInfo.RegionName),
                    "y/N");

                if (response.ToLower() != "y")
                {
                    MainConsole.Instance.OutputFormat(
                        "Aborting delete of {0} objects from {1}", deletes.Count, m_scene.RegionInfo.RegionName);

                    return;
                }
            }

            m_console.OutputFormat("Deleting {0} objects in {1}", deletes.Count, m_scene.RegionInfo.RegionName);

            foreach (SceneObjectGroup g in deletes)
            {
                m_console.OutputFormat("Deleting object {0} {1}", g.UUID, g.Name);
                m_scene.DeleteSceneObject(g, false);
            }
        }
Пример #26
0
        private void HandleDebugThreadpoolSet(string module, string[] args)
        {
            if (args.Length != 6)
            {
                Notice("Usage: debug threadpool set worker|iocp min|max <n>");
                return;
            }

            int newThreads;

            if (!ConsoleUtil.TryParseConsoleInt(m_console, args[5], out newThreads))
            {
                return;
            }

            string poolType = args[3];
            string bound    = args[4];

            bool fail = false;
            int  workerThreads, iocpThreads;

            if (poolType == "worker")
            {
                if (bound == "min")
                {
                    ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);

                    if (!ThreadPool.SetMinThreads(newThreads, iocpThreads))
                    {
                        fail = true;
                    }
                }
                else
                {
                    ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

                    if (!ThreadPool.SetMaxThreads(newThreads, iocpThreads))
                    {
                        fail = true;
                    }
                }
            }
            else
            {
                if (bound == "min")
                {
                    ThreadPool.GetMinThreads(out workerThreads, out iocpThreads);

                    if (!ThreadPool.SetMinThreads(workerThreads, newThreads))
                    {
                        fail = true;
                    }
                }
                else
                {
                    ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

                    if (!ThreadPool.SetMaxThreads(workerThreads, newThreads))
                    {
                        fail = true;
                    }
                }
            }

            if (fail)
            {
                Notice("ERROR: Could not set {0} {1} threads to {2}", poolType, bound, newThreads);
            }
            else
            {
                int minWorkerThreads, maxWorkerThreads, minIocpThreads, maxIocpThreads;

                ThreadPool.GetMinThreads(out minWorkerThreads, out minIocpThreads);
                ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxIocpThreads);

                Notice("Min worker threads now {0}", minWorkerThreads);
                Notice("Min IOCP threads now {0}", minIocpThreads);
                Notice("Max worker threads now {0}", maxWorkerThreads);
                Notice("Max IOCP threads now {0}", maxIocpThreads);
            }
        }
Пример #27
0
        public override void Step(GameBoard board)
        {
            ConsoleUtil.WriteBlanks();
            Console.SetCursorPosition(0, Console.WindowHeight / 2);
            Console.WriteLine(board.WhiteToMove
                ? "White to move! Press any key to continue..."
                : "Black to move! Press any key to continue...");

            Console.ReadKey();
            var  layer      = board.WhiteToMove ? GameBoard.BoardType.WhiteShips : GameBoard.BoardType.BlackShips;
            bool horizontal = true;
            int  length     = board.ShipCounts
                              .Where(s => board.CountShipsWithSize(board.Board[(int)layer], s.Key) < s.Value)
                              .Max(s => s.Key);

            do
            {
                bool choosing = true;
                while (choosing)
                {
                    ConsoleUtil.WriteBlanks();
                    _renderer.RenderShips(board.Board[(int)layer], length, horizontal);
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine("\nUse G to autogenerate board instead!");
                    Console.WriteLine("Use R to revert move");
                    Console.Write("Press Q to quit!");
                    var input = Console.ReadKey();
                    switch (input.Key)
                    {
                    case ConsoleKey.UpArrow:
                        _renderer.HighlightY = Math.Max(0, _renderer.HighlightY - 1);
                        break;

                    case ConsoleKey.DownArrow:
                        _renderer.HighlightY = Math.Min(board.Height - (horizontal ? 1 : length),
                                                        _renderer.HighlightY + 1);
                        break;

                    case ConsoleKey.RightArrow:
                        _renderer.HighlightX = Math.Min(board.Width - (horizontal ? length : 1),
                                                        _renderer.HighlightX + 1);
                        break;

                    case ConsoleKey.LeftArrow:
                        _renderer.HighlightX = Math.Max(0, _renderer.HighlightX - 1);
                        break;

                    case ConsoleKey.Enter:
                        choosing = false;
                        break;

                    case ConsoleKey.Spacebar:
                        horizontal           = !horizontal;
                        _renderer.HighlightX = Math.Min(board.Width - (horizontal ? length : 1),
                                                        _renderer.HighlightX);
                        _renderer.HighlightY = Math.Min(board.Height - (horizontal ? 1 : length),
                                                        _renderer.HighlightY);
                        break;

                    case ConsoleKey.Q:
                        ExitCallback?.Invoke();
                        return;

                    case ConsoleKey.G:
                        int n = 0;
                        while (n < 10 || !board.GenerateBoard())
                        {
                            n++;
                        }
                        return;

                    case ConsoleKey.R:
                        board.RevertMove();
                        return;
                    }
                }
            } while (!PlaceShipCallback?.Invoke(_renderer.HighlightY, _renderer.HighlightX, length, horizontal) ??
                     true);

            _renderer.HighlightX = 0;
            _renderer.HighlightY = 0;
        }
Пример #28
0
 public static void ShowPetInfo(CPet pet)
 {
     ConsoleUtil.WriteColor(GetPetInfo(pet));
 }
Пример #29
0
        public static void DisplayPet(int row = 10)
        {
            var pets = LoadPetShell(PlayerManager.CurrentPlayer.Name);

            if (pets == null)
            {
                return;
            }

            var page  = 0;
            var index = 0;

            while (true)
            {
                Console.Clear();

                var list = pets.Count - 1 >= page * row + row
          ? pets.GetRange(page * row, row)
          : pets.GetRange(page * row, pets.Count - page * row);

                for (var i = 0; i < list.Count; i++)
                {
                    var msg = $"{page * row + i + 1}. {list[i].Name}";

                    if (i == index)
                    {
                        ConsoleUtil.WriteColor(msg);
                    }
                    else
                    {
                        ConsoleUtil.WriteColor(msg, Colors.txtMuted);
                    }
                }

                ConsoleUtil.WriteColor("");
                ConsoleUtil.WriteColor($"\n페이지: {page + 1}, 개수 : {page * row + index + 1}/{pets.Count}");
                ConsoleUtil.WriteColor("↑ ↓ ← →");
                ConsoleUtil.WriteColor("Enter로 선택, Esc로 종료");

                var key = Console.ReadKey().Key;

                if (pets.Count > 0)
                {
                    switch (key)
                    {
                    case ConsoleKey.UpArrow:
                        if (index != 0)
                        {
                            index--;
                        }
                        break;

                    case ConsoleKey.DownArrow:
                        if (index != pets.Count - 1)
                        {
                            index++;
                        }
                        break;

                    case ConsoleKey.LeftArrow:
                        if (page != 0)
                        {
                            page--;
                            index = 0;
                        }

                        break;

                    case ConsoleKey.RightArrow:
                        var maxPage = (int)Math.Ceiling(((double)pets.Count / row)) - 1;
                        if (page != maxPage)
                        {
                            page++;
                            index = 0;
                        }

                        break;

                    case ConsoleKey.Enter:
                        ShowPetInfo(list[index]);
                        ConsoleUtil.Pause();

                        break;

                    case ConsoleKey.Escape:
                        return;

                    case ConsoleKey.D1:
                        if (pets.Count > 0)
                        {
                            index = 0;
                        }
                        break;

                    case ConsoleKey.D2:
                        if (pets.Count > 1)
                        {
                            index = 1;
                        }
                        break;

                    case ConsoleKey.D3:
                        if (pets.Count > 2)
                        {
                            index = 2;
                        }
                        break;

                    case ConsoleKey.D4:
                        if (pets.Count > 3)
                        {
                            index = 3;
                        }
                        break;

                    case ConsoleKey.D5:
                        if (pets.Count > 4)
                        {
                            index = 4;
                        }
                        break;

                    case ConsoleKey.D6:
                        if (pets.Count > 5)
                        {
                            index = 5;
                        }
                        break;

                    case ConsoleKey.D7:
                        if (pets.Count > 6)
                        {
                            index = 6;
                        }
                        break;

                    case ConsoleKey.D8:
                        if (pets.Count > 7)
                        {
                            index = 7;
                        }
                        break;

                    case ConsoleKey.D9:
                        if (pets.Count > 8)
                        {
                            index = 8;
                        }
                        break;

                    case ConsoleKey.D0:
                        if (pets.Count > 9)
                        {
                            index = 9;
                        }
                        break;
                    }
                }
                else
                {
                    return;
                }
            }
        }
Пример #30
0
 protected override void Dispose(bool disposing)
 {
     base.Dispose(disposing);
     ConsoleUtil.LogDisposed(this);
 }