Exemple #1
0
        public static void SpawnMobs(WorldManager world, bool spawnHostileMobs, bool spawnPeacefulMobs)
        {
            var players = world.Server.GetAuthenticatedClients().Where(c => c.Owner.World == world).Select(c => c.Owner).ToArray();
            HashSet<int> chunksToSpawnIn = new HashSet<int>();

            #region Get a list of all chunks within 8 chunks of any players
            foreach (var player in players)
            {
                UniversalCoords coord = UniversalCoords.FromAbsWorld(player.Position);

                for (int x = -MaxSpawnDistance; x <= MaxSpawnDistance; x++)
                {
                    for (int z = -MaxSpawnDistance; z <= MaxSpawnDistance; z++)
                    {
                        chunksToSpawnIn.Add(UniversalCoords.FromChunkToPackedChunk(coord.ChunkX + x, coord.ChunkZ + z));
                    }
                }
            }
            #endregion

            // Get a list of Mob entities outside of the loop so we only get it once
            Mob[] mobEntities = world.GetEntities().Where(e => e is Mob).Select((e) => e as Mob).ToArray();

            // TODO: need to use Biome to get the list of mob types available for each category
            // TODO: make the maximum count of mobs per category configurable
            if (spawnHostileMobs)
            {
                DoSpawn(world, chunksToSpawnIn, mobEntities, Monsters, MaxMonsters);
            }
            if (spawnPeacefulMobs)
            {
                DoSpawn(world, chunksToSpawnIn, mobEntities, Creatures, MaxCreatures);
                DoSpawn(world, chunksToSpawnIn, mobEntities, WaterCreatures, MaxWaterCreatures, true);
            }
        }
 public override void GenerateB(WorldManager world, int i, int j, int k, int l, byte[] abyte0)
 {
     int i1 = rand.nextInt(rand.nextInt(rand.nextInt(40) + 1) + 1);
     if (rand.nextInt(15) != 0)
     {
         i1 = 0;
     }
     for (int j1 = 0; j1 < i1; j1++)
     {
         double d = i * 16 + rand.nextInt(16);
         double d1 = rand.nextInt(rand.nextInt(120) + 8);
         double d2 = j * 16 + rand.nextInt(16);
         int k1 = 1;
         if (rand.nextInt(4) == 0)
         {
             UnknownA(k, l, abyte0, d, d1, d2);
             k1 += rand.nextInt(4);
         }
         for (int l1 = 0; l1 < k1; l1++)
         {
             float f = rand.nextFloat() * 3.141593F * 2.0F;
             float f1 = ((rand.nextFloat() - 0.5F) * 2.0F) / 8F;
             float f2 = rand.nextFloat() * 2.0F + rand.nextFloat();
             UnknownB(k, l, abyte0, d, d1, d2, f2, f, f1, 0, 0, 1.0D);
         }
     }
 }
Exemple #3
0
 internal ChunkBase(WorldManager world, int x, int z)
 {
     World = world;
     X = x;
     Z = z;
     _UpdateTimer = new Timer(UpdateBlocksToNearbyPlayers, null, Timeout.Infinite, Timeout.Infinite);
 }
Exemple #4
0
        public Chunk ProvideChunk(int x, int z, WorldManager world)
        {
            Chunk chunk = new Chunk(world, UniversalCoords.FromChunk(x, z));
            InitGen();

            byte[] data = new byte[32768];
            #if PROFILE
            Stopwatch watch = new Stopwatch();
            watch.Start();
            #endif
            GenerateTerrain(chunk, data, x, z);
            GenerateFlora(chunk, data, x, z);
            chunk.SetAllBlocks(data);

            chunk.RecalculateHeight();
            chunk.LightToRecalculate = true;
            #if PROFILE
            watch.Stop();

            _World.Logger.Log(Logger.LogLevel.Info, "Chunk {0} {1}, {2}", false, x, z, watch.ElapsedMilliseconds);
            #endif

            _World.AddChunk(chunk);
            chunk.MarkToSave();

            return chunk;
        }
