Example #1
0
        protected WorldDescription LoadFromFile(string fileName)
        {
            WorldDescription desc = WorldIO.Load(fileName);

            SetTerrain(desc.Terrain);
            return(desc);
        }
        public void LoadWorld(string name)
        {
            World.UnloadTerrain();
            WorldDescription desc = WorldIO.Load(name, false);

            World.SetTerrain(desc.Terrain);
            WorldEditor.TerrainEditor.ClearUndoRedo();

            Window.UpdateTitle(name);
            CurrentFile = name;

            var commandposts = desc.GetObjectsByTag("CommandPost");

            foreach (WorldObjectDescription ob in commandposts)
            {
                Vector3           position          = ob.GetVector3("Position");
                CommandPostObject editorCommandPost = new CommandPostObject(position);
                Team team = (Team)(ob.GetField <byte>("Team") ?? 0);
                editorCommandPost.Team = team;

                World.AddGameObject(editorCommandPost);
            }

            var intels = desc.GetObjectsByTag("Intel");

            foreach (WorldObjectDescription ob in intels)
            {
                Vector3     position    = ob.GetVector3("Position");
                IntelObject editorIntel = new IntelObject(position);
                Team        team        = (Team)(ob.GetField <byte>("Team") ?? 0);
                editorIntel.Team = team;

                World.AddGameObject(editorIntel);
            }
        }
Example #3
0
    public void Save()
    {
        if (!isServer)
        {
            return;
        }

        // Save all tile layers to file.
        TileMap.SaveAll();

        // Save the player inventory:
        // This will only save the host's inventory. TODO support other clients saving inventory data.
        InventoryIO.SaveInventory(RealityName);

        // Save current gear held and worn by local player. TODO see above.
        InventoryIO.SaveGear(RealityName, Player.Local);

        // Save currently held item. TODO see above.
        InventoryIO.SaveHolding(RealityName, Player.Local);

        // Save player state (position, health, etc.)
        PlayerIO.SavePlayerState(RealityName, Player.Local);

        // Save all world items to file.
        ItemIO.ItemsToFile(RealityName, GameObject.FindObjectsOfType <Item>());

        // Save placed furniture...
        FurnitureIO.SaveFurniture(RealityName, Furniture.GetAllFurniture());

        // Save the building inventory...
        BuildingIO.SaveBuildingInventory(RealityName, Player.Local);

        // Save the world state to file.
        WorldIO.SaveWorldState(this);
    }
Example #4
0
        /// <summary>
        /// Start
        /// </summary>
        private void Start()
        {
            InputControllerScript input_controller = GetComponent <InputControllerScript>();

            if (input_controller)
            {
                input_controller.OnAnyKeyPressed += ShowMainMenu;
            }
            WorldIO.CreateClearCacheTask();
        }
        public static BackupIOReturn LoadWorld(string Name)
        {
            WorldIO.LoadWorld(Statics.WorldPath + Path.DirectorySeparatorChar + Name);

            if (WorldModify.loadFailed && !WorldModify.loadSuccess)
            {
                return(BackupIOReturn.LOAD_FAIL);
            }

            return(BackupIOReturn.SUCCESS);
        }
        public void SaveWorld(string filePath)
        {
            if (World.Terrain != null)
            {
                CurrentFile = filePath;
                Window.UpdateTitle(filePath);

                WorldDescription desc = World.CreateDescription();
                WorldIO.Save(filePath, desc, false);
            }
        }
        public void SaveWorld()
        {
            if (CurrentFile == null)
            {
                throw new InvalidOperationException("File has not yet been saved!");
            }

            if (World.Terrain != null)
            {
                WorldIO.Save(CurrentFile, World.CreateDescription(), false);
            }
        }
        public static BackupIOReturn SaveWorld(string Name)
        {
            if (WorldModify.saveLock)
            {
                return(BackupIOReturn.SAVE_LOCK);
            }
            //Please wait for the current operation to finish.

            if (WorldIO.saveWorld(Statics.WorldPath + Path.DirectorySeparatorChar + Name))
            {
                return(BackupIOReturn.SUCCESS);
            }
            else
            {
                return(BackupIOReturn.SAVE_FAIL);
            }
        }
Example #9
0
        public static void SetSpawn(ISender sender, ArgumentList args)
        {
            if (sender is Player)
            {
                var player    = sender as Player;
                var saveWorld = args.TryPop("-save");

                Main.spawnTileX = (int)(player.Position.X / 16);
                Main.spawnTileY = (int)(player.Position.Y / 16);

                if (saveWorld)
                {
                    WorldIO.SaveWorld(World.SavePath);
                }

                Server.notifyOps(String.Format("{0} set Spawn to {1}, {2}.", sender.Name, Main.spawnTileX, Main.spawnTileY));
            }
        }
Example #10
0
 public bool LoadFromFile(string fileName)
 {
     DashCMD.WriteImportant("[ServerWorld] Loading world '{0}'...", fileName);
     try
     {
         Description = WorldIO.Load(CurrentWorldName = fileName);
         SetTerrain(Description.Terrain);
         Terrain.LockBottomLayer = true;
         DashCMD.WriteImportant("[ServerWorld] Successfully loaded world '{0}'.", fileName);
         return(true);
     }
     catch (IOException ioex)
     {
         DashCMD.WriteError("[ServerWorld] Failed to load world '{0}'!", fileName);
         DashCMD.WriteError(ioex);
         return(false);
     }
 }
Example #11
0
        public static BackupResult SaveWorld(string Path)
        {
            if (WorldModify.saveLock)
            {
                return(BackupResult.SAVE_LOCK);
            }
            //Please wait for the current operation to finish.

            if (WorldIO.SaveWorld(Path))
            {
                if (Program.properties.CompressBackups)
                {
                    Compress(Path); // it just adds ".zip" to the timestamp+".wld"
                }
                return(BackupResult.SUCCESS);
            }
            else
            {
                return(BackupResult.SAVE_FAIL);
            }
        }
Example #12
0
    public void Load()
    {
        if (!isServer)
        {
            return;
        }

        // Load world state from file.
        WorldIO.LoadWorldState(this);

        // Load player state (position, health, etc.)
        PlayerIO.LoadPlayerState(RealityName, Player.Local);

        // Load all world items to map.
        ItemIO.FileToWorldItems(RealityName, true);

        // Load the player inventory.
        // This will only load the host's inventory. TODO support other clients loading inventory data.
        InventoryIO.LoadInventory(RealityName);

        // Save current gear held and worn by local player. TODO see above.
        InventoryIO.LoadGear(RealityName, Player.Local);

        // Load currently held item. TODO see above.
        InventoryIO.LoadHolding(RealityName, Player.Local);

        // Load furniture...
        FurnitureIO.LoadFurniture(this);

        // Load player building inventory...
        BuildingIO.LoadBuildingInventory(RealityName, Player.Local);

        // No need to load tile layers, this is done all the time passively.

        // Call post-load
        PostLoad();
    }
