Example #1
0
 static void GenerateMain()
 {
     Logger.Log(LogType.SystemActivity, "main level not found, generating..");
     mainLevel = new Level(ServerConfig.MainLevel, 128, 64, 128);
     MapGen.Generate(mainLevel, "flat", "", null);
     mainLevel.Save();
 }
Example #2
0
        internal static void LoadZones(Level level, string name)
        {
            if (!Database.TableExists("Zone" + name))
            {
                return;
            }
            int  id = 0;
            bool changedPerbuild = false;

            using (DataTable table = Database.Backend.GetRows("Zone" + name, "*")) {
                foreach (DataRow row in table.Rows)
                {
                    Zone z = new Zone(level);
                    z.MinX = ushort.Parse(row["SmallX"].ToString());
                    z.MinY = ushort.Parse(row["SmallY"].ToString());
                    z.MinZ = ushort.Parse(row["SmallZ"].ToString());
                    z.MaxX = ushort.Parse(row["BigX"].ToString());
                    z.MaxY = ushort.Parse(row["BigY"].ToString());
                    z.MaxZ = ushort.Parse(row["BigZ"].ToString());

                    string owner = row["Owner"].ToString();
                    if (owner.StartsWith("grp"))
                    {
                        Group grp = Group.Find(owner.Substring(3));
                        if (grp != null)
                        {
                            z.Access.Min = grp.Permission;
                        }
                    }
                    else if (z.CoversMap(level))
                    {
                        level.BuildAccess.Whitelisted.Add(owner);
                        changedPerbuild = true;
                        continue;
                    }
                    else
                    {
                        z.Access.Whitelisted.Add(owner);
                        z.Access.Min = LevelPermission.Admin;
                    }

                    z.Config.Name = "Zone" + id;
                    id++;
                    z.AddTo(level);
                }
            }

            if (changedPerbuild)
            {
                Level.SaveSettings(level);
            }
            if (level.Zones.Count > 0 && !level.Save(true))
            {
                return;
            }
            Database.Backend.DeleteTable("Zone" + name);
            Logger.Log(LogType.SystemActivity, "Upgraded zones for map " + name);
        }
Example #3
0
        static void GenerateMain()
        {
            Logger.Log(LogType.SystemActivity, "main level not found, generating..");
            mainLevel = new Level(Server.Config.MainLevel, 128, 64, 128);

            MapGen.Find("Flat").Generate(Player.Console, mainLevel, "");
            mainLevel.Save();
            LevelInfo.Add(mainLevel);
        }
Example #4
0
        internal static void LoadZones(Level level, string map)
        {
            if (!Database.TableExists("Zone" + map))
            {
                return;
            }

            List <Zone> zones = new List <Zone>();

            Database.Backend.ReadRows("Zone" + map, "*", zones, ListZones);

            bool changedPerbuild = false;

            for (int i = 0; i < zones.Count; i++)
            {
                Zone   z     = zones[i];
                string owner = z.Config.Name;

                if (owner.StartsWith("grp"))
                {
                    Group grp = Group.Find(owner.Substring(3));
                    if (grp != null)
                    {
                        z.Access.Min = grp.Permission;
                    }
                }
                else if (z.CoversMap(level))
                {
                    level.BuildAccess.Whitelisted.Add(owner);
                    changedPerbuild = true;
                    continue;
                }
                else
                {
                    z.Access.Whitelisted.Add(owner);
                    z.Access.Min = LevelPermission.Admin;
                }

                z.Config.Name = "Zone" + i;
                z.AddTo(level);
            }

            if (changedPerbuild)
            {
                level.SaveSettings();
            }
            if (level.Zones.Count > 0 && !level.Save(true))
            {
                return;
            }

            Database.Backend.DeleteTable("Zone" + map);
            Logger.Log(LogType.SystemActivity, "Upgraded zones for map " + map);
        }