Exemple #5
0
 internal Ocelot(WorldManager world, int entityId, MobType type, MetaData data)
     : base(world, entityId, type, data)
 {
     Data.IsSitting = false;
     Data.IsTamed = false;
     Data.IsAggressive = false;
     FishUntilTamed = Server.Rand.Next(20);
 }
Exemple #6
0
 internal Wolf(WorldManager world, int entityId, MetaData data = null)
     : base(world, entityId, MobType.Wolf, data)
 {
     Data.IsSitting = false;
     Data.IsTamed = false;
     Data.IsAggressive = false;
     BonesUntilTamed = Server.Rand.Next(10); // How many bones required to tame this wolf?
 }
Exemple #7
0
 internal Wolf(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.Wolf, data)
 {
     this.Data.IsSitting    = false;
     this.Data.IsTamed      = false;
     this.Data.IsAggressive = false;
     this.BonesUntilTamed   = Server.Rand.Next(10); // How many bones required to tame this wolf?
 }
Exemple #8
0
 protected Mob(WorldManager world, int entityId, MobType type, MetaData data)
     : base(world.Server, entityId, data)
 {
     this.Type = type;
     this.World = world;
     this.MobUpdateFrequency = 1;
     this.Speed = 0.7;
 }
Exemple #9
0
 public static void StopBurning(WorldManager world, UniversalCoords coords)
 {
     string id = String.Format("{0}-{1},{2},{3}", world.Name, coords.WorldX, coords.WorldY, coords.WorldZ);
     lock (_staticLock)
     {
         if (_furnaceInstances.ContainsKey(id))
             _furnaceInstances[id].StopBurning();
     }
 }
Exemple #10
0
        public Vector3 gotoPos; // Location entity should move towards

        #endregion Fields

        #region Constructors

        protected Mob(WorldManager world, int entityId, MobType type, MetaData data)
            : base(world.Server, entityId)
        {
            if (data == null)
                data = new MetaData();
            this.Data = data;
            this.Type = type;
            this.World = world;
            this.Health = this.MaxHealth;
        }
Exemple #11
0
        public static PersistentContainer Instance(WorldManager world, UniversalCoords coords)
        {
            PersistentContainer container;
            Chunk chunk = world.GetChunk(coords) as Chunk;
            if (chunk == null)
                return null; 
            BlockData.Blocks block = chunk.GetType(coords);
            if (!chunk.Containers.ContainsKey(coords.BlockPackedCoords))
            {
                switch (block)
                {
                    case BlockData.Blocks.Furnace:
                    case BlockData.Blocks.Burning_Furnace:
                        container = new FurnaceContainer();
                        container.Initialize(world, coords);
                        (container as FurnaceContainer).StartBurning();
                        break;
                    case BlockData.Blocks.Dispenser:
                        container = new DispenserContainer();
                        container.Initialize(world, coords);
                        break;
                    case BlockData.Blocks.Chest:
                        // Double chest?
                        if (IsDoubleChest(chunk, coords))
                        {
                            UniversalCoords[] doubleChestCoords = GetDoubleChestCoords(world, coords);
                            if (doubleChestCoords == null)
                                return null;
                            chunk.Containers.TryRemove(doubleChestCoords[0].BlockPackedCoords, out container);
                            chunk.Containers.TryRemove(doubleChestCoords[1].BlockPackedCoords, out container);

                            container = new LargeChestContainer(doubleChestCoords[1]);
                            container.Initialize(world, doubleChestCoords[0]);
                            chunk.Containers.TryAdd(doubleChestCoords[0].BlockPackedCoords, container);
                            chunk.Containers.TryAdd(doubleChestCoords[1].BlockPackedCoords, container);
                        }
                        else
                        {
                            container = new SmallChestContainer();
                            container.Initialize(world, coords);
                        }
                        break;
                    default:
                        return null;
                }
                chunk.Containers.TryAdd(coords.BlockPackedCoords, container);
            }
            else
            {
                chunk.Containers.TryGetValue(coords.BlockPackedCoords, out container);
            }
            return container;
        }