Example #13
0
    public void RealityNameChange()
    {
        if (RealityName == null)
        {
            Title.text          = "LoadReality_SelectPrompt".Translate();
            D_Day.text          = "LoadReality_DayLabel".Translate("<color=white>---</color>");
            D_LastPlayed.text   = "LoadReality_LastPlayed".Translate("<color=white>---</color>", "");
            EnterReality.text   = "LoadReality_NoneSelected".Translate();
            Play.interactable   = false;
            Delete.interactable = false;
        }
        else
        {
            Title.text          = RealityName.Trim();
            D_Day.text          = "LoadReality_DayLabel".Translate("<color=white>0</color>");
            D_LastPlayed.text   = "LoadReality_LastPlayed".Translate("<color=white>Never</color>", "");
            EnterReality.text   = "LoadReality_EnterReality".Translate(RealityName.Trim());
            Play.interactable   = true;
            Delete.interactable = true;

            WorldSaveState st = null;
            try
            {
                st = WorldIO.GetSaveState(RealityName);
            }
            catch
            {
                Debug.LogWarning(string.Format("Error loading reality state for '{0}'", RealityName));
            }

            if (st != null)
            {
                D_Day.text        = "LoadReality_DayLabel".Translate("<b><color=white>" + (int)(st.Time) + "</color></b>");
                D_LastPlayed.text = "LoadReality_LastPlayed".Translate("<b><color=white>" + st.LastPlayed.ToString("g") + "</color></b>", "<b><color=white>" + st.LastPlayed.TimeAgo() + "</color></b>");
            }
        }
    }