Example #5
0
        protected override void ApplyChanges(Player p, Level lvl, string msg)
        {
            lvl.Save(true);
            msg += " &Sin " + ColoredName;
            Logger.Log(LogType.UserActivity, "{0} &Son {1}", msg, lvl.name);

            lvl.Message(msg);
            if (p.level != lvl)
            {
                p.Message("{0} &Son {1}", msg, lvl.ColoredName);
            }
        }
Example #6
0
        void LoadMainLevel()
        {
            try {
                if (LevelInfo.ExistsOffline(level))
                {
                    mainLevel        = Level.Load(level);
                    mainLevel.unload = false;
                    if (mainLevel == null)
                    {
                        if (File.Exists(LevelInfo.LevelPath(level) + ".backup"))
                        {
                            Log("Attempting to load backup of " + level + ".");
                            File.Copy(LevelInfo.LevelPath(level) + ".backup", LevelInfo.LevelPath(level), true);
                            mainLevel = Level.Load(level);
                            if (mainLevel == null)
                            {
                                Log("BACKUP FAILED!");
                                Console.ReadLine(); return;
                            }
                        }
                        else
                        {
                            Log("mainlevel not found");
                            mainLevel = new Level(level, 128, 64, 128, "flat");
                            mainLevel.Save();
                            Level.CreateLeveldb(level);
                        }
                    }
                }
                else
                {
                    Log("mainlevel not found");
                    mainLevel = new Level(level, 128, 64, 128, "flat");
                    mainLevel.Save();
                    Level.CreateLeveldb(level);
                }
                LevelInfo.Loaded.Add(mainLevel);

                // fenderrock - Make sure the level does have a physics thread
                if (mainLevel.physThread == null)
                {
                    mainLevel.StartPhysics();
                }
            } catch (Exception e) {
                ErrorLog(e);
            }
        }
Example #7
0
        /// <summary> Copies a map and related metadata. </summary>
        /// <remarks> Backups and BlockDB are NOT copied. </remarks>
        public static bool Copy(Player p, string src, string dst)
        {
            if (LevelInfo.MapExists(dst))
            {
                p.Message("&WLevel \"{0}\" already exists.", dst); return(false);
            }

            // Make sure any changes to live map are saved first
            Level lvl = LevelInfo.FindExact(src);

            if (lvl != null && !lvl.Save(true))
            {
                p.Message("&WUnable to save {0}! Some recent block changes may not be copied.", src);
            }

            File.Copy(LevelInfo.MapPath(src), LevelInfo.MapPath(dst));
            DoAll(src, dst, action_copy);
            CopyDatabaseTables(src, dst);
            OnLevelCopiedEvent.Call(src, dst);
            return(true);
        }