Exemple #12
0
 public static void Destroy(WorldManager world, UniversalCoords coords)
 {
     PersistentContainer container = Instance(world, coords);
     if (container == null)
         return;
     Chunk chunk = world.GetChunk(coords);
     if (chunk == null)
         return;
     PersistentContainer unused;
     container.Destroy();
     chunk.Containers.TryRemove(container.Coords.BlockPackedCoords, out unused);
     if (container is LargeChestContainer)
         chunk.Containers.TryRemove((container as LargeChestContainer).SecondCoords.BlockPackedCoords, out unused);
 }
Exemple #13
0
 public virtual void Initialize(WorldManager world, UniversalCoords coords)
 {
     World = world;
     Coords = coords;
     Slots = new ItemInventory[SlotsCount];
     DataFile = string.Format("x{0}y{1}z{2}.dat", Coords.WorldX, Coords.WorldY, Coords.WorldZ);
     string chunkFolder = string.Format("x{0}z{1}", Coords.ChunkX, Coords.ChunkZ);
     ContainerFolder = Path.Combine(DataPath, chunkFolder);
     if (!Directory.Exists(ContainerFolder))
     {
         Directory.CreateDirectory(ContainerFolder);
     }
     Load();
 }
Exemple #14
0
 public virtual void GenerateA(ChunkGenerator gen, WorldManager world, int x, int z, byte[] data)
 {
     int radius = field_947_a;
     rand.setSeed(world.GetSeed());
     long l = (rand.nextLong() / 2L) * 2L + 1L;
     long l1 = (rand.nextLong() / 2L) * 2L + 1L;
     for (int ix = x - radius; ix <= x + radius; ix++)
     {
         for (int iz = z - radius; iz <= z + radius; iz++)
         {
             rand.setSeed((long)ix * l + (long)iz * l1 ^ world.GetSeed());
             GenerateB(world, ix, iz, x, z, data);
         }
     }
 }
Exemple #15
0
        internal Chunk(WorldManager world, int x, int z)
            : base(world, x, z)
        {
            /*using(StreamWriter sw  = new StreamWriter("chunkStack.log", true))
                {
                    sw.WriteLine("Instance: {0}, {1}, Thread: {2}", X, Z, Thread.CurrentThread.ManagedThreadId);

                    StackTrace stackTrace = new StackTrace();           // get call stack
                    StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

                    // write call stack method names
                    foreach (StackFrame stackFrame in stackFrames)
                    {
                        sw.WriteLine(stackFrame.GetMethod().ReflectedType.FullName + "." + stackFrame.GetMethod().Name + " line: {0}", stackFrame.GetFileLineNumber());   // write method name
                    }
                    sw.WriteLine("\r\n");
                }*/
        }
Exemple #16
0
        public static UniversalCoords[] GetDoubleChestCoords(WorldManager world, UniversalCoords coords)
        {
            Chunk chunk = world.GetChunk(coords);
            if (chunk == null || !IsDoubleChest(chunk, coords))
                return null;
            // Is this chest the "North or East", or the "South or West"
            BlockData.Blocks[] nsewBlocks = new BlockData.Blocks[4];
            UniversalCoords[] nsewBlockPositions = new UniversalCoords[4];
            int nsewCount = 0;
            byte? blockId;
            chunk.ForNSEW(coords, uc =>
            {
                blockId = world.GetBlockId(uc) ?? 0;
                nsewBlocks[nsewCount] = (BlockData.Blocks)blockId;
                nsewBlockPositions[nsewCount] = uc;
                nsewCount++;
            });
            UniversalCoords firstCoords;
            UniversalCoords secondCoords;

            if ((byte)nsewBlocks[0] == (byte)BlockData.Blocks.Chest) // North
            {
                firstCoords = nsewBlockPositions[0];
                secondCoords = coords;
            }
            else if ((byte)nsewBlocks[2] == (byte)BlockData.Blocks.Chest) // East
            {
                firstCoords = nsewBlockPositions[2];
                secondCoords = coords;
            }
            else if ((byte)nsewBlocks[1] == (byte)BlockData.Blocks.Chest) // South
            {
                firstCoords = coords;
                secondCoords = nsewBlockPositions[1];
            }
            else// if ((byte)nsewBlocks[3] == (byte)BlockData.Blocks.Chest) // West
            {
                firstCoords = coords;
                secondCoords = nsewBlockPositions[3];
            }
            return new UniversalCoords[] { firstCoords, secondCoords };
        }
