MC 1.17/1.18 Terrain/Entity/Inventory (#1943)

Merge branch 'master' of github.com:milutinke/Minecraft-Console-Client into milutinke-master

Manually fix merge conflicts
Additional changes:
 - WindowItems: Fix data type for "elements" below 1.17
 - DestroyEntities: Fix packet palettes and remove DestroyEntity
 - EntityMetadata: Throw exception if health field mapping is not updated

Co-authored-by: Milutinke <bgteam@live.com>
Co-authored-by: BruceChen <MrChen131217@gmail.com>
This commit is contained in:
ORelio 2022-08-19 16:35:55 +02:00
commit 1ce7850193
34 changed files with 5983 additions and 920 deletions

View file

@ -450,6 +450,7 @@ namespace MinecraftClient.Protocol.Handlers
// NBT root name
string rootName = Encoding.ASCII.GetString(ReadData(ReadNextUShort(cache), cache));
if (!String.IsNullOrEmpty(rootName))
nbtData[""] = rootName;
}
@ -706,10 +707,13 @@ namespace MinecraftClient.Protocol.Handlers
// NBT root name
string rootName = null;
if (nbt.ContainsKey(""))
rootName = nbt[""] as string;
if (rootName == null)
rootName = "";
bytes.AddRange(GetUShort((ushort)rootName.Length));
bytes.AddRange(Encoding.ASCII.GetBytes(rootName));
}
@ -1010,10 +1014,10 @@ namespace MinecraftClient.Protocol.Handlers
{
// MC 1.13 and greater
if (item == null || item.IsEmpty)
slotData.Add(0); // No item
slotData.AddRange(GetBool(false)); // No item
else
{
slotData.Add(1); // Item is present
slotData.AddRange(GetBool(true)); // Item is present
slotData.AddRange(GetVarInt(itemPalette.ToId(item.Type)));
slotData.Add((byte)item.Count);
slotData.AddRange(GetNbt(item.NBT));
@ -1034,6 +1038,24 @@ namespace MinecraftClient.Protocol.Handlers
return slotData.ToArray();
}
/// <summary>
/// Get a byte array representing an array of item slots
/// </summary>
/// <param name="items">Items</param>
/// <param name="itemPalette">Item Palette</param>
/// <returns>Array of Item slot representations</returns>
public byte[] GetSlotsArray(Dictionary<int, Item> items, ItemPalette itemPalette)
{
byte[] slotsArray = new byte[items.Count];
foreach (KeyValuePair<int, Item> item in items)
{
slotsArray = ConcatBytes(slotsArray, GetShort((short)item.Key), GetItemSlot(item.Value, itemPalette));
}
return slotsArray;
}
/// <summary>
/// Get protocol block face from Direction
/// </summary>
@ -1076,6 +1098,11 @@ namespace MinecraftClient.Protocol.Handlers
return result.ToArray();
}
/// <summary>
/// Convert a byte array to an hexadecimal string representation (for debugging purposes)
/// </summary>
/// <param name="bytes">Byte array</param>
/// <returns>String representation</returns>
public string ByteArrayToString(byte[] bytes)
{
return BitConverter.ToString(bytes).Replace("-", " ");

View file

@ -64,7 +64,7 @@ namespace MinecraftClient.Protocol.Handlers.PacketPalettes
{ 0x37, PacketTypesIn.FacePlayer },
{ 0x38, PacketTypesIn.PlayerPositionAndLook },
{ 0x39, PacketTypesIn.UnlockRecipes },
{ 0x3A, PacketTypesIn.DestroyEntity },
{ 0x3A, PacketTypesIn.DestroyEntities },
{ 0x3B, PacketTypesIn.RemoveEntityEffect },
{ 0x3C, PacketTypesIn.ResourcePackSend },
{ 0x3D, PacketTypesIn.Respawn },

View file

@ -64,7 +64,7 @@ namespace MinecraftClient.Protocol.Handlers.PacketPalettes
{ 0x37, PacketTypesIn.FacePlayer },
{ 0x38, PacketTypesIn.PlayerPositionAndLook },
{ 0x39, PacketTypesIn.UnlockRecipes },
{ 0x3A, PacketTypesIn.DestroyEntity },
{ 0x3A, PacketTypesIn.DestroyEntities },
{ 0x3B, PacketTypesIn.RemoveEntityEffect },
{ 0x3C, PacketTypesIn.ResourcePackSend },
{ 0x3D, PacketTypesIn.Respawn },

View file

@ -62,7 +62,7 @@ namespace MinecraftClient.Protocol.Handlers.PacketPalettes
{ 0x35, PacketTypesIn.FacePlayer }, // (Wiki name: Player Look At)
{ 0x36, PacketTypesIn.PlayerPositionAndLook }, // (Wiki name: Player Position)
{ 0x37, PacketTypesIn.UnlockRecipes }, // (Wiki name: Recipe)
{ 0x38, PacketTypesIn.DestroyEntity }, // (Wiki name: Remove Entites)
{ 0x38, PacketTypesIn.DestroyEntities }, // (Wiki name: Remove Entites)
{ 0x39, PacketTypesIn.RemoveEntityEffect },
{ 0x3A, PacketTypesIn.ResourcePackSend }, // (Wiki name: Resource Pack)
{ 0x3B, PacketTypesIn.Respawn }, // Changed in 1.19 (Heavy changes) - DONE

View file

@ -112,7 +112,6 @@ namespace MinecraftClient.Protocol.Handlers
WorldBorderCenter,
ActionBar,
Tags,
DestroyEntity, // For 1.17+
DeathCombatEvent,
EnterCombatEvent,
EndCombatEvent,

View file

@ -729,7 +729,7 @@ namespace MinecraftClient.Protocol.Handlers
return false; //Currently not implemented
}
public bool SendWindowAction(int windowId, int slotId, WindowActionType action, Item item)
public bool SendWindowAction(int windowId, int slotId, WindowActionType action, Item item, List<Tuple<short, Item>> changedSlots, int stateId)
{
return false; //Currently not implemented
}

