World instance
Inheritance: IClassy
Example #1
1
        public FeedData( Block _textType, Vector3I _pos, Bitmap Image, World world, Direction direction_, Player player_ )
        {
            direction = direction_;
            Blocks = new ConcurrentDictionary<string, Vector3I>();
            Init( Image, world );
            Pos = _pos;
            textType = ( byte )_textType;
            bgType = ( byte )Block.Air;
            FeedData.AddMessages();
            MessageCount = 0;
            Sentence = FeedData.Messages[MessageCount];
            Id = System.Threading.Interlocked.Increment( ref feedCounter );
            player = player_;
            NormalBrush brush = new NormalBrush( Block.Wood );
            DrawOperation Operation = new CuboidWireframeDrawOperation( player );
            Operation.AnnounceCompletion = false;
            Operation.Brush = brush;
            Operation.Context = BlockChangeContext.Drawn;

            if ( !Operation.Prepare( new Vector3I[] { StartPos, FinishPos } ) ) {
                throw new Exception( "Unable to cubw frame." );
            }

            Operation.Begin();
            AddFeedToList( this, world );

            Start();
        }
Example #2
0
        public static void MakeNormalFoliage( World w, Vector3I Pos, int Height )
        {
            int topy = Pos.Z + Height - 1;
            int start = topy - 2;
            int end = topy + 2;

            for ( int y = start; y < end; y++ ) {
                int rad;
                if ( y > start + 1 ) {
                    rad = 1;
                } else {
                    rad = 2;
                }
                for ( int xoff = -rad; xoff < rad + 1; xoff++ ) {
                    for ( int zoff = -rad; zoff < rad + 1; zoff++ ) {
                        if ( w.Map != null && w.IsLoaded ) {
                            if ( Rand.NextDouble() > .618 &&
                                Math.Abs( xoff ) == Math.Abs( zoff ) &&
                                Math.Abs( xoff ) == rad ) {
                                continue;
                            }
                            w.Map.QueueUpdate( new
                                 BlockUpdate( null, ( short )( Pos.X + xoff ), ( short )( Pos.Y + zoff ), ( short )y, Block.Leaves ) );
                        }
                    }
                }
            }
        }
Example #3
0
 public SandTask(World world, Vector3I position, Block Type)
     : base(world)
 {
     _pos = position;
     _nextPos = position.Z - 1;
     _type = Type;
 }
Example #4
0
 // This constructor is used to create dummy players (such as Console and /dummy)
 // It will soon be replaced by a generic Entity class
 internal Player( World _world, string _name )
 {
     world = _world;
     name = _name;
     nick = name;
     info = new PlayerInfo( _name, ClassList.highestClass );
 }
Example #5
0
 public BlockFloat(World world, Vector3I position, Block Type)
     : base(world)
 {
     _pos = position;
     _nextPos = position.Z + 1;
     type = Type;
 }
Example #6
0
 public FireworkParticle(World world, Vector3I pos, Block block)
     : base(world)
 {
     _startingPos = pos;
     _nextZ = pos.Z - 1;
     _block = block;
 }
Example #7
0
 // This constructor is used to create dummy players (such as Console and /dummy)
 // It will soon be replaced by a generic Entity class
 internal Player( World world, string name ) {
     if( name == null ) throw new ArgumentNullException( "name" );
     World = world;
     Info = new PlayerInfo( name, RankManager.HighestRank, true, RankChangeType.AutoPromoted );
     spamBlockLog = new Queue<DateTime>( Info.Rank.AntiGriefBlocks );
     ResetAllBinds();
 }
        private World _world = null; //to be able to remove players left the game

        #endregion Fields

        #region Constructors

        public PlayerProximityTracker( int xSize, int ySize, World world )
        {
            _players = new List<Player>[xSize, ySize];
            foreach ( Player p in world.Players ) {
                AddPlayer( p, p.Position.ToBlockCoords() );
            }
        }
Example #9
0
        // generate info for a new player
        public PlayerInfo( World world, Player player ) {
            name = player.name;
            lastIP = player.session.GetIP();

            playerClass = world.classes.defaultClass;
            classChangeDate = DateTime.MinValue;
            classChangedBy = "-";

            banned = false;
            banDate = DateTime.MinValue;
            bannedBy = "-";
            unbanDate = DateTime.MinValue;
            unbannedBy = "-";
            banReason = "-";
            unbanReason = "-";

            lastFailedLoginDate = DateTime.MinValue;
            lastFailedLoginIP = IPAddress.None;
            failedLoginCount = 0;

            firstLoginDate = DateTime.Now;
            lastLoginDate = firstLoginDate;

            totalTimeOnServer = new TimeSpan( 0 );
            blocksBuilt = 0;
            blocksDeleted = 0;
            timesVisited = 1;

            linesWritten = 0;
            thanksReceived = 0;
            warningsReceived = 0;
        }
Example #10
0
        public Session( World _world, TcpClient _client ) {

            world = _world;
            loginTime = DateTime.Now;

            canReceive = true;
            canQueue = true;
            canSend = false;
            canDispose = false;

            outputQueue = new Queue<Packet>();
            priorityOutputQueue = new Queue<Packet>();
            queueLock = new object();
            priorityQueueLock = new object();

            client = _client;
            client.SendTimeout = 10000;
            client.ReceiveTimeout = 10000;
            
            reader = new BinaryReader( client.GetStream() );
            writer = new PacketWriter( new BinaryWriter( client.GetStream() ) );

            world.log.Log( "Session: {0}", LogType.Debug, ToString() );

            ioThread = new Thread( IoLoop );
            ioThread.IsBackground = true;
            ioThread.Start();
        }
Example #11
0
File: UI.cs Project: fragmer/fCraft
        void StartUp( object sender, EventArgs a ) {
            world = new World( "" );

            world.OnLog += Log;
            world.OnURLChange += SetURL;
            world.OnPlayerListChange += UpdatePlayerList;


            if( world.Init() ) {
                Text = "fCraft " + Updater.GetVersionString() + " - " + world.config.GetString( "ServerName" );

                UpdaterResult update = Updater.CheckForUpdates( world );
                if( update.UpdateAvailable ) {
                    if( world.config.GetString( "AutomaticUpdates" ) == "Notify" ) {
                        Log( String.Format( Environment.NewLine +
                                            "*** A new version of fCraft is available: v{0:0.000}, released {1:0} day(s) ago. ***"+
                                            Environment.NewLine,
                                            Decimal.Divide( update.NewVersionNumber, 1000 ),
                                            DateTime.Now.Subtract( update.ReleaseDate ).TotalDays ), LogType.ConsoleOutput );
                        StartServer();
                    } else {
                        UpdateWindow updateWindow = new UpdateWindow( update, this, world.config.GetString( "AutomaticUpdates" ) == "Auto" );
                        updateWindow.StartPosition = FormStartPosition.CenterParent;
                        updateWindow.ShowDialog();
                    }
                } else {
                    StartServer();
                }
            } else {
                world.log.Log( "---- Could Not Initialize World ----", LogType.FatalError );
                world = null;
            }
        }
Example #12
0
 internal Commands( World _world ) {
     world = _world;
     mapCommands = new MapCommands( world, this );
     blockCommands = new BlockCommands( world, this );
     infoCommands = new InfoCommands( world, this );
     standardCommands = new StandardCommands( world, this );
     drawCommands = new DrawCommands( world, this );
 }
Example #13
0
 public static void GameAdder(World world)
 {
     world.Games.Add(pinkPlatform);
     world.Games.Add(shootBlack);
     world.Games.Add(math1);
     world.Games.Add(math2);
     world.Games.Add(getOffGrass);
 }
Example #14
0
 // Normal constructor
 internal Player( World _world, string _name, Session _session, Position _pos ) {
     world = _world;
     name = _name;
     nick = name;
     session = _session;
     pos = _pos;
     info = world.db.FindPlayerInfo( this );
 }
Example #15
0
 // Normal constructor
 internal Player( World world, string name, Session session, Position position ) {
     if( name == null ) throw new ArgumentNullException( "name" );
     if( session == null ) throw new ArgumentNullException( "session" );
     World = world;
     Session = session;
     Position = position;
     Info = PlayerDB.FindOrCreateInfoForPlayer( name, session.IP );
     spamBlockLog = new Queue<DateTime>( Info.Rank.AntiGriefBlocks );
     ResetAllBinds();
 }
Example #16
0
 public ZombieGame( World world )
 {
     _world = world;
     startTime = DateTime.Now;
     _humanCount = _world.Players.Length;
     _task = new SchedulerTask( Interval, false ).RunForever( TimeSpan.FromSeconds( 1 ) );
     _world.gameMode = GameMode.ZombieSurvival;
     Player.Moved += OnPlayerMoved;
     Player.JoinedWorld += OnChangedWorld;
 }
