public World NewWorld()
        {
            var world = new World();

            Worlds.Add(world);
            return(world);
        }
Esempio n. 2
0
        public void InitializeWorldsList()
        {
            DirectoryInfo serverDir = new DirectoryInfo(Path.Combine(App.ServerPath, Server.Name));

            if (!serverDir.Exists)
            {
                return;
            }

            Application.Current.Dispatcher?.Invoke(() => Worlds.Clear());
            foreach (DirectoryInfo directory in serverDir.EnumerateDirectories())
            {
                WorldValidationInfo worldVal = DirectoryValidator.ValidateWorldDirectory(directory);
                if (worldVal.IsValid)
                {
                    World world = new World(worldVal.Name, this, directory);
                    if (Server.ServerSettings.LevelName.Equals(world.Name))
                    {
                        world.IsActive = true;
                    }

                    Application.Current.Dispatcher?.Invoke(() => Worlds.Add(world));
                }
            }
        }
Esempio n. 3
0
        public void Parse(InputMessage message)
        {
            byte worlds = message.GetU8();

            for (int i = 0; i < worlds; i++)
            {
                var world = new World();
                world.ID       = message.GetU8();
                world.Name     = message.GetString();
                world.HostName = message.GetString();
                world.Port     = message.GetU16();
                world.Preview  = message.GetBool();
                Worlds.Add(world);
            }

            byte characters = message.GetU8();

            for (int i = 0; i < characters; i++)
            {
                Character character = new Character();
                character.World = message.GetU8();
                character.Name  = message.GetString();
                Characters.Add(character);
            }

            AccountState     = message.GetU8();
            IsPremium        = message.GetBool();
            PremiumTimeStamp = message.GetU32();

            InfinitePremium = (IsPremium && PremiumTimeStamp == 0);
        }
Esempio n. 4
0
        public void Configure()
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo
                         .Console()
                         .CreateLogger();

            var config = ServerConfig.Instance;

            config.DatabaseConnectionType = DatabaseConnectionType.InMemory;
            config.DatabaseConnection     = Guid.NewGuid().ToString();
            config.AddDefaultWorld();

            Login = new LoginServer(this);

            ServerConfig.Instance.Worlds.ForEach(x =>
            {
                var world = new World(x);
                Worlds.Add(world);

                for (byte i = 0; i < x.Channels; i++)
                {
                    var game = new GameServer(this, world, ServerConfig.Instance.ChannelPort++, i);
                    world.Add(game);
                }
            });
        }
Esempio n. 5
0
        void LoadWorldList()
        {
            if (Worlds.Count > 0)
            {
                Worlds.Clear();
            }
            if (!File.Exists(Paths.WorldListFileName))
            {
                return;
            }

            try {
                XDocument doc  = XDocument.Load(Paths.WorldListFileName);
                XElement  root = doc.Root;
                if (root == null)
                {
                    MessageBox.Show("Worlds.xml is empty or corrupted.");
                    return;
                }

                string errorLog = "";
                using (LogRecorder logRecorder = new LogRecorder()) {
                    foreach (XElement el in root.Elements("World"))
                    {
                        try {
                            Worlds.Add(new WorldListEntry(el));
                        } catch (Exception ex) {
                            errorLog += ex + Environment.NewLine;
                        }
                    }
                    if (logRecorder.HasMessages)
                    {
                        MessageBox.Show(logRecorder.MessageString, "World list loading warnings.");
                    }
                }
                if (errorLog.Length > 0)
                {
                    MessageBox.Show("Some errors occured while loading the world list:" + Environment.NewLine + errorLog, "Warning");
                }

                FillWorldList();
                XAttribute mainWorldAttr = root.Attribute("main");
                if (mainWorldAttr != null)
                {
                    foreach (WorldListEntry world in Worlds)
                    {
                        if (world.Name.ToLower() == mainWorldAttr.Value.ToLower())
                        {
                            cMainWorld.SelectedItem = world.Name;
                            break;
                        }
                    }
                }
            } catch (Exception ex) {
                MessageBox.Show("Error occured while loading the world list: " + Environment.NewLine + ex, "Warning");
            }

            Worlds.ListChanged += SomethingChanged;
        }