Exemple #17
0
 public ChunkGenerator(WorldManager world, long seed)
 {
     SandNoise = new double[256];
     GravelNoise = new double[256];
     StoneNoise = new double[256];
     CaveGen = new MapGenCaves();
     field_707_i = new int[32][];
     for (int i = 0; i < 32; i++)
     {
         field_707_i[i] = new int[32];
     }
     World = world;
     Rand = new Random(seed);
     Noise1 = new NoiseGeneratorOctaves(Rand, 16);
     Noise2 = new NoiseGeneratorOctaves(Rand, 16);
     Noise3 = new NoiseGeneratorOctaves(Rand, 8);
     Noise4 = new NoiseGeneratorOctaves(Rand, 4);
     Noise5 = new NoiseGeneratorOctaves(Rand, 4);
     Noise6 = new NoiseGeneratorOctaves(Rand, 10);
     Noise7 = new NoiseGeneratorOctaves(Rand, 16);
     MobSpawnerNoise = new NoiseGeneratorOctaves(Rand, 8);
 }
Exemple #18
0
        /// <summary>
        /// Creates a new world.
        /// </summary>
        /// <param name="name">The name of the folder to contain and identify the world.</param>
        /// <returns>The newly created world.</returns>
        internal WorldManager CreateWorld(string name)
        {

            WorldManager world = new WorldManager(this);

            //Event
            WorldCreatedEventArgs e = new WorldCreatedEventArgs(world);
            PluginManager.CallEvent(Event.WorldCreate, e);
            if (e.EventCanceled) return null;
            //End Event

            lock (Worlds)
                Worlds.Add(world);

            return world;
        }
Exemple #19
0
        /*public IEnumerable<IEntityBase> GetNearbyLivings(IWorldManager world, AbsWorldCoords coords)
        {
            int radius = ChraftConfig.SightRadius << 4;
            foreach (EntityBase entity in GetEntities())
            {
                if (!(entity is LivingEntity))
                    continue;

                if (entity.World == world && Math.Abs(coords.X - entity.Position.X) <= radius && Math.Abs(coords.Y - entity.Position.Y) <= radius && Math.Abs(coords.Z - entity.Position.Z) <= radius)
                    yield return (entity as LivingEntity);
            }
        }*/

        internal IEnumerable<LivingEntity> GetNearbyLivingsInternal(WorldManager world, UniversalCoords coords)
        {
            int radius = ChraftConfig.MaxSightRadius;
            foreach (EntityBase entity in GetEntities())
            {
                if (!(entity is LivingEntity))
                    continue;
                int entityChunkX = (int)Math.Floor(entity.Position.X) >> 4;
                int entityChunkZ = (int)Math.Floor(entity.Position.Z) >> 4;

                if (entity.World == world && Math.Abs(coords.ChunkX - entityChunkX) <= radius && Math.Abs(coords.ChunkZ - entityChunkZ) <= radius)
                    yield return (entity as LivingEntity);
            }
        }