Example #8
0
        public void Start()
        {

            shuttingDown = false;
            Log("Starting Server");
            {
                try
                {
                    if (File.Exists("Restarter.exe"))
                    {
                        File.Delete("Restarter.exe");
                    }
                }
                catch { }
                try
                {
                    if (File.Exists("Restarter.pdb"))
                    {
                        File.Delete("Restarter.pdb");
                    }
                }
                catch { }
                if (!File.Exists("MySql.Data.dll"))
                {
                    Log("MySql.Data.dll doesn't exist, Downloading");
                    try
                    {
                        using (WebClient WEB = new WebClient())
                        {
                            WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/MySql.Data.dll?raw=true", "MySql.Data.dll");
                        }
                        if (File.Exists("MySql.Data.dll"))
                        {
                            Log("MySql.Data.dll download succesful!");
                        }
                    }
                    catch
                    {
                        Log("Downloading MySql.Data.dll failed, please try again later");
                    }
                }
                if (!File.Exists("System.Data.SQLite.dll"))
                {
                    Log("System.Data.SQLite.dll doesn't exist, Downloading");
                    try
                    {
                        using (WebClient WEB = new WebClient())
                        {
                            WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/System.Data.SQLite.dll?raw=true", "System.Data.SQLite.dll");
                        }
                        if (File.Exists("System.Data.SQLite.dll"))
                        {
                            Log("System.Data.SQLite.dll download succesful!");
                        }
                    }
                    catch
                    {
                        Log("Downloading System.Data.SQLite.dll failed, please try again later");
                    }
                }
                if (!File.Exists("sqlite3.dll"))
                {
                    Log("sqlite3.dll doesn't exist, Downloading");
                    try
                    {
                        using (WebClient WEB = new WebClient())
                        {
                            WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/sqlite3.dll?raw=true", "sqlite3.dll");
                        }
                        if (File.Exists("sqlite3.dll"))
                        {
                            Log("sqlite3.dll download succesful!");
                        }
                    }
                    catch
                    {
                        Log("Downloading sqlite3.dll failed, please try again later");
                    }
                }
                if (!File.Exists("Newtonsoft.Json.dll"))
                {
                	Log("Newtonsoft.Json.dll doesn't exist, Downloading");
                	try
                	{
                		using (WebClient WEB = new WebClient())
                		{
                            WEB.DownloadFile("https://github.com/Hetal728/MCGalaxy/blob/master/Newtonsoft.Json/Newtonsoft.Json.dll?raw=true", "Newtonsoft.Json.dll");
                		}
                		if (File.Exists("Newtonsoft.Json.dll"))
                		{
                			Log("Newtonsoft.Json.dll download successful!");
                		}
                	}
                	catch
                	{
                		Log("Download Newtonsoft.Json.dll failed, please try again later");
                	}
                }
            }
            //UpdateGlobalSettings();
            if (!Directory.Exists("properties")) Directory.CreateDirectory("properties");
            if (!Directory.Exists("levels")) Directory.CreateDirectory("levels");
            if (!Directory.Exists("bots")) Directory.CreateDirectory("bots");
            if (!Directory.Exists("text")) Directory.CreateDirectory("text");
            if (!File.Exists("text/tempranks.txt")) File.CreateText("text/tempranks.txt").Dispose();
            if (!File.Exists("text/rankinfo.txt")) File.CreateText("text/rankinfo.txt").Dispose();
            if (!File.Exists("text/transexceptions.txt")) File.CreateText("text/transexceptions.txt").Dispose();
            if (!File.Exists("text/gcaccepted.txt")) File.CreateText("text/gcaccepted.txt").Dispose();
            if (!File.Exists("text/bans.txt")) File.CreateText("text/bans.txt").Dispose();
            // DO NOT STICK ANYTHING IN BETWEEN HERE!!!!!!!!!!!!!!!
            else
            {
                string bantext = File.ReadAllText("text/bans.txt");
                if (!bantext.Contains("%20") && bantext != "")
                {
                    bantext = bantext.Replace("~", "%20");
                    bantext = bantext.Replace("-", "%20");
                    File.WriteAllText("text/bans.txt", bantext);
                }
            }



            if (!Directory.Exists("extra")) Directory.CreateDirectory("extra");
            if (!Directory.Exists("extra/undo")) Directory.CreateDirectory("extra/undo");
            if (!Directory.Exists("extra/undoPrevious")) Directory.CreateDirectory("extra/undoPrevious");
            if (!Directory.Exists("extra/copy/")) { Directory.CreateDirectory("extra/copy/"); }
            if (!Directory.Exists("extra/copyBackup/")) { Directory.CreateDirectory("extra/copyBackup/"); }
            if (!Directory.Exists("extra/Waypoints")) { Directory.CreateDirectory("extra/Waypoints"); }

            try
            {
                if (File.Exists("server.properties")) File.Move("server.properties", "properties/server.properties");
                if (File.Exists("rules.txt")) File.Move("rules.txt", "text/rules.txt");
                if (File.Exists("welcome.txt")) File.Move("welcome.txt", "text/welcome.txt");
                if (File.Exists("messages.txt")) File.Move("messages.txt", "text/messages.txt");
                if (File.Exists("externalurl.txt")) File.Move("externalurl.txt", "text/externalurl.txt");
                if (File.Exists("autoload.txt")) File.Move("autoload.txt", "text/autoload.txt");
                if (File.Exists("IRC_Controllers.txt")) File.Move("IRC_Controllers.txt", "ranks/IRC_Controllers.txt");
                if (useWhitelist) if (File.Exists("whitelist.txt")) File.Move("whitelist.txt", "ranks/whitelist.txt");
            }
            catch { }

            if (File.Exists("text/custom$s.txt"))
            {
                using (StreamReader r = new StreamReader("text/custom$s.txt"))
                {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        if (line.StartsWith("//")) continue;
                        var split = line.Split(new[] { ':' }, 2);
                        if (split.Length == 2 && !String.IsNullOrEmpty(split[0]))
                        {
                            customdollars.Add(split[0], split[1]);
                        }
                    }
                }
            }
            else
            {
                s.Log("custom$s.txt does not exist, creating");
                using (StreamWriter SW = File.CreateText("text/custom$s.txt"))
                {
                    SW.WriteLine("// This is used to create custom $s");
                    SW.WriteLine("// If you start the line with a // it wont be used");
                    SW.WriteLine("// It should be formatted like this:");
                    SW.WriteLine("// $website:mcgalaxy.ml");
                    SW.WriteLine("// That would replace '$website' in any message to 'mcgalaxy.ml'");
                    SW.WriteLine("// It must not start with a // and it must not have a space between the 2 sides and the colon (:)");
                    SW.Close();
                }
            }

            if (File.Exists("text/emotelist.txt"))
            {
                foreach (string s in File.ReadAllLines("text/emotelist.txt"))
                {
                    Player.emoteList.Add(s);
                }
            }
            else
            {
                File.Create("text/emotelist.txt").Dispose();
            }


            // LavaSurvival constructed here...
            lava = new LavaSurvival();

            zombie = new ZombieGame();

            LoadAllSettings();

            //derp
            if (!Server.LevelList.Contains("#(Must be comma seperated, no spaces. Must have changing levels and use level list enabled.)"))
                Server.LevelList.Add("#(Must be comma seperated, no spaces. Must have changing levels and use level list enabled.)");

            // OmniBan
            omniban = new OmniBan();

            timeOnline = DateTime.Now;
            {//MYSQL stuff
                try
                {
                    Database.executeQuery("CREATE DATABASE if not exists `" + MySQLDatabaseName + "`", true); // works in both now, SQLite simply ignores this.
                }
                //catch (MySql.Data.MySqlClient.MySqlException e)
                //{
                //    Server.s.Log("MySQL settings have not been set! Many features will not be available if MySQL is not enabled");
                //  //  Server.ErrorLog(e);
                //}
                catch (Exception e)
                {
                    ErrorLog(e);
                    s.Log("MySQL settings have not been set! Please Setup using the properties window.");
                    //process.Kill();
                    return;
                }
                Database.executeQuery(string.Format("CREATE TABLE if not exists Players (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Name TEXT, IP CHAR(15), FirstLogin DATETIME, LastLogin DATETIME, totalLogin MEDIUMINT, Title CHAR(20), TotalDeaths SMALLINT, Money MEDIUMINT UNSIGNED, totalBlocks BIGINT, totalCuboided BIGINT, totalKicked MEDIUMINT, TimeSpent VARCHAR(20), color VARCHAR(6), title_color VARCHAR(6){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : "")));
                Database.executeQuery(string.Format("CREATE TABLE if not exists Opstats (ID INTEGER {0}AUTO{1}INCREMENT NOT NULL, Time DATETIME, Name TEXT, Cmd VARCHAR(40), Cmdmsg VARCHAR(40){2});", (useMySQL ? "" : "PRIMARY KEY "), (useMySQL ? "_" : ""), (Server.useMySQL ? ", PRIMARY KEY (ID)" : "")));
                if (!File.Exists("extra/alter.txt") && Server.useMySQL) {
                	Database.executeQuery("ALTER TABLE Players MODIFY Name TEXT");
                	Database.executeQuery("ALTER TABLE Opstats MODIFY Name TEXT");
                	File.Create("extra/alter.txt");
                }
                //since 5.5.11 we are cleaning up the table Playercmds
                string query = Server.useMySQL ? "SHOW TABLES LIKE 'Playercmds'" : "SELECT name FROM sqlite_master WHERE type='table' AND name='Playercmds';";
                DataTable playercmds = Database.fillData(query); DataTable opstats = Database.fillData("SELECT * FROM Opstats");
                //if Playercmds exists copy-filter to Ostats and remove Playercmds
                if (playercmds.Rows.Count != 0) {
                    foreach (string cmd in Server.Opstats)
                        Database.executeQuery(string.Format("INSERT INTO Opstats (Time, Name, Cmd, Cmdmsg) SELECT Time, Name, Cmd, Cmdmsg FROM Playercmds WHERE cmd = '{0}';", cmd));
                    Database.executeQuery("INSERT INTO Opstats (Time, Name, Cmd, Cmdmsg) SELECT Time, Name, Cmd, Cmdmsg FROM Playercmds WHERE cmd = 'review' AND cmdmsg = 'next';");
                    Database.fillData("DROP TABLE Playercmds");
                }
                playercmds.Dispose(); opstats.Dispose();

                // Here, since SQLite is a NEW thing from 5.3.0.0, we do not have to check for existing tables in SQLite.
                if (useMySQL)
                {
                    // Check if the color column exists.
                    DataTable colorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='color'");

                    if (colorExists.Rows.Count == 0)
                    {
                        MySQL.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
                        //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN color VARCHAR(6) AFTER totalKicked");
                    }
                    colorExists.Dispose();

                    // Check if the title color column exists.
                    DataTable tcolorExists = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='title_color'");

                    if (tcolorExists.Rows.Count == 0)
                    {
                        MySQL.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
                        // else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN title_color VARCHAR(6) AFTER color");
                    }
                    tcolorExists.Dispose();

                    DataTable timespent = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='TimeSpent'");

                    if (timespent.Rows.Count == 0)
                        MySQL.executeQuery("ALTER TABLE Players ADD COLUMN TimeSpent VARCHAR(20) AFTER totalKicked"); //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN TimeSpent VARCHAR(20) AFTER totalKicked");
                    timespent.Dispose();

                    DataTable totalCuboided = MySQL.fillData("SHOW COLUMNS FROM Players WHERE `Field`='totalCuboided'");

                    if (totalCuboided.Rows.Count == 0)
                        MySQL.executeQuery("ALTER TABLE Players ADD COLUMN totalCuboided BIGINT AFTER totalBlocks"); //else SQLite.executeQuery("ALTER TABLE Players ADD COLUMN totalCuboided BIGINT AFTER totalBlocks");
                    totalCuboided.Dispose();
                }
            }

            Economy.LoadDatabase();
            UpdateStaffList();

            if (levels != null)
                foreach (Level l in levels) { l.Unload(); }
            ml.Queue(delegate
            {
                try
                {
                    levels = new List<Level>(maps);
                    MapGen = new RealisticMapGen();

                    if (File.Exists("levels/" + level + ".lvl"))
                    {
                        mainLevel = Level.Load(level);
                        mainLevel.unload = false;
                        if (mainLevel == null)
                        {
                            if (File.Exists("levels/" + level + ".lvl.backup"))
                            {
                                Log("Attempting to load backup of " + level + ".");
                                File.Copy("levels/" + level + ".lvl.backup", "levels/" + level + ".lvl", true);
                                mainLevel = Level.Load(level);
                                if (mainLevel == null)
                                {
                                    Log("BACKUP FAILED!");
                                    Console.ReadLine(); return;
                                }
                            }
                            else
                            {
                                Log("mainlevel not found");
                                mainLevel = new Level(level, 128, 64, 128, "flat") { permissionvisit = LevelPermission.Guest, permissionbuild = LevelPermission.Guest };
                                mainLevel.Save();
                                Level.CreateLeveldb(level);
                            }
                        }
                        //Wom Textures
                        if (UseTextures)
                        {
                            mainLevel.textures.sendwomid = true;
                            mainLevel.textures.enabled = true;
                            mainLevel.textures.MOTD = motd;
                            mainLevel.textures.CreateCFG();
                        }
                    }
                    else
                    {
                        Log("mainlevel not found");
                        mainLevel = new Level(level, 128, 64, 128, "flat") { permissionvisit = LevelPermission.Guest, permissionbuild = LevelPermission.Guest };
                        mainLevel.Save();
                        Level.CreateLeveldb(level);
                    }

                    addLevel(mainLevel);

                    // fenderrock - Make sure the level does have a physics thread
                    if (mainLevel.physThread == null)
                        mainLevel.StartPhysics();
                }
                catch (Exception e) { ErrorLog(e); }
            });
            Plugin.Load();
            ml.Queue(delegate
            {
                bannedIP = PlayerList.Load("banned-ip.txt", null);
                ircControllers = PlayerList.Load("IRC_Controllers.txt", null);
                muted = PlayerList.Load("muted.txt", null);

                foreach (Group grp in Group.GroupList)
                    grp.playerList = PlayerList.Load(grp.fileName, grp);
                if (useWhitelist)
                    whiteList = PlayerList.Load("whitelist.txt", null);
                if (!File.Exists("ranks/jailed.txt")) { File.Create("ranks/jailed.txt").Close(); Server.s.Log("CREATED NEW: ranks/jailed.txt"); }
                Extensions.UncapitalizeAll("ranks/banned.txt");
                Extensions.UncapitalizeAll("ranks/muted.txt");
            });

            ml.Queue(delegate
            {
                if (File.Exists("text/autoload.txt"))
                {
                    try
                    {
                        string[] lines = File.ReadAllLines("text/autoload.txt");
                        foreach (string _line in lines.Select(line => line.Trim()))
                        {
                            try
                            {
                                if (_line == "") { continue; }
                                if (_line[0] == '#') { continue; }

                                string key = _line.Split('=')[0].Trim();
                                string value;
                                try
                                {
                                    value = _line.Split('=')[1].Trim();
                                }
                                catch
                                {
                                    value = "0";
                                }

                                if (!key.Equals(mainLevel.name))
                                {
                                    Command.all.Find("load").Use(null, key + " " + value);
                                    Level l = Level.FindExact(key);
                                }
                                else
                                {
                                    try
                                    {
                                        int temp = int.Parse(value);
                                        if (temp >= 0 && temp <= 3)
                                        {
                                            mainLevel.setPhysics(temp);
                                        }
                                    }
                                    catch
                                    {
                                        s.Log("Physics variable invalid");
                                    }
                                }


                            }
                            catch
                            {
                                s.Log(_line + " failed.");
                            }
                        }
                    }
                    catch
                    {
                        s.Log("autoload.txt error");
                    }
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                else
                {
                    Log("autoload.txt does not exist");
                }
            });

            ml.Queue(delegate
            {
                foreach (string line in File.ReadAllLines("text/gcaccepted.txt"))
                {
                    gcaccepted.Add(line); //loading all playernames of people who turned off translation
                }
                Log("Creating listening socket on port " + port + "... ");
                Setup();
                //s.Log(Setup() ? "Done." : "Could not create socket connection. Shutting down.");
            });

            ml.Queue(delegate
            {
                updateTimer.Elapsed += delegate
                {
                    Player.GlobalUpdate();
                    PlayerBot.GlobalUpdatePosition();
                };

                updateTimer.Start();
            });


            // Heartbeat code here:

            ml.Queue(delegate
            {
                try
                {
                    Heart.Init();
                }
                catch (Exception e)
                {
                    Server.ErrorLog(e);
                }
            });

            ml.Queue(delegate
            {
                messageTimer.Elapsed += delegate
                {
                    RandomMessage();
                };
                messageTimer.Start();

                if (File.Exists("text/messages.txt"))
                {
                    using (StreamReader r = File.OpenText("text/messages.txt"))
                    {
                        while (!r.EndOfStream)
                            messages.Add(r.ReadLine());
                    }
                }
                else File.Create("text/messages.txt").Close();

                try
                {
                    APIServer = new WebServer(SendResponse, "http://localhost:8080/api/");
                    APIServer.Run();
                    InfoServer = new WebServer(WhoIsResponse, "http://localhost:8080/whois/");
                    InfoServer.Run();
                }
                catch
                {
                    Server.s.Log("Failed to start local API server");
                }

                IRC = new ForgeBot(Server.ircChannel, Server.ircOpChannel, Server.ircNick, Server.ircServer);
                GlobalChat = new GlobalChatBot(GlobalChatNick());

                if (Server.irc) IRC.Connect();
                if (Server.UseGlobalChat) GlobalChat.Connect();

                // OmniBan stuff!
                new Thread(new ThreadStart(() => omniban.Load(true))).Start();

                omnibanCheckTimer.Elapsed += delegate
                {
                    omniban.Load(true);
                    omniban.KickAll();
                };
                omnibanCheckTimer.Start();


                new AutoSaver(Server.backupInterval);

                blockThread = new Thread(new ThreadStart(delegate
                {
                    while (true)
                    {
                        Thread.Sleep(blockInterval * 1000);
                        try {
                            levels.ForEach(
                                delegate(Level l) {
                                    try {
                                        l.saveChanges();
                                    } catch (Exception e) {
                                        Server.ErrorLog(e);
                                    }
                                });
                        } catch (Exception e) {
                            // an exception is raised on Mono if level list is modified
                            // while enumerating over it with ForEach
                            Server.ErrorLog(e);
                        }
                    }
                }));
                blockThread.Name = "MCG_BlockUpdates";
                blockThread.Start();

                locationChecker = new Thread(new ThreadStart(delegate
                {
                    Player p, who;
                    ushort x, y, z;
                    int i;
                    while (true)
                    {
                        Thread.Sleep(3);
                        for (i = 0; i < Player.players.Count; i++)
                        {
                            try
                            {
                                p = Player.players[i];

                                if (p.frozen)
                                {
                                    unchecked { p.SendPos((byte)-1, p.pos[0], p.pos[1], p.pos[2], p.rot[0], p.rot[1]); } continue;
                                }
                                else if (p.following != "")
                                {
                                    who = Player.Find(p.following);
                                    if (who == null || who.level != p.level)
                                    {
                                        p.following = "";
                                        if (!p.canBuild)
                                        {
                                            p.canBuild = true;
                                        }
                                        if (who != null && who.possess == p.name)
                                        {
                                            who.possess = "";
                                        }
                                        continue;
                                    }
                                    if (p.canBuild)
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], (ushort)(who.pos[1] - 16), who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                    else
                                    {
                                        unchecked { p.SendPos((byte)-1, who.pos[0], who.pos[1], who.pos[2], who.rot[0], who.rot[1]); }
                                    }
                                }
                                else if (p.possess != "")
                                {
                                    who = Player.Find(p.possess);
                                    if (who == null || who.level != p.level)
                                        p.possess = "";
                                }

                                x = (ushort)(p.pos[0] / 32);
                                y = (ushort)(p.pos[1] / 32);
                                z = (ushort)(p.pos[2] / 32);

                                if (p.level.Death)
                                    p.RealDeath(x, y, z);
                                p.CheckBlock(x, y, z);

                                p.oldBlock = (ushort)(x + y + z);
                            }
                            catch (Exception e) { Server.ErrorLog(e); }
                        }
                    }
                }));
                locationChecker.Name = "MCG_LocationCheck";
                locationChecker.Start();
#if DEBUG
	  UseTextures = true;          
#endif
                Log("Finished setting up server");
                ServerSetupFinished = true;
                Checktimer.StartTimer();
                Commands.CommandKeywords.SetKeyWords();
                try
                {
                    if (Server.lava.startOnStartup)
                        Server.lava.Start();
                    if (Server.startZombieModeOnStartup)
                        Server.zombie.StartGame(1, 0);
                    //This doesnt use the main map
                    if (Server.UseCTF)
                        ctf = new Auto_CTF();
                }
                catch (Exception e) { Server.ErrorLog(e); }
                BlockQueue.Start();
            });
        }
Example #9
0
        public static Level Load(Stream lvlStream, string fileName)
        {
            byte[] temp = new byte[8];
            using (Level lvl = new Level(fileName, 0, 0, 0, "empty"))
            {
                byte[] data;
                int length;
                try
                {
                    lvlStream.Seek(-4, SeekOrigin.End);
                    lvlStream.Read(temp, 0, sizeof(int));
                    lvlStream.Seek(0, SeekOrigin.Begin);
                    length = BitConverter.ToInt32(temp, 0);
                    data = new byte[length];
                    using (GZipStream reader = new GZipStream(lvlStream, CompressionMode.Decompress, true))
                    {
                        reader.Read(data, 0, length);
                    }

                    for (int i = 0; i < length - 1; i++)
                    {
                        if (data[i] == 0xAC && data[i + 1] == 0xED)
                        {

                            // bypassing the header crap
                            int pointer = i + 6;
                            Array.Copy(data, pointer, temp, 0, sizeof(short));
                            pointer += IPAddress.HostToNetworkOrder(BitConverter.ToInt16(temp, 0));
                            pointer += 13;

                            int headerEnd = 0;
                            // find the end of serialization listing
                            for (headerEnd = pointer; headerEnd < data.Length - 1; headerEnd++)
                            {
                                if (data[headerEnd] == 0x78 && data[headerEnd + 1] == 0x70)
                                {
                                    headerEnd += 2;
                                    break;
                                }
                            }

                            // start parsing serialization listing
                            int offset = 0;
                            while (pointer < headerEnd)
                            {
                                if (data[pointer] == 'Z') offset++;
                                else if (data[pointer] == 'I' || data[pointer] == 'F') offset += 4;
                                else if (data[pointer] == 'J') offset += 8;

                                pointer += 1;
                                Array.Copy(data, pointer, temp, 0, sizeof(short));
                                short skip = IPAddress.HostToNetworkOrder(BitConverter.ToInt16(temp, 0));
                                pointer += 2;

                                // look for relevant variables
                                Array.Copy(data, headerEnd + offset - 4, temp, 0, sizeof(int));
                                if (MemCmp(data, pointer, "width"))
                                {
                                    lvl.width = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
                                }
                                else if (MemCmp(data, pointer, "depth"))
                                {
                                    lvl.depth = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
                                }
                                else if (MemCmp(data, pointer, "height"))
                                {
                                    lvl.height = (ushort)IPAddress.HostToNetworkOrder(BitConverter.ToInt32(temp, 0));
                                }

                                pointer += skip;
                            }

                            lvl.spawnx = (ushort)(lvl.width / 1.3);
                            lvl.spawny = (ushort)(lvl.depth / 1.3);
                            lvl.spawnz = (ushort)(lvl.height / 1.3);

                            // find the start of the block array
                            bool foundBlockArray = false;
                            offset = Array.IndexOf<byte>(data, 0x00, headerEnd);
                            while (offset != -1 && offset < data.Length - 2)
                            {
                                if (data[offset] == 0x00 && data[offset + 1] == 0x78 && data[offset + 2] == 0x70)
                                {
                                    foundBlockArray = true;
                                    pointer = offset + 7;
                                }
                                offset = Array.IndexOf<byte>(data, 0x00, offset + 1);
                            }

                            // copy the block array... or fail
                            if (foundBlockArray)
                            {
                                lvl.CopyBlocks(data, pointer);
                                lvl.Save(true);
                            }
                            else
                            {
                                throw new Exception("Could not locate block array.");
                            }
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Server.s.Log("Conversion failed");
                    Server.ErrorLog(ex);
                    return null;
                }

                return lvl;
            }
        }
Example #10
0
 void Update()
 {
     lvl.Save(true);
 }