Exemple #1
0
        private void GenerateParticles(Random random, Level level, PlayerLocation point, float yoffset, Vector3 multiplier, double d)
        {
            float vx = (float)random.NextDouble();

            vx *= random.Next(2) == 0 ? 1 : -1;
            vx *= (float)multiplier.X;

            float vy = (float)random.NextDouble();

            //vy *= random.Next(2) == 0 ? 1 : -1;
            vy *= (float)multiplier.Y;

            float vz = (float)random.NextDouble();

            vz *= random.Next(2) == 0 ? 1 : -1;
            vz *= (float)multiplier.Z;

            McpeLevelEvent mobParticles = McpeLevelEvent.CreateObject();

            mobParticles.eventId = (short)(0x4000 | GetParticle(random.Next(0, m < 1 ? 2 : 5)));
            mobParticles.x       = point.X + vx;
            mobParticles.y       = (point.Y - 2) + yoffset + vy;
            mobParticles.z       = point.Z + vz;
            level.RelayBroadcast(mobParticles);
        }
Exemple #2
0
        public void curse(Player player)
        {
            McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();

            levelEvent.eventId = 2006;
            levelEvent.data    = 1;
            player.Level.RelayBroadcast(levelEvent);
        }
Exemple #3
0
        public override void Spawn(Player[] players)
        {
            var particleEvent = McpeLevelEvent.CreateObject();

            particleEvent.eventId  = (short)(0x4000 | Id);
            particleEvent.position = Position;
            particleEvent.data     = Data;
            Level.RelayBroadcast(players, particleEvent);
        }
Exemple #4
0
        private void SendBlockBreakEnd(BlockCoordinates coordinates)
        {
            McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();

            levelEvent.position = coordinates;
            levelEvent.eventId  = 3601;    //Block stop cracking
            levelEvent.data     = 0;
            Level.RelayBroadcast(levelEvent);
        }
        public override void Spawn()
        {
            McpeLevelEvent particleEvent = McpeLevelEvent.CreateObject();

            particleEvent.eventId  = 2001;
            particleEvent.position = Position;
            particleEvent.data     = Data;
            Level.RelayBroadcast(particleEvent);
        }
Exemple #6
0
        public virtual void Spawn()
        {
            McpeLevelEvent particleEvent = McpeLevelEvent.CreateObject();

            particleEvent.eventId  = (short)(0x4000 | Id);
            particleEvent.position = Position;
            particleEvent.data     = Data;
            Level.RelayBroadcast(particleEvent);
        }
Exemple #7
0
        public void ToggleDownfall(Player player)
        {
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                for (int i = 0; i < short.MaxValue; i = i + 2000)
                {
                    var data = i;
                    {
                        McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
                        levelEvent.eventId        = 3001;
                        levelEvent.data           = data;
                        player.SendPackage(levelEvent);
                    }
                    //{
                    //	McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
                    //	levelEvent.eventId = 3002;
                    //	levelEvent.data = i;
                    //	player.SendPackage(levelEvent);
                    //}
                    player.SendMessage("Downfall " + data, type: MessageType.Raw);
                    Thread.Sleep(5000);
                }
                for (int i = short.MaxValue; i >= 0; i = i - 2000)
                {
                    {
                        McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
                        levelEvent.eventId        = 3001;
                        levelEvent.data           = i;
                        player.SendPackage(levelEvent);
                    }
                    //{
                    //	McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
                    //	levelEvent.eventId = 3002;
                    //	levelEvent.data = i;
                    //	player.SendPackage(levelEvent);
                    //}

                    player.SendMessage("Downfall " + i, type: MessageType.Raw);
                    Thread.Sleep(5000);
                }
            });

            //{
            //	McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
            //	levelEvent.eventId = 3001;
            //	levelEvent.data = 100000;
            //	player.SendPackage(levelEvent);
            //}
            //{
            //	McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
            //	levelEvent.eventId = 3002;
            //	levelEvent.data = 36625;
            //	player.SendPackage(levelEvent);
            //}
            player.SendMessage("Toggled downfall", type: MessageType.Raw);
        }