Exemple #20
0
        /// <summary>
        /// Yields an enumerable of nearby entities, including players.  Thread-safe.
        /// </summary>
        /// <param name="world">The world containing the coordinates.</param>
        /// <param name="x">The center X coordinate.</param>
        /// <param name="y">The center Y coordinate.</param>
        /// <param name="z">The center Z coordinate.</param>
        /// <returns>A lazy enumerable of nearby entities.</returns>
        /*public IEnumerable<EntityBase> GetNearbyEntities(WorldManager world, AbsWorldCoords coords)
        {
            int radius = ChraftConfig.SightRadius << 4;
            foreach (EntityBase e in GetEntities())
            {
                if (e.World == world && Math.Abs(coords.X - e.Position.X) <= radius && Math.Abs(coords.Y - e.Position.Y) <= radius && Math.Abs(coords.Z - e.Position.Z) <= radius)
                    yield return e;
            }
        }*/

        /// <summary>
        /// Yields an enumerable of nearby entities, including players.  Thread-safe.
        /// </summary>
        /// <param name="world">The world containing the coordinates.</param>
        /// <param name="x">The center X coordinate.</param>
        /// <param name="y">The center Y coordinate.</param>
        /// <param name="z">The center Z coordinate.</param>
        /// <returns>A lazy enumerable of nearby entities.</returns>
        internal IEnumerable<EntityBase> GetNearbyEntitiesInternal(WorldManager world, UniversalCoords coords)
        {
            int radius = ChraftConfig.MaxSightRadius;

            foreach (EntityBase e in GetEntities())
            {
                int entityChunkX = (int)Math.Floor(e.Position.X) >> 4;
                int entityChunkZ = (int)Math.Floor(e.Position.Z) >> 4;

                if (e.World == world && Math.Abs(coords.ChunkX - entityChunkX) <= radius && Math.Abs(coords.ChunkZ - entityChunkZ) <= radius)
                    yield return e;
            }
        }
Exemple #21
0
 /// <summary>
 /// Yields an enumerable of nearby players, thread-safe.
 /// </summary>
 /// <param name="world">The world containing the coordinates.</param>
 /// <param name="coords">The center coordinates.</param>
 /// <returns>A lazy enumerable of nearby players.</returns>
 internal IEnumerable<Client> GetNearbyPlayersInternal(WorldManager world, UniversalCoords coords)
 {
     int radius = ChraftConfig.MaxSightRadius;
     foreach (Client c in GetAuthenticatedClients())
     {
         int playerChunkX = (int)Math.Floor(c.Owner.Position.X) >> 4;
         int playerChunkZ = (int)Math.Floor(c.Owner.Position.Z) >> 4;
         if (c.Owner.World == world && Math.Abs(coords.ChunkX - playerChunkX) <= radius && Math.Abs(coords.ChunkZ - playerChunkZ) <= radius)
             yield return c;
     }
 }
Exemple #22
0
        /// <summary>
        /// Sends packets in parallel to each nearby player.
        /// </summary>
        /// <param name="world">The world containing the coordinates.</param>
        /// <param name="coords">The center coordinates.</param>
        /// <param name="packets">The list of packets to send</param>
        internal void SendPacketsToNearbyPlayers(WorldManager world, UniversalCoords coords, List<Packet> packets, Client excludedClient = null)
        {
            Client[] nearbyClients = GetNearbyPlayersInternal(world, coords).ToArray();

            if (nearbyClients.Length == 0)
                return;

            foreach (Packet packet in packets)
                packet.SetShared(Logger, nearbyClients.Length);

            Parallel.ForEach(nearbyClients, (client) =>
            {
                if (excludedClient != client)
                {
                    foreach (Packet packet in packets)
                        client.SendPacket(packet);
                }
                else
                {
                    foreach (Packet packet in packets)
                        packet.Release();
                }           
            });
        }
Exemple #23
0
        // TODO: This should be removed in favor of the one below
        /// <summary>
        /// Sends a packet in parallel to each nearby player.
        /// </summary>
        /// <param name="world">The world containing the coordinates.</param>
        /// <param name="absCoords>The center coordinates.</param>
        /// <param name="packet">The packet to send</param>
        internal void SendPacketToNearbyPlayers(WorldManager world, AbsWorldCoords absCoords, Packet packet)
        {
            Client[] nearbyClients = GetNearbyPlayersInternal(world, UniversalCoords.FromAbsWorld(absCoords)).ToArray();      

            if (nearbyClients.Length == 0)
                return;

            packet.SetShared(Logger, nearbyClients.Length);
            Parallel.ForEach(nearbyClients, (client) =>
            {
                client.SendPacket(packet);
            });
        }
Exemple #24
0
 internal Enderman(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.Blaze, data)
 {
 }