Esempio n. 6
0
 /// <summary>
 /// Adds a world to this level.
 /// </summary>
 public void AddWorld(World world)
 {
     if (Worlds.Any(w => w.Name.ToUpper() == world.Name.ToUpper()))
     {
         throw new InvalidOperationException("A world with the same name already exists in this level.");
     }
     Worlds.Add(world);
 }
Esempio n. 7
0
        public void AddWorld(IWorld world)
        {
            Worlds.Add(world);
            world.BlockRepository = BlockRepository;
            world.BlockChanged   += HandleBlockChanged;
            var manager = new EntityManager(this, world);

            EntityManagers.Add(manager);
        }
Esempio n. 8
0
        public World(IWorldGenerator generator, int Dimension)
        {
            Init();

            this.DimensionID = Dimension;

            Difficulty          = Difficulty.Easy;
            this._chunkProvider = new ChunkProvider(generator);
            Worlds.Add(this, Dimension);
        }
Esempio n. 9
0
        private void LoadSaveList()
        {
            Worlds.Clear();
            var list = new List <WorldResource>();

            #region local saves

            if (Directory.Exists(BaseLocalPath.SavesPath))
            {
                var userPaths = Directory.GetDirectories(BaseLocalPath.SavesPath);

                foreach (var userPath in userPaths)
                {
                    var userName = Path.GetFileName(userPath);
                    list.AddRange(FindSaveFiles(userPath, userName, SaveWorldType.Local, BaseLocalPath));
                }
            }

            #endregion

            #region Host Server

            if (Directory.Exists(BaseDedicatedServerHostPath.SavesPath))
            {
                list.AddRange(FindSaveFiles(BaseDedicatedServerHostPath.SavesPath, "Local / Console", SaveWorldType.DedicatedServerHost, BaseDedicatedServerHostPath));
            }

            #endregion

            #region Service Server

            if (Directory.Exists(BaseDedicatedServerServicePath.SavesPath))
            {
                var instancePaths = Directory.GetDirectories(BaseDedicatedServerServicePath.SavesPath);

                foreach (var instancePath in instancePaths)
                {
                    var lastLoadedPath = Path.Combine(instancePath, "Saves");

                    if (Directory.Exists(lastLoadedPath))
                    {
                        var instanceName = Path.GetFileName(instancePath);
                        var dataPath     = new UserDataPath(lastLoadedPath, Path.Combine(instancePath, "Mods"));
                        list.AddRange(FindSaveFiles(lastLoadedPath, instanceName, SaveWorldType.DedicatedServerService, dataPath));
                    }
                }
            }

            #endregion

            foreach (var item in list.OrderByDescending(w => w.LastLoadTime))
            {
                Worlds.Add(item);
            }
        }
Esempio n. 10
0
        public static async Task SaveOrAddWorldAsync(World world)
        {
            var worldFromList = Worlds.Where(x => x.Name == world.Name).ToList();

            if (worldFromList.Count != 0)
            {
                int index = Worlds.IndexOf(worldFromList.First());
                Worlds[index] = world;
            }
            else
            {
                Worlds.Add(world);
            }
            await Task.CompletedTask;
        }
Esempio n. 11
0
        public static async Task <World> GetWorld(string worldName)
        {
            if (Worlds.TryGetValue(worldName, out var w))
            {
                return(w);
            }
            else if (await IsWorldExist(worldName))
            {
                World world = await LoadWorld(worldName);

                Worlds.Add(worldName, world);
                return(world);
            }
            return(GenerateNormalWorld(worldName));
        }