Example #14
0
 public override void Load(TagCompound tag)
 {
     WorldIO.LoadModData(tag.GetList <TagCompound>("list"));
     WorldIO.LoadNPCs(tag.GetList <TagCompound>("mysteryNPCs"));
     WorldIO.LoadNPCKillCounts(tag.GetList <TagCompound>("mysteryKillCounts"));
 }
        public static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main";

            //header: Terraria's Dedicated Server Mod. (1.1.2 #36) ~ Build: 37 [CodeName]
            string codeName = Statics.CODENAME.Length > 0 ? String.Format(" [{0}]", Statics.CODENAME) : String.Empty;
            string MODInfo  = String.Format(
                "Terraria's Dedicated Server Mod. ({0} #{1}) ~ Build: {2}{3}",
                Statics.VERSION_NUMBER,
                Statics.CURRENT_TERRARIA_RELEASE,
                Statics.BUILD,
                codeName
                );

            try
            {
                try
                {
                    Console.Title = MODInfo;
                }
                catch { }

                var lis = new Logging.LogTraceListener();
                System.Diagnostics.Trace.Listeners.Clear();
                System.Diagnostics.Trace.Listeners.Add(lis);
                System.Diagnostics.Debug.Listeners.Clear();
                System.Diagnostics.Debug.Listeners.Add(lis);

                using (var prog = new ProgressLogger(1, "Loading language definitions"))
                    Languages.LoadClass(Collections.Registries.LANGUAGE_FILE);

                if (Languages.Startup_Initializing == null)
                {
                    ProgramLog.Error.Log("Please update the language file, either by deleting or finding another online.");
                    Console.ReadKey(true);
                    return;
                }

                ProgramLog.Log("{0} {1}", Languages.Startup_Initializing, MODInfo);

                ProgramLog.Log(Languages.Startup_SettingUpPaths);
                if (!SetupPaths())
                {
                    return;
                }

                Platform.InitPlatform();

                ProgramLog.Log(Languages.Startup_SettingUpProperties);
                bool propertiesExist = File.Exists("server.properties");
                SetupProperties();

                if (!propertiesExist)
                {
                    ProgramLog.Console.Print(Languages.Startup_NoPropertiesFileFound);
                    if (Console.ReadLine().ToLower() == "y")
                    {
                        //ProgramLog.Console.Print(Languages.Startup_PropertiesCreationComplete);
                        ProgramLog.Log(Languages.ExitRequestCommand);
                        //Console.ReadKey(true);
                        return;
                    }
                }

                var logFile = Statics.DataPath + Path.DirectorySeparatorChar + "server.log";
                ProgramLog.OpenLogFile(logFile);

                string PIDFile = properties.PIDFile.Trim();
                if (PIDFile.Length > 0)
                {
                    string ProcessUID = Process.GetCurrentProcess().Id.ToString();
                    bool   Issue      = false;
                    if (File.Exists(PIDFile))
                    {
                        try
                        {
                            File.Delete(PIDFile);
                        }
                        catch (Exception)
                        {
                            ProgramLog.Console.Print(Languages.Startup_IssueDeletingPID);
                            if (Console.ReadLine().ToLower() == "n")
                            {
                                ProgramLog.Console.Print(Languages.Startup_PressAnyKeyToExit);
                                Console.ReadKey(true);
                                return;
                            }
                            Issue = true;
                        }
                    }
                    if (!Issue)
                    {
                        try
                        {
                            File.WriteAllText(PIDFile, ProcessUID);
                        }
                        catch (Exception)
                        {
                            ProgramLog.Console.Print(Languages.Startup_IssueCreatingPID);
                            if (Console.ReadLine().ToLower() == "n")
                            {
                                ProgramLog.Console.Print(Languages.Startup_PressAnyKeyToExit);
                                Console.ReadKey(true);
                                return;
                            }
                        }
                        ProgramLog.Log(Languages.Startup_PIDCreated + ProcessUID);
                    }
                }

                ParseArgs(args);

                try
                {
                    if (UpdateManager.PerformProcess())
                    {
                        ProgramLog.Log(Languages.Startup_RestartingIntoNewUpdate);
                        return;
                    }
                }
                catch (UpdateCompleted)
                {
                    throw;
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, Languages.Startup_ErrorUpdating);
                }

                LoadMonitor.Start();

                ProgramLog.Log(Languages.Startup_StartingRCON);
                RemoteConsole.RConServer.Start("rcon_logins.properties");

                ProgramLog.Log(Languages.Startup_StartingPermissions);
                permissionManager = new PermissionManager();

                ProgramLog.Log(Languages.Startup_PreparingServerData);

                using (var prog = new ProgressLogger(1, Languages.Startup_LoadingItemDefinitions))
                    Collections.Registries.Item.Load();
                using (var prog = new ProgressLogger(1, Languages.Startup_LoadingNPCDefinitions))
                    Collections.Registries.NPC.Load(Collections.Registries.NPC_FILE);
                using (var prog = new ProgressLogger(1, Languages.Startup_LoadingProjectileDefinitions))
                    Collections.Registries.Projectile.Load(Collections.Registries.PROJECTILE_FILE);

                //if (Languages.IsOutOfDate())
                //    ProgramLog.Error.Log(
                //        String.Format("{0}\n{1}",
                //        Languages.Startup_LanguageFileOOD, Languages.Startup_LanguageFileUpdate)
                //        , true);

                commandParser = new CommandParser();
                commandParser.ReadPermissionNodes();

                LoadPlugins();

                /* Save access languages - once only */
                Languages.Save(Collections.Registries.LANGUAGE_FILE);

                HookContext ctx;
                HookArgs.ServerStateChange eArgs;

                string   worldFile = properties.WorldPath;
                FileInfo file      = new FileInfo(worldFile);

                if (!file.Exists)
                {
                    try
                    {
                        file.Directory.Create();
                    }
                    catch (Exception exception)
                    {
                        ProgramLog.Log(exception);
                        ProgramLog.Console.Print(Languages.Startup_PressAnyKeyToExit);
                        Console.ReadKey(true);
                        return;
                    }

                    ctx = new HookContext
                    {
                        Sender = World.Sender,
                    };

                    eArgs = new HookArgs.ServerStateChange
                    {
                        ServerChangeState = ServerState.GENERATING
                    };

                    HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);

                    ProgramLog.Log("{0} '{1}'", Languages.Startup_GeneratingWorld, worldFile);

                    string seed = properties.Seed;
                    if (seed == "-1")
                    {
                        seed = WorldModify.genRand.Next(Int32.MaxValue).ToString();
                        ProgramLog.Log("{0} {1}", Languages.Startup_GeneratedSeed, seed);
                    }

                    int worldX = properties.GetMapSizes()[0];
                    int worldY = properties.GetMapSizes()[1];
                    if (properties.UseCustomTiles)
                    {
                        int X = properties.MaxTilesX;
                        int Y = properties.MaxTilesY;
                        if (X > 0 && Y > 0)
                        {
                            worldX = X;
                            worldY = Y;
                        }

                        if (worldX < (int)World.MAP_SIZE.SMALL_X || worldY < (int)World.MAP_SIZE.SMALL_Y)
                        {
                            ProgramLog.Log("{0} {1}x{2}", Languages.Startup_WorldSizingError, (int)World.MAP_SIZE.SMALL_X, (int)World.MAP_SIZE.SMALL_Y);
                            worldX = (int)((int)World.MAP_SIZE.SMALL_Y * 3.5);
                            worldY = (int)World.MAP_SIZE.SMALL_Y;
                        }

                        ProgramLog.Log("{0} {1}x{2}", Languages.Startup_GeneratingWithCustomSize, worldX, worldY);
                    }

                    Terraria_Server.Main.maxTilesX = worldX;
                    Terraria_Server.Main.maxTilesY = worldY;

                    WorldIO.ClearWorld();
                    Terraria_Server.Main.Initialize();
                    if (properties.UseCustomGenOpts)
                    {
                        WorldGen.numDungeons = properties.DungeonAmount;
                        WorldModify.ficount  = properties.FloatingIslandAmount;
                    }
                    else
                    {
                        WorldGen.numDungeons = 1;
                        WorldModify.ficount  = (int)((double)Terraria_Server.Main.maxTilesX * 0.0008);                        //The Statics one was generating with default values, We want it to use the actual tileX for the world
                    }
                    WorldGen.GenerateWorld(null, seed);
                    WorldIO.SaveWorld(worldFile, true);
                }

                ctx = new HookContext
                {
                    Sender = World.Sender,
                };

                eArgs = new HookArgs.ServerStateChange
                {
                    ServerChangeState = ServerState.LOADING
                };

                HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);

                // TODO: read map size from world file instead of config
                int worldXtiles = properties.GetMapSizes()[0];
                int worldYtiles = properties.GetMapSizes()[1];

                if (properties.UseCustomTiles)
                {
                    int X = properties.MaxTilesX;
                    int Y = properties.MaxTilesY;
                    if (X > 0 && Y > 0)
                    {
                        worldXtiles = X;
                        worldYtiles = Y;
                    }

                    if (worldXtiles < (int)World.MAP_SIZE.SMALL_X || worldYtiles < (int)World.MAP_SIZE.SMALL_Y)
                    {
                        ProgramLog.Log("{0} {1}x{2}", Languages.Startup_WorldSizingError, (int)World.MAP_SIZE.SMALL_X, (int)World.MAP_SIZE.SMALL_Y);
                        worldXtiles = (int)((int)World.MAP_SIZE.SMALL_Y * 3.5);
                        worldYtiles = (int)World.MAP_SIZE.SMALL_Y;
                    }

                    ProgramLog.Log("{0} {1}x{2}", Languages.Startup_GeneratingWithCustomSize, worldXtiles, worldXtiles);
                }

                World.SavePath = worldFile;

                Server.InitializeData(properties.MaxPlayers,
                                      Statics.DataPath + Path.DirectorySeparatorChar + "whitelist.txt",
                                      Statics.DataPath + Path.DirectorySeparatorChar + "banlist.txt",
                                      Statics.DataPath + Path.DirectorySeparatorChar + "oplist.txt");
                NetPlay.password   = properties.Password;
                NetPlay.serverPort = properties.Port;
                NetPlay.serverSIP  = properties.ServerIP;
                Terraria_Server.Main.Initialize();

                Terraria_Server.Main.maxTilesX    = worldXtiles;
                Terraria_Server.Main.maxTilesY    = worldYtiles;
                Terraria_Server.Main.maxSectionsX = worldXtiles / 200;
                Terraria_Server.Main.maxSectionsY = worldYtiles / 150;

                WorldIO.LoadWorld(null, null, World.SavePath);

                ctx = new HookContext
                {
                    Sender = World.Sender,
                };

                eArgs = new HookArgs.ServerStateChange
                {
                    ServerChangeState = ServerState.LOADED
                };

                HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);

                updateThread = new ProgramThread("Updt", Program.UpdateLoop);

                ProgramLog.Log(Languages.Startup_StartingTheServer);
                NetPlay.StartServer();

                while (!NetPlay.ServerUp)
                {
                }

                ThreadPool.QueueUserWorkItem(CommandThread);
                ProgramLog.Console.Print(Languages.Startup_YouCanNowInsertCommands);

                while (WorldModify.saveLock || NetPlay.ServerUp || Restarting)
                {
                    Thread.Sleep(100);
                }

                ProgramLog.Log(Languages.Startup_Exiting);
                Thread.Sleep(1000);
            }
            catch (UpdateCompleted) { }
            catch (Exception e)
            {
                try
                {
                    using (StreamWriter streamWriter = new StreamWriter(Statics.DataPath + Path.DirectorySeparatorChar + "crashlog.txt", true))
                    {
                        streamWriter.WriteLine(DateTime.Now);
                        streamWriter.WriteLine(String.Format("{0} {1}", Languages.Startup_CrashlogGeneratedBy, MODInfo));
                        streamWriter.WriteLine(e);
                        streamWriter.WriteLine();
                    }
                    ProgramLog.Log(e, Languages.Startup_ProgramCrash);
                    ProgramLog.Log("{0} crashlog.txt -> http://tdsm.org/", Languages.Startup_PleaseSend);
                }
                catch { }
            }

            if (properties != null && File.Exists(properties.PIDFile.Trim()))
            {
                File.Delete(properties.PIDFile.Trim());
            }

            Thread.Sleep(500);
            ProgramLog.Log(Languages.Startup_LogEnd);
            ProgramLog.Close();

            RemoteConsole.RConServer.Stop();
        }
Example #16
0
 public override void LoadWorldData(TagCompound tag)
 {
     WorldIO.LoadModData(tag.GetList <TagCompound>("list"));
     WorldIO.LoadNPCs(tag.GetList <TagCompound>("unloadedNPCs"));
     WorldIO.LoadNPCKillCounts(tag.GetList <TagCompound>("unloadedKillCounts"));
 }
        private static void UpdateTime()
        {
            Time += 1.0;

            if (!dayTime)
            {
                if (WorldModify.spawnEye && Time > 4860.0)
                {
                    foreach (Player player in players)
                    {
                        if (player.Active && !player.dead && (double)player.Position.Y < worldSurface * 16.0)
                        {
                            NPC.SpawnOnPlayer(player.whoAmi, 4);
                            WorldModify.spawnEye = false;
                            break;
                        }
                    }
                }

                if (Time > 32400.0)
                {
                    checkXmas();

                    if (invasionDelay > 0)
                    {
                        invasionDelay--;
                    }

                    WorldModify.spawnNPC = 0;
                    checkForSpawns       = 0;
                    Time      = 0.0;
                    bloodMoon = false;
                    dayTime   = true;
                    moonPhase++;
                    if (moonPhase >= 8)
                    {
                        moonPhase = 0;
                    }

                    NetMessage.SendData(7);
                    WorldIO.SaveWorldThreaded();

                    if (WorldModify.shadowOrbSmashed)
                    {
                        var startInvasion = !NPC.downedGoblins ? rand.Next(3) == 0 : rand.Next(15) == 0;
                        if (startInvasion)
                        {
                            StartInvasion();
                        }
                    }
                }
                if (Time > 16200.0 && WorldModify.spawnMeteor)
                {
                    WorldModify.spawnMeteor = false;
                    WorldModify.dropMeteor(null, null);
                    return;
                }
            }
            else
            {
                bloodMoon = false;
                if (Time > 54000.0)
                {
                    WorldModify.spawnNPC = 0;
                    checkForSpawns       = 0;
                    if (rand.Next(50) == 0 && WorldModify.shadowOrbSmashed)
                    {
                        WorldModify.spawnMeteor = true;
                    }

                    if (!NPC.downedBoss1)
                    {
                        bool flag = false;
                        foreach (Player player in players)
                        {
                            if (player.Active && player.statLifeMax >= 200 && player.statDefense > 10)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (flag && rand.Next(3) == 0)
                        {
                            int num = 0;
                            for (int i = 0; i < NPC.MAX_NPCS; i++)
                            {
                                if (npcs[i].Active && npcs[i].townNPC)
                                {
                                    num++;
                                }
                            }

                            if (num >= 4)
                            {
                                WorldModify.spawnEye = true;

                                NetMessage.SendData(25, -1, -1, "You feel an evil presence watching you...", 255, 50f, 255f, 130f);
                            }
                        }
                    }
                    if (!WorldModify.spawnEye && moonPhase != 4 && rand.Next(9) == 0)
                    {
                        for (int i = 0; i < 255; i++)
                        {
                            if (players[i].Active && players[i].statLifeMax > 100)
                            {
                                bloodMoon = true;
                                break;
                            }
                        }

                        if (bloodMoon)
                        {
                            NetMessage.SendData(25, -1, -1, "The Blood Moon is rising...", 255, 50f, 255f, 130f);
                        }
                    }
                    Time    = 0.0;
                    dayTime = false;

                    NetMessage.SendData(7);
                }

                //checkForSpawns++;
                if (++checkForSpawns >= 7200)
                {
                    int num2 = 0;
                    for (int i = 0; i < 255; i++)
                    {
                        if (players[i].Active)
                        {
                            num2++;
                        }
                    }

                    checkForSpawns       = 0;
                    WorldModify.spawnNPC = 0;
                    int num3  = 0;
                    int num4  = 0;
                    int num5  = 0;
                    int num6  = 0;
                    int num7  = 0;
                    int num8  = 0;
                    int num9  = 0;
                    int num10 = 0;
                    int num11 = 0;

                    int goblin = 0, wizard = 0, mechanic = 0, santa = 0;

                    for (int i = 0; i < NPC.MAX_NPCS; i++)
                    {
                        if (npcs[i].Active && npcs[i].townNPC)
                        {
                            if (npcs[i].type != NPCType.N37_OLD_MAN && !npcs[i].homeless)
                            {
                                WorldModify.QuickFindHome(null, i);
                            }

                            switch (npcs[i].type)
                            {
                            case NPCType.N37_OLD_MAN:
                                num8++;
                                break;

                            case NPCType.N17_MERCHANT:
                                num3++;
                                break;

                            case NPCType.N18_NURSE:
                                num4++;
                                break;

                            case NPCType.N19_ARMS_DEALER:
                                num6++;
                                break;

                            case NPCType.N20_DRYAD:
                                num5++;
                                break;

                            case NPCType.N22_GUIDE:
                                num7++;
                                break;

                            case NPCType.N38_DEMOLITIONIST:
                                num9++;
                                break;

                            case NPCType.N54_CLOTHIER:
                                num10++;
                                break;

                            case NPCType.N107_GOBLIN_TINKERER:
                                goblin++;
                                break;

                            case NPCType.N108_WIZARD:
                                wizard++;
                                break;

                            case NPCType.N124_MECHANIC:
                                mechanic++;
                                break;

                            case NPCType.N142_SANTA_CLAUS:
                                santa++;
                                break;
                            }
                            num11++;
                        }
                    }
                    if (WorldModify.spawnNPC == 0)
                    {
                        int  num12 = 0;
                        bool flag2 = false;
                        int  num13 = 0;
                        bool flag3 = false;
                        bool flag4 = false;
                        for (int i = 0; i < 255; i++)
                        {
                            if (players[i].Active)
                            {
                                for (int j = 0; j < 44; j++)
                                {
                                    if (players[i].inventory[j] != null & players[i].inventory[j].Stack > 0)
                                    {
                                        if (players[i].inventory[j].Type == 71)
                                        {
                                            num12 += players[i].inventory[j].Stack;
                                        }
                                        if (players[i].inventory[j].Type == 72)
                                        {
                                            num12 += players[i].inventory[j].Stack * 100;
                                        }
                                        if (players[i].inventory[j].Type == 73)
                                        {
                                            num12 += players[i].inventory[j].Stack * 10000;
                                        }
                                        if (players[i].inventory[j].Type == 74)
                                        {
                                            num12 += players[i].inventory[j].Stack * 1000000;
                                        }
                                        if (players[i].inventory[j].Ammo == ProjectileType.N14_BULLET || players[i].inventory[j].UseAmmo == ProjectileType.N14_BULLET)
                                        {
                                            flag3 = true;
                                        }
                                        if (players[i].inventory[j].Type == 166 || players[i].inventory[j].Type == 167 || players[i].inventory[j].Type == 168 || players[i].inventory[j].Type == 235)
                                        {
                                            flag4 = true;
                                        }
                                    }
                                }
                                int num14 = players[i].statLifeMax / 20;
                                if (num14 > 5)
                                {
                                    flag2 = true;
                                }
                                num13 += num14;
                            }
                        }

                        if (!NPC.downedBoss3 && num8 == 0)
                        {
                            int num15 = NPC.NewNPC(dungeonX * 16 + 8, dungeonY * 16, 37, 0);
                            npcs[num15].homeless  = false;
                            npcs[num15].homeTileX = dungeonX;
                            npcs[num15].homeTileY = dungeonY;
                        }

                        if (WorldModify.spawnNPC == 0 && num7 < 1)
                        {
                            WorldModify.spawnNPC = 22;
                        }
                        if (WorldModify.spawnNPC == 0 && (double)num12 > 5000.0 && num3 < 1)
                        {
                            WorldModify.spawnNPC = 17;
                        }
                        if (WorldModify.spawnNPC == 0 && flag2 && num4 < 1)
                        {
                            WorldModify.spawnNPC = 18;
                        }
                        if (WorldModify.spawnNPC == 0 && flag3 && num6 < 1)
                        {
                            WorldModify.spawnNPC = 19;
                        }
                        if (WorldModify.spawnNPC == 0 && (NPC.downedBoss1 || NPC.downedBoss2 || NPC.downedBoss3) && num5 < 1)
                        {
                            WorldModify.spawnNPC = 20;
                        }
                        if (WorldModify.spawnNPC == 0 && flag4 && num3 > 0 && num9 < 1)
                        {
                            WorldModify.spawnNPC = 38;
                        }
                        if (WorldModify.spawnNPC == 0 && NPC.downedBoss3 && num10 < 1)
                        {
                            WorldModify.spawnNPC = 54;
                        }
                        if (WorldModify.spawnNPC == 0 && NPC.savedGoblin && goblin < 1)
                        {
                            WorldModify.spawnNPC = 107;
                        }
                        if (WorldModify.spawnNPC == 0 && NPC.savedWizard && wizard < 1)
                        {
                            WorldModify.spawnNPC = 108;
                        }
                        if (WorldModify.spawnNPC == 0 && NPC.savedMech && mechanic < 1)
                        {
                            WorldModify.spawnNPC = 124;
                        }
                        if (WorldModify.spawnNPC == 0 && NPC.downedFrost && santa < 1 && Xmas)
                        {
                            WorldModify.spawnNPC = 142;
                        }
                    }
                }
            }
        }
        public static void ServerLoop()
        {
            Main.players[255].whoAmi = 255;
            NetPlay.serverIP         = IPAddress.Parse(serverSIP);
            NetPlay.serverListenIP   = NetPlay.serverIP;
            NetPlay.disconnect       = false;

            //			for (int i = 0; i < 256; i++)
            //			{
            ////                Netplay.slots[i] = new ServerSlot();
            //                Netplay.slots[i].whoAmI = i;
            //				Netplay.slots[i].Reset();
            //			}
            Init();

            NetPlay.tcpListener = new TcpListener(NetPlay.serverListenIP, NetPlay.serverPort);

            try
            {
                NetPlay.tcpListener.Start();
            }
            catch (Exception exception)
            {
                ProgramLog.Error.Log("Error Starting the Server: {0}", exception);
                NetPlay.disconnect = true;
            }

            if (!NetPlay.disconnect)
            {
                if (!Program.updateThread.IsAlive)
                {
                    Program.updateThread.Start();
                }
                ProgramLog.Admin.Log("{0} {1}:{2}", Language.Languages.ServerStartedOn, serverSIP, serverPort);
                //                ProgramLog.Log("Loading Plugins...");
                //				PluginManager.LoadAllPlugins();
                //                ProgramLog.Log("Plugins Loaded: " + PluginManager.Plugins.Count.ToString());
                //Statics.serverStarted = true;
            }
            else
            {
                return;
            }

            SlotManager.Initialize(Program.properties.MaxPlayers, Program.properties.OverlimitSlots);

            ServerUp = true;
            var serverSock = NetPlay.tcpListener.Server;

            try
            {
                while (!NetPlay.disconnect)
                {
                    NetPlay.anyClients = Networking.ClientConnection.All.Count > 0;                     //clientList.Count > 0;

                    serverSock.Poll(500000, SelectMode.SelectRead);

                    if (NetPlay.disconnect)
                    {
                        break;
                    }

                    // Accept new clients
                    while (NetPlay.tcpListener.Pending())
                    {
                        var client   = NetPlay.tcpListener.AcceptSocket();
                        var accepted = AcceptClient(client);
                        if (accepted)
                        {
                            NetPlay.anyClients = true;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                ProgramLog.Log(e, "ServerLoop terminated with exception");
            }

            NetPlay.anyClients = false;

            try
            {
                tcpListener.Stop();
            }
            catch (SocketException) { }



            lock (Networking.ClientConnection.All)
            {
                var conns = Networking.ClientConnection.All.ToArray();

                foreach (var conn in conns)
                {
                    conn.Kick("Server is shutting down.");
                }
            }

            for (int i = 0; i < 255; i++)
            {
                try
                {
                    slots[i].Kick("Server is shutting down.");
                }
                catch { }
            }

            Thread.Sleep(1000);

            for (int i = 0; i < 255; i++)
            {
                try
                {
                    slots[i].Reset();
                }
                catch { }
            }

            if (!WorldIO.SaveWorld(World.SavePath, true))
            {
                ProgramLog.Error.Log("Saving failed.  Quitting without saving.");
            }

            ServerUp = false;
        }
Example #19
0
        //static TimeChangedEvent timeEvent = new TimeChangedEvent();
        private static void UpdateTime()
        {
            Main.time += 1.0;

            //Server.PluginManager.processHook(Hooks.TIME_CHANGED, timeEvent);

            if (!Main.dayTime)
            {
                if (WorldModify.spawnEye)
                {
                    if (Main.time > 4860.0)
                    {
                        int count = 0;
                        foreach (Player player in Main.players)
                        {
                            if (player.Active && !player.dead && (double)player.Position.Y < Main.worldSurface * 16.0)
                            {
                                NPC.SpawnOnPlayer(player, count, 4);
                                WorldModify.spawnEye = false;
                                break;
                            }
                            count++;
                        }
                    }
                }

                if (Main.time > 32400.0)
                {
                    if (Main.invasionDelay > 0)
                    {
                        Main.invasionDelay--;
                    }
                    WorldModify.spawnNPC = 0;
                    Main.checkForSpawns  = 0;
                    Main.time            = 0.0;
                    Main.bloodMoon       = false;
                    Main.dayTime         = true;
                    Main.moonPhase++;
                    if (Main.moonPhase >= 8)
                    {
                        Main.moonPhase = 0;
                    }

                    NetMessage.SendData(7);
                    WorldIO.SaveWorldThreaded();

                    if (Main.rand.Next(15) == 0)
                    {
                        Main.StartInvasion();
                    }
                }
                if (Main.time > 16200.0 && WorldModify.spawnMeteor)
                {
                    WorldModify.spawnMeteor = false;
                    WorldModify.dropMeteor();
                }
            }
            else
            {
                if (Main.time > 54000.0)
                {
                    WorldModify.spawnNPC = 0;
                    Main.checkForSpawns  = 0;
                    if (Main.rand.Next(50) == 0 && WorldModify.shadowOrbSmashed)
                    {
                        WorldModify.spawnMeteor = true;
                    }
                    if (!NPC.downedBoss1)
                    {
                        bool flag = false;
                        foreach (Player player in Main.players)
                        {
                            if (player.Active && player.statLifeMax >= 200)
                            {
                                flag = true;
                                break;
                            }
                        }
                        if (flag && Main.rand.Next(3) == 0)
                        {
                            int num = 0;
                            for (int i = 0; i < NPC.MAX_NPCS; i++)
                            {
                                if (Main.npcs[i].Active)
                                {
                                    if (Main.npcs[i].townNPC)
                                    {
                                        num++;
                                    }
                                }
                            }
                            if (num >= 4)
                            {
                                WorldModify.spawnEye = true;

                                NetMessage.SendData(25, -1, -1, "You feel an evil presence watching you...", 255, 50f, 255f, 130f);
                            }
                        }
                    }
                    if (!WorldModify.spawnEye && Main.moonPhase != 4 && Main.rand.Next(7) == 0)
                    {
                        for (int i = 0; i < 255; i++)
                        {
                            if (Main.players[i].Active && Main.players[i].statLifeMax > 100)
                            {
                                Main.bloodMoon = true;
                                break;
                            }
                        }
                        if (Main.bloodMoon)
                        {
                            NetMessage.SendData(25, -1, -1, "The Blood Moon is rising...", 255, 50f, 255f, 130f);
                        }
                    }
                    Main.time    = 0.0;
                    Main.dayTime = false;

                    NetMessage.SendData(7);
                }
                Main.checkForSpawns++;
                if (Main.checkForSpawns >= 7200)
                {
                    int num2 = 0;
                    for (int i = 0; i < 255; i++)
                    {
                        if (Main.players[i].Active)
                        {
                            num2++;
                        }
                    }
                    Main.checkForSpawns  = 0;
                    WorldModify.spawnNPC = 0;
                    int num3  = 0;
                    int num4  = 0;
                    int num5  = 0;
                    int num6  = 0;
                    int num7  = 0;
                    int num8  = 0;
                    int num9  = 0;
                    int num10 = 0;
                    int num11 = 0;
                    for (int i = 0; i < NPC.MAX_NPCS; i++)
                    {
                        if (Main.npcs[i].Active && Main.npcs[i].townNPC)
                        {
                            if (Main.npcs[i].type != NPCType.N37_OLD_MAN && !Main.npcs[i].homeless)
                            {
                                WorldModify.QuickFindHome(i);
                            }
                            else
                            {
                                num8++;
                            }
                            switch (Main.npcs[i].type)
                            {
                            case NPCType.N17_MERCHANT:
                                num3++;
                                break;

                            case NPCType.N18_NURSE:
                                num4++;
                                break;

                            case NPCType.N19_ARMS_DEALER:
                                num6++;
                                break;

                            case NPCType.N20_DRYAD:
                                num5++;
                                break;

                            case NPCType.N22_GUIDE:
                                num7++;
                                break;

                            case NPCType.N38_DEMOLITIONIST:
                                num9++;
                                break;

                            case NPCType.N54_CLOTHIER:
                                num10++;
                                break;
                            }
                            num11++;
                        }
                    }
                    if (WorldModify.spawnNPC == 0)
                    {
                        int  num12 = 0;
                        bool flag2 = false;
                        int  num13 = 0;
                        bool flag3 = false;
                        bool flag4 = false;
                        for (int i = 0; i < 255; i++)
                        {
                            if (Main.players[i].Active)
                            {
                                for (int j = 0; j < 44; j++)
                                {
                                    if (Main.players[i].inventory[j] != null & Main.players[i].inventory[j].Stack > 0)
                                    {
                                        if (Main.players[i].inventory[j].Type == 71)
                                        {
                                            num12 += Main.players[i].inventory[j].Stack;
                                        }
                                        if (Main.players[i].inventory[j].Type == 72)
                                        {
                                            num12 += Main.players[i].inventory[j].Stack * 100;
                                        }
                                        if (Main.players[i].inventory[j].Type == 73)
                                        {
                                            num12 += Main.players[i].inventory[j].Stack * 10000;
                                        }
                                        if (Main.players[i].inventory[j].Type == 74)
                                        {
                                            num12 += Main.players[i].inventory[j].Stack * 1000000;
                                        }
                                        if (Main.players[i].inventory[j].Ammo == ProjectileType.N14_BULLET || Main.players[i].inventory[j].UseAmmo == ProjectileType.N14_BULLET)
                                        {
                                            flag3 = true;
                                        }
                                        if (Main.players[i].inventory[j].Type == 166 || Main.players[i].inventory[j].Type == 167 || Main.players[i].inventory[j].Type == 168 || Main.players[i].inventory[j].Type == 235)
                                        {
                                            flag4 = true;
                                        }
                                    }
                                }
                                int num14 = Main.players[i].statLifeMax / 20;
                                if (num14 > 5)
                                {
                                    flag2 = true;
                                }
                                num13 += num14;
                            }
                        }
                        if (num7 < 1)
                        {
                            WorldModify.spawnNPC = 22;
                        }
                        if ((double)num12 > 5000.0 && num3 < 1)
                        {
                            WorldModify.spawnNPC = 17;
                        }
                        if (flag2 && num4 < 1)
                        {
                            WorldModify.spawnNPC = 18;
                        }
                        if (flag3 && num6 < 1)
                        {
                            WorldModify.spawnNPC = 19;
                        }
                        if ((NPC.downedBoss1 || NPC.downedBoss2 || NPC.downedBoss3) && num5 < 1)
                        {
                            WorldModify.spawnNPC = 20;
                        }
                        if (flag4 && num3 > 0 && num9 < 1)
                        {
                            WorldModify.spawnNPC = 38;
                        }
                        if (NPC.downedBoss3 && num10 < 1)
                        {
                            WorldModify.spawnNPC = 54;
                        }
                        if (num12 > 100000 && num3 < 2 && num2 > 2)
                        {
                            WorldModify.spawnNPC = 17;
                        }
                        if (num13 >= 20 && num4 < 2 && num2 > 2)
                        {
                            WorldModify.spawnNPC = 18;
                        }
                        if (num12 > 5000000 && num3 < 3 && num2 > 4)
                        {
                            WorldModify.spawnNPC = 17;
                        }
                        if (!NPC.downedBoss3 && num8 == 0)
                        {
                            int num15 = NPC.NewNPC(Main.dungeonX * 16 + 8, Main.dungeonY * 16, 37, 0);
                            Main.npcs[num15].homeless  = false;
                            Main.npcs[num15].homeTileX = Main.dungeonX;
                            Main.npcs[num15].homeTileY = Main.dungeonY;
                        }
                    }
                }
            }
        }
Example #20
0
 public override void Load(TagCompound tag)
 {
     WorldIO.LoadModData(tag.GetList <TagCompound>("list"));
 }
Example #21
0
        public static void Main(string[] args)
        {
            Thread.CurrentThread.Name = "Main";
            try
            {
                string MODInfo = "Terraria's Dedicated Server Mod. (" + VERSION_NUMBER + " {" + Statics.CURRENT_TERRARIA_RELEASE + "}) #"
                                 + Statics.BUILD;
                try
                {
                    Console.Title = MODInfo;
                }
                catch
                {
                }

                var lis = new Logging.LogTraceListener();
                System.Diagnostics.Trace.Listeners.Clear();
                System.Diagnostics.Trace.Listeners.Add(lis);
                System.Diagnostics.Debug.Listeners.Clear();
                System.Diagnostics.Debug.Listeners.Add(lis);

                ProgramLog.Log("Initializing " + MODInfo);

                ProgramLog.Log("Setting up Paths.");
                if (!SetupPaths())
                {
                    return;
                }

                Platform.InitPlatform();

                ProgramLog.Log("Setting up Properties.");
                bool propertiesExist = File.Exists("server.properties");
                SetupProperties();

                if (!propertiesExist)
                {
                    ProgramLog.Console.Print("New properties file created. Would you like to exit for editing? [Y/n]: ");
                    if (Console.ReadLine().ToLower() == "y")
                    {
                        ProgramLog.Console.Print("Complete, Press any Key to Exit...");
                        Console.ReadKey(true);
                        return;
                    }
                }

                var logFile = Statics.DataPath + Path.DirectorySeparatorChar + "server.log";
                ProgramLog.OpenLogFile(logFile);

                string PIDFile = properties.PIDFile.Trim();
                if (PIDFile.Length > 0)
                {
                    string ProcessUID = Process.GetCurrentProcess().Id.ToString();
                    bool   Issue      = false;
                    if (File.Exists(PIDFile))
                    {
                        try
                        {
                            File.Delete(PIDFile);
                        }
                        catch (Exception)
                        {
                            ProgramLog.Console.Print("Issue deleting PID file, Continue? [Y/n]: ");
                            if (Console.ReadLine().ToLower() == "n")
                            {
                                ProgramLog.Console.Print("Press any Key to Exit...");
                                Console.ReadKey(true);
                                return;
                            }
                            Issue = true;
                        }
                    }
                    if (!Issue)
                    {
                        try
                        {
                            File.WriteAllText(PIDFile, ProcessUID);
                        }
                        catch (Exception)
                        {
                            ProgramLog.Console.Print("Issue creating PID file, Continue? [Y/n]: ");
                            if (Console.ReadLine().ToLower() == "n")
                            {
                                ProgramLog.Console.Print("Press any Key to Exit...");
                                Console.ReadKey(true);
                                return;
                            }
                        }
                        ProgramLog.Log("PID File Created, Process ID: " + ProcessUID);
                    }
                }

                ParseArgs(args);

                try
                {
                    if (UpdateManager.performProcess())
                    {
                        ProgramLog.Log("Restarting into new update!");
                        return;
                    }
                }
                catch (UpdateCompleted)
                {
                    throw;
                }
                catch (Exception e)
                {
                    ProgramLog.Log(e, "Error updating");
                }

                LoadMonitor.Start();

                ProgramLog.Log("Starting remote console server");
                RemoteConsole.RConServer.Start("rcon_logins.properties");

                ProgramLog.Log("Starting permissions manager");
                permissionManager = new PermissionManager();

                ProgramLog.Log("Preparing Server Data...");

                using (var prog = new ProgressLogger(1, "Loading item definitions"))
                    Collections.Registries.Item.Load();
                using (var prog = new ProgressLogger(1, "Loading NPC definitions"))
                    Collections.Registries.NPC.Load(Collections.Registries.NPC_FILE);
                using (var prog = new ProgressLogger(1, "Loading projectile definitions"))
                    Collections.Registries.Projectile.Load(Collections.Registries.PROJECTILE_FILE);

                commandParser = new CommandParser();
                commandParser.ReadPermissionNodes();

                ProgramLog.Log("Loading plugins...");
                Terraria_Server.Plugins.PluginManager.Initialize(Statics.PluginPath, Statics.LibrariesPath);

                var ctx = new HookContext()
                {
                    Sender = new ConsoleSender()
                };

                var eArgs = new HookArgs.ServerStateChange()
                {
                    ServerChangeState = ServerState.INITIALIZING
                };

                HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);
                PluginManager.LoadPlugins();
                ProgramLog.Log("Plugins loaded: " + PluginManager.PluginCount);

                string   worldFile = properties.WorldPath;
                FileInfo file      = new FileInfo(worldFile);

                if (!file.Exists)
                {
                    try
                    {
                        file.Directory.Create();
                    }
                    catch (Exception exception)
                    {
                        ProgramLog.Log(exception);
                        ProgramLog.Console.Print("Press any key to continue...");
                        Console.ReadKey(true);
                        return;
                    }

                    ctx = new HookContext
                    {
                        Sender = World.Sender,
                    };

                    eArgs = new HookArgs.ServerStateChange
                    {
                        ServerChangeState = ServerState.GENERATING
                    };

                    HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);

                    ProgramLog.Log("Generating world '{0}'", worldFile);

                    string seed = properties.Seed;
                    if (seed == "-1")
                    {
                        seed = new Random().Next(100).ToString();
                        ProgramLog.Log("Generated seed: {0}", seed);
                    }

                    int worldX = properties.GetMapSizes()[0];
                    int worldY = properties.GetMapSizes()[1];
                    if (properties.UseCustomTiles)
                    {
                        int X = properties.MaxTilesX;
                        int Y = properties.MaxTilesY;
                        if (X > 0 && Y > 0)
                        {
                            worldX = X;
                            worldY = Y;
                        }

                        if (worldX < (int)World.MAP_SIZE.SMALL_X || worldY < (int)World.MAP_SIZE.SMALL_Y)
                        {
                            ProgramLog.Log("World dimensions need to be equal to or larger than {0} by {1}; using built-in 'small'", (int)World.MAP_SIZE.SMALL_X, (int)World.MAP_SIZE.SMALL_Y);
                            worldX = (int)((int)World.MAP_SIZE.SMALL_Y * 3.5);
                            worldY = (int)World.MAP_SIZE.SMALL_Y;
                        }

                        ProgramLog.Log("Generating world with custom map size: {0}x{1}", worldX, worldY);
                    }

                    Terraria_Server.Main.maxTilesX = worldX;
                    Terraria_Server.Main.maxTilesY = worldY;

                    WorldIO.clearWorld();
                    Terraria_Server.Main.Initialize();
                    if (properties.UseCustomGenOpts)
                    {
                        WorldGen.numDungeons = properties.DungeonAmount;
                        WorldModify.ficount  = properties.FloatingIslandAmount;
                    }
                    else
                    {
                        WorldGen.numDungeons = 1;
                        WorldModify.ficount  = (int)((double)Terraria_Server.Main.maxTilesX * 0.0008); //The Statics one was generating with default values, We want it to use the actual tileX for the world
                    }
                    WorldGen.GenerateWorld(seed);
                    WorldIO.saveWorld(worldFile, true);
                }

                ctx = new HookContext
                {
                    Sender = World.Sender,
                };

                eArgs = new HookArgs.ServerStateChange
                {
                    ServerChangeState = ServerState.LOADING
                };

                HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);

                // TODO: read map size from world file instead of config
                int worldXtiles = properties.GetMapSizes()[0];
                int worldYtiles = properties.GetMapSizes()[1];

                if (properties.UseCustomTiles)
                {
                    int X = properties.MaxTilesX;
                    int Y = properties.MaxTilesY;
                    if (X > 0 && Y > 0)
                    {
                        worldXtiles = X;
                        worldYtiles = Y;
                    }

                    if (worldXtiles < (int)World.MAP_SIZE.SMALL_X || worldYtiles < (int)World.MAP_SIZE.SMALL_Y)
                    {
                        ProgramLog.Log("World dimensions need to be equal to or larger than {0} by {1}; using built-in 'small'", (int)World.MAP_SIZE.SMALL_X, (int)World.MAP_SIZE.SMALL_Y);
                        worldXtiles = (int)((int)World.MAP_SIZE.SMALL_Y * 3.5);
                        worldYtiles = (int)World.MAP_SIZE.SMALL_Y;
                    }

                    ProgramLog.Log("Using world with custom map size: {0}x{1}", worldXtiles, worldYtiles);
                }

                World world = new World(worldXtiles, worldYtiles);
                world.SavePath = worldFile;

                Server.InitializeData(world, properties.MaxPlayers,
                                      Statics.DataPath + Path.DirectorySeparatorChar + "whitelist.txt",
                                      Statics.DataPath + Path.DirectorySeparatorChar + "banlist.txt",
                                      Statics.DataPath + Path.DirectorySeparatorChar + "oplist.txt");
                NetPlay.password   = properties.Password;
                NetPlay.serverPort = properties.Port;
                NetPlay.serverSIP  = properties.ServerIP;
                Terraria_Server.Main.Initialize();

                Terraria_Server.Main.maxTilesX    = worldXtiles;
                Terraria_Server.Main.maxTilesY    = worldYtiles;
                Terraria_Server.Main.maxSectionsX = worldXtiles / 200;
                Terraria_Server.Main.maxSectionsY = worldYtiles / 150;

                WorldIO.LoadWorld(Server.World.SavePath);

                ctx = new HookContext
                {
                    Sender = World.Sender,
                };

                eArgs = new HookArgs.ServerStateChange
                {
                    ServerChangeState = ServerState.LOADED
                };

                HookPoints.ServerStateChange.Invoke(ref ctx, ref eArgs);

                updateThread = new ProgramThread("Updt", Program.UpdateLoop);

                ProgramLog.Log("Starting the Server");
                NetPlay.StartServer();

                while (!NetPlay.ServerUp)
                {
                }

                ProgramLog.Console.Print("You can now insert Commands.");

                while (!Statics.Exit)
                {
                    try
                    {
                        string line = Console.ReadLine();
                        if (line.Length > 0)
                        {
                            commandParser.ParseConsoleCommand(line);
                        }
                    }
                    catch (ExitException e)
                    {
                        ProgramLog.Log(e.Message);
                        break;
                    }
                    catch (Exception e)
                    {
                        ProgramLog.Log(e, "Issue parsing console command");
                    }
                }

                while (WorldModify.saveLock || NetPlay.ServerUp)
                {
                    Thread.Sleep(100);
                }

                ProgramLog.Log("Exiting...");
                Thread.Sleep(1000);
            }
            catch (UpdateCompleted)
            {
            }
            catch (Exception e)
            {
                try
                {
                    using (StreamWriter streamWriter = new StreamWriter(Statics.DataPath + Path.DirectorySeparatorChar + "crashlog.txt", true))
                    {
                        streamWriter.WriteLine(DateTime.Now);
                        streamWriter.WriteLine("Crash Log Generated by TDSM #" + Statics.BUILD + " for " + //+ " r" + Statics.revision + " for " +
                                               VERSION_NUMBER + " {" + Statics.CURRENT_TERRARIA_RELEASE + "}");
                        streamWriter.WriteLine(e);
                        streamWriter.WriteLine("");
                    }
                    ProgramLog.Log(e, "Program crash");
                    ProgramLog.Log("Please send crashlog.txt to http://tdsm.org/");
                }
                catch
                {
                }
            }

            if (File.Exists(properties.PIDFile.Trim()))
            {
                File.Delete(properties.PIDFile.Trim());
            }

            Thread.Sleep(500);
            ProgramLog.Log("Log end.");
            ProgramLog.Close();

            RemoteConsole.RConServer.Stop();
        }