Exemple #25
0
 public FurnaceInstance(WorldManager world, UniversalCoords coords)
 {
     this.World = world;
     Coords = coords;
 }
Exemple #26
0
 public CustomChunkGenerator(WorldManager world, long seed)
 {
     _Seed = seed;
     _World = world;
 }
Exemple #27
0
        public static Chunk Load(UniversalCoords coords, WorldManager world)
        {
            string path = world.Folder + "/x" + coords.ChunkX + "_z" + coords.ChunkZ + ".gz";

            if (!CanLoad(path))
                return null;

            Stream zip = null;

            Chunk chunk = new Chunk(world, coords);

            try
            {
                zip = new DeflateStream(File.Open(path, FileMode.Open), CompressionMode.Decompress);

                int version = zip.ReadByte();

                switch(version)
                {
                    /* When there's a new mod you do:
                    case 1:
                    {
                     * dosomething
                     * goto case 0;
                    }*/
                    case 0:
                    {
                        chunk.LightToRecalculate = Convert.ToBoolean(zip.ReadByte());
                        chunk.HeightMap = new byte[16,16];
                        int height;
                        chunk.MaxHeight = 0;
                        for (int x = 0; x < 16; ++x)
                        {
                            for (int z = 0; z < 16; ++z)
                            {
                                height = chunk.HeightMap[x, z] = (byte) zip.ReadByte();

                                if (chunk.MaxHeight < height)
                                    chunk.MaxHeight = height;
                            }
                        }
                        chunk.LoadAllBlocks(zip);
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                world.Logger.Log(ex);
                return null;
            }
            if (zip != null)
                zip.Dispose();

            (BlockHelper.Instance((byte) BlockData.Blocks.Sign_Post) as BlockSignBase).LoadSignsFromDisk(chunk, world.SignsFolder);

            return chunk;
        }
Exemple #28
0
 internal Ghast(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.Ghast, data)
 {
 }
Exemple #29
0
 internal Chunk(WorldManager world, int x, int z)
     : base(world, x, z)
 {
 }
Exemple #30
0
 internal Spider(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.Spider, data)
 {
 }
Exemple #31
0
 internal ZombiePigman(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.PigZombie, data)
 {
 }
Exemple #32
0
 internal Skeleton(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.Skeleton, data)
 {
 }
Exemple #33
0
        public Chunk(WorldManager world, UniversalCoords coords)
        {
            LightToRecalculate = true;
            World = world;
            Coords = coords;

            if(_Sections == null)
                _Sections = new Section[_MaxSections = 16];
        }
Exemple #34
0
 internal Sheep(Chraft.World.WorldManager world, int entityId, Chraft.Net.MetaData data = null)
     : base(world, entityId, MobType.Sheep, data)
 {
     Data.Sheared   = false;
     Data.WoolColor = _woolColor.SelectRandom(world.Server.Rand);
 }
Exemple #35
0
 public Chunk(WorldManager world, UniversalCoords coords, int maxSections) : this(world, coords)
 {
     _Sections = new Section[maxSections];
     _MaxSections = maxSections;
 }
Exemple #36
0
 internal Chunk(WorldManager world, UniversalCoords coords)
     : base(world, coords)
 {
     LightToRecalculate = true;
 }
Exemple #37
0
        /// <summary>
        /// Sends a packet in parallel to each nearby player.
        /// </summary>
        /// <param name="world">The world containing the coordinates.</param>
        /// <param name="coords">The center coordinates.</param>
        /// <param name="packet">The packet to send</param>
        public void SendPacketToNearbyPlayers(WorldManager world, UniversalCoords coords, Packet packet, Client excludedClient = null)
        {
            Client[] nearbyClients = GetNearbyPlayers(world, coords).ToArray();

            if (nearbyClients.Length == 0 || (excludedClient != null && nearbyClients.Length == 1))
                return;

            packet.SetShared(Logger, excludedClient == null ? nearbyClients.Length : nearbyClients.Length - 1);

            Parallel.ForEach(nearbyClients, (client) =>
            {
                if (excludedClient != client)
                    client.SendPacket(packet);
            });
        }