Exemple #8
0
		public void ToggleDownfall(Player player)
		{
			ThreadPool.QueueUserWorkItem(delegate(object state)
			{
				for (int i = 0; i < short.MaxValue; i = i+2000)
				{
					var data = i;
					{
						McpeLevelEvent levelEvent = new McpeLevelEvent();
						levelEvent.eventId = 3001;
						levelEvent.data = data;
						player.SendPackage(levelEvent);
					}
					//{
					//	McpeLevelEvent levelEvent = new McpeLevelEvent();
					//	levelEvent.eventId = 3002;
					//	levelEvent.data = i;
					//	player.SendPackage(levelEvent);
					//}
					player.SendMessage("Downfall " + data, type: MessageType.Raw);
					Thread.Sleep(5000);
				}
				for (int i = short.MaxValue; i >= 0; i = i - 2000)
				{
					{
						McpeLevelEvent levelEvent = new McpeLevelEvent();
						levelEvent.eventId = 3001;
						levelEvent.data = i;
						player.SendPackage(levelEvent);
					}
					//{
					//	McpeLevelEvent levelEvent = new McpeLevelEvent();
					//	levelEvent.eventId = 3002;
					//	levelEvent.data = i;
					//	player.SendPackage(levelEvent);
					//}

					player.SendMessage("Downfall " + i, type: MessageType.Raw);
					Thread.Sleep(5000);
				}
			});

			//{
			//	McpeLevelEvent levelEvent = new McpeLevelEvent();
			//	levelEvent.eventId = 3001;
			//	levelEvent.data = 100000;
			//	player.SendPackage(levelEvent);
			//}
			//{
			//	McpeLevelEvent levelEvent = new McpeLevelEvent();
			//	levelEvent.eventId = 3002;
			//	levelEvent.data = 36625;
			//	player.SendPackage(levelEvent);
			//}
			player.SendMessage("Toggled downfall", type: MessageType.Raw);
		}
Exemple #9
0
        public virtual void Spawn(Level level)
        {
            McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();

            levelEvent.eventId  = Id;
            levelEvent.data     = Pitch;
            levelEvent.position = Position;

            level.RelayBroadcast(levelEvent);
        }
Exemple #10
0
		public void ToggleDownfall(Player player, int value)
		{
			{
				McpeLevelEvent levelEvent = new McpeLevelEvent();
				levelEvent.eventId = 3001;
				levelEvent.data = value;
				player.SendPackage(levelEvent);
			}
			player.SendMessage("Downfall " + value, type: MessageType.Raw);
		}
Exemple #11
0
        private static void OnMcpeLevelEvent(Package message)
        {
            McpeLevelEvent msg = (McpeLevelEvent)message;

            Log.DebugFormat("Event ID: {0}", msg.eventId);
            Log.DebugFormat("X: {0}", msg.x);
            Log.DebugFormat("Y: {0}", msg.y);
            Log.DebugFormat("Z: {0}", msg.z);
            Log.DebugFormat("Data: {0}", msg.data);
        }
Exemple #12
0
 public void ToggleDownfall(Player player, int value)
 {
     {
         McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();
         levelEvent.eventId = 3001;
         levelEvent.data    = value;
         player.SendPackage(levelEvent);
     }
     player.SendMessage("Downfall " + value, type: MessageType.Raw);
 }
Exemple #13
0
        public override void Spawn()
        {
            McpeLevelEvent particleEvent = McpeLevelEvent.CreateObject();

            particleEvent.eventId = 2001;
            particleEvent.x       = (float)Position.X;
            particleEvent.y       = (float)Position.Y;
            particleEvent.z       = (float)Position.Z;
            particleEvent.data    = Data;
            Level.RelayBroadcast(particleEvent);
        }
Exemple #14
0
        public override void HandleMcpeLevelEvent(McpeLevelEvent message)
        {
            int data = message.data;

            if (message.eventId == 2001)
            {
                int blockId  = data & 0xff;
                int metadata = data >> 12;
                Log.Debug($"BlockID={blockId}, Metadata={metadata}");
            }
        }
Exemple #15
0
        public void LevelEvent(Player player, short value, int data)
        {
            McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();

            levelEvent.eventId  = value;
            levelEvent.data     = data;
            levelEvent.position = player.KnownPosition.ToVector3();
            player.Level.RelayBroadcast(levelEvent);

            player.Level.BroadcastMessage($"Sent level event {value}", type: MessageType.Raw);
        }
Exemple #16
0
        public virtual void Spawn(Player[] players)
        {
            McpeLevelEvent particleEvent = McpeLevelEvent.CreateObject();

            particleEvent.eventId = (short)(0x4000 | Id);
            particleEvent.x       = (float)Position.X;
            particleEvent.y       = (float)Position.Y;
            particleEvent.z       = (float)Position.Z;
            particleEvent.data    = Data;
            Level.RelayBroadcast(players, particleEvent);
        }
Exemple #17
0
        public virtual void Spawn(Level level)
        {
            McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();

            levelEvent.eventId = Id;
            levelEvent.data    = Pitch;
            levelEvent.x       = (float)Position.X;
            levelEvent.y       = (float)Position.Y;
            levelEvent.z       = (float)Position.Z;

            level.RelayBroadcast(levelEvent);
        }