Example #17
0
 // Register help commands
 internal BlockCommands( World _world, Commands commands ) {
     world = _world;
     commands.AddCommand( "grass", Grass, false );
     commands.AddCommand( "water", Water, false );
     commands.AddCommand( "lava", Lava, false );
     commands.AddCommand( "solid", Solid, false );
     commands.AddCommand( "s", Solid, false );
     commands.AddCommand( "paint", Paint, false );
     //CommandUtils.AddCommand( "sand", Sand ); // TODO: after sand sim is done
 }
Example #18
0
 internal DrawCommands( World _world, Commands commands ) {
     world = _world;
     commands.AddCommand( "cuboid", Cuboid, true );
     commands.AddCommand( "cub", Cuboid, true );
     commands.AddCommand( "ellipsoid", Ellipsoid, true );
     commands.AddCommand( "ell", Ellipsoid, true );
     commands.AddCommand( "mark", Mark, true );
     commands.AddCommand( "undo", UndoDraw, true );
     commands.AddCommand( "cancel", CancelDraw, true );
 }
Example #19
0
        /// <summary>
        /// Sets a bot, as well as the bot values. Must be called before any other bot classes.
        /// </summary>
        public void setBot(String botName, String skinName, String modelName, World botWorld, Position pos, sbyte entityID) {
            Name = botName;
            SkinName =  (skinName ?? SkinName);
            Model =  (modelName ?? Model);
            World = botWorld;
            Position = pos;
            ID = entityID;

            World.Bots.Add(this);
            Server.SaveEntity(this);
        }
Example #20
0
 public static TeamDeathMatch GetInstance(World world)
 {
     if (instance == null)
     {
         TDMworld_ = world;
         instance = new TeamDeathMatch();
         startTime = DateTime.UtcNow;
         task_ = new SchedulerTask(Interval, true).RunForever(TimeSpan.FromSeconds(1));
     }
     return instance;
 }
Example #21
0
        private bool _isMoving; //if the bot can move, can be changed if it is not boxed in ect

        #endregion Fields

        #region Constructors

        public Bot(string name, Position pos, int iD, World world_)
        {
            Name = name; //bots should be gray :P
            Pos = pos;
            ID = iD;
            world = world_;
            _isMoving = false;
            _direction = Direction.South; //start off at south
            StartNewAIMovement(); //start the while loop in a new thread. I want to change the way the thread works
            //its only like this for testing purposes
        }
Example #22
0
 // Register help commands
 internal InfoCommands( World _world, Commands commands ){
     world = _world;
     commands.AddCommand( "help", Help, true );
     commands.AddCommand( "info", Info, true );
     commands.AddCommand( "baninfo", BanInfo, true );
     commands.AddCommand( "class", ClassInfo, true );
     commands.AddCommand( "rules", Rules, true );
     
     commands.AddCommand( "where", Compass, false );
     commands.AddCommand( "compass", Compass, false );
 }
Example #23
0
 public FontHandler(Block textColor, Vector3I[] Marks, World world_, Player p)
 {
     blockCount = 0;
     world = world_;
     marks = Marks;
     player = p;
     PixelPos.X = marks[0].X;
     PixelPos.Y = marks[0].Y;
     PixelPos.Z = marks[0].Z;
     PixelPos.pixel = textColor;
     PixelPos.space = Block.Air;
 }
Example #24
0
 public void Interval( SchedulerTask task )
 {
     //check to stop Interval
     if ( _world.gameMode != GameMode.ZombieSurvival || _world == null ) {
         _world = null;
         task.Stop();
         return;
     }
     if ( !_started ) {
         if ( startTime != null && ( DateTime.Now - startTime ).TotalMinutes > 1 ) {
             /*if (_world.Players.Length < 3){
                 _world.Players.Message("&WThe game failed to start: 2 or more players need to be in the world");
                 Stop(null);
                 return;
             }*/
             ShufflePlayerPositions();
             _started = true;
             RandomPick();
             lastChecked = DateTime.Now;
             return;
         }
     }
     //calculate humans
     _humanCount = _world.Players.Where( p => p.iName != _zomb ).Count();
     //check if zombies have won already
     if ( _started ) {
         if ( _humanCount == 1 && _world.Players.Count() == 1 ) {
             _world.Players.Message( "&WThe Zombies have failed to infect everyone... &9HUMANS WIN!" );
             Stop( null );
             return;
         }
         if ( _humanCount == 0 ) {
             _world.Players.Message( "&WThe Humans have failed to survive... &9ZOMBIES WIN!" );
             Stop( null );
             return;
         }
     }
     //check if 5mins is up and all zombies have failed
     if ( _started && startTime != null && ( DateTime.Now - startTime ).TotalMinutes > 6 ) {
         _world.Players.Message( "&WThe Zombies have failed to infect everyone... &9HUMANS WIN!" );
         Stop( null );
         return;
     }
     //if no one has won, notify players of their status every 31s
     if ( lastChecked != null && ( DateTime.Now - lastChecked ).TotalSeconds > 30 ) {
         _world.Players.Message( "&WThere are {0} humans", _humanCount.ToString() );
         foreach ( Player p in _world.Players ) {
             if ( p.iName == _zomb ) p.Message( "&8You are " + _zomb );
             else p.Message( "&8You are a Human" );
         }
         lastChecked = DateTime.Now;
     }
 }
Example #25
0
 public ExplodingBug( Player p )
 {
     player = p;
     world = player.World;
     guild = GuildManager.PlayersGuild( player.Info );
     end = player.Position.ToBlockCoords();
     block = new Vector3I( end.X, end.Y, end.Z - 1 );
     Started = true;
     task = Scheduler.NewBackgroundTask( t => StartAI() ).RunForever( TimeSpan.FromMilliseconds( 230 ) );
     endTask = Scheduler.NewTask( t => Stop() ).RunOnce( TimeSpan.FromSeconds( 25 ) );
     player.PublicAuxStateObjects.Add( "bug", this );
 }
Example #26
0
        public static void CreateMessageBlock( MessageBlock MessageBlock, World source )
        {
            World world = WorldManager.FindWorldExact( MessageBlock.World );

            if ( source.Map.MessageBlocks == null ) {
                source.Map.MessageBlocks = new ArrayList();
            }

            lock ( source.Map.MessageBlocks.SyncRoot ) {
                source.Map.MessageBlocks.Add( MessageBlock );
            }
        }
Example #27
0
 public static bool SetMainWorld( this World newWorld ) {
     if( newWorld == null ) throw new ArgumentNullException( "newWorld" );
     if( RaiseMainWorldChangingEvent( MainWorld, newWorld ) ) return false;
     World oldWorld;
     lock( WorldListLock ) {
         newWorld.ToggleNeverUnloadFlag( true );
         oldWorld = MainWorld;
         oldWorld.ToggleNeverUnloadFlag( false );
         MainWorld = newWorld;
     }
     RaiseMainWorldChangedEvent( oldWorld, newWorld );
     return true;
 }
Example #28
0
File: UI.cs Project: fragmer/fCraft
        public void StartServer() {
            if( args.Length == 1 ) {
                world.LoadMap( args[0] );
            } else {
                world.LoadMap( Map.DefaultFileName );
            }

            System.Diagnostics.Process.GetCurrentProcess().PriorityClass = world.config.GetBasePriority();

            if( !world.Start() ) {
                world = null;
            }
        }
Example #29
0
        public Zone( string raw, World world ) {
            string[] parts = raw.Split( ',' );

            string[] header = parts[0].Split( ' ' );
            Name = header[0];
            Bounds = new BoundingBox( Int32.Parse( header[1] ), Int32.Parse( header[2] ), Int32.Parse( header[3] ),
                                      Int32.Parse( header[4] ), Int32.Parse( header[5] ), Int32.Parse( header[6] ) );

            Rank buildRank = RankManager.ParseRank( header[7] );
            // if all else fails, fall back to lowest class
            if( buildRank == null ) {
                if( world != null ) {
                    Controller.MinRank = world.BuildSecurity.MinRank;
                } else {
                    Controller.MinRank = null;
                }
                Logger.Log( "Zone: Error parsing zone definition: unknown rank \"{0}\". Permission reset to default ({1}).", LogType.Error,
                            header[7], Controller.MinRank.Name );
            } else {
                Controller.MinRank = buildRank;
            }


            // Part 2:
            foreach( string player in parts[1].Split( ' ' ) ) {
                if( !Player.IsValidName( player ) ) continue;
                PlayerInfo info = PlayerDB.FindPlayerInfoExact( player );
                if( info == null ) continue; // player name not found in the DB (discarded)
                Controller.Include( info );
            }

            // Part 3: excluded list
            foreach( string player in parts[2].Split( ' ' ) ) {
                if( !Player.IsValidName( player ) ) continue;
                PlayerInfo info = PlayerDB.FindPlayerInfoExact( player );
                if( info == null ) continue; // player name not found in the DB (discarded)
                Controller.Exclude( info );
            }

            Controller.UpdatePlayerListCache();

            // Part 4: extended header
            if( parts.Length > 3 ) {
                string[] xheader = parts[3].Split( ' ' );
                CreatedBy = PlayerDB.FindPlayerInfoExact( xheader[0] );
                if( CreatedBy != null ) CreatedDate = DateTime.Parse( xheader[1] );
                EditedBy = PlayerDB.FindPlayerInfoExact( xheader[2] );
                if( EditedBy != null ) EditedDate = DateTime.Parse( xheader[3] );
            }
        }