View file

@ -12,7 +12,6 @@ using MinecraftClient.Mapping.BlockPalettes;
using MinecraftClient.Mapping.EntityPalettes;
using MinecraftClient.Protocol.Handlers.Forge;
using MinecraftClient.Inventory;
using System.Data.SqlClient;
using System.Diagnostics;
using MinecraftClient.Inventory.ItemPalettes;
using MinecraftClient.Protocol.Handlers.PacketPalettes;
@ -92,19 +91,19 @@ namespace MinecraftClient.Protocol.Handlers
this.log = handler.GetLogger();
this.randomGen = RandomNumberGenerator.Create();
if (handler.GetTerrainEnabled() && protocolversion > MC_1_16_5_Version)
if (handler.GetTerrainEnabled() && protocolversion > MC_1_18_2_Version)
{
log.Error(Translations.Get("extra.terrainandmovement_disabled"));
handler.SetTerrainEnabled(false);
}
if (handler.GetInventoryEnabled() && (protocolversion < MC_1_10_Version || protocolversion > MC_1_16_5_Version))
if (handler.GetInventoryEnabled() && (protocolversion < MC_1_10_Version || protocolversion > MC_1_18_2_Version))
{
log.Error(Translations.Get("extra.inventory_disabled"));
handler.SetInventoryEnabled(false);
}
if (handler.GetEntityHandlingEnabled() && (protocolversion < MC_1_10_Version || protocolversion > MC_1_16_5_Version))
if (handler.GetEntityHandlingEnabled() && (protocolversion < MC_1_10_Version || protocolversion > MC_1_18_2_Version))
{
log.Error(Translations.Get("extra.entity_disabled"));
handler.SetEntityHandlingEnabled(false);
@ -113,8 +112,11 @@ namespace MinecraftClient.Protocol.Handlers
// Block palette
if (protocolversion >= MC_1_13_Version)
{
if (protocolVersion > MC_1_16_5_Version && handler.GetTerrainEnabled())
if (protocolVersion > MC_1_18_2_Version && handler.GetTerrainEnabled())
throw new NotImplementedException(Translations.Get("exception.palette.block"));
if (protocolVersion >= MC_1_17_Version)
Block.Palette = new Palette117();
else if (protocolVersion >= MC_1_16_Version)
if (protocolVersion >= MC_1_16_Version)
Block.Palette = new Palette116();
else if (protocolVersion >= MC_1_15_Version)
@ -128,8 +130,11 @@ namespace MinecraftClient.Protocol.Handlers
// Entity palette
if (protocolversion >= MC_1_13_Version)
{
if (protocolversion > MC_1_16_5_Version && handler.GetEntityHandlingEnabled())
if (protocolversion > MC_1_18_2_Version && handler.GetEntityHandlingEnabled())
throw new NotImplementedException(Translations.Get("exception.palette.entity"));
if (protocolversion >= MC_1_17_Version)
entityPalette = new EntityPalette117();
else if (protocolversion >= MC_1_16_2_Version)
if (protocolversion >= MC_1_16_2_Version)
entityPalette = new EntityPalette1162();
else if (protocolversion >= MC_1_16_Version)
@ -143,10 +148,15 @@ namespace MinecraftClient.Protocol.Handlers
else entityPalette = new EntityPalette112();
// Item palette
if (protocolversion >= MC_1_16_Version)
if (protocolversion >= MC_1_16_2_Version)
{
if (protocolversion > MC_1_16_5_Version && handler.GetInventoryEnabled())
if (protocolversion > MC_1_18_2_Version && handler.GetInventoryEnabled())
throw new NotImplementedException(Translations.Get("exception.palette.item"));
if (protocolversion >= MC_1_18_1_Version)
itemPalette = new ItemPalette118();
else if (protocolversion >= MC_1_17_Version)
itemPalette = new ItemPalette117();
else if (protocolversion >= MC_1_16_2_Version)
if (protocolversion >= MC_1_16_2_Version)
itemPalette = new ItemPalette1162();
else itemPalette = new ItemPalette1161();
@ -229,6 +239,7 @@ namespace MinecraftClient.Protocol.Handlers
packetData.Clear();
int size = dataTypes.ReadNextVarIntRAW(socketWrapper); //Packet size
byte[] rawpacket = socketWrapper.ReadDataRAW(size); //Packet contents
for (int i = 0; i < rawpacket.Length; i++)
packetData.Enqueue(rawpacket[i]);
@ -341,9 +352,8 @@ namespace MinecraftClient.Protocol.Handlers
if (protocolversion >= MC_1_16_Version)
currentDimensionName = dataTypes.ReadNextString(packetData); // Dimension Name (World Name) - 1.16 and above
// Implementation in PR#1943
// if (protocolversion >= MC_1_16_2_Version)
// handler.GetWorld().SetDimension(currentDimensionName, currentDimensionType);
if (protocolversion >= MC_1_16_2_Version)
World.SetDimension(currentDimensionName, currentDimensionType);
if (protocolversion >= MC_1_15_Version)
dataTypes.ReadNextLong(packetData); // Hashed world seed - 1.15 and above
@ -430,13 +440,13 @@ namespace MinecraftClient.Protocol.Handlers
break;
case PacketTypesIn.Respawn:
string? dimensionNameInRespawn = null;
Dictionary<string, object>? dimensionTypeInRespawn = null;
Dictionary<string, object> dimensionTypeInRespawn = null;
if (protocolversion >= MC_1_16_Version)
{
if (protocolversion >= MC_1_19_Version)
dataTypes.ReadNextString(packetData); // Dimension Type: Identifier
else if (protocolversion >= MC_1_16_2_Version)
currentDimensionType = dataTypes.ReadNextNbt(packetData); // Dimension Type: NBT Tag Compound
dimensionTypeInRespawn = dataTypes.ReadNextNbt(packetData); // Dimension Type: NBT Tag Compound
else
dataTypes.ReadNextString(packetData);
this.currentDimension = 0;
@ -449,9 +459,8 @@ namespace MinecraftClient.Protocol.Handlers
if (protocolversion >= MC_1_16_Version)
dimensionNameInRespawn = dataTypes.ReadNextString(packetData); // Dimension Name (World Name) - 1.16 and above
// Implementation in PR#1943
// if (protocolversion >= MC_1_16_2_Version)
// handler.GetWorld().SetDimension(currentDimensionName, currentDimensionType);
if (protocolversion >= MC_1_16_2_Version)
World.SetDimension(dimensionNameInRespawn, dimensionTypeInRespawn);
if (protocolversion < MC_1_14_Version)
dataTypes.ReadNextByte(packetData); // Difficulty - 1.13 and below
@ -509,56 +518,88 @@ namespace MinecraftClient.Protocol.Handlers
SendPacket(PacketTypesOut.TeleportConfirm, dataTypes.GetVarInt(teleportID));
}
if (protocolversion >= MC_1_17_Version) dataTypes.ReadNextBool(packetData);
if (protocolversion >= MC_1_17_Version)
dataTypes.ReadNextBool(packetData); // Dismount Vehicle - 1.17 and above
break;
case PacketTypesIn.ChunkData: //TODO implement for 1.17, bit mask is not limited to 0-15 anymore
case PacketTypesIn.ChunkData:
if (handler.GetTerrainEnabled())
{
int chunkX = dataTypes.ReadNextInt(packetData);
int chunkZ = dataTypes.ReadNextInt(packetData);
bool chunksContinuous = dataTypes.ReadNextBool(packetData);
if (protocolversion >= MC_1_16_Version && protocolversion <= MC_1_16_1_Version)
dataTypes.ReadNextBool(packetData); // Ignore old data - 1.16 to 1.16.1 only
ushort chunkMask = protocolversion >= MC_1_9_Version
? (ushort)dataTypes.ReadNextVarInt(packetData)
: dataTypes.ReadNextUShort(packetData);
if (protocolversion < MC_1_8_Version)
if (protocolversion >= MC_1_17_Version)
{
ushort addBitmap = dataTypes.ReadNextUShort(packetData);
int compressedDataSize = dataTypes.ReadNextInt(packetData);
byte[] compressed = dataTypes.ReadData(compressedDataSize, packetData);
byte[] decompressed = ZlibUtils.Decompress(compressed);
ulong[]? verticalStripBitmask = null;
if (protocolversion == MC_1_17_Version || protocolversion == MC_1_17_1_Version)
verticalStripBitmask = dataTypes.ReadNextULongArray(packetData); // Bit Mask Le:ngth and Primary Bit Mask
dataTypes.ReadNextNbt(packetData); // Heightmaps
if (protocolversion == MC_1_17_Version || protocolversion == MC_1_17_1_Version)
{
int biomesLength = dataTypes.ReadNextVarInt(packetData); // Biomes length
for (int i = 0; i < biomesLength; i++)
{
dataTypes.SkipNextVarInt(packetData); // Biomes
}
}
int dataSize = dataTypes.ReadNextVarInt(packetData); // Size
Interlocked.Increment(ref handler.GetWorld().chunkCnt);
Interlocked.Increment(ref handler.GetWorld().chunkLoadNotCompleted);
new Task(() =>
{
pTerrain.ProcessChunkColumnData(chunkX, chunkZ, chunkMask, addBitmap, currentDimension == 0, chunksContinuous, currentDimension, new Queue<byte>(decompressed));
pTerrain.ProcessChunkColumnData(chunkX, chunkZ, verticalStripBitmask, packetData);
Interlocked.Decrement(ref handler.GetWorld().chunkLoadNotCompleted);
}).Start();
}
else
{
if (protocolversion >= MC_1_14_Version)
dataTypes.ReadNextNbt(packetData); // Heightmaps - 1.14 and above
int biomesLength = 0;
if (protocolversion >= MC_1_16_2_Version)
if (chunksContinuous)
biomesLength = dataTypes.ReadNextVarInt(packetData); // Biomes length - 1.16.2 and above
if (protocolversion >= MC_1_15_Version && chunksContinuous)
bool chunksContinuous = dataTypes.ReadNextBool(packetData);
if (protocolversion >= MC_1_16_Version && protocolversion <= MC_1_16_1_Version)
dataTypes.ReadNextBool(packetData); // Ignore old data - 1.16 to 1.16.1 only
ushort chunkMask = protocolversion >= MC_1_9_Version
? (ushort)dataTypes.ReadNextVarInt(packetData)
: dataTypes.ReadNextUShort(packetData);
if (protocolversion < MC_1_8_Version)
{
if (protocolversion >= MC_1_16_2_Version)
ushort addBitmap = dataTypes.ReadNextUShort(packetData);
int compressedDataSize = dataTypes.ReadNextInt(packetData);
byte[] compressed = dataTypes.ReadData(compressedDataSize, packetData);
byte[] decompressed = ZlibUtils.Decompress(compressed);
new Task(() =>
{
for (int i = 0; i < biomesLength; i++)
{
// Biomes - 1.16.2 and above
// Don't use ReadNextVarInt because it cost too much time
dataTypes.SkipNextVarInt(packetData);
}
}
else dataTypes.ReadData(1024 * 4, packetData); // Biomes - 1.15 and above
pTerrain.ProcessChunkColumnData(chunkX, chunkZ, chunkMask, addBitmap, currentDimension == 0, chunksContinuous, currentDimension, new Queue<byte>(decompressed));
}).Start();
}
int dataSize = dataTypes.ReadNextVarInt(packetData);
new Task(() =>
else
{
pTerrain.ProcessChunkColumnData(chunkX, chunkZ, chunkMask, 0, false, chunksContinuous, currentDimension, packetData);
}).Start();
if (protocolversion >= MC_1_14_Version)
dataTypes.ReadNextNbt(packetData); // Heightmaps - 1.14 and above
int biomesLength = 0;
if (protocolversion >= MC_1_16_2_Version)
if (chunksContinuous)
biomesLength = dataTypes.ReadNextVarInt(packetData); // Biomes length - 1.16.2 and above
if (protocolversion >= MC_1_15_Version && chunksContinuous)
{
if (protocolversion >= MC_1_16_2_Version)
{
for (int i = 0; i < biomesLength; i++)
{
// Biomes - 1.16.2 and above
// Don't use ReadNextVarInt because it cost too much time
dataTypes.SkipNextVarInt(packetData);
}
}
else dataTypes.ReadData(1024 * 4, packetData); // Biomes - 1.15 and above
}
int dataSize = dataTypes.ReadNextVarInt(packetData);
new Task(() =>
{
pTerrain.ProcessChunkColumnData(chunkX, chunkZ, chunkMask, 0, false, chunksContinuous, currentDimension, packetData);
}).Start();
}
}
}
break;
@ -666,7 +707,7 @@ namespace MinecraftClient.Protocol.Handlers
int sectionX = (int)(chunkSection >> 42);
int sectionY = (int)((chunkSection << 44) >> 44);
int sectionZ = (int)((chunkSection << 22) >> 42);
dataTypes.ReadNextBool(packetData); // Useless boolean
dataTypes.ReadNextBool(packetData); // Useless boolean (Related to light update)
int blocksSize = dataTypes.ReadNextVarInt(packetData);
for (int i = 0; i < blocksSize; i++)
{
@ -820,6 +861,13 @@ namespace MinecraftClient.Protocol.Handlers
{
int chunkX = dataTypes.ReadNextInt(packetData);
int chunkZ = dataTypes.ReadNextInt(packetData);
// Warning: It is legal to include unloaded chunks in the UnloadChunk packet.
// Since chunks that have not been loaded are not recorded, this may result
// in loading chunks that should be unloaded and inaccurate statistics.
if (handler.GetWorld()[chunkX, chunkZ] != null)
Interlocked.Decrement(ref handler.GetWorld().chunkCnt);
handler.GetWorld()[chunkX, chunkZ] = null;
}
break;
@ -985,24 +1033,45 @@ namespace MinecraftClient.Protocol.Handlers
if (handler.GetInventoryEnabled())
{
byte windowId = dataTypes.ReadNextByte(packetData);
short elements = dataTypes.ReadNextShort(packetData);
int stateId = -1;
int elements = 0;
if (protocolversion >= MC_1_17_1_Version)
{
// State ID and Elements as VarInt - 1.17.1 and above
stateId = dataTypes.ReadNextVarInt(packetData);
elements = dataTypes.ReadNextVarInt(packetData);
}
else
{
// Elements as Short - 1.17.0 and below
dataTypes.ReadNextShort(packetData);
}
Dictionary<int, Item> inventorySlots = new Dictionary<int, Item>();
for (short slotId = 0; slotId < elements; slotId++)
for (int slotId = 0; slotId < elements; slotId++)
{
Item item = dataTypes.ReadNextItemSlot(packetData, itemPalette);
if (item != null)
inventorySlots[slotId] = item;
}
handler.OnWindowItems(windowId, inventorySlots);
if (protocolversion >= MC_1_17_1_Version) // Carried Item - 1.17.1 and above
dataTypes.ReadNextItemSlot(packetData, itemPalette);
handler.OnWindowItems(windowId, inventorySlots, stateId);
}
break;
case PacketTypesIn.SetSlot:
if (handler.GetInventoryEnabled())
{
byte windowID = dataTypes.ReadNextByte(packetData);
int stateId = -1;
if (protocolversion >= MC_1_17_1_Version)
stateId = dataTypes.ReadNextVarInt(packetData); // State ID - 1.17.1 and above
short slotID = dataTypes.ReadNextShort(packetData);
Item item = dataTypes.ReadNextItemSlot(packetData, itemPalette);
handler.OnSetSlot(windowID, slotID, item);
handler.OnSetSlot(windowID, slotID, item, stateId);
}
break;
case PacketTypesIn.WindowConfirmation:
@ -1024,7 +1093,9 @@ namespace MinecraftClient.Protocol.Handlers
if (protocolversion >= MC_1_17_Version)
{
forced = dataTypes.ReadNextBool(packetData);
String forcedMessage = ChatParser.ParseText(dataTypes.ReadNextString(packetData));
string forcedMessage = ChatParser.ParseText(dataTypes.ReadNextString(packetData));
dataTypes.ReadNextBool(packetData); // Has Prompt Message (Boolean) - 1.17 and above
dataTypes.ReadNextString(packetData); // Prompt Message (Optional Chat) - 1.17 and above
}
// Some server plugins may send invalid resource packs to probe the client and we need to ignore them (issue #1056)
if (!url.StartsWith("http") && hash.Length != 40) // Some server may have null hash value
@ -1121,19 +1192,15 @@ namespace MinecraftClient.Protocol.Handlers
case PacketTypesIn.DestroyEntities:
if (handler.GetEntityHandlingEnabled())
{
int EntityCount = dataTypes.ReadNextVarInt(packetData);
int[] EntitiesList = new int[EntityCount];
for (int i = 0; i < EntityCount; i++)
int entityCount = 1; // 1.17.0 has only one entity per packet
if (protocolversion != MC_1_17_Version)
entityCount = dataTypes.ReadNextVarInt(packetData); // All other versions have a "count" field
int[] entityList = new int[entityCount];
for (int i = 0; i < entityCount; i++)
{
EntitiesList[i] = dataTypes.ReadNextVarInt(packetData);
entityList[i] = dataTypes.ReadNextVarInt(packetData);
}
handler.OnDestroyEntities(EntitiesList);
}
break;
case PacketTypesIn.DestroyEntity:
if (handler.GetEntityHandlingEnabled())
{
handler.OnDestroyEntities(new[] { dataTypes.ReadNextVarInt(packetData) });
handler.OnDestroyEntities(entityList);
}
break;
case PacketTypesIn.EntityPosition:
@ -1206,7 +1273,16 @@ namespace MinecraftClient.Protocol.Handlers
{
int EntityID = dataTypes.ReadNextVarInt(packetData);
Dictionary<int, object> metadata = dataTypes.ReadNextMetadata(packetData, itemPalette);
int healthField = protocolversion >= MC_1_14_Version ? 8 : 7; // Health is field no. 7 in 1.10+ and 8 in 1.14+
// See https://wiki.vg/Entity_metadata#Living_Entity
int healthField = 7; // From 1.10 to 1.13.2
if (protocolversion >= MC_1_14_Version)
healthField = 8; // 1.14 and above
if (protocolversion >= MC_1_17_Version)
healthField = 9; // 1.17 and above
if (protocolversion > MC_1_18_2_Version)
throw new NotImplementedException(Translations.Get("exception.palette.healthfield"));
if (metadata.ContainsKey(healthField) && metadata[healthField] != null && metadata[healthField].GetType() == typeof(float))
handler.OnEntityHealth(EntityID, (float)metadata[healthField]);
handler.OnEntityMetadata(EntityID, metadata);
@ -1292,7 +1368,9 @@ namespace MinecraftClient.Protocol.Handlers
break;
case PacketTypesIn.UpdateScore:
string entityname = dataTypes.ReadNextString(packetData);
byte action3 = dataTypes.ReadNextByte(packetData);
int action3 = protocolversion >= MC_1_18_2_Version
? dataTypes.ReadNextVarInt(packetData)
: dataTypes.ReadNextByte(packetData);
string objectivename2 = string.Empty;
int value = -1;
if (action3 != 1 || protocolversion >= MC_1_8_Version)
@ -1995,7 +2073,12 @@ namespace MinecraftClient.Protocol.Handlers
if (protocolversion >= MC_1_9_Version)
fields.AddRange(dataTypes.GetVarInt(mainHand));
if (protocolversion >= MC_1_17_Version)
fields.Add(0); // Enables text filtering. Always false
{
if (protocolversion >= MC_1_18_1_Version)
fields.Add(0); // 1.18 and above - Enable text filtering. (Always false)
else
fields.Add(1); // 1.17 and 1.17.1 - Disable text filtering. (Always true)
}
if (protocolversion >= MC_1_18_1_Version)
fields.Add(1); // 1.18 and above - Allow server listings
SendPacket(PacketTypesOut.ClientSettings, fields);
@ -2250,7 +2333,7 @@ namespace MinecraftClient.Protocol.Handlers
catch (ObjectDisposedException) { return false; }
}
public bool SendWindowAction(int windowId, int slotId, WindowActionType action, Item item)
public bool SendWindowAction(int windowId, int slotId, WindowActionType action, Item item, List<Tuple<short, Item>> changedSlots, int stateId)
{
try
{
@ -2286,14 +2369,48 @@ namespace MinecraftClient.Protocol.Handlers
}
List<byte> packet = new List<byte>();
packet.Add((byte)windowId);
packet.AddRange(dataTypes.GetShort((short)slotId));
packet.Add(button);
if (protocolversion < MC_1_17_Version) packet.AddRange(dataTypes.GetShort(actionNumber));
packet.Add((byte)windowId); // Window ID
// 1.18+
if (protocolversion >= MC_1_18_1_Version)
{
packet.AddRange(dataTypes.GetVarInt(stateId)); // State ID
packet.AddRange(dataTypes.GetShort((short)slotId)); // Slot ID
}
// 1.17.1
else if (protocolversion == MC_1_17_1_Version)
{
packet.AddRange(dataTypes.GetShort((short)slotId)); // Slot ID
packet.AddRange(dataTypes.GetVarInt(stateId)); // State ID
}
// Older
else
{
packet.AddRange(dataTypes.GetShort((short)slotId)); // Slot ID
}
packet.Add(button); // Button
if (protocolversion < MC_1_17_Version)
packet.AddRange(dataTypes.GetShort(actionNumber));
if (protocolversion >= MC_1_9_Version)
packet.AddRange(dataTypes.GetVarInt(mode));
packet.AddRange(dataTypes.GetVarInt(mode)); // Mode
else packet.Add(mode);
packet.AddRange(dataTypes.GetItemSlot(item, itemPalette));
// 1.17+ Array of changed slots
if (protocolversion >= MC_1_17_Version)
{
packet.AddRange(dataTypes.GetVarInt(changedSlots.Count)); // Length of the array
foreach (var slot in changedSlots)
{
packet.AddRange(dataTypes.GetShort(slot.Item1)); // slot ID
packet.AddRange(dataTypes.GetItemSlot(slot.Item2, itemPalette)); // slot Data
}
}
packet.AddRange(dataTypes.GetItemSlot(item, itemPalette)); // Carried item (Clicked item)
SendPacket(PacketTypesOut.ClickWindow, packet);
return true;
}

View file

@ -28,7 +28,188 @@ namespace MinecraftClient.Protocol.Handlers
}
/// <summary>
/// Process chunk column data from the server and (un)load the chunk from the Minecraft world
/// Reading the "Block states" field: consists of 4096 entries, representing all the blocks in the chunk section.
/// </summary>
/// <param name="chunk">Blocks will store in this chunk</param>
/// <param name="cache">Cache for reading data</param>
private Chunk ReadBlockStatesField(ref Chunk chunk, Queue<byte> cache)
{
// read Block states (Type: Paletted Container)
byte bitsPerEntry = dataTypes.ReadNextByte(cache);
// 1.18(1.18.1) add a pattle named "Single valued" to replace the vertical strip bitmask in the old
if (bitsPerEntry == 0 && protocolversion >= Protocol18Handler.MC_1_18_1_Version)
{
// Palettes: Single valued - 1.18(1.18.1) and above
ushort value = (ushort)dataTypes.ReadNextVarInt(cache);
dataTypes.SkipNextVarInt(cache); // Data Array Length will be zero
// Empty chunks will not be stored
if (new Block(value).Type == Material.Air)
return null;
for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
{
for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
{
for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
{
chunk[blockX, blockY, blockZ] = new Block(value);
}
}
}
}
else
{
// Palettes: Indirect or Direct
bool usePalette = (bitsPerEntry <= 8);
// Indirect Mode: For block states with bits per entry <= 4, 4 bits are used to represent a block.
if (bitsPerEntry < 4) bitsPerEntry = 4;
// Direct Mode: Bit mask covering bitsPerEntry bits
// EG, if bitsPerEntry = 5, valueMask = 00011111 in binary
uint valueMask = (uint)((1 << bitsPerEntry) - 1);
int paletteLength = 0; // Assume zero when length is absent
if (usePalette) paletteLength = dataTypes.ReadNextVarInt(cache);
int[] palette = new int[paletteLength];
for (int i = 0; i < paletteLength; i++)
palette[i] = dataTypes.ReadNextVarInt(cache);
// Block IDs are packed in the array of 64-bits integers
ulong[] dataArray = dataTypes.ReadNextULongArray(cache);
int longIndex = 0;
int startOffset = 0 - bitsPerEntry;
for (int blockY = 0; blockY < Chunk.SizeY; blockY++)
{
for (int blockZ = 0; blockZ < Chunk.SizeZ; blockZ++)
{
for (int blockX = 0; blockX < Chunk.SizeX; blockX++)
{
// NOTICE: In the future a single ushort may not store the entire block id;
// the Block class may need to change if block state IDs go beyond 65535
ushort blockId;
// Calculate location of next block ID inside the array of Longs
startOffset += bitsPerEntry;
if ((startOffset + bitsPerEntry) > 64)
{
// In MC 1.16+, padding is applied to prevent overlapping between Longs:
// [ LONG INTEGER ][ LONG INTEGER ]
// [Block][Block][Block]XXXXX[Block][Block][Block]XXXXX
// When overlapping, move forward to the beginning of the next Long
startOffset = 0;
longIndex++;
}
// Extract Block ID
blockId = (ushort)((dataArray[longIndex] >> startOffset) & valueMask);
// Map small IDs to actual larger block IDs
if (usePalette)
{
if (paletteLength <= blockId)
{
int blockNumber = (blockY * Chunk.SizeZ + blockZ) * Chunk.SizeX + blockX;
throw new IndexOutOfRangeException(String.Format("Block ID {0} is outside Palette range 0-{1}! (bitsPerBlock: {2}, blockNumber: {3})",
blockId,
paletteLength - 1,
bitsPerEntry,
blockNumber));
}
blockId = (ushort)palette[blockId];
}
// We have our block, save the block into the chunk
chunk[blockX, blockY, blockZ] = new Block(blockId);
}
}
}
}
return chunk;
}
/// <summary>
/// Process chunk column data from the server and (un)load the chunk from the Minecraft world - 1.17 and above
/// </summary>
/// <param name="chunkX">Chunk X location</param>
/// <param name="chunkZ">Chunk Z location</param>
/// <param name="verticalStripBitmask">Chunk mask for reading data, store in bitset, used in 1.17 and 1.17.1</param>
/// <param name="cache">Cache for reading chunk data</param>
public void ProcessChunkColumnData(int chunkX, int chunkZ, ulong[] verticalStripBitmask, Queue<byte> cache)
{
var world = handler.GetWorld();
int chunkColumnSize = (World.GetDimension().height + 15) / 16; // Round up
if (protocolversion >= Protocol18Handler.MC_1_17_Version)
{
// 1.17 and above chunk format
// Unloading chunks is handled by a separate packet
for (int chunkY = 0; chunkY < chunkColumnSize; chunkY++)
{
// 1.18 and above always contains all chunk section in data
// 1.17 and 1.17.1 need vertical strip bitmask to know if the chunk section is included
if ((protocolversion >= Protocol18Handler.MC_1_18_1_Version) ||
(((protocolversion == Protocol18Handler.MC_1_17_Version) ||
(protocolversion == Protocol18Handler.MC_1_17_1_Version)) &&
((verticalStripBitmask[chunkY / 64] & (1UL << (chunkY % 64))) != 0)))
{
// Non-air block count inside chunk section, for lighting purposes
int blockCnt = dataTypes.ReadNextShort(cache);
// Read Block states (Type: Paletted Container)
Chunk chunk = new Chunk();
ReadBlockStatesField(ref chunk, cache);
//We have our chunk, save the chunk into the world
handler.InvokeOnMainThread(() =>
{
if (handler.GetWorld()[chunkX, chunkZ] == null)
handler.GetWorld()[chunkX, chunkZ] = new ChunkColumn(chunkColumnSize);
handler.GetWorld()[chunkX, chunkZ][chunkY] = chunk;
});
// Skip Read Biomes (Type: Paletted Container) - 1.18(1.18.1) and above
if (protocolversion >= Protocol18Handler.MC_1_18_1_Version)
{
byte bitsPerEntryBiome = dataTypes.ReadNextByte(cache); // Bits Per Entry
if (bitsPerEntryBiome == 0)
{
dataTypes.SkipNextVarInt(cache); // Value
dataTypes.SkipNextVarInt(cache); // Data Array Length
// Data Array must be empty
}
else
{
if (bitsPerEntryBiome <= 3)
{
int paletteLength = dataTypes.ReadNextVarInt(cache); // Palette Length
for (int i = 0; i < paletteLength; i++)
dataTypes.SkipNextVarInt(cache); // Palette
}
int dataArrayLength = dataTypes.ReadNextVarInt(cache); // Data Array Length
dataTypes.ReadData(dataArrayLength * 8, cache); // Data Array
}
}
}
}
// Don't worry about skipping remaining data since there is no useful data afterwards in 1.9
// (plus, it would require parsing the tile entity lists' NBT)
}
handler.GetWorld()[chunkX, chunkZ].FullyLoaded = true;
}
/// <summary>
/// Process chunk column data from the server and (un)load the chunk from the Minecraft world - 1.17 below
/// </summary>
/// <param name="chunkX">Chunk X location</param>
/// <param name="chunkZ">Chunk Z location</param>
@ -40,11 +221,12 @@ namespace MinecraftClient.Protocol.Handlers
/// <param name="cache">Cache for reading chunk data</param>
public void ProcessChunkColumnData(int chunkX, int chunkZ, ushort chunkMask, ushort chunkMask2, bool hasSkyLight, bool chunksContinuous, int currentDimension, Queue<byte> cache)
{
const int chunkColumnSize = 16;
if (protocolversion >= Protocol18Handler.MC_1_9_Version)
{
// 1.9 and above chunk format
// Unloading chunks is handled by a separate packet
for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
for (int chunkY = 0; chunkY < chunkColumnSize; chunkY++)
{
if ((chunkMask & (1 << chunkY)) != 0)
{
@ -200,7 +382,7 @@ namespace MinecraftClient.Protocol.Handlers
else
{
//Load chunk data from the server
for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
for (int chunkY = 0; chunkY < chunkColumnSize; chunkY++)
{
if ((chunkMask & (1 << chunkY)) != 0)
{
@ -224,7 +406,7 @@ namespace MinecraftClient.Protocol.Handlers
}
//Skip light information
for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
for (int chunkY = 0; chunkY < chunkColumnSize; chunkY++)
{
if ((chunkMask & (1 << chunkY)) != 0)
{
@ -258,7 +440,7 @@ namespace MinecraftClient.Protocol.Handlers
//Count chunk sections
int sectionCount = 0;
int addDataSectionCount = 0;
for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
for (int chunkY = 0; chunkY < chunkColumnSize; chunkY++)
{
if ((chunkMask & (1 << chunkY)) != 0)
sectionCount++;
@ -286,7 +468,7 @@ namespace MinecraftClient.Protocol.Handlers
dataTypes.ReadData(Chunk.SizeX * Chunk.SizeZ, cache); //Biomes
//Load chunk data
for (int chunkY = 0; chunkY < ChunkColumn.ColumnSize; chunkY++)
for (int chunkY = 0; chunkY < chunkColumnSize; chunkY++)
{
if ((chunkMask & (1 << chunkY)) != 0)
{
@ -307,6 +489,7 @@ namespace MinecraftClient.Protocol.Handlers
}
}
}
handler.GetWorld()[chunkX, chunkZ].FullyLoaded = true;
}
}
}

View file

@ -95,7 +95,7 @@ namespace MinecraftClient.Protocol
/// <param name="data">packet Data</param>
/// <returns>True if message was successfully sent</returns>
bool SendPluginChannelPacket(string channel, byte[] data);
/// <summary>
/// Send Entity Action packet to the server.
/// </summary>
@ -103,7 +103,7 @@ namespace MinecraftClient.Protocol
/// <param name="type">Type of packet to send</param>
/// <returns>True if packet was successfully sent</returns>
bool SendEntityAction(int EntityID, int type);
/// <summary>
/// Send a held item change packet to the server.
/// </summary>
@ -141,7 +141,7 @@ namespace MinecraftClient.Protocol
/// <param name="Z">Z coordinate for "interact at"</param>
/// <returns>True if packet was successfully sent</returns>
bool SendInteractEntity(int EntityID, int type, float X, float Y, float Z);
/// <summary>
/// Send an entity interaction packet to the server.
/// </summary>
@ -164,10 +164,12 @@ namespace MinecraftClient.Protocol
/// </summary>
/// <param name="windowId">Id of the window being clicked</param>
/// <param name="slotId">Id of the clicked slot</param>
/// <param name="buttom">Action to perform</param>
/// <param name="action">Action to perform</param>
/// <param name="item">Item in the clicked slot</param>
/// <param name="changedSlots">Slots that have been changed in this event: List<SlotID, Changed Items> </param>
/// <param name="stateId">Inventory's stateId</param>
/// <returns>True if packet was successfully sent</returns>
bool SendWindowAction(int windowId, int slotId, WindowActionType action, Item item);
bool SendWindowAction(int windowId, int slotId, WindowActionType action, Item item, List<Tuple<short, Item>> changedSlots, int stateId);
/// <summary>
/// Request Creative Mode item creation into regular/survival Player Inventory
@ -224,7 +226,7 @@ namespace MinecraftClient.Protocol
/// <param name="line4">New line 4</param>
/// <returns>True if packet was succcessfully sent</returns>
bool SendUpdateSign(Location location, string line1, string line2, string line3, string line4);
/// <summary>
/// Update command block
/// </summary>

View file

@ -285,7 +285,8 @@ namespace MinecraftClient.Protocol
/// </summary>
/// <param name="inventoryID">Inventory ID</param>
/// <param name="itemList">Item list</param>
void OnWindowItems(byte inventoryID, Dictionary<int, Item> itemList);
/// <param name="stateId">State ID</param>
void OnWindowItems(byte inventoryID, Dictionary<int, Item> itemList, int stateId);
/// <summary>
/// Called when a single slot has been updated inside an inventory
@ -293,7 +294,8 @@ namespace MinecraftClient.Protocol
/// <param name="inventoryID">Window ID</param>
/// <param name="slotID">Slot ID</param>
/// <param name="item">Item (may be null for empty slot)</param>
void OnSetSlot(byte inventoryID, short slotID, Item item);
/// <param name="stateId">State ID</param>
void OnSetSlot(byte inventoryID, short slotID, Item item, int stateId);
/// <summary>
/// Called when player health or hunger changed.
@ -397,7 +399,7 @@ namespace MinecraftClient.Protocol
/// <param name="action">0 to create/update an item. 1 to remove an item.</param>
/// <param name="objectivename">The name of the objective the score belongs to</param>
/// <param name="value">he score to be displayed next to the entry. Only sent when Action does not equal 1.</param>
void OnUpdateScore(string entityname, byte action, string objectivename, int value);
void OnUpdateScore(string entityname, int action, string objectivename, int value);
/// <summary>
/// Called when tradeList is received from server