Exemple #18
0
        public virtual void Spawn(Level level)
        {
            McpeLevelEvent levelEvent = new McpeLevelEvent
            {
                eventId = Id,
                data    = Pitch,
                x       = (float)Position.X,
                y       = (float)Position.Y,
                z       = (float)Position.Z
            };

            level.RelayBroadcast(levelEvent);
        }
Exemple #19
0
        public void LevelEvent(Player player, short value, int data)
        {
            McpeLevelEvent levelEvent = new McpeLevelEvent
            {
                eventId = value,
                data    = data,
                x       = player.KnownPosition.X,
                y       = player.KnownPosition.Y,
                z       = player.KnownPosition.Z
            };

            player.Level.RelayBroadcast(levelEvent);

            player.Level.BroadcastMessage($"Sent level event {value}", type: MessageType.Raw);
        }
Exemple #20
0
        public virtual void SpawnToPlayers(Player[] players)
        {
            if (players == null)
            {
                return;
            }
            if (players.Length == 0)
            {
                return;
            }

            McpeLevelEvent levelEvent = McpeLevelEvent.CreateObject();

            levelEvent.eventId  = Id;
            levelEvent.data     = Pitch;
            levelEvent.position = Position;
            levelEvent.AddReferences(players.Length - 1);

            foreach (var player in players)
            {
                player.SendPacket(levelEvent);
            }
        }