Esempio n. 12
0
        private static void Configurate()
        {
            using (Config config = new Config(@"..\DataSvr\" + Program.ConfigurationFile))
            {
                Name      = Program.ConfigurationFile.Replace(".img", "");
                Port      = config.GetUShort("", "port");
                AdminPort = config.GetUShort("", "adminPort");

                IPAddress ipAddress;
                string    ipString = config.GetString("", "PublicIP");

                if (!IPAddress.TryParse(ipString, out ipAddress))
                {
                    ipAddress = Dns.GetHostEntry(ipString).AddressList[0];
                }

                PublicIP = ipAddress;

                PrivateIP = IPAddress.Parse(config.GetString("", "PrivateIP"));

                List <string> worldNames = config.GetBlocks("center", true);

                foreach (string worldName in worldNames)
                {
                    World world = new World();

                    world.Name     = worldName;
                    world.ID       = config.GetByte(worldName, "world");
                    world.Channels = config.GetByte(worldName, "channelNo");

                    Worlds.Add(world.ID, world);
                }
            }

            using (Config config = new Config(@"..\DataSvr\Database.img"))
            {
                string host     = config.GetString("", "Host");
                string schema   = config.GetString("", "Schema");
                string username = config.GetString("", "Username");
                string password = config.GetString("", "Password");

                Database = new Database(username, password, schema, host);
            }

            LoginAcceptor = new Acceptor(Port);
            LoginAcceptor.OnClientAccepted += new Action <Socket>(OnClientConnected);
            LoginAcceptor.Start();
        }
Esempio n. 13
0
        /// <summary>
        /// Creates and adds a world to this level, with the given name.
        /// </summary>
        public void AddWorld(string name, IWorldGenerator worldGenerator = null)
        {
            if (Worlds.Any(w => w.Name.ToUpper() == name.ToUpper()))
            {
                throw new InvalidOperationException("A world with the same name already exists in this level.");
            }
            var world = new World(name);

            if (worldGenerator == null)
            {
                world.WorldGenerator = WorldGenerator;
            }
            else
            {
                world.WorldGenerator = worldGenerator;
            }
            Worlds.Add(world);
        }
Esempio n. 14
0
        public void AddWorld(IWorld world)
        {
            Worlds.Add(world);
            world.BlockRepository = BlockRepository;
            world.ChunkGenerated += HandleChunkGenerated;
            world.ChunkLoaded    += HandleChunkLoaded;
            world.BlockChanged   += HandleBlockChanged;
            var manager = new EntityManager(this, world);

            EntityManagers.Add(manager);
            var lighter = new WorldLighting(world, BlockRepository);

            WorldLighters.Add(lighter);
            foreach (var chunk in world)
            {
                HandleChunkLoaded(world, new ChunkLoadedEventArgs(chunk));
            }
        }
        public Multiverse(HughFor game, TmxMap map)
        {
            Game           = game;
            UniverseLayout = map.Properties["layout"];

            BorderTexture = new Texture2D(game.GraphicsDevice, 1, 1);
            BorderTexture.SetData(new[] { Color.Black });

            LayoutHeight = CountChars(UniverseLayout, ';');
            LayoutWidth  = CountChars(UniverseLayout, '|') / LayoutHeight + 1;

            for (int i = 1; i <= LayoutHeight * LayoutWidth; i++)
            {
                Worlds.Add(new World(game, map, i));
            }

            HasWon  = false;
            HasDied = false;
        }
Esempio n. 16
0
        public virtual async Task StartAsync(CancellationToken cancellationToken)
        {
            await Configure();

            Login = new LoginServer(this);
            Login.Start();

            ServerConfig.Instance.Worlds.ForEach(x =>
            {
                var world = new World(x);
                Worlds.Add(world);

                for (byte i = 0; i < x.Channels; i++)
                {
                    var game = new GameServer(this, world, ServerConfig.Instance.ChannelPort++, i);
                    world.Add(game);
                    game.Start();
                }
            });

            Shop = new ShopServer(this);
            Shop.Start();
        }
Esempio n. 17
0
        private World GetOrCreateWorld(string name, uint ip, ushort port)
        {
            string ipAddress = new System.Net.IPAddress(ip).ToString();

            foreach (var world in Worlds)
            {
                if (world.Name == name && world.HostName == ipAddress && world.Port == port)
                {
                    return(world);
                }
            }

            World newWorld = new World {
                _id      = Worlds.Count,
                Name     = name,
                HostName = ipAddress,
                Port     = port,
                Preview  = false
            };

            Worlds.Add(newWorld);
            return(newWorld);
        }
Esempio n. 18
0
 public void LoadWorlds()
 {
     ExitThreads = false;
     try
     {
         System.IO.DirectoryInfo worldDirectory = System.IO.Directory.CreateDirectory(DwarfGame.GetGameDirectory() + ProgramData.DirChar + OverworldDirectory);
         foreach (System.IO.DirectoryInfo file in worldDirectory.EnumerateDirectories())
         {
             WorldLoadDescriptor descriptor = new WorldLoadDescriptor
             {
                 DirectoryName  = file.FullName,
                 WorldName      = file.FullName.Split(ProgramData.DirChar).Last(),
                 ScreenshotName = file.FullName + ProgramData.DirChar + "screenshot.png",
                 FileName       = file.FullName + ProgramData.DirChar + "world." + OverworldFile.CompressedExtension,
             };
             Worlds.Add(descriptor);
         }
     }
     catch (System.IO.IOException exception)
     {
         Console.Error.WriteLine(exception.Message);
         Dialog.Popup(GUI, "Error.", "Error loading worlds:\n" + exception.Message, Dialog.ButtonType.OK);
     }
 }
Esempio n. 19
0
        private static void Main(string[] args)
        {
            if (args.Length == 1 && args[0].ToLower() == "setup" || !File.Exists(Application.ExecutablePath + "WvsLogin.ini"))
            {
                WvsLoginSetup.Run();
            }

            Worlds  = new Worlds();
            Clients = new LoginClients();

            Log.Entitle("Destiny - Login Server v.{0}.{1}", Application.MapleVersion, Application.PatchVersion);

            try
            {
                Settings.Initialize(Application.ExecutablePath + "WvsLogin.ini");

                Database.Test();
                Database.Analyze(false);

                RequireStaffIP = Settings.GetBool("Server/RequireStaffIP");
                Log.Inform("Staff will{0}be required to connect through a staff IP.", RequireStaffIP ? " " : " not ");

                AutoRegister = Settings.GetBool("Server/AutoRegister");
                Log.Inform("Automatic registration {0}.", AutoRegister ? "enabled" : "disabled");

                RequestPin = Settings.GetBool("Server/RequestPin");
                Log.Inform("Pin will{0}be requested upon login.", RequestPin ? " " : " not ");

                RequestPic = Settings.GetBool("Server/RequestPic");
                Log.Inform("Pic will{0}be requested upon character selection.", RequestPic ? " " : " not ");

                MaxCharacters = Settings.GetInt("Server/MaxCharacters");
                Log.Inform("Maximum of {0} characters per account.", MaxCharacters);

                for (byte i = 0; i < Settings.GetByte("Server/Worlds"); i++)
                {
                    Worlds.Add(new World(i));
                }

                isAlive = true;
            }
            catch (Exception e)
            {
                Log.Error(e);
            }

            if (IsAlive)
            {
                CenterConnectionDone.Reset();

                new Thread(new ThreadStart(LoginToCenterServer.Main)).Start();

                CenterConnectionDone.WaitOne();
            }
            else
            {
                Log.SkipLine();
                Log.Inform("Could not start server because of errors.");
            }

            while (IsAlive)
            {
                AcceptDone.Reset();
                Listener.BeginAcceptSocket(new AsyncCallback(OnAcceptSocket), null);
                AcceptDone.WaitOne();
            }

            foreach (LoginClient client in Clients)
            {
                client.Stop();
            }

            Dispose();

            Log.SkipLine();
            Log.Warn("Server stopped.");

            Console.Read();
        }
Esempio n. 20
0
        public static void ServerLoop()
        {
            AcceptDone = new ManualResetEvent(false);
            Worlds     = new Worlds();
            Clients    = new List <Client>();

            Log.SetLogFile(".\\Logs\\LoginLog.log");
            Log.Entitle("Login Server (CLIENT VERSION {0})", ServerConstants.CLIENT_VERSION);

            try
            {
                Settings.Initialize();

                Database.Test();
                Database.Analyze(false);

                SecurityCode = Settings.GetString("SecurityCode", "Interconnection");
                Log.Inform("Cross-servers code '{0}' assigned.", Log.MaskString(LoginServer.SecurityCode));

                RequireStaffIP   = Settings.GetBool("RequireStaffIP", "Login");
                IsMaintenance    = Settings.GetBool("isMaintenance", "Login");
                PatchVer         = Settings.GetInt("PatchVersion", "Login");
                PatchDownloadUrl = Settings.GetString("PatchDownloadUrl", "Login");

                Log.Inform("Staff will {0} be required to connect through a staff IP.",
                           LoginServer.RequireStaffIP ? " " : " not ");
                Log.Debug("IsMaintenance: {0}", IsMaintenance);
                TcpListener Listener = new TcpListener(IPAddress.Any, Settings.GetInt("Port", "Login"));
                Listener.Start();
                Log.Inform("Initialized clients listener on {0}.", Listener.LocalEndpoint);

                LoginServer.Pinger.Interval = Settings.GetInt("PingInterval");
                LoginServer.Pinger.Start();
                Log.Inform("Clients pinger set to {0} ms.", LoginServer.Pinger.Interval);

                foreach (string world in Settings.GetBlocksFromBlock("Worlds", 1))
                {
                    Worlds.Add(new World()
                    {
                        ID              = Settings.GetByte("ID", world),
                        HostIP          = Settings.GetIPAddress("Host", world),
                        Flag            = Settings.GetEnum <ServerUtilities.ServerFlag>("Flag", world),
                        Channel         = Settings.GetByte("Channel", world),
                        EventMessage    = Settings.GetString("EventMessage", world),
                        DisableCreation = Settings.GetBool("DisableCreation", world),
                        ScrollingHeader = Settings.GetString("ScrollingHeader", world),
                        Rates           = new ServerUtilities.Rates()
                        {
                            Experience           = Settings.GetInt("ExperienceRate", world),
                            QuestExperience      = Settings.GetInt("QuestExperienceRate", world),
                            PartyQuestExperience = Settings.GetInt("PartyQuestExperience", world),

                            Meso = Settings.GetInt("MesoDropRate", world),
                            Loot = Settings.GetInt("LootDropRate", world)
                        }
                    });
                }

                IsAlive = true;

                Log.Success("Server started on thread {0}.", Thread.CurrentThread.ManagedThreadId);

                AppDomain.CurrentDomain.UnhandledException += (s, e) =>
                {
                    Log.Error("Unhandled exception from Server: \n{0}", e.ExceptionObject.ToString());
                };

                new Thread(new ThreadStart(InteroperabilityServer.ServerLoop)).Start();

                while (IsAlive)
                {
                    AcceptDone.Reset();

                    Listener.BeginAcceptSocket((iar) =>
                    {
                        new Client(Listener.EndAcceptSocket(iar));

                        AcceptDone.Set();
                    }, null);

                    AcceptDone.WaitOne();
                }

                InteroperabilityServer.Stop();

                Client[] remainingClients = Clients.ToArray();

                foreach (Client client in remainingClients)
                {
                    client.Dispose();
                }

                Listener.Stop();

                Log.Warn("Login stopped.");
            }
            catch (Exception e)
            {
                Log.Error(e);
                Log.Inform("Could not start server because of errors.");
            }
            finally
            {
                Console.Read();
            }
        }
Esempio n. 21
0
        private static World GenerateNormalWorld(string worldName)
        {
            World world = new World(worldName, 100, 60);

            Random rand = new Random();

            int doorPos = rand.Next(0, 100), width = 100, height = 60;

            for (int x = 0; x < width; x++)
            {
                for (int y = 0; y < height; y++)
                {
                    int square = x + y * 100;
                    world.Blocks[square] = new Block(new Vector2i(x, y));

                    var block = world.Blocks[square];

                    if (y >= height / 2)
                    {
                        if (y >= height - 5)
                        {
                            block.Fg = Tile.Parse(8);
                            block.Bg = Tile.Parse(14);
                        }
                        else if (y == height / 2 && x == doorPos)
                        {
                            block.Fg = Tile.Parse(8);
                            block.Bg = Tile.Parse(14);
                        }
                        else if (y <= height - 5 && y >= height - 10)
                        {
                            var num = rand.Next(0, 76);
                            block.Fg = Tile.Parse(num > 20 ? 2 : (num > 4 ? 4 : 10));
                            block.Bg = Tile.Parse(14);
                        }
                        else
                        {
                            block.Fg = Tile.Parse(2);
                            block.Bg = Tile.Parse(14);
                            if (y >= (height / 2) + 2)
                            {
                                block.Fg = Tile.Parse(rand.Next(0, 51) > 1 ? 2 : 10);
                            }
                        }
                    }
                    else if (y == height / 2 - 1 && x == doorPos)
                    {
                        block.Fg = Tile.Parse(6);
                        block.Bg = Tile.Parse(14);
                    }
                    else
                    {
                        block.Fg = Tile.Parse(0);
                        block.Bg = Tile.Parse(0);
                    }
                }
            }

            SaveWorld(world);
            Worlds.Add(world.Name, world);

            return(world);
        }
Esempio n. 22
0
        public void Parse(Internal.CommunicationStream message)
        {
            if (OpenTibiaUnity.GameManager.ClientVersion >= 1010)
            {
                byte worlds = message.ReadUnsignedByte();
                for (int i = 0; i < worlds; i++)
                {
                    var world = new World {
                        _id      = message.ReadUnsignedByte(),
                        Name     = message.ReadString(),
                        HostName = message.ReadString(),
                        Port     = message.ReadUnsignedShort(),
                        Preview  = message.ReadBoolean()
                    };
                    Worlds.Add(world);
                }

                byte characters = message.ReadUnsignedByte();
                for (int i = 0; i < characters; i++)
                {
                    Character character = new Character {
                        WorldId = message.ReadUnsignedByte(),
                        Name    = message.ReadString()
                    };
                    Characters.Add(character);
                }
            }
            else
            {
                byte characters = message.ReadUnsignedByte();
                for (int i = 0; i < characters; i++)
                {
                    var characterName = message.ReadString();
                    var worldName     = message.ReadString();
                    var worldIpLong   = message.ReadUnsignedInt();
                    var worldPort     = message.ReadUnsignedShort();

                    var world     = GetOrCreateWorld(worldName, worldIpLong, worldPort);
                    var character = new Character {
                        Name    = characterName,
                        WorldId = world._id
                    };
                    Characters.Add(character);
                }
            }

            uint now = (uint)System.DateTime.Now.Second;

            if (OpenTibiaUnity.GameManager.ClientVersion >= 1077)
            {
                AccountState     = message.ReadUnsignedByte();
                IsPremium        = message.ReadBoolean();
                PremiumTimeStamp = message.ReadUnsignedInt();
                if (PremiumTimeStamp > now)
                {
                    PremiumDays = (ushort)((PremiumTimeStamp - now) / 86400U);
                }
                else
                {
                    PremiumDays = 0;
                }

                InfinitePremium = (IsPremium && PremiumTimeStamp == 0);
            }
            else
            {
                AccountState = 0;
                PremiumDays  = message.ReadUnsignedShort();
                if (PremiumDays > 0)
                {
                    PremiumTimeStamp = now + PremiumDays * 86400U;
                }
                else
                {
                    PremiumTimeStamp = 0;
                }

                IsPremium       = PremiumDays > 0;
                InfinitePremium = PremiumDays == 65535;
            }
        }