Example #30
0
 public GrassTask( World world )
     : base(world)
 {
     int w, l;
     lock ( world.SyncRoot ) {
         w = _map.Width;
         l = _map.Length;
     }
     _rndCoords = new Coords[w * l]; //up to 250K per world with grass physics
     for ( short i = 0; i < w; ++i )
         for ( short j = 0; j < l; ++j )
             _rndCoords[i * l + j] = new Coords() { X = i, Y = j };
     Util.RndPermutate( _rndCoords );
 }
Example #31
0
 public void HitPlayer(World world, Vector3I pos, Player hitted, Player by, ref int restDistance, IList <BlockUpdate> updates)
 {
     hitted.Kill(world, String.Format("{0}&S was blown up by {1}", hitted.ClassyName, hitted.ClassyName == by.ClassyName ? "theirself" : by.ClassyName));
 }
Example #32
0
 public void HitPlayer(World world, Vector3I pos, Player hitted, Player by, ref int restDistance, IList <BlockUpdate> updates)
 {
     hitted.Kill(world, String.Format("{0}&S was shot by {1}", hitted.ClassyName, hitted.ClassyName == by.ClassyName ? "theirself" : by.ClassyName));
     updates.Add(new BlockUpdate(null, pos, Block.Air));
     restDistance = 0;
 }
Example #33
0
        public bool VisitBlock(World world, Vector3I pos, Block block, Player owner, ref int restDistance,
                               IList <BlockUpdate> updates, Block sending)
        {
            if (Block.Air != block) //hit a building
            {
                if (owner.bluePortal.Count > 0)
                {
                    if (pos == owner.bluePortal[0] || pos == owner.bluePortal[1])
                    {
                        return(false);
                    }
                }
                if (owner.orangePortal.Count > 0)
                {
                    if (pos == owner.orangePortal[0] || pos == owner.orangePortal[1])
                    {
                        return(false);
                    }
                }
                //blue portal
                if (sending == Block.Water)
                {
                    if (CanPlacePortal(pos.X, pos.Y, pos.Z, world.Map))
                    {
                        if (owner.bluePortal.Count > 0)
                        {
                            int i = 0;
                            foreach (Vector3I b in owner.bluePortal)
                            {
                                world.Map.QueueUpdate(new BlockUpdate(null, b, owner.blueOld[i]));
                                i++;
                            }
                            owner.blueOld.Clear();
                            owner.bluePortal.Clear();
                        }

                        owner.blueOld.Add(world.Map.GetBlock(pos));
                        owner.blueOld.Add(world.Map.GetBlock(pos.X, pos.Y, pos.Z + 1));
                        owner.orangeOut = owner.Position.R;
                        for (double z = pos.Z; z < pos.Z + 2; z++)
                        {
                            world.Map.QueueUpdate(new BlockUpdate(null, (short)(pos.X), (short)(pos.Y), (short)z,
                                                                  Block.Water));
                            owner.bluePortal.Add(new Vector3I((int)pos.X, (int)pos.Y, (int)z));
                        }
                        return(false);
                    }
                    else
                    {
                        return(false);
                    }
                }

                //orange portal
                else if (sending == Block.Lava)
                {
                    if (CanPlacePortal(pos.X, pos.Y, pos.Z, world.Map))
                    {
                        if (owner.orangePortal.Count > 0)
                        {
                            int i = 0;
                            foreach (Vector3I b in owner.orangePortal)
                            {
                                world.Map.QueueUpdate(new BlockUpdate(null, b, owner.orangeOld[i]));
                                i++;
                            }
                            owner.orangeOld.Clear();
                            owner.orangePortal.Clear();
                        }
                        owner.orangeOld.Add(world.Map.GetBlock(pos));
                        owner.orangeOld.Add(world.Map.GetBlock(pos.X, pos.Y, pos.Z + 1));
                        owner.blueOut = owner.Position.R;
                        for (double z = pos.Z; z < pos.Z + 2; z++)
                        {
                            world.Map.QueueUpdate(new BlockUpdate(null, (short)(pos.X), (short)(pos.Y), (short)z,
                                                                  Block.Lava));
                            owner.orangePortal.Add(new Vector3I((int)pos.X, (int)pos.Y, (int)z));
                        }
                        return(false);
                    }
                    else
                    {
                        return(false);
                    }
                }
                updates.Add(new BlockUpdate(null, pos, world.Map.GetBlock(pos))); //restore
                restDistance = 0;
                return(false);
            }
            return(true);
        }
Example #34
0
 public void HitPlayer(World world, Vector3I pos, Player hitted, Player by, ref int restDistance,
                       IList <BlockUpdate> updates)
 {
 }
Example #35
0
        public World ChangeMap([NotNull] Map newMap, [NotNull] string newMapChangedBy)
        {
            if (newMap == null)
            {
                throw new ArgumentNullException("newMap");
            }
            if (newMapChangedBy == null)
            {
                throw new ArgumentNullException("newMapChangedBy");
            }
            lock ( SyncRoot ) {
                if (mapWasChanged)
                {
                    throw new InvalidOperationException("A map change is already pending!");
                }

                World newWorld = new World(Name)
                {
                    AccessSecurity = (SecurityController)AccessSecurity.Clone(),
                    BuildSecurity  = (SecurityController)BuildSecurity.Clone(),
                    IsHidden       = IsHidden,
                    BlockDB        = BlockDB,
                    lastBackup     = lastBackup,
                    BackupInterval = BackupInterval,
                    IsLocked       = IsLocked,
                    LockedBy       = LockedBy,
                    UnlockedBy     = UnlockedBy,
                    LockedOn       = LockedOn,
                    UnlockedOn     = UnlockedOn,
                    LoadedBy       = LoadedBy,
                    LoadedOn       = LoadedOn,
                    MapChangedBy   = newMapChangedBy,
                    MapChangedOn   = DateTime.UtcNow,
                    FogColor       = FogColor,
                    CloudColor     = CloudColor,
                    SkyColor       = SkyColor,
                    EdgeLevel      = EdgeLevel,
                    EdgeBlock      = EdgeBlock
                };
                newMap.World     = newWorld;
                newWorld.Map     = newMap;
                newWorld.Preload = preload;

                // save a backup, just in case
                if (ConfigKey.BackupOnMapChange.Enabled())
                {
                    if (Map != null && Map.HasChangedSinceSave)
                    {
                        SaveMap();
                    }
                    string backupFileName = String.Format(MapChangeBackupFormat, Name, DateTime.Now);   // localized
                    SaveBackup(Path.Combine(Paths.BackupPath, backupFileName));
                }

                // register the new world, and unregister this one
                WorldManager.ReplaceWorld(this, newWorld);
                mapWasChanged = true;

                // clear BlockDB for the old map
                using (BlockDB.GetWriteLock()) {
                    BlockDB.Clear();
                    BlockDB.World = newWorld;
                }

                // tell players to go ahead
                foreach (Player player in Players)
                {
                    player.JoinWorld(newWorld, WorldChangeReason.Rejoin);
                }
                return(newWorld);
            }
        }
Example #36
0
        internal static bool LoadWorldList()
        {
            World newMainWorld = null;

            Worlds = new World[0];
            if (File.Exists(Paths.WorldListFileName))
            {
                try {
                    XDocument doc  = XDocument.Load(Paths.WorldListFileName);
                    XElement  root = doc.Root;
                    if (root != null)
                    {
                        foreach (XElement el in root.Elements("World"))
                        {
#if !DEBUG
                            try {
#endif
                            LoadWorldListEntry(el);
#if !DEBUG
                        }
                        catch (Exception ex) {
                            Logger.LogAndReportCrash("An error occured while trying to parse one of the entries on the world list",
                                                     "fCraft", ex, false);
                        }
#endif
                        }

                        XAttribute temp;
                        if ((temp = root.Attribute("main")) != null)
                        {
                            World suggestedMainWorld = FindWorldExact(temp.Value);

                            if (suggestedMainWorld != null)
                            {
                                newMainWorld = suggestedMainWorld;
                            }
                            else if (firstWorld != null)
                            {
                                // if specified main world does not exist, use first-defined world
                                Logger.Log(LogType.Warning,
                                           "The specified main world \"{0}\" does not exist. " +
                                           "\"{1}\" was designated main instead. You can use /WMain to change it.",
                                           temp.Value, firstWorld.Name);
                                newMainWorld = firstWorld;
                            }
                            // if firstWorld was also null, LoadWorldList() should try creating a new mainWorld
                        }
                        else if (firstWorld != null)
                        {
                            newMainWorld = firstWorld;
                        }
                    }
                } catch (Exception ex) {
                    Logger.LogAndReportCrash("Error occured while trying to load the world list.", "fCraft", ex, true);
                    return(false);
                }

                if (newMainWorld == null)
                {
                    Logger.Log(LogType.Error,
                               "Server.Start: Could not load any of the specified worlds, or no worlds were specified. " +
                               "Creating default \"main\" world.");
                    newMainWorld = AddWorld(null, "main", MapGenerator.GenerateFlatgrass(128, 128, 64), true);
                }
            }
            else
            {
                Logger.Log(LogType.SystemActivity,
                           "Server.Start: No world list found. Creating default \"main\" world.");
                newMainWorld = AddWorld(null, "main", MapGenerator.GenerateFlatgrass(128, 128, 64), true);
            }

            // if there is no default world still, die.
            if (newMainWorld == null)
            {
                throw new Exception("Could not create any worlds.");
            }
            else if (newMainWorld.AccessSecurity.HasRestrictions)
            {
                Logger.Log(LogType.Warning,
                           "Server.LoadWorldList: Main world cannot have any access restrictions. " +
                           "Access permission for \"{0}\" has been reset.",
                           newMainWorld.Name);
                newMainWorld.AccessSecurity.Reset();
            }

            MainWorld = newMainWorld;

            return(true);
        }
Example #37
0
        /// <summary> Saves the current world list to worlds.xml. Thread-safe. </summary>
        public static void SaveWorldList()
        {
            const string worldListTempFileName = Paths.WorldListFileName + ".tmp";

            // Save world list
            lock ( SyncRoot ) {
                XDocument doc  = new XDocument();
                XElement  root = new XElement("fCraftWorldList");

                foreach (World world in Worlds)
                {
                    XElement temp = new XElement("World");
                    temp.Add(new XAttribute("name", world.Name));

                    if (world.AccessSecurity.HasRestrictions)
                    {
                        temp.Add(world.AccessSecurity.Serialize(AccessSecurityXmlTagName));
                    }
                    if (world.BuildSecurity.HasRestrictions)
                    {
                        temp.Add(world.BuildSecurity.Serialize(BuildSecurityXmlTagName));
                    }

                    if (world.BackupInterval != World.DefaultBackupInterval)
                    {
                        temp.Add(new XAttribute("backup", world.BackupInterval.ToTickString()));
                    }

                    if (world.NeverUnload)
                    {
                        temp.Add(new XAttribute("noUnload", true));
                    }
                    if (world.IsHidden)
                    {
                        temp.Add(new XAttribute("hidden", true));
                    }
                    temp.Add(world.BlockDB.SaveSettings());

                    World world1 = world;
                    foreach (Rank mainedRank in RankManager.Ranks.Where(r => r.MainWorld == world1))
                    {
                        temp.Add(new XElement(RankMainXmlTagName, mainedRank.FullName));
                    }

                    if (!String.IsNullOrEmpty(world.LoadedBy))
                    {
                        temp.Add(new XElement("LoadedBy", world.LoadedBy));
                    }
                    if (world.LoadedOn != DateTime.MinValue)
                    {
                        temp.Add(new XElement("LoadedOn", world.LoadedOn.ToUnixTime()));
                    }
                    if (!String.IsNullOrEmpty(world.MapChangedBy))
                    {
                        temp.Add(new XElement("MapChangedBy", world.MapChangedBy));
                    }
                    if (world.MapChangedOn != DateTime.MinValue)
                    {
                        temp.Add(new XElement("MapChangedOn", world.MapChangedOn.ToUnixTime()));
                    }

                    XElement elEnv = new XElement(EnvironmentXmlTagName);
                    if (world.CloudColor > -1)
                    {
                        elEnv.Add(new XAttribute("cloud", world.CloudColor));
                    }
                    if (world.FogColor > -1)
                    {
                        elEnv.Add(new XAttribute("fog", world.FogColor));
                    }
                    if (world.SkyColor > -1)
                    {
                        elEnv.Add(new XAttribute("sky", world.SkyColor));
                    }
                    if (world.EdgeLevel > -1)
                    {
                        elEnv.Add(new XAttribute("level", world.EdgeLevel));
                    }
                    if (world.EdgeBlock != Block.Water)
                    {
                        elEnv.Add(new XAttribute("edge", world.EdgeBlock));
                    }
                    if (elEnv.HasAttributes)
                    {
                        temp.Add(elEnv);
                    }

                    root.Add(temp);
                }
                root.Add(new XAttribute("main", MainWorld.Name));

                doc.Add(root);
                doc.Save(worldListTempFileName);
                Paths.MoveOrReplace(worldListTempFileName, Paths.WorldListFileName);
            }
        }
Example #38
0
        internal static void RealmAccess(Player player, Command cmd, string worldName, string name)
        {

            // Print information about the current realm
            if (worldName == null)
            {
                if (player.World == null)
                {
                    player.Message("Error.");
                }
                else
                {
                    player.Message(player.World.AccessSecurity.GetDescription(player.World, "realm", "accessed"));
                }
                return;
            }

            // Find a realm by name
            World realm = WorldManager.FindWorldOrPrintMatches(player, worldName);
            if (realm == null) return;



            if (name == null)
            {
                player.Message(realm.AccessSecurity.GetDescription(realm, "realm", "accessed"));
                return;
            }
            if (realm == WorldManager.MainWorld)
            {
                player.Message("The main realm cannot have access restrictions.");
                return;
            }

            bool changesWereMade = false;
            do
            {
                if (name.Length < 2) continue;
                // Whitelisting individuals
                if (name.StartsWith("+"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;

                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }

                    // prevent players from whitelisting themselves to bypass protection


                    if (realm.AccessSecurity.CheckDetailed(info) == SecurityCheckResult.Allowed)
                    {
                        player.Message("{0}&S is already allowed to access {1}&S (by rank)",
                                        info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player) target = null; // to avoid duplicate messages

                    switch (realm.AccessSecurity.Include(info))
                    {
                        case PermissionOverride.Deny:
                            if (realm.AccessSecurity.Check(info))
                            {
                                player.Message("{0}&S is unbanned from Realm {1}",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("You are now unbanned from Realm {0}&S (removed from blacklist by {1}&S).",
                                                    realm.ClassyName, player.ClassyName);
                                }
                            }
                            else
                            {
                                player.Message("{0}&S was unbanned from Realm {1}&S. " +
                                                "Player is still NOT allowed to join (by rank).",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("You were Unbanned from Realm {0}&S by {1}&S. " +
                                                    "You are still NOT allowed to join (by rank).",
                                                    player.ClassyName, realm.ClassyName);
                                }
                            }
                            Logger.Log(LogType.UserActivity, "{0} removed {1} from the access blacklist of {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;

                        case PermissionOverride.None:
                            player.Message("{0}&S is now allowed to access {1}",
                                            info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("You can now access realm {0}&S (whitelisted by {1}&S).",
                                                realm.ClassyName, player.ClassyName);
                            }
                            Logger.Log(LogType.UserActivity, "{0} added {1} to the access whitelist on realm {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;

                        case PermissionOverride.Allow:
                            player.Message("{0}&S is already on the access whitelist of {1}",
                                            info.ClassyName, realm.ClassyName);
                            break;
                    }

                    // Blacklisting individuals
                }
                else if (name.StartsWith("-"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }

                    if (realm.AccessSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooHigh ||
                        realm.AccessSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooLow)
                    {
                        player.Message("{0}&S is already barred from accessing {1}&S (by rank)",
                                        info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player) target = null; // to avoid duplicate messages

                    switch (realm.AccessSecurity.Exclude(info))
                    {
                        case PermissionOverride.Deny:
                            player.Message("{0}&S is already banned from Realm {1}",
                                            info.ClassyName, realm.ClassyName);
                            break;

                        case PermissionOverride.None:
                            player.Message("{0}&S is now banned from accessing {1}",
                                            info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("&WYou were banned by {0}&W from accessing realm {1}",
                                                player.ClassyName, realm.ClassyName);
                            }
                            Logger.Log(LogType.UserActivity, "{0} added {1} to the access blacklist on realm {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;

                        case PermissionOverride.Allow:
                            if (realm.AccessSecurity.Check(info))
                            {
                                player.Message("{0}&S is no longer on the access whitelist of {1}&S. " +
                                                "Player is still allowed to join (by rank).",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("You were banned from Realm {0}&S by {1}&S. " +
                                                    "You are still allowed to join (by rank).",
                                                    player.ClassyName, realm.ClassyName);
                                }
                            }
                            else
                            {
                                player.Message("{0}&S is no longer allowed to access {1}",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("&WYou were banned from Realm {0}&W (Banned by {1}&W).",
                                                    realm.ClassyName, player.ClassyName);
                                }
                            }
                            Logger.Log(LogType.UserActivity, "{0} removed {1} from the access whitelist on realm {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;
                    }

                    // Setting minimum rank
                }
                else
                {
                    Rank rank = RankManager.FindRank(name);
                    if (rank == null)
                    {
                        player.MessageNoRank(name);

                    }

                    else
                    {
                        // list players who are redundantly blacklisted
                        var exceptionList = realm.AccessSecurity.ExceptionList;
                        PlayerInfo[] noLongerExcluded = exceptionList.Excluded.Where(excludedPlayer => excludedPlayer.Rank < rank).ToArray();
                        if (noLongerExcluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be blacklisted to be barred from {0}&S: {1}",
                                            realm.ClassyName,
                                            noLongerExcluded.JoinToClassyString());
                        }

                        // list players who are redundantly whitelisted
                        PlayerInfo[] noLongerIncluded = exceptionList.Included.Where(includedPlayer => includedPlayer.Rank >= rank).ToArray();
                        if (noLongerIncluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be whitelisted to access {0}&S: {1}",
                                            realm.ClassyName,
                                            noLongerIncluded.JoinToClassyString());
                        }

                        // apply changes
                        realm.AccessSecurity.MinRank = rank;
                        changesWereMade = true;
                        if (realm.AccessSecurity.MinRank == RankManager.LowestRank)
                        {
                            Server.Message("{0}&S made the realm {1}&S accessible to everyone.",
                                              player.ClassyName, realm.ClassyName);
                        }
                        else
                        {
                            Server.Message("{0}&S made the realm {1}&S accessible only by {2}+",
                                              player.ClassyName, realm.ClassyName,
                                              realm.AccessSecurity.MinRank.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} set access rank for realm {1} to {2}+",
                                    player.Name, realm.Name, realm.AccessSecurity.MinRank.Name);
                    }
                }
            } while ((name = cmd.Next()) != null);

            if (changesWereMade)
            {
                var playersWhoCantStay = realm.Players.Where(p => !p.CanJoin(realm));
                foreach (Player p in playersWhoCantStay)
                {
                    p.Message("&WYou are no longer allowed to join realm {0}", realm.ClassyName);
                    p.JoinWorld(WorldManager.MainWorld, WorldChangeReason.PermissionChanged);
                }

                WorldManager.SaveWorldList();
            }
        }
Example #39
0
        internal static void RealmBuild(Player player, Command cmd, string worldName, string name, string NameIfRankIsName)
        {


            // Print information about the current realm
            if (worldName == null)
            {
                if (player.World == null)
                {
                    player.Message("When calling /wbuild from console, you must specify a realm name.");
                }
                else
                {
                    player.Message(player.World.BuildSecurity.GetDescription(player.World, "realm", "modified"));
                }
                return;
            }

            // Find a realm by name
            World realm = WorldManager.FindWorldOrPrintMatches(player, worldName);
            if (realm == null) return;


            if (name == null)
            {
                player.Message(realm.BuildSecurity.GetDescription(realm, "realm", "modified"));
                return;
            }

            bool changesWereMade = false;
            do
            {
                if (name.Length < 2) continue;
                // Whitelisting individuals
                if (name.StartsWith("+"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }



                    if (realm.BuildSecurity.CheckDetailed(info) == SecurityCheckResult.Allowed)
                    {
                        player.Message("{0}&S is already allowed to build in {1}&S (by rank)",
                                        info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player) target = null; // to avoid duplicate messages

                    switch (realm.BuildSecurity.Include(info))
                    {
                        case PermissionOverride.Deny:
                            if (realm.BuildSecurity.Check(info))
                            {
                                player.Message("{0}&S is no longer barred from building in {1}",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("You can now build in realm {0}&S (removed from blacklist by {1}&S).",
                                                    realm.ClassyName, player.ClassyName);
                                }
                            }
                            else
                            {
                                player.Message("{0}&S was removed from the build blacklist of {1}&S. " +
                                                "Player is still NOT allowed to build (by rank).",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("You were removed from the build blacklist of realm {0}&S by {1}&S. " +
                                                    "You are still NOT allowed to build (by rank).",
                                                    player.ClassyName, realm.ClassyName);
                                }
                            }
                            Logger.Log(LogType.UserActivity, "{0} removed {1} from the build blacklist of {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;

                        case PermissionOverride.None:
                            player.Message("{0}&S is now allowed to build in {1}",
                                            info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("You can now build in realm {0}&S (whitelisted by {1}&S).",
                                                realm.ClassyName, player.ClassyName);
                            }
                            Logger.Log(LogType.UserActivity, "{0} added {1} to the build whitelist on realm {2}",
                                        player.Name, info.Name, realm.Name);
                            break;

                        case PermissionOverride.Allow:
                            player.Message("{0}&S is already on the build whitelist of {1}",
                                            info.ClassyName, realm.ClassyName);
                            break;
                    }

                    // Blacklisting individuals
                }
                else if (name.StartsWith("-"))
                {
                    PlayerInfo info;
                    if (!PlayerDB.FindPlayerInfo(name.Substring(1), out info))
                    {
                        player.Message("More than one player found matching \"{0}\"", name.Substring(1));
                        continue;
                    }
                    else if (info == null)
                    {
                        player.MessageNoPlayer(name.Substring(1));
                        continue;
                    }

                    if (realm.BuildSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooHigh ||
                        realm.BuildSecurity.CheckDetailed(info) == SecurityCheckResult.RankTooLow)
                    {
                        player.Message("{0}&S is already barred from building in {1}&S (by rank)",
                                        info.ClassyName, realm.ClassyName);
                        continue;
                    }

                    Player target = info.PlayerObject;
                    if (target == player) target = null; // to avoid duplicate messages

                    switch (realm.BuildSecurity.Exclude(info))
                    {
                        case PermissionOverride.Deny:
                            player.Message("{0}&S is already on build blacklist of {1}",
                                            info.ClassyName, realm.ClassyName);
                            break;

                        case PermissionOverride.None:
                            player.Message("{0}&S is now barred from building in {1}",
                                            info.ClassyName, realm.ClassyName);
                            if (target != null)
                            {
                                target.Message("&WYou were barred by {0}&W from building in realm {1}",
                                                player.ClassyName, realm.ClassyName);
                            }
                            Logger.Log(LogType.UserActivity, "{0} added {1} to the build blacklist on realm {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;

                        case PermissionOverride.Allow:
                            if (realm.BuildSecurity.Check(info))
                            {
                                player.Message("{0}&S is no longer on the build whitelist of {1}&S. " +
                                                "Player is still allowed to build (by rank).",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("You were removed from the build whitelist of realm {0}&S by {1}&S. " +
                                                    "You are still allowed to build (by rank).",
                                                    player.ClassyName, realm.ClassyName);
                                }
                            }
                            else
                            {
                                player.Message("{0}&S is no longer allowed to build in {1}",
                                                info.ClassyName, realm.ClassyName);
                                if (target != null)
                                {
                                    target.Message("&WYou can no longer build in realm {0}&W (removed from whitelist by {1}&W).",
                                                    realm.ClassyName, player.ClassyName);
                                }
                            }
                            Logger.Log(LogType.UserActivity, "{0} removed {1} from the build whitelist on realm {2}",
                                        player.Name, info.Name, realm.Name);
                            changesWereMade = true;
                            break;
                    }

                    // Setting minimum rank
                }
                else
                {
                    Rank rank = RankManager.FindRank(name);
                    if (rank == null)
                    {
                        player.MessageNoRank(name);
                    }
                    else if (!player.Info.Rank.AllowSecurityCircumvention &&
                             realm.BuildSecurity.MinRank > rank &&
                             realm.BuildSecurity.MinRank > player.Info.Rank)
                    {
                        player.Message("&WYou must be ranked {0}&W+ to lower build restrictions for realm {1}",
                                        realm.BuildSecurity.MinRank.ClassyName, realm.ClassyName);
                    }
                    else
                    {
                        // list players who are redundantly blacklisted
                        var exceptionList = realm.BuildSecurity.ExceptionList;
                        PlayerInfo[] noLongerExcluded = exceptionList.Excluded.Where(excludedPlayer => excludedPlayer.Rank < rank).ToArray();
                        if (noLongerExcluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be blacklisted on realm {0}&S: {1}",
                                            realm.ClassyName,
                                            noLongerExcluded.JoinToClassyString());
                        }

                        // list players who are redundantly whitelisted
                        PlayerInfo[] noLongerIncluded = exceptionList.Included.Where(includedPlayer => includedPlayer.Rank >= rank).ToArray();
                        if (noLongerIncluded.Length > 0)
                        {
                            player.Message("Following players no longer need to be whitelisted on realm {0}&S: {1}",
                                            realm.ClassyName,
                                            noLongerIncluded.JoinToClassyString());
                        }

                        // apply changes
                        realm.BuildSecurity.MinRank = rank;
                        changesWereMade = true;
                        if (realm.BuildSecurity.MinRank == RankManager.LowestRank)
                        {
                            Server.Message("{0}&S allowed anyone to build on realm {1}",
                                              player.ClassyName, realm.ClassyName);
                        }
                        else
                        {
                            Server.Message("{0}&S allowed only {1}+&S to build in realm {2}",
                                              player.ClassyName, realm.BuildSecurity.MinRank.ClassyName, realm.ClassyName);
                        }
                        Logger.Log(LogType.UserActivity, "{0} set build rank for realm {1} to {2}+",
                                    player.Name, realm.Name, realm.BuildSecurity.MinRank.Name);
                    }
                }
            } while ((name = cmd.Next()) != null);

            if (changesWereMade)
            {
                WorldManager.SaveWorldList();
            }
        }
Example #40
0
        // Applies pending updates and sends them to players (if applicable).
        internal void ProcessUpdates()
        {
            if (World == null)
            {
                throw new InvalidOperationException("Map must be assigned to a world to process updates.");
            }

            if (World.IsLocked)
            {
                if (World.IsPendingMapUnload)
                {
                    World.UnloadMap(true);
                }
                return;
            }

            int         packetsSent         = 0;
            bool        canFlush            = false;
            int         maxPacketsPerUpdate = Server.CalculateMaxPacketsPerUpdate(World);
            BlockUpdate update = new BlockUpdate();

            while (packetsSent < maxPacketsPerUpdate)
            {
                if (!updates.Dequeue(ref update))
                {
                    if (World.IsFlushing)
                    {
                        canFlush = true;
                    }
                    break;
                }
                HasChangedSinceSave = true;
                if (!InBounds(update.X, update.Y, update.Z))
                {
                    continue;
                }
                int blockIndex = Index(update.X, update.Y, update.Z);
                Blocks[blockIndex] = (byte)update.BlockType;

                if (!World.IsFlushing)
                {
                    Packet packet = PacketWriter.MakeSetBlock(update.X, update.Y, update.Z, update.BlockType);
                    World.Players.SendLowPriority(update.Origin, packet);
                }
                packetsSent++;
            }

            if (drawOps.Count > 0)
            {
                lock ( drawOpLock ) {
                    if (drawOps.Count > 0)
                    {
                        packetsSent += ProcessDrawOps(maxPacketsPerUpdate - packetsSent);
                    }
                }
            }
            else if (canFlush)
            {
                World.EndFlushMapBuffer();
            }

            if (packetsSent == 0 && World.IsPendingMapUnload)
            {
                World.UnloadMap(true);
            }
        }
Example #41
0
        static void ZoneRenameHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;

            if (playerWorld == null)
            {
                PlayerOpException.ThrowNoWorld(player);
            }

            // make sure that both parameters are given
            string oldName = cmd.Next();
            string newName = cmd.Next();

            if (oldName == null || newName == null)
            {
                CdZoneRename.PrintUsage(player);
                return;
            }

            // make sure that the new name is valid
            if (!World.IsValidName(newName))
            {
                player.Message("\"{0}\" is not a valid zone name", newName);
                return;
            }

            // find the old zone
            var  zones   = player.WorldMap.Zones;
            Zone oldZone = zones.Find(oldName);

            if (oldZone == null)
            {
                player.MessageNoZone(oldName);
                return;
            }

            // Check if a zone with "newName" name already exists
            Zone newZone = zones.FindExact(newName);

            if (newZone != null && newZone != oldZone)
            {
                player.Message("A zone with the name \"{0}\" already exists.", newName);
                return;
            }

            // check if any change is needed
            string fullOldName = oldZone.Name;

            if (fullOldName == newName)
            {
                player.Message("The zone is already named \"{0}\"", fullOldName);
                return;
            }

            // actually rename the zone
            zones.Rename(oldZone, newName);

            // announce the rename
            playerWorld.Players.Message("&SZone \"{0}\" was renamed to \"{1}&S\" by {2}",
                                        fullOldName, oldZone.ClassyName, player.ClassyName);
            Logger.Log(LogType.UserActivity,
                       "Player {0} renamed zone \"{1}\" to \"{2}\" on world {3}",
                       player.Name, fullOldName, newName, playerWorld.Name);
        }
Example #42
0
        static void LoadWorldListEntry([NotNull] XElement el)
        {
            if (el == null)
            {
                throw new ArgumentNullException("el");
            }
            XAttribute tempAttr;

            if ((tempAttr = el.Attribute("name")) == null)
            {
                Logger.Log(LogType.Error, "WorldManager: World tag with no name skipped.");
                return;
            }
            string worldName = tempAttr.Value;

            bool neverUnload = (el.Attribute("noUnload") != null);

            World world;

            try {
                world = AddWorld(null, worldName, null, neverUnload);
            } catch (WorldOpException ex) {
                Logger.Log(LogType.Error,
                           "WorldManager: Error adding world \"{0}\": {1}",
                           worldName, ex.Message);
                return;
            }

            if ((tempAttr = el.Attribute("hidden")) != null)
            {
                bool isHidden;
                if (Boolean.TryParse(tempAttr.Value, out isHidden))
                {
                    world.IsHidden = isHidden;
                }
                else
                {
                    Logger.Log(LogType.Warning,
                               "WorldManager: Could not parse \"hidden\" attribute of world \"{0}\", assuming NOT hidden.",
                               worldName);
                }
            }
            if (firstWorld == null)
            {
                firstWorld = world;
            }

            XElement tempEl;

            if ((tempEl = el.Element(AccessSecurityXmlTagName)) != null)
            {
                world.AccessSecurity = new SecurityController(tempEl, true);
            }
            else if ((tempEl = el.Element("accessSecurity")) != null)
            {
                world.AccessSecurity = new SecurityController(tempEl, true);
            }
            if ((tempEl = el.Element(BuildSecurityXmlTagName)) != null)
            {
                world.BuildSecurity = new SecurityController(tempEl, true);
            }
            else if ((tempEl = el.Element("buildSecurity")) != null)
            {
                world.BuildSecurity = new SecurityController(tempEl, true);
            }

            if ((tempAttr = el.Attribute("backup")) != null)
            {
                TimeSpan backupInterval;
                if (tempAttr.Value.ToTimeSpan(out backupInterval))
                {
                    world.BackupInterval = backupInterval;
                }
                else
                {
                    world.BackupInterval = World.DefaultBackupInterval;
                    Logger.Log(LogType.Warning,
                               "WorldManager: Could not parse \"backup\" attribute of world \"{0}\", assuming default ({1}).",
                               worldName,
                               world.BackupInterval.ToMiniString());
                }
            }
            else
            {
                world.BackupInterval = World.DefaultBackupInterval;
            }

            XElement blockEl = el.Element(BlockDB.XmlRootName);

            if (blockEl != null)
            {
                world.BlockDB.LoadSettings(blockEl);
            }

            XElement envEl = el.Element(EnvironmentXmlTagName);

            if (envEl != null)
            {
                if ((tempAttr = envEl.Attribute("cloud")) != null)
                {
                    if (!Int32.TryParse(tempAttr.Value, out world.CloudColor))
                    {
                        world.CloudColor = -1;
                        Logger.Log(LogType.Warning,
                                   "WorldManager: Could not parse \"cloud\" attribute of Environment settings for world \"{0}\", assuming default (normal).",
                                   worldName);
                    }
                }
                if ((tempAttr = envEl.Attribute("fog")) != null)
                {
                    if (!Int32.TryParse(tempAttr.Value, out world.FogColor))
                    {
                        world.FogColor = -1;
                        Logger.Log(LogType.Warning,
                                   "WorldManager: Could not parse \"fog\" attribute of Environment settings for world \"{0}\", assuming default (normal).",
                                   worldName);
                    }
                }
                if ((tempAttr = envEl.Attribute("sky")) != null)
                {
                    if (!Int32.TryParse(tempAttr.Value, out world.SkyColor))
                    {
                        world.SkyColor = -1;
                        Logger.Log(LogType.Warning,
                                   "WorldManager: Could not parse \"sky\" attribute of Environment settings for world \"{0}\", assuming default (normal).",
                                   worldName);
                    }
                }
                if ((tempAttr = envEl.Attribute("level")) != null)
                {
                    if (!Int32.TryParse(tempAttr.Value, out world.EdgeLevel))
                    {
                        world.EdgeLevel = -1;
                        Logger.Log(LogType.Warning,
                                   "WorldManager: Could not parse \"level\" attribute of Environment settings for world \"{0}\", assuming default (normal).",
                                   worldName);
                    }
                }
                if ((tempAttr = envEl.Attribute("edge")) != null)
                {
                    Block block = Map.GetBlockByName(tempAttr.Value);
                    if (block == Block.Undefined)
                    {
                        world.EdgeBlock = Block.Water;
                        Logger.Log(LogType.Warning,
                                   "WorldManager: Could not parse \"edge\" attribute of Environment settings for world \"{0}\", assuming default (Water).",
                                   worldName);
                    }
                    else
                    {
                        if (Map.GetEdgeTexture(block) == null)
                        {
                            world.EdgeBlock = Block.Water;
                            Logger.Log(LogType.Warning,
                                       "WorldManager: Unacceptable blocktype given for \"edge\" attribute of Environment settings for world \"{0}\", assuming default (Water).",
                                       worldName);
                        }
                        else
                        {
                            world.EdgeBlock = block;
                        }
                    }
                }
            }

            foreach (XElement mainedRankEl in el.Elements(RankMainXmlTagName))
            {
                Rank rank = Rank.Parse(mainedRankEl.Value);
                if (rank != null)
                {
                    if (rank < world.AccessSecurity.MinRank)
                    {
                        world.AccessSecurity.MinRank = rank;
                        Logger.Log(LogType.Warning,
                                   "WorldManager: Lowered access MinRank of world {0} to allow it to be the main world for that rank.",
                                   rank.Name);
                    }
                    rank.MainWorld = world;
                }
            }

            CheckMapFile(world);
        }
Example #43
0
        // Makes sure that the map file exists, is properly named, and is loadable.
        static void CheckMapFile([NotNull] World world)
        {
            if (world == null)
            {
                throw new ArgumentNullException("world");
            }
            // Check the world's map file
            string fullMapFileName = world.MapFileName;
            string fileName        = Path.GetFileName(fullMapFileName);

            if (Paths.FileExists(fullMapFileName, false))
            {
                if (!Paths.FileExists(fullMapFileName, true))
                {
                    // Map file has wrong capitalization
                    FileInfo[] matches = Paths.FindFiles(fullMapFileName);
                    if (matches.Length == 1)
                    {
                        // Try to rename the map file to match world's capitalization
                        // ReSharper disable AssignNullToNotNullAttribute
                        Paths.ForceRename(matches[0].FullName, fileName);
                        // ReSharper restore AssignNullToNotNullAttribute
                        if (Paths.FileExists(fullMapFileName, true))
                        {
                            Logger.Log(LogType.Warning,
                                       "WorldManager.CheckMapFile: Map file for world \"{0}\" was renamed from \"{1}\" to \"{2}\"",
                                       world.Name, matches[0].Name, fileName);
                        }
                        else
                        {
                            Logger.Log(LogType.Error,
                                       "WorldManager.CheckMapFile: Failed to rename map file of \"{0}\" from \"{1}\" to \"{2}\"",
                                       world.Name, matches[0].Name, fileName);
                            return;
                        }
                    }
                    else
                    {
                        Logger.Log(LogType.Warning,
                                   "WorldManager.CheckMapFile: More than one map file exists matching the world name \"{0}\". " +
                                   "Please check the map directory and use /WLoad to load the correct file.",
                                   world.Name);
                        return;
                    }
                }
                // Try loading the map header
                try {
                    MapUtility.LoadHeader(world.MapFileName);
                } catch (Exception ex) {
                    Logger.Log(LogType.Warning,
                               "WorldManager.CheckMapFile: Could not load map file for world \"{0}\": {1}",
                               world.Name, ex);
                }
            }
            else
            {
                Logger.Log(LogType.Warning,
                           "WorldManager.CheckMapFile: Map file for world \"{0}\" was not found.",
                           world.Name);
            }
        }
Example #44
0
        public static void RealmLoad(Player player, Command cmd, string fileName, string worldName)
        {

            if (worldName == null && player.World == null)
            {
                player.Message("When using /realm from console, you must specify the realm name.");
                return;
            }

            if (fileName == null)
            {
                // No params given at all
                
                return;
            }

            string fullFileName = WorldManager.FindMapFile(player, fileName);
            if (fullFileName == null) return;

            // Loading map into current realm
            if (worldName == null)
            {
                if (!cmd.IsConfirmed)
                {
                    player.Confirm(cmd, "About to replace THIS REALM with \"{0}\".", fileName);
                    return;
                }
                Map map;
                try
                {
                    map = MapUtility.Load(fullFileName);
                }
                catch (Exception ex)
                {
                    player.MessageNow("Could not load specified file: {0}: {1}", ex.GetType().Name, ex.Message);
                    return;
                }
                World realm = player.World;

                // Loading to current realm
                realm.MapChangedBy = player.Name;
                realm.ChangeMap(map);

                realm.Players.Message(player, "{0}&S loaded a new map for this realm.",
                                              player.ClassyName);
                player.MessageNow("New map loaded for the realm {0}", realm.ClassyName);

                Logger.Log(LogType.UserActivity,
                            "{0} loaded new map for realm \"{1}\" from {2}",
                            player.Name, realm.Name, fileName);
                realm.IsHidden = false;
                realm.IsRealm = true;
                WorldManager.SaveWorldList();


            }
            else
            {
                // Loading to some other (or new) realm
                if (!World.IsValidName(worldName))
                {
                    player.MessageInvalidWorldName(worldName);
                    return;
                }

                string buildRankName = cmd.Next();
                string accessRankName = cmd.Next();
                Rank buildRank = RankManager.DefaultBuildRank;
                Rank accessRank = null;
                if (buildRankName != null)
                {
                    buildRank = RankManager.FindRank(buildRankName);
                    if (buildRank == null)
                    {
                        player.MessageNoRank(buildRankName);
                        return;
                    }
                    if (accessRankName != null)
                    {
                        accessRank = RankManager.FindRank(accessRankName);
                        if (accessRank == null)
                        {
                            player.MessageNoRank(accessRankName);
                            return;
                        }
                    }
                }

                // Retype realm name, if needed
                if (worldName == "-")
                {
                    if (player.LastUsedWorldName != null)
                    {
                        worldName = player.LastUsedWorldName;
                    }
                    else
                    {
                        player.Message("Cannot repeat realm name: you haven't used any names yet.");
                        return;
                    }
                }

                lock (WorldManager.SyncRoot)
                {
                    World realm = WorldManager.FindWorldExact(worldName);
                    if (realm != null)
                    {
                        player.LastUsedWorldName = realm.Name;
                        // Replacing existing realm's map
                        if (!cmd.IsConfirmed)
                        {
                            player.Confirm(cmd, "About to replace realm map for {0}&S with \"{1}\".",
                                            realm.ClassyName, fileName);
                            return;
                        }

                        Map map;
                        try
                        {
                            map = MapUtility.Load(fullFileName);
                            realm.IsHidden = false;
                            realm.IsRealm = true;
                            WorldManager.SaveWorldList();
                        }
                        catch (Exception ex)
                        {
                            player.MessageNow("Could not load specified file: {0}: {1}", ex.GetType().Name, ex.Message);
                            return;
                        }

                        try
                        {
                            realm.MapChangedBy = player.Name;
                            realm.ChangeMap(map);
                            realm.IsHidden = false;
                            realm.IsRealm = true;
                            WorldManager.SaveWorldList();
                        }
                        catch (WorldOpException ex)
                        {
                            Logger.Log(LogType.Error,
                                        "Could not complete RealmLoad operation: {0}", ex.Message);
                            player.Message("&WRealmLoad: {0}", ex.Message);
                            return;
                        }

                        realm.Players.Message(player, "{0}&S loaded a new map for the realm {1}",
                                               player.ClassyName, realm.ClassyName);
                        player.MessageNow("New map for the realm {0}&S has been loaded.", realm.ClassyName);
                        Logger.Log(LogType.UserActivity,
                                    "{0} loaded new map for realm \"{1}\" from {2}",
                                    player.Name, realm.Name, fullFileName);
                        

                    }
                    else
                    {
                        // Adding a new realm
                        string targetFullFileName = Path.Combine(Paths.MapPath, worldName + ".fcm");
                        if (!cmd.IsConfirmed &&
                            File.Exists(targetFullFileName) && // target file already exists
                            !Paths.Compare(targetFullFileName, fullFileName))
                        {
                            // and is different from sourceFile
                            player.Confirm(cmd,
                                            "A map named \"{0}\" already exists, and will be overwritten with \"{1}\".",
                                            Path.GetFileName(targetFullFileName), Path.GetFileName(fullFileName));
                            return;
                        }

                        Map map;
                        try
                        {
                            map = MapUtility.Load(fullFileName);
                            //realm.IsHidden = false;
                            //realm.IsRealm = true;
                            //WorldManager.SaveWorldList();
                        }
                        catch (Exception ex)
                        {
                            player.MessageNow("Could not load \"{0}\": {1}: {2}",
                                               fileName, ex.GetType().Name, ex.Message);
                            return;
                        }

                        World newWorld;
                        try
                        {
                            newWorld = WorldManager.AddWorld(player, worldName, map, false);
                            
                        }
                        catch (WorldOpException ex)
                        {
                            player.Message("RealmLoad: {0}", ex.Message);
                            return;
                        }

                        player.LastUsedWorldName = worldName;
                        newWorld.BuildSecurity.MinRank = buildRank;
                        if (accessRank == null)
                        {
                            newWorld.AccessSecurity.ResetMinRank();
                        }
                        else
                        {
                            newWorld.AccessSecurity.MinRank = accessRank;
                        }
                        newWorld.BlockDB.AutoToggleIfNeeded();
                        if (BlockDB.IsEnabledGlobally && newWorld.BlockDB.IsEnabled)
                        {
                            player.Message("BlockDB is now auto-enabled on realm {0}", newWorld.ClassyName);
                        }
                        newWorld.LoadedBy = player.Name;
                        newWorld.LoadedOn = DateTime.UtcNow;
                        Server.Message("{0}&S created a new realm named {1}",
                                        player.ClassyName, newWorld.ClassyName);
                        Logger.Log(LogType.UserActivity,
                                    "{0} created a new realm named \"{1}\" (loaded from \"{2}\")",
                                    player.Name, worldName, fileName);
                        newWorld.IsHidden = false;
                        newWorld.IsRealm = true;
                        WorldManager.SaveWorldList();
                        player.MessageNow("Access permission is {0}+&S, and build permission is {1}+",
                                           newWorld.AccessSecurity.MinRank.ClassyName,
                                           newWorld.BuildSecurity.MinRank.ClassyName);
                        
                    }
                }
            }

            Server.RequestGC();
        }
Example #45
0
        static void ZoneAddHandler(Player player, Command cmd)
        {
            World playerWorld = player.World;

            if (playerWorld == null)
            {
                PlayerOpException.ThrowNoWorld(player);
            }

            string givenZoneName = cmd.Next();

            if (givenZoneName == null)
            {
                CdZoneAdd.PrintUsage(player);
                return;
            }

            if (!player.Info.Rank.AllowSecurityCircumvention)
            {
                SecurityCheckResult buildCheck = playerWorld.BuildSecurity.CheckDetailed(player.Info);
                switch (buildCheck)
                {
                case SecurityCheckResult.BlackListed:
                    player.Message("Cannot add zones to world {0}&S: You are barred from building here.",
                                   playerWorld.ClassyName);
                    return;

                case SecurityCheckResult.RankTooLow:
                    player.Message("Cannot add zones to world {0}&S: You are not allowed to build here.",
                                   playerWorld.ClassyName);
                    return;
                    //case SecurityCheckResult.RankTooHigh:
                }
            }

            Zone           newZone        = new Zone();
            ZoneCollection zoneCollection = player.WorldMap.Zones;

            if (givenZoneName.StartsWith("+"))
            {
                // personal zone (/ZAdd +Name)
                givenZoneName = givenZoneName.Substring(1);

                // Find the target player
                PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches(player, givenZoneName);
                if (info == null)
                {
                    return;
                }

                // Make sure that the name is not taken already.
                // If a zone named after the player already exists, try adding a number after the name (e.g. "Notch2")
                newZone.Name = info.Name;
                for (int i = 2; zoneCollection.Contains(newZone.Name); i++)
                {
                    newZone.Name = givenZoneName + i;
                }

                newZone.Controller.MinRank = info.Rank.NextRankUp ?? info.Rank;
                newZone.Controller.Include(info);
                player.Message("Zone: Creating a {0}+&S zone for player {1}&S.",
                               newZone.Controller.MinRank.ClassyName, info.ClassyName);
            }
            else
            {
                // Adding an ordinary, rank-restricted zone.
                if (!World.IsValidName(givenZoneName))
                {
                    player.Message("\"{0}\" is not a valid zone name", givenZoneName);
                    return;
                }

                if (zoneCollection.Contains(givenZoneName))
                {
                    player.Message("A zone with this name already exists. Use &H/ZEdit&S to edit.");
                    return;
                }

                newZone.Name = givenZoneName;

                string rankName = cmd.Next();
                if (rankName == null)
                {
                    player.Message("No rank was specified. See &H/Help zone");
                    return;
                }
                Rank minRank = RankManager.FindRank(rankName);

                if (minRank != null)
                {
                    string name;
                    while ((name = cmd.Next()) != null)
                    {
                        if (name.Length == 0)
                        {
                            continue;
                        }

                        if (name.ToLower().StartsWith("msg="))
                        {
                            newZone.Message = name.Substring(4) + " " + (cmd.NextAll() ?? "");
                            player.Message("Zone: Custom denied messaged changed to '" + newZone.Message + "'");
                            break;
                        }

                        PlayerInfo info = PlayerDB.FindPlayerInfoOrPrintMatches(player, name.Substring(1));
                        if (info == null)
                        {
                            return;
                        }

                        if (name.StartsWith("+"))
                        {
                            newZone.Controller.Include(info);
                        }
                        else if (name.StartsWith("-"))
                        {
                            newZone.Controller.Exclude(info);
                        }
                    }

                    newZone.Controller.MinRank = minRank;
                }
                else
                {
                    player.MessageNoRank(rankName);
                    return;
                }
            }
            player.Message("Zone " + newZone.ClassyName + "&S: Place a block or type &H/Mark&S to use your location.");
            player.SelectionStart(2, ZoneAddCallback, newZone, CdZoneAdd.Permissions);
        }
Example #46
0
        /// <summary> Changes the name of the given world. </summary>
        public static void RenameWorld([NotNull] World world, [NotNull] string newName, bool moveMapFile, bool overwrite)
        {
            if (newName == null)
            {
                throw new ArgumentNullException("newName");
            }
            if (world == null)
            {
                throw new ArgumentNullException("world");
            }

            if (!World.IsValidName(newName))
            {
                throw new WorldOpException(newName, WorldOpExceptionCode.InvalidWorldName);
            }

            lock (world.SyncRoot) {
                string oldName = world.Name;
                if (oldName == newName)
                {
                    throw new WorldOpException(world.Name, WorldOpExceptionCode.NoChangeNeeded);
                }

                lock ( SyncRoot ) {
                    World newWorld = FindWorldExact(newName);
                    if (newWorld != null && newWorld != world)
                    {
                        if (overwrite)
                        {
                            RemoveWorld(newWorld);
                        }
                        else
                        {
                            throw new WorldOpException(newName, WorldOpExceptionCode.DuplicateWorldName);
                        }
                    }

                    WorldIndex.Remove(world.Name.ToLower());
                    world.Name = newName;
                    WorldIndex.Add(newName.ToLower(), world);
                    UpdateWorldList();

                    if (moveMapFile)
                    {
                        string oldMapFile = Path.Combine(Paths.MapPath, oldName + ".fcm");
                        string newMapFile = newName + ".fcm";
                        if (File.Exists(oldMapFile))
                        {
                            try {
                                Paths.ForceRename(oldMapFile, newMapFile);
                            } catch (Exception ex) {
                                throw new WorldOpException(world.Name,
                                                           WorldOpExceptionCode.MapMoveError,
                                                           ex);
                            }
                        }

                        lock (world.BlockDB.SyncRoot) {
                            string oldBlockDBFile = Path.Combine(Paths.BlockDBDirectory, oldName + ".fbdb");
                            string newBockDBFile  = newName + ".fbdb";
                            if (File.Exists(oldBlockDBFile))
                            {
                                try {
                                    Paths.ForceRename(oldBlockDBFile, newBockDBFile);
                                } catch (Exception ex) {
                                    throw new WorldOpException(world.Name,
                                                               WorldOpExceptionCode.MapMoveError,
                                                               ex);
                                }
                            }
                        }
                    }
                }
            }
        }