Exemple #21
0
        /// <summary>
        ///     Handles the specified package.
        /// </summary>
        /// <param name="message">The package.</param>
        /// <param name="senderEndpoint">The sender's endpoint.</param>
        private void HandlePackage(Package message, IPEndPoint senderEndpoint)
        {
            if (typeof(McpeBatch) == message.GetType())
            {
                Log.Debug("Processing Batch package");
                McpeBatch batch = (McpeBatch)message;

                var messages = new List <Package>();

                // Get bytes
                byte[] payload = batch.payload;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = new MemoryStream();
                    defStream2.CopyTo(destination);
                    destination.Position = 0;
                    NbtBinaryReader reader = new NbtBinaryReader(destination, true);
                    do
                    {
                        int    len            = reader.ReadInt32();
                        byte[] internalBuffer = reader.ReadBytes(len);
                        messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer) ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                    } while (destination.Position < destination.Length);                     // throw new Exception("Have more data");
                }
                foreach (var msg in messages)
                {
                    HandlePackage(msg, senderEndpoint);
                    msg.PutPool();
                }
                return;
            }

            TraceReceive(message);

            if (typeof(UnknownPackage) == message.GetType())
            {
                return;
            }

            if (typeof(McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect)message;
                Log.InfoFormat("Disconnect {1}: {0}", msg.message, Username);
                SendDisconnectionNotification();
                StopClient();
                return;
            }

            if (typeof(ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing)message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            if (typeof(McpeFullChunkData) == message.GetType())
            {
                //McpeFullChunkData msg = (McpeFullChunkData) message;
                //ChunkColumn chunk = ClientUtils.DecocedChunkColumn(msg.chunkData);
                //if (chunk != null)
                //{
                //	Log.DebugFormat("Chunk X={0}", chunk.x);
                //	Log.DebugFormat("Chunk Z={0}", chunk.z);

                //	//ClientUtils.SaveChunkToAnvil(chunk);
                //}
                return;
            }

            if (typeof(ConnectionRequestAccepted) == message.GetType())
            {
                Thread.Sleep(50);
                SendNewIncomingConnection();
                //_connectedPingTimer = new Timer(state => SendConnectedPing(), null, 1000, 1000);
                Thread.Sleep(50);
                SendLogin(Username);
                return;
            }

            if (typeof(McpeSetSpawnPosition) == message.GetType())
            {
                McpeSetSpawnPosition msg = (McpeSetSpawnPosition)message;
                _spawn        = new Vector3(msg.x, msg.y, msg.z);
                _level.SpawnX = (int)_spawn.X;
                _level.SpawnY = (int)_spawn.Y;
                _level.SpawnZ = (int)_spawn.Z;

                return;
            }

            if (typeof(McpeStartGame) == message.GetType())
            {
                McpeStartGame msg = (McpeStartGame)message;
                _entityId        = msg.entityId;
                _spawn           = new Vector3(msg.x, msg.y, msg.z);
                _level.LevelName = "Default";
                _level.Version   = 19133;
                _level.GameType  = msg.gamemode;

                //ClientUtils.SaveLevel(_level);

                return;
            }

            if (typeof(McpeTileEvent) == message.GetType())
            {
                McpeTileEvent msg = (McpeTileEvent)message;
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Case 1: {0}", msg.case1);
                Log.DebugFormat("Case 2: {0}", msg.case2);
                return;
            }
            if (typeof(McpeAddEntity) == message.GetType())
            {
                McpeAddEntity msg = (McpeAddEntity)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                Log.DebugFormat("Entity Type: {0}", msg.entityType);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Yaw: {0}", msg.yaw);
                Log.DebugFormat("Pitch: {0}", msg.pitch);
                Log.DebugFormat("Velocity X: {0}", msg.speedX);
                Log.DebugFormat("Velocity Y: {0}", msg.speedY);
                Log.DebugFormat("Velocity Z: {0}", msg.speedZ);
                //Log.DebugFormat("Metadata: {0}", msg.metadata.ToString());
                //Log.DebugFormat("Links count: {0}", msg.links);

                return;
            }
            if (typeof(McpeSetEntityData) == message.GetType())
            {
                McpeSetEntityData msg = (McpeSetEntityData)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                MetadataDictionary metadata = msg.metadata;
                Log.DebugFormat("Metadata: {0}", metadata.ToString());
                return;
            }

            if (typeof(McpeMovePlayer) == message.GetType())
            {
                //McpeMovePlayer msg = (McpeMovePlayer) message;
                //Log.DebugFormat("Entity ID: {0}", msg.entityId);

                //CurrentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
                //SendMcpeMovePlayer();
                return;
            }

            if (typeof(McpeUpdateBlock) == message.GetType())
            {
                McpeUpdateBlock msg = (McpeUpdateBlock)message;
                Log.DebugFormat("No of Blocks: {0}", msg.blocks.Count);
                return;
            }

            if (typeof(McpeLevelEvent) == message.GetType())
            {
                McpeLevelEvent msg = (McpeLevelEvent)message;
                Log.DebugFormat("Event ID: {0}", msg.eventId);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Data: {0}", msg.data);
                return;
            }

            if (typeof(McpeContainerSetContent) == message.GetType())
            {
                McpeContainerSetContent msg = (McpeContainerSetContent)message;
                Log.DebugFormat("Window ID: 0x{0:x2}, Count: {1}", msg.windowId, msg.slotData.Count);
                var slots = msg.slotData.GetValues();

                foreach (var entry in slots)
                {
                    MetadataSlot slot = (MetadataSlot)entry;
                    //Log.DebugFormat(" - Id: {0}, Metadata: {1}, Count: {2}", slot.Value.Item.Id, slot.Value.Item.Metadata, slot.Value.Count);
                }
                return;
            }

            if (typeof(McpeCraftingData) == message.GetType())
            {
                string fileName = Path.GetTempPath() + "Recipes_" + Guid.NewGuid() + ".txt";
                Log.Info("Writing recipes to filename: " + fileName);
                FileStream file = File.OpenWrite(fileName);

                McpeCraftingData   msg    = (McpeCraftingData)message;
                IndentedTextWriter writer = new IndentedTextWriter(new StreamWriter(file));

                writer.WriteLine("static RecipeManager()");
                writer.WriteLine("{");
                writer.Indent++;
                writer.WriteLine("Recipes = new Recipes");
                writer.WriteLine("{");
                writer.Indent++;

                foreach (Recipe recipe in msg.recipes)
                {
                    ShapelessRecipe shapelessRecipe = recipe as ShapelessRecipe;
                    if (shapelessRecipe != null)
                    {
                        writer.WriteLine(string.Format("new ShapelessRecipe(new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", shapelessRecipe.Result.Id, shapelessRecipe.Result.Metadata, shapelessRecipe.Result.Count));
                        writer.Indent++;
                        writer.WriteLine("new List<ItemStack>");
                        writer.WriteLine("{");
                        writer.Indent++;
                        foreach (var itemStack in shapelessRecipe.Input)
                        {
                            writer.WriteLine(string.Format("new ItemStack(ItemFactory.GetItem({0}, {1}), {2}),", itemStack.Id, itemStack.Metadata, itemStack.Count));
                        }
                        writer.Indent--;
                        writer.WriteLine("}),");
                        writer.Indent--;

                        continue;
                    }

                    ShapedRecipe shapedRecipe = recipe as ShapedRecipe;
                    if (shapedRecipe != null)
                    {
                        writer.WriteLine(string.Format("new ShapedRecipe({0}, {1}, new ItemStack(ItemFactory.GetItem({2}, {3}), {4}),", shapedRecipe.Width, shapedRecipe.Height, shapedRecipe.Result.Id, shapedRecipe.Result.Metadata, shapedRecipe.Result.Count));
                        writer.Indent++;
                        writer.WriteLine("new Item[]");
                        writer.WriteLine("{");
                        writer.Indent++;
                        foreach (Item item in shapedRecipe.Input)
                        {
                            writer.WriteLine(string.Format("ItemFactory.GetItem({0}, {1}),", item.Id, item.Metadata));
                        }
                        writer.Indent--;
                        writer.WriteLine("}),");
                        writer.Indent--;

                        continue;
                    }
                }

                writer.WriteLine("};");
                writer.Indent--;
                writer.WriteLine("}");
                writer.Indent--;

                writer.Flush();

                file.Close();
                Environment.Exit(0);
                return;
            }
        }
Exemple #22
0
 public virtual void HandleMcpeLevelEvent(McpeLevelEvent message)
 {
 }
Exemple #23
0
        /// <summary>
        ///		Handles player actions like Start & Stop break
        /// </summary>
        /// <param name="message"></param>
        public override void HandleMcpePlayerAction(McpePlayerAction message)
        {
            var action = (PlayerAction)message.actionId;

            lock (_breakSync)
            {
                if (GameMode == GameMode.Creative)
                {
                    return;
                }

                Block block;
                if (action == PlayerAction.StartBreak)
                {
                    block = Level.GetBlock(message.coordinates);
                    var inHand = Inventory.GetItemInHand();
                    var drops  = block.GetDrops(inHand);

                    float tooltypeFactor = drops == null || drops.Length == 0 ? 5f : 1.5f;                     // 1.5 if proper tool

                    var multiplier = 1f;
                    switch (inHand.ItemMaterial)
                    {
                    case ItemMaterial.None:
                        break;

                    case ItemMaterial.Wood:
                        multiplier = 2f;
                        break;

                    case ItemMaterial.Stone:
                        multiplier = 4f;
                        break;

                    case ItemMaterial.Gold:
                        multiplier = 12f;
                        break;

                    case ItemMaterial.Iron:
                        multiplier = 6f;
                        break;

                    case ItemMaterial.Diamond:
                        multiplier = 8f;
                        break;
                    }

                    foreach (var enchantment in inHand.GetEnchantings())
                    {
                        if (enchantment.Id == EnchantingType.Efficiency && enchantment.Level > 0)
                        {
                            multiplier += MathF.Sqrt(enchantment.Level) + 1;
                        }
                    }

                    if (Effects.TryGetValue(EffectType.Haste, out var effect))
                    {
                        if (effect is Haste haste && haste.Level > 0f)
                        {
                            multiplier *= 1f + (haste.Level * 0.2f);
                        }
                    }

                    var hardness = block.Hardness;

                    double breakTime = MathF.Ceiling((hardness * tooltypeFactor * 20f));

                    McpeLevelEvent message1 = McpeLevelEvent.CreateObject();
                    message1.eventId  = 3600;
                    message1.position = message.coordinates;
                    message1.data     = (int)((double)ushort.MaxValue / (breakTime / multiplier));

                    Level.RelayBroadcast(message1);

                    BlockFace face = (BlockFace)message.face;

                    IsBreakingBlock = true;
                    BlockBreakTimer.Restart();
                    BreakingBlockCoordinates = block.Coordinates;
                    BlockBreakTime           = breakTime / multiplier;
                    BreakingFace             = face;

                    //		Log.Info(
                    //			$"Start Breaking block. Hardness: {hardness} | ToolTypeFactor; {tooltypeFactor} | BreakTime: {breakTime} | Multiplier: {multiplier} | BLockBreakTime: {breakTime / multiplier} | IsBreaking: {IsBreakingBlock}");

                    var blockStartBreak = new BlockStartBreakEvent(this, block);
                    EventDispatcher.DispatchEventAsync(blockStartBreak).Then(result =>
                    {
                        if (result.IsCancelled)
                        {
                            SendBlockBreakEnd(block.Coordinates);
                            return;
                        }
                    });

                    return;
                }
                else if (action == PlayerAction.AbortBreak)
                {
                    var elapsed      = BlockBreakTimer.ElapsedMilliseconds;
                    var elapsedTicks = elapsed / 50d;

                    //	Log.Info($"!! Abort Break !!! Ticks elapsed: {elapsedTicks} | Required: {BlockBreakTime} | IsBreaking: {IsBreakingBlock}");

                    block = Level.GetBlock(message.coordinates);
                    if (IsBreakingBlock && BreakingBlockCoordinates == block.Coordinates)
                    {
                        IsBreakingBlock = false;
                        BlockBreakTimer.Reset();

                        EventDispatcher.DispatchEventAsync(new BlockAbortBreakEvent(this, block)).Then(result =>
                        {
                            if (!result.IsCancelled)
                            {
                                SendBlockBreakEnd(block.Coordinates);
                                return;
                            }
                        });
                    }

                    return;
                }
                else if (action == PlayerAction.StopBreak)
                {
                    var elapsed      = BlockBreakTimer.ElapsedMilliseconds;
                    var elapsedTicks = elapsed / 50d;

                    //Log.Info($"## !! Stop Break !!! Ticks elapsed: {elapsedTicks} | Required: {BlockBreakTime} | IsBreaking: {IsBreakingBlock}");

                    if (IsBreakingBlock)
                    {
                        //BlockFace face = (BlockFace) message.face;
                        if (elapsedTicks >= BlockBreakTime || Math.Abs(elapsedTicks - BlockBreakTime) < 2.5
                            )                     //Give a max time difference of 2.5 ticks.
                        {
                            StopBreak(BreakingBlockCoordinates);
                        }
                        else
                        {
                        }
                    }
                    else
                    {
                        IsBreakingBlock = false;
                        BlockBreakTimer.Reset();
                    }

                    return;
                }
            }

            base.HandleMcpePlayerAction(message);
        }
Exemple #24
0
 public override void HandleMcpeLevelEvent(McpeLevelEvent message)
 {
 }
Exemple #25
0
        /// <summary>
        ///     Handles the specified package.
        /// </summary>
        /// <param name="message">The package.</param>
        /// <param name="senderEndpoint">The sender's endpoint.</param>
        private void HandlePackage(Package message, IPEndPoint senderEndpoint)
        {
            if (typeof(McpeBatch) == message.GetType())
            {
                McpeBatch batch = (McpeBatch)message;

                var messages = new List <Package>();

                // Get bytes
                byte[] payload = batch.payload;
                // Decompress bytes

                MemoryStream stream = new MemoryStream(payload);
                if (stream.ReadByte() != 0x78)
                {
                    throw new InvalidDataException("Incorrect ZLib header. Expected 0x78 0x9C");
                }
                stream.ReadByte();
                using (var defStream2 = new DeflateStream(stream, CompressionMode.Decompress, false))
                {
                    // Get actual package out of bytes
                    MemoryStream destination = new MemoryStream();
                    defStream2.CopyTo(destination);
                    byte[] internalBuffer = destination.ToArray();
                    messages.Add(PackageFactory.CreatePackage(internalBuffer[0], internalBuffer) ?? new UnknownPackage(internalBuffer[0], internalBuffer));
                }
                foreach (var msg in messages)
                {
                    HandlePackage(msg, senderEndpoint);
                }
                return;
            }

            TraceReceive(message);

            if (typeof(UnknownPackage) == message.GetType())
            {
                return;
            }

            if (typeof(McpeDisconnect) == message.GetType())
            {
                McpeDisconnect msg = (McpeDisconnect)message;
                Log.Debug(msg.message);
                StopServer();
                return;
            }

            if (typeof(ConnectedPing) == message.GetType())
            {
                ConnectedPing msg = (ConnectedPing)message;
                SendConnectedPong(msg.sendpingtime);
                return;
            }

            if (typeof(McpeFullChunkData) == message.GetType())
            {
                McpeFullChunkData msg   = (McpeFullChunkData)message;
                ChunkColumn       chunk = ClientUtils.DecocedChunkColumn(msg.chunkData);
                if (chunk != null)
                {
                    Log.DebugFormat("Chunk X={0}", chunk.x);
                    Log.DebugFormat("Chunk Z={0}", chunk.z);

                    ClientUtils.SaveChunkToAnvil(chunk);
                }
                return;
            }

            if (typeof(ConnectionRequestAccepted) == message.GetType())
            {
                Thread.Sleep(50);
                SendNewIncomingConnection();
                var t1 = new Timer(state => SendConnectedPing(), null, 2000, 5000);
                Thread.Sleep(50);
                SendLogin("Client12");
                return;
            }

            if (typeof(McpeSetSpawnPosition) == message.GetType())
            {
                McpeSetSpawnPosition msg = (McpeSetSpawnPosition)message;
                _spawn        = new Vector3(msg.x, msg.y, msg.z);
                _level.SpawnX = (int)_spawn.X;
                _level.SpawnY = (int)_spawn.Y;
                _level.SpawnZ = (int)_spawn.Z;

                return;
            }

            if (typeof(McpeStartGame) == message.GetType())
            {
                McpeStartGame msg = (McpeStartGame)message;
                _entityId        = msg.entityId;
                _spawn           = new Vector3(msg.x, msg.y, msg.z);
                _level.LevelName = "Default";
                _level.Version   = 19133;
                _level.GameType  = msg.gamemode;

                ClientUtils.SaveLevel(_level);

                return;
            }

            if (typeof(McpeTileEvent) == message.GetType())
            {
                McpeTileEvent msg = (McpeTileEvent)message;
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Case 1: {0}", msg.case1);
                Log.DebugFormat("Case 2: {0}", msg.case2);
                return;
            }
            if (typeof(McpeAddEntity) == message.GetType())
            {
                McpeAddEntity msg = (McpeAddEntity)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                Log.DebugFormat("Entity Type: {0}", msg.entityType);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Yaw: {0}", msg.yaw);
                Log.DebugFormat("Pitch: {0}", msg.pitch);
                Log.DebugFormat("Velocity X: {0}", msg.speedX);
                Log.DebugFormat("Velocity Y: {0}", msg.speedY);
                Log.DebugFormat("Velocity Z: {0}", msg.speedZ);
                Log.DebugFormat("Metadata: {0}", msg.metadata.ToString());
                Log.DebugFormat("Links count: {0}", msg.links);

                return;
            }
            if (typeof(McpeSetEntityData) == message.GetType())
            {
                McpeSetEntityData msg = (McpeSetEntityData)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);
                MetadataDictionary metadata = msg.metadata;
                Log.DebugFormat("Metadata: {0}", metadata.ToString());
                return;
            }

            if (typeof(McpeMovePlayer) == message.GetType())
            {
                McpeMovePlayer msg = (McpeMovePlayer)message;
                Log.DebugFormat("Entity ID: {0}", msg.entityId);

                _currentLocation = new PlayerLocation(msg.x, msg.y + 10, msg.z);
                SendMcpeMovePlayer();
                return;
            }

            if (typeof(McpeUpdateBlock) == message.GetType())
            {
                McpeUpdateBlock msg = (McpeUpdateBlock)message;
                Log.DebugFormat("No of Blocks: {0}", msg.blocks.Count);
                return;
            }

            if (typeof(McpeLevelEvent) == message.GetType())
            {
                McpeLevelEvent msg = (McpeLevelEvent)message;
                Log.DebugFormat("Event ID: {0}", msg.eventId);
                Log.DebugFormat("X: {0}", msg.x);
                Log.DebugFormat("Y: {0}", msg.y);
                Log.DebugFormat("Z: {0}", msg.z);
                Log.DebugFormat("Data: {0}", msg.data);
                return;
            }
        }
 public abstract void HandleMcpeLevelEvent(McpeLevelEvent message);
Exemple #27
0
        public void DisplaySelection(bool force = false, int particleId = 10)
        {
            if (!force && !ShowSelection)
            {
                return;                                       // don't render at all
            }
            if (force && ShowSelection)
            {
                return;                                     // Will be rendered on regular tick instead
            }
            Level level = Player.Level;

            if (!Monitor.TryEnter(_sync))
            {
                return;
            }

            try
            {
                BoundingBox box = GetSelection();

                var numberOfParticles = box.Height * box.Width * 2 + box.Height * box.Depth * 2;

                bool isBig = numberOfParticles > 500;

                List <McpeLevelEvent> packets = new List <McpeLevelEvent>();

                {
                    //if ((Math.Abs(box.Width) > 0) || (Math.Abs(box.Height) > 0) || (Math.Abs(box.Depth) > 0))
                    {
                        var minX = Math.Min(box.Min.X, box.Max.X);
                        var maxX = Math.Max(box.Min.X, box.Max.X) + 1;

                        var minY = Math.Max(0, Math.Min(box.Min.Y, box.Max.Y));
                        var maxY = Math.Min(255, Math.Max(box.Min.Y, box.Max.Y)) + 1;

                        var minZ = Math.Min(box.Min.Z, box.Max.Z);
                        var maxZ = Math.Max(box.Min.Z, box.Max.Z) + 1;

                        // x/y
                        for (float x = minX; x <= maxX; x++)
                        {
                            for (float y = minY; y <= maxY; y++)
                            {
                                foreach (var z in new float[] { minZ, maxZ })
                                {
                                    if (isBig)
                                    {
                                        if (x != minX && x != maxX && y != minY && y != maxY)
                                        {
                                            continue;
                                        }
                                    }

                                    if (!level.IsAir(new BlockCoordinates((int)x, (int)y, (int)z)))
                                    {
                                        continue;
                                    }

                                    //var particle = new Particle(particleId, Player.Level) {Position = new Vector3(x, y, z) + new Vector3(0.5f, 0.5f, 0.5f)};
                                    //var particle = new Particle(particleId, Player.Level) { Position = new Vector3(x, y, z) };
                                    //particle.Spawn(new[] { Player });

                                    McpeLevelEvent particleEvent = McpeLevelEvent.CreateObject();
                                    particleEvent.eventId  = (short)(0x4000 | 10);
                                    particleEvent.position = new Vector3(x, y, z);
                                    particleEvent.data     = 0;
                                    packets.Add(particleEvent);
                                }
                            }
                        }

                        // x/z
                        //for (float x = minX; x <= maxX; x++)
                        //{
                        //	foreach (var y in new float[] {minY, maxY})
                        //	{
                        //		for (float z = minZ; z <= maxZ; z++)
                        //		{
                        //			if (!level.IsAir(new BlockCoordinates((int) x, (int) y, (int) z))) continue;

                        //			//var particle = new Particle(10, Player.Level) {Position = new Vector3(x, y, z) + new Vector3(0.5f, 0.5f, 0.5f)};
                        //			var particle = new Particle(10, Player.Level) {Position = new Vector3(x, y, z)};
                        //			particle.Spawn(new[] {Player});
                        //		}
                        //	}
                        //}

                        // z/y
                        foreach (var x in new float[] { minX, maxX })
                        {
                            for (float y = minY; y <= maxY; y++)
                            {
                                for (float z = minZ; z <= maxZ; z++)
                                {
                                    if (isBig)
                                    {
                                        if (z != minZ && z != maxZ && y != minY && y != maxY)
                                        {
                                            continue;
                                        }
                                    }

                                    if (!level.IsAir(new BlockCoordinates((int)x, (int)y, (int)z)))
                                    {
                                        continue;
                                    }

                                    //var particle = new Particle(10, Player.Level) {Position = new Vector3(x, y, z) + new Vector3(0.5f, 0.5f, 0.5f)};
                                    //var particle = new Particle(10, Player.Level) { Position = new Vector3(x, y, z) };
                                    //particle.Spawn(new[] { Player });

                                    McpeLevelEvent particleEvent = McpeLevelEvent.CreateObject();
                                    particleEvent.eventId  = (short)(0x4000 | 10);
                                    particleEvent.position = new Vector3(x, y, z);
                                    particleEvent.data     = 0;
                                    packets.Add(particleEvent);
                                }
                            }
                        }
                    }

                    if (packets.Count > 500)
                    {
                        if (force)
                        {
                            Log.Warn($"Selection size is {numberOfParticles}. Number of particles is {packets.Count} ");
                        }

                        return;                         // too many particles
                    }


                    if (packets.Count > 0)
                    {
                        var packet = BatchUtils.CreateBatchPacket(CompressionLevel.Optimal, packets.ToArray());
                        Player.SendPacket(packet);
                        //level.RelayBroadcast(new[] { Player }, packet);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error("Display selection", e);
            }
            finally
            {
                Monitor.Exit(_sync);
            }
        }
Exemple #28
0
        public override void TakeHit(Entity source, int damage = 1, DamageCause cause = DamageCause.Unknown)
        {
            if (!(source is Player))
            {
                return;
            }

            // Pets must die in void or they get stuck forever :-(
            if (cause == DamageCause.Void)
            {
                base.TakeHit(source, damage, cause);
                return;                 // Love denied!
            }

            int size = Entity.Level.Random.Next(0, 3);             // The size of the hearts

            Pet pet = Entity as Pet;

            if (pet != null)
            {
                if (pet.AttackTarget != null)
                {
                    return;
                }

                // He is still angry, better not pet him right now.
                if (!pet.IsInRage && IsOnFire && pet.Level.Random.Next(10) == 0)
                {
                    pet.AttackTarget = (Player)source;
                    pet.RageTick     = 20 * 3;
                    return;
                }

                // Only owner do petting with my pet!
                if (pet.Owner == source)
                {
                    // Don't trust animals!
                    if (pet.Level.Random.Next(500) == 0)
                    {
                        pet.AttackTarget = (Player)source;
                        pet.RageTick     = 20 * 2;
                        return;
                    }

                    var msg = McpeLevelEvent.CreateObject();
                    msg.eventId = 0x4000 | 15;
                    msg.x       = Entity.KnownPosition.X;
                    msg.y       = (float)(Entity.KnownPosition.Y + Entity.Height + 0.85d);
                    msg.z       = Entity.KnownPosition.Z;
                    msg.data    = size;
                    pet.Level.RelayBroadcast(msg);
                }
                else
                {
                    // HAHA Steal IT!
                    if (pet.Level.Random.Next(50) == 0)
                    {
                        pet.Owner        = (Player)source;
                        pet.AttackTarget = null;
                        pet.RageTick     = 0;
                        return;
                    }

                    // Don't trust animals!
                    if (pet.Level.Random.Next(30) == 0)
                    {
                        pet.AttackTarget = (Player)source;
                        pet.RageTick     = 20 * 3;
                        return;
                    }
                }
            }
        }
Exemple #29
0
 public override void HandleMcpeLevelEvent(McpeLevelEvent message)
 {
     UnhandledPackage(message);
 }