From f506c2573a48c070f5317cabd870c792f08e91ef Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 12 Mar 2026 05:28:52 -0400 Subject: [PATCH] Added rabbits, door types, enchantments, multiserver support, written books, crafting, enchantments, NPC support, fixed death animations. --- README.md | 2 +- constants.js | 24 +- src/javaclienthandler.js | 429 +++++++- src/lanbroadcast.js | 12 +- src/lceproxy.js | 1248 +++++++++++++++++++++-- src/mappings/blockmapping.js | 6 + src/mappings/entitymapping.js | 1 + src/mappings/itemmapping.js | 16 + src/mappings/recipemapping.js | 969 +++++++++++++++++- src/packetreader.js | 11 + src/packets/senders/containerpackets.js | 24 +- src/packets/senders/entitypackets.js | 72 +- src/packetwriter.js | 9 + src/utils/items.js | 116 ++- src/utils/skins.js | 40 + 15 files changed, 2804 insertions(+), 175 deletions(-) diff --git a/README.md b/README.md index f854086..459f2de 100644 --- a/README.md +++ b/README.md @@ -180,7 +180,7 @@ # UI -- [ ] Crafting _(Hard to implement, coming soon)_ +- [x] Crafting - [x] Brewing stand - [x] Furnace - [x] Villager trading diff --git a/constants.js b/constants.js index 728d30b..1006b09 100644 --- a/constants.js +++ b/constants.js @@ -1,21 +1,27 @@ /* --------------------------------------------------------------- */ /* constants.js */ /* --------------------------------------------------------------- */ +const USE_LEGACY_USERNAME = false; +const CUSTOM_USERNAME = "LCE_Player"; + +const SERVERS = [ + { server: "us-1.creepernation.net:25568", cracked: true }, + { server: "hypixel.net", cracked: false }, + { server: "localhost:25564", cracked: true }, +]; + +/* DONT TOUCH THESE BELOW THINGS UNLESS YOU KNOW WHAT YOURE DOING! */ + const GAME_PORT = 25565; const WIN64_LAN_DISCOVERY_PORT = 25566; const MINECRAFT_NET_VERSION = 560; -const JAVA_SERVER_HOST = "localhost"; // The java edition server host that the proxy will connect to. -const JAVA_SERVER_PORT = 25564; // The java edition server port that the proxy will connect to. -const PROXY_NAME = JAVA_SERVER_HOST + ":" + JAVA_SERVER_PORT; + module.exports = { GAME_PORT, WIN64_LAN_DISCOVERY_PORT, MINECRAFT_NET_VERSION, - USE_JAVA_ACCOUNT: false, // Allows use of a microsoft java account for online servers. (Disable this if you don't own java - you'll only be able to connect to cracked/offline servers.) - USE_LEGACY_USERNAME: false, // You can use your legacy edition username, or a custom username below. (offline servers only) - CUSTOM_USERNAME: "LCE_Player", // The custom username used if USE_LEGACY_USERNAME is false. Ensure it's UNDER 16 characters. (offline servers only) - JAVA_SERVER_HOST, - JAVA_SERVER_PORT, - PROXY_NAME, + USE_LEGACY_USERNAME, + CUSTOM_USERNAME, + SERVERS, }; /* --------------------------------------------------------------- */ diff --git a/src/javaclienthandler.js b/src/javaclienthandler.js index ed219ff..4411b54 100644 --- a/src/javaclienthandler.js +++ b/src/javaclienthandler.js @@ -1,11 +1,11 @@ /* --------------------------------------------------------------- */ /* javaclienthandler.js */ /* --------------------------------------------------------------- */ + +//beware that there are a lot of magic numbers, need to do a refractor soon. + const mc = require("minecraft-protocol"); const { - JAVA_SERVER_HOST, - JAVA_SERVER_PORT, - USE_JAVA_ACCOUNT, USE_LEGACY_USERNAME, CUSTOM_USERNAME, } = require("../constants"); @@ -15,13 +15,20 @@ const { mapJavaItemToLCE, mapJavaBlockToLCE } = require("./mappings"); const { mapJavaSoundToLCE } = require("./mappings/soundmapping"); const { parseChatComponent, stripColorCodes } = require("./utils/chat"); const { countSetBits, compressRLE } = require("./utils/chunk"); -const { downloadSkin, generateCustomSkinName } = require("./utils/skins"); +const { + downloadSkin, + downloadCape, + generateCustomSkinName, + generateCustomCapeName, +} = require("./utils/skins"); const zlib = require("zlib"); async function connectToJavaServer(proxy, client) { + const serverConfig = client.serverConfig; + let authConfig = { - host: JAVA_SERVER_HOST, - port: JAVA_SERVER_PORT, + host: serverConfig.host, + port: serverConfig.port, username: !USE_LEGACY_USERNAME ? CUSTOM_USERNAME : client.username || "undefined", @@ -29,11 +36,11 @@ async function connectToJavaServer(proxy, client) { version: "1.8.9", }; - if (USE_JAVA_ACCOUNT) { + if (!serverConfig.cracked) { if (msAuth.isAuthenticated()) { authConfig = { - host: JAVA_SERVER_HOST, - port: JAVA_SERVER_PORT, + host: serverConfig.host, + port: serverConfig.port, username: msAuth.username, session: { accessToken: msAuth.accessToken, @@ -46,7 +53,22 @@ async function connectToJavaServer(proxy, client) { version: "1.8.9", }; } else { - console.error("Not authenticated! This should not happen."); + console.log(`Server ${serverConfig.name} requires authentication. Authenticating...`); + await msAuth.authenticate(); + authConfig = { + host: serverConfig.host, + port: serverConfig.port, + username: msAuth.username, + session: { + accessToken: msAuth.accessToken, + selectedProfile: { + id: msAuth.uuid, + name: msAuth.username, + }, + }, + auth: "microsoft", + version: "1.8.9", + }; } } @@ -249,6 +271,19 @@ async function connectToJavaServer(proxy, client) { return; } + if (packet.windowId >= 0) { + if (!client._windowInventories) { + client._windowInventories = {}; + } + if (!client._windowInventories[packet.windowId]) { + client._windowInventories[packet.windowId] = {}; + } + + for (let i = 0; i < packet.items.length; i++) { + client._windowInventories[packet.windowId][i] = packet.items[i]; + } + } + if (packet.windowId === 0) { if (!client.inventory) client.inventory = {}; for (let i = 0; i < packet.items.length; i++) { @@ -276,7 +311,42 @@ async function connectToJavaServer(proxy, client) { for (let i = 0; i < packet.items.length; i++) { try { - proxy.writeItem(invWriter, packet.items[i]); + const item = packet.items[i]; + + if (item && item.nbtData) { + let displayName = null; + let isEnchanted = false; + try { + if ( + item.nbtData.value && + item.nbtData.value.display && + item.nbtData.value.display.value + ) { + if (item.nbtData.value.display.value.Name) { + displayName = item.nbtData.value.display.value.Name.value; + } + } + if ( + item.nbtData.value && + (item.nbtData.value.ench || + item.nbtData.value.Enchantments || + item.nbtData.value.StoredEnchantments) + ) { + isEnchanted = true; + } + } catch (err) { + /* do nothing */ + } + + if (displayName) { + item.displayName = displayName.replace(/§[0-9a-fk-or]/gi, ""); + } + if (isEnchanted) { + item.enchanted = true; + } + } + + proxy.writeItem(invWriter, item); } catch (err) { invWriter.writeShort(-1); } @@ -376,7 +446,42 @@ async function connectToJavaServer(proxy, client) { const slotWriter = new PacketWriter(); slotWriter.writeByte(packet.windowId); slotWriter.writeShort(packet.slot); - proxy.writeItem(slotWriter, packet.item); + + const item = packet.item; + if (item && item.nbtData) { + let displayName = null; + let isEnchanted = false; + try { + if ( + item.nbtData.value && + item.nbtData.value.display && + item.nbtData.value.display.value + ) { + if (item.nbtData.value.display.value.Name) { + displayName = item.nbtData.value.display.value.Name.value; + } + } + if ( + item.nbtData.value && + (item.nbtData.value.ench || + item.nbtData.value.Enchantments || + item.nbtData.value.StoredEnchantments) + ) { + isEnchanted = true; + } + } catch (err) { + /* do nothing */ + } + + if (displayName) { + item.displayName = displayName; + } + if (isEnchanted) { + item.enchanted = true; + } + } + + proxy.writeItem(slotWriter, item); const payload = slotWriter.toBuffer(); @@ -524,13 +629,26 @@ async function connectToJavaServer(proxy, client) { for (const playerData of packet.data) { const uuid = playerData.UUID || playerData.uuid; if (uuid) { - const existingPlayer = client.javaPlayers.get(uuid); - const wasAlreadySpawned = - existingPlayer && existingPlayer.spawned; + let existingPlayer = client.javaPlayers.get(uuid); + if (!existingPlayer) { + existingPlayer = { + name: playerData.name, + addedToTablistTime: Date.now(), + gamemode: 0, + ping: 0, + spawned: false, + }; + client.javaPlayers.set(uuid, existingPlayer); + } else { + existingPlayer.addedToTablistTime = Date.now(); + } + const wasAlreadySpawned = existingPlayer.spawned; let skinId = 0; let skinUrl = null; let customTextureName = null; + let capeUrl = null; + let customCapeName = null; if (playerData.properties) { const texturesProp = playerData.properties.find( (p) => p.name === "textures", @@ -566,6 +684,37 @@ async function connectToJavaServer(proxy, client) { client, existingPlayerForSkin.entityId, customTextureName, + 0, + ); + } + }) + .catch((err) => { + /* do nothing */ + }); + } + if (parsed.textures && parsed.textures.CAPE) { + capeUrl = parsed.textures.CAPE.url; + customCapeName = generateCustomCapeName(playerData.name); + + downloadCape(capeUrl) + .then((capeData) => { + proxy.sendTexturePacket( + client, + customCapeName, + capeData, + ); + + const existingPlayerForCape = + client.javaPlayers.get(uuid); + if ( + existingPlayerForCape && + existingPlayerForCape.entityId + ) { + proxy.sendTextureChangePacket( + client, + existingPlayerForCape.entityId, + customCapeName, + 1, ); } }) @@ -579,13 +728,17 @@ async function connectToJavaServer(proxy, client) { } } + const playerName = playerData.name || "Player"; + const isNPC = playerName.startsWith("[ZNPC]"); const updatedPlayer = { - name: playerData.name || "Player", + name: playerName, gamemode: playerData.gamemode || 0, ping: playerData.ping || 0, skinId: skinId, skinUrl: skinUrl, customTextureName: customTextureName, + capeUrl: capeUrl, + customCapeName: customCapeName, entityId: existingPlayer ? existingPlayer.entityId : null, javaEntityId: existingPlayer ? existingPlayer.javaEntityId @@ -600,6 +753,11 @@ async function connectToJavaServer(proxy, client) { ? existingPlayer.readyToSpawn : false, needsSpawn: wasAlreadySpawned, + addedViaPlayerInfo: true, + isNPC: isNPC, + addedToTablistTime: existingPlayer + ? existingPlayer.addedToTablistTime + : Date.now(), }; client.javaPlayers.set(uuid, updatedPlayer); @@ -621,6 +779,10 @@ async function connectToJavaServer(proxy, client) { const uuid = playerData.UUID || playerData.uuid; if (uuid && client.javaPlayers.has(uuid)) { const player = client.javaPlayers.get(uuid); + if (player.spawned) { + player.isNPC = true; + continue; + } if (player.spawned && player.entityId) { const isDying = client._dyingPlayers && @@ -672,12 +834,15 @@ async function connectToJavaServer(proxy, client) { } if (!playerInfo) { + const isNPC = playerName.startsWith("[ZNPC]"); playerInfo = { name: playerName, gamemode: 0, ping: 0, entityId: packet.entityId, spawned: false, + isNPC: isNPC, + spawnTime: Date.now(), }; client.javaPlayers.set(uuid, playerInfo); } else { @@ -731,6 +896,22 @@ async function connectToJavaServer(proxy, client) { playerInfo.spawned = true; try { proxy.sendAddPlayerPacket(client, playerInfo); + if (playerInfo.customTextureName) { + proxy.sendTextureChangePacket( + client, + playerInfo.entityId, + playerInfo.customTextureName, + 0, + ); + } + if (playerInfo.customCapeName) { + proxy.sendTextureChangePacket( + client, + playerInfo.entityId, + playerInfo.customCapeName, + 1, + ); + } } catch (err) { /* do nothing */ } @@ -748,6 +929,7 @@ async function connectToJavaServer(proxy, client) { proxy.sendContainerOpenPacket(client, packet); client.openWindowId = packet.windowId; client.openWindowType = windowType; + client._lastOpenTime = Date.now(); const isChest = windowType === "minecraft:chest" || @@ -780,9 +962,29 @@ async function connectToJavaServer(proxy, client) { }); javaClient.on("custom_payload", (packet) => { - if (client.state === "play" && packet.channel === "MC|TrList") { - const windowId = client.openWindowId || 1; - proxy.sendVillagerTrades(client, windowId, packet.data); + if (client.state === "play") { + if (packet.channel === "MC|TrList") { + const windowId = client.openWindowId || 1; + proxy.sendVillagerTrades(client, windowId, packet.data); + } else if (packet.channel === "MC|BOpen") { + let bookItem = null; + if (client.inventory) { + for (let i = 0; i < 45; i++) { + const item = client.inventory[i]; + if (item && item.blockId === 387) { + bookItem = item; + break; + } + } + } + + if (bookItem && (bookItem.nbt || bookItem.nbtData)) { + if (!bookItem.nbt && bookItem.nbtData) { + bookItem.nbt = bookItem.nbtData; + } + proxy.sendBookAsChestGUI(client, bookItem); + } + } } }); @@ -860,6 +1062,9 @@ async function connectToJavaServer(proxy, client) { ) { lceBlockId = 31; lceMetadata = 1; + } else if (javaBlockId === 165) { + lceBlockId = 95; + lceMetadata = 5; } if (lceBlockId < 0 || lceBlockId > 170) { @@ -1023,6 +1228,9 @@ async function connectToJavaServer(proxy, client) { ) { lceBlockId = 31; lceMetadata = 1; + } else if (javaBlockId === 165) { + lceBlockId = 95; + lceMetadata = 5; } if (lceBlockId < 0 || lceBlockId > 170) { @@ -1073,12 +1281,6 @@ async function connectToJavaServer(proxy, client) { const javaType = proxy.getJavaEntityType(packet.type); const lceEntityType = proxy.javaEntityTypeMapping[javaType]; - if (!lceEntityType) { - } - - if (lceEntityType < 0 || lceEntityType > 200) { - } - const lceEntityId = proxy.mapJavaEntityIdToLce(client, packet.entityId); const entityInfo = { @@ -1100,6 +1302,11 @@ async function connectToJavaServer(proxy, client) { metadata: packet.metadata || [], }; + if (javaType === "Rabbit") { + entityInfo.metadata.push({ key: 10, type: 4, value: "Rabbit" }); + entityInfo.metadata.push({ key: 11, type: 0, value: 1 }); + } + entityInfo.spawnTime = Date.now(); client.javaEntities.set(packet.entityId, entityInfo); @@ -1111,7 +1318,7 @@ async function connectToJavaServer(proxy, client) { } const relevantMetadata = entityInfo.metadata.filter((m) => { - return [12, 13, 16].includes(m.key) && m.type !== 5; + return [10, 11, 12, 13, 16].includes(m.key) && m.type !== 5; }); if (relevantMetadata.length > 0) { @@ -1127,6 +1334,9 @@ async function connectToJavaServer(proxy, client) { javaClient.on("spawn_entity", (packet) => { try { if (client.state === "play") { + //if (packet && packet.type === 71) { + // console.log(packet); + //} if ( !packet || packet.entityId === undefined || @@ -1212,13 +1422,29 @@ async function connectToJavaServer(proxy, client) { } } + let tileX = packet.x / 32; + let tileY = packet.y / 32; + let tileZ = packet.z / 32; + + // if (lceEntityType === 71 && itemFrameDirection !== null) { + // if (itemFrameDirection === 0) { + // tileZ--; + // } else if (itemFrameDirection === 1) { + // tileX++; + // } else if (itemFrameDirection === 2) { + // tileZ++; + // } else if (itemFrameDirection === 3) { + // tileX -= 1; + // } + // } + const entityInfo = { entityId: lceEntityId, javaEntityId: packet.entityId, type: lceEntityType, - x: packet.x / 32, - y: packet.y / 32, - z: packet.z / 32, + x: tileX, + y: tileY, + z: tileZ, yaw: lceEntityType === 60 ? 0 : (packet.yaw / 256) * 360, pitch: lceEntityType === 60 ? 0 : (packet.pitch / 256) * 360, data: @@ -1635,12 +1861,29 @@ async function connectToJavaServer(proxy, client) { packet.item.blockId !== undefined && packet.item.blockId !== -1 ) { - proxy.sendSetEquippedItemPacket( - client, - player, - packet.slot, - packet.item, - ); + const item = packet.item; + if (item.blockId === 387) { + item.enchanted = true; + } + if (item.nbtData) { + let isEnchanted = false; + try { + if ( + item.nbtData.value && + (item.nbtData.value.ench || + item.nbtData.value.Enchantments || + item.nbtData.value.StoredEnchantments) + ) { + isEnchanted = true; + } + } catch (err) { + /* do nothing */ + } + if (isEnchanted) { + item.enchanted = true; + } + } + proxy.sendSetEquippedItemPacket(client, player, packet.slot, item); } else { proxy.sendSetEquippedItemPacket(client, player, packet.slot, { blockId: -1, @@ -1659,12 +1902,29 @@ async function connectToJavaServer(proxy, client) { packet.item.blockId !== undefined && packet.item.blockId !== -1 ) { - proxy.sendSetEquippedItemPacket( - client, - entity, - packet.slot, - packet.item, - ); + const item = packet.item; + if (item.blockId === 387) { + item.enchanted = true; + } + if (item.nbtData) { + let isEnchanted = false; + try { + if ( + item.nbtData.value && + (item.nbtData.value.ench || + item.nbtData.value.Enchantments || + item.nbtData.value.StoredEnchantments) + ) { + isEnchanted = true; + } + } catch (err) { + /* do nothing */ + } + if (isEnchanted) { + item.enchanted = true; + } + } + proxy.sendSetEquippedItemPacket(client, entity, packet.slot, item); } } } @@ -1729,7 +1989,29 @@ async function connectToJavaServer(proxy, client) { (m) => m.key === 10 && m.type === 5, ); if (itemMetadata && itemMetadata.value) { - proxy.sendSetItemDataPacket(client, entity, itemMetadata.value); + const itemData = itemMetadata.value; + if (itemData && itemData.blockId === 387) { + itemData.enchanted = true; + } + if (itemData && itemData.nbtData) { + let isEnchanted = false; + try { + if ( + itemData.nbtData.value && + (itemData.nbtData.value.ench || + itemData.nbtData.value.Enchantments || + itemData.nbtData.value.StoredEnchantments) + ) { + isEnchanted = true; + } + } catch (err) { + /* do nothing */ + } + if (isEnchanted) { + itemData.enchanted = true; + } + } + proxy.sendSetItemDataPacket(client, entity, itemData); entity.waitingForItemData = false; } } @@ -1891,8 +2173,13 @@ async function connectToJavaServer(proxy, client) { let isPlayer = false; for (const [uuid, player] of client.javaPlayers) { if (player.javaEntityId === entityId && player.spawned) { - const deathEvent = { entityId: player.entityId }; - proxy.sendEntityEventPacket(client, deathEvent, 3); + const isDying = + client._dyingPlayers && + client._dyingPlayers.has(player.javaEntityId); + if (isDying) { + const deathEvent = { entityId: player.entityId }; + proxy.sendEntityEventPacket(client, deathEvent, 3); + } const lceEntityId = player.entityId; const javaEntityId = entityId; @@ -2085,6 +2372,57 @@ async function connectToJavaServer(proxy, client) { //proxy.sendFlatChunk(client, chunkX, chunkZ); } }); + + javaClient.on("update_sign", (packet) => { + try { + if (!packet.location) return; + + const x = packet.location.x; + const y = packet.location.y; + const z = packet.location.z; + + const text1 = parseChatComponent(packet.text1); + const text2 = parseChatComponent(packet.text2); + const text3 = parseChatComponent(packet.text3); + const text4 = parseChatComponent(packet.text4); + + const writer = new PacketWriter(); + writer.writeInt(x); + writer.writeShort(y); + writer.writeInt(z); + writer.writeBoolean(true); + writer.writeBoolean(false); + + writer.writeUtf(text1); + writer.writeUtf(text2); + writer.writeUtf(text3); + writer.writeUtf(text4); + + proxy.sendPacket(client, 0x82, writer.toBuffer()); + } catch (err) { + /* do nothing */ + } + }); + + javaClient.on("open_sign_entity", (packet) => { + try { + if (!packet.location) return; + + const x = packet.location.x; + const y = packet.location.y; + const z = packet.location.z; + + const writer = new PacketWriter(); + writer.writeByte(0); + writer.writeInt(x); + writer.writeInt(y); + writer.writeInt(z); + + proxy.sendPacket(client, 0x85, writer.toBuffer()); + } catch (err) { + /* do nothing */ + } + }); } function convertAndSendJavaChunk(proxy, client, javaChunk) { @@ -2195,6 +2533,9 @@ function convertAndSendJavaChunk(proxy, client, javaChunk) { } else if (javaBlockId === 32) { lceBlockId = 31; lceMetadata = 1; + } else if (javaBlockId === 165) { + lceBlockId = 95; + lceMetadata = 5; } if (lceBlockId < 0 || lceBlockId > 174) { diff --git a/src/lanbroadcast.js b/src/lanbroadcast.js index 34dfb38..7ae1e0e 100644 --- a/src/lanbroadcast.js +++ b/src/lanbroadcast.js @@ -1,20 +1,16 @@ /* --------------------------------------------------------------- */ /* lanbroadcast.js */ /* --------------------------------------------------------------- */ -const { - MINECRAFT_NET_VERSION, - GAME_PORT, - PROXY_NAME, -} = require("../constants"); +const { MINECRAFT_NET_VERSION } = require("../constants"); class LANBroadcast { - constructor() { + constructor(serverName, gamePort) { this.buffer = Buffer.allocUnsafe(86); this.buffer.writeUInt32LE(0x4d434c4e, 0); this.buffer.writeUInt16LE(MINECRAFT_NET_VERSION, 4); - this.buffer.writeUInt16LE(GAME_PORT, 6); + this.buffer.writeUInt16LE(gamePort, 6); - const hostName = PROXY_NAME; + const hostName = serverName || "Minecraft Server"; for (let i = 0; i < 32; i++) { const char = i < hostName.length ? hostName.charCodeAt(i) : 0; this.buffer.writeUInt16LE(char, 8 + i * 2); diff --git a/src/lceproxy.js b/src/lceproxy.js index db2c16e..baaa177 100644 --- a/src/lceproxy.js +++ b/src/lceproxy.js @@ -1,6 +1,9 @@ /* --------------------------------------------------------------- */ /* lceproxy.js */ /* --------------------------------------------------------------- */ + +//beware that there are a lot of magic numbers, need to do a refractor soon. + const dgram = require("dgram"); const net = require("net"); const mc = require("minecraft-protocol"); @@ -8,12 +11,11 @@ const { GAME_PORT, WIN64_LAN_DISCOVERY_PORT, MINECRAFT_NET_VERSION, - USE_JAVA_ACCOUNT, USE_LEGACY_USERNAME, CUSTOM_USERNAME, - PROXY_NAME, + SERVERS, } = require("../constants"); -const msAuth = require("./auth"); + const PacketWriter = require("./packetwriter"); const PacketReader = require("./packetreader"); const LANBroadcast = require("./lanbroadcast"); @@ -46,8 +48,10 @@ class LCEProxy { constructor() { this.clients = []; this.udpSocket = null; - this.tcpServer = null; + this.tcpServers = []; this.broadcastInterval = null; + this.broadcasts = []; + this.serverConfigs = []; this.nextSmallId = 1; this.usedSmallIds = new Set(); @@ -63,10 +67,10 @@ class LCEProxy { 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x3c, 0x3d, 0x3e, 0x46, 0x64, 0x65, - 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x82, 0x83, 0x96, 0x97, - 0x98, 0x9a, 0x9d, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, - 0xd1, 0xfa, 0xfc, 0xfd, 0xfe, 0xff, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x3c, 0x3d, 0x3e, 0x46, 0x64, + 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x82, 0x83, 0x85, + 0x96, 0x97, 0x98, 0x9a, 0x9d, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, + 0xcf, 0xd0, 0xd1, 0xfa, 0xfc, 0xfd, 0xfe, 0xff, ]); } @@ -74,7 +78,7 @@ class LCEProxy { if (this.javaBlockMapping[javaBlockId] !== undefined) { return this.javaBlockMapping[javaBlockId]; } - return 0; + return 1; } mapJavaParticleToLCE(particleId) { @@ -159,7 +163,6 @@ class LCEProxy { return lceItemId; } - //console.log(`lce to java item ${lceItemId} not found`); return null; } @@ -178,27 +181,17 @@ class LCEProxy { } async start() { - if (USE_JAVA_ACCOUNT) { - try { - await msAuth.authenticate(); - console.log("Logged in as: " + msAuth.username); - } catch (err) { - console.log("\Failed to log into java account! (", err.message, ")"); - console.log( - "If you enabled this by accident and would like to only join offline servers for free,", - ); - console.log("set USE_JAVA_ACCOUNT to false in constants.js\n"); - process.exit(1); - } - } - this.startBroadcasting(); this.startTCPServer(); console.log("\nProxy is now running!"); console.log( - 'Java Edition server "' + PROXY_NAME + '" should appear on Minecraft.', + `Broadcasting ${SERVERS.length} server(s) as LAN games on Minecraft Legacy Edition.`, ); + SERVERS.forEach((server, index) => { + const serverStr = typeof server === 'string' ? server : server.server; + console.log(` - ${serverStr} on port ${GAME_PORT + index}`); + }); console.log("Press Ctrl+C to stop.\n"); } @@ -208,73 +201,96 @@ class LCEProxy { this.udpSocket.setBroadcast(true); }); - const broadcast = new LANBroadcast(); + this.broadcasts = SERVERS.map((server, index) => { + const gamePort = GAME_PORT + index; + const serverStr = typeof server === 'string' ? server : server.server; + const parts = serverStr.split(':'); + this.serverConfigs[index] = { + host: parts[0], + port: parts[1] ? parseInt(parts[1]) : 25565, + name: serverStr, + cracked: typeof server === 'object' ? server.cracked : false, + gamePort: gamePort, + }; + return new LANBroadcast(serverStr, gamePort); + }); this.broadcastInterval = setInterval(() => { - this.udpSocket.send( - broadcast.buffer, - 0, - broadcast.buffer.length, - WIN64_LAN_DISCOVERY_PORT, - "255.255.255.255", - ); + this.broadcasts.forEach((broadcast) => { + this.udpSocket.send( + broadcast.buffer, + 0, + broadcast.buffer.length, + WIN64_LAN_DISCOVERY_PORT, + "255.255.255.255", + ); + }); }, 1000); } startTCPServer() { - this.tcpServer = net.createServer((socket) => { - socket.setNoDelay(true); + this.serverConfigs.forEach((serverConfig, index) => { + const tcpServer = net.createServer((socket) => { + socket.setNoDelay(true); - let smallId = 1; - while (this.usedSmallIds.has(smallId) && smallId <= 8) { - smallId++; - } - - if (smallId > 8) { - socket.destroy(); - return; - } - - this.usedSmallIds.add(smallId); - - const client = { - socket: socket, - smallId: smallId, - buffer: Buffer.alloc(0), - state: "prelogin", - javaClient: null, - breakingBlock: null, - javaPlayers: new Map(), - nextLceEntityId: 100, - javaToLceEntityId: new Map(), - javaEntities: new Map(), - }; - - this.clients.push(client); - - const smallIdBuffer = Buffer.from([smallId]); - socket.write(smallIdBuffer); - - socket.on("data", (data) => { - this.handleClientData(client, data); - }); - - socket.on("end", () => { - this.removeClient(client); - }); - - socket.on("error", (err) => { - this.removeClient(client); - }); - - socket.on("close", () => { - if (this.clients.indexOf(client) > -1) { - this.removeClient(client); + let smallId = 1; + while (this.usedSmallIds.has(smallId) && smallId <= 8) { + smallId++; } - }); - }); - this.tcpServer.listen(GAME_PORT, () => {}); + if (smallId > 8) { + socket.destroy(); + return; + } + + this.usedSmallIds.add(smallId); + + const client = { + socket: socket, + smallId: smallId, + buffer: Buffer.alloc(0), + state: "prelogin", + javaClient: null, + breakingBlock: null, + javaPlayers: new Map(), + nextLceEntityId: 100, + javaToLceEntityId: new Map(), + javaEntities: new Map(), + serverConfig: serverConfig, + }; + + this.clients.push(client); + + const smallIdBuffer = Buffer.from([smallId]); + socket.write(smallIdBuffer); + + socket.on("data", (data) => { + this.handleClientData(client, data); + }); + + socket.on("end", () => { + this.removeClient(client); + }); + + socket.on("error", (err) => { + this.removeClient(client); + }); + + socket.on("close", () => { + if (this.clients.indexOf(client) > -1) { + this.removeClient(client); + } + }); + }); + + tcpServer.listen(serverConfig.gamePort, () => { + console.log( + `Server ${serverConfig.name} should now be visible on LCE.`, + ); + }); + + this.tcpServers.push(tcpServer); + }); } getPacketDataSize(packetId, data, offset) { @@ -403,6 +419,25 @@ class LCEProxy { case 0x98: return 1 + 4; + case 0x82: + try { + let signSize = 1 + 4 + 2 + 4 + 1 + 1; + let pos = offset + 1 + 4 + 2 + 4 + 1 + 1; + for (let i = 0; i < 4; i++) { + if (pos + 2 > data.length) return null; + const strLen = data.readInt16BE(pos); + pos += 2; + signSize += 2 + strLen * 2; + pos += strLen * 2; + } + return signSize; + } catch (err) { + return null; + } + + case 0x85: + return 1 + 1 + 4 + 4 + 4; + default: return null; } @@ -561,6 +596,11 @@ class LCEProxy { this.handleCustomPayload(client, packetData); } break; + case 0x82: + if (client.state === "play") { + this.handleSignUpdate(client, packetData); + } + break; case 0x6b: //SetCreativeModeSlotPacket - 107 if (client.state === "play") { this.handleSetCreativeModeSlot(client, packetData); @@ -806,13 +846,13 @@ class LCEProxy { this.sendPacket(client, 0x9a, writer.toBuffer()); } - sendTextureChangePacket(client, entityId, textureName) { + sendTextureChangePacket(client, entityId, textureName, textureType = 0) { if (!client || !client.socket || client.socket.destroyed) { return; } const writer = new PacketWriter(); writer.writeInt(entityId); - writer.writeByte(0); + writer.writeByte(textureType); writer.writeUTF(textureName); this.sendPacket(client, 0x9d, writer.toBuffer()); @@ -820,10 +860,13 @@ class LCEProxy { sendAddPlayerPacket(client, playerInfo) { let playerName = playerInfo.name || "undefined"; + if (playerInfo.isNPC) { + playerName = ""; + } if (playerName.length > 20) { playerName = playerName.substring(0, 20); } - if (playerName.length === 0) { + if (playerName.length === 0 && !playerInfo.isNPC) { playerName = "undefined"; } @@ -963,6 +1006,7 @@ class LCEProxy { 92: "Cow", 93: "Chicken", 94: "Squid", + 101: "Rabbit", 95: "Wolf", 96: "MushroomCow", 97: "SnowMan", @@ -970,6 +1014,7 @@ class LCEProxy { 99: "VillagerGolem", 100: "EntityHorse", 120: "Villager", + 71: "ItemFrame", }; return typeMap[typeId] || "Unknown"; } @@ -1030,6 +1075,15 @@ class LCEProxy { sendSetItemDataPacket(client, entity, itemData) { return packetSenders.sendSetItemDataPacket(this, client, entity, itemData); } + sendSetItemFrameDataPacket(client, entity, itemData, rotation) { + return packetSenders.sendSetItemFrameDataPacket( + this, + client, + entity, + itemData, + rotation, + ); + } sendSetEntityDataPacket(client, entity) { return packetSenders.sendSetEntityDataPacket(this, client, entity); } @@ -1104,6 +1158,214 @@ class LCEProxy { return packetSenders.sendVillagerTrades(this, client, windowId, packetData); } + sendBookAsChestGUI(client, bookItem) { + if (!bookItem.nbt) { + return; + } + + let bookTitle = "Book"; + if (bookItem.nbt.value && bookItem.nbt.value.title) { + bookTitle = bookItem.nbt.value.title.value || "Book"; + } + + let pages = []; + if (bookItem.nbt.value && bookItem.nbt.value.pages) { + if ( + bookItem.nbt.value.pages.value && + bookItem.nbt.value.pages.value.value + ) { + pages = bookItem.nbt.value.pages.value.value; + } else if (Array.isArray(bookItem.nbt.value.pages)) { + pages = bookItem.nbt.value.pages; + } + } + + if (pages.length === 0) { + return; + } + + if (!client._bookGUI) { + client._bookGUI = { + pages: pages, + currentPage: 0, + clickActions: {}, + bookTitle: bookTitle, + }; + } else { + client._bookGUI.clickActions = {}; + client._bookGUI.bookTitle = bookTitle; + } + + const windowId = 1; + client.openWindowId = windowId; + client.openWindowType = "minecraft:chest"; + + const fakeOpenPacket = { + windowId: windowId, + inventoryType: "minecraft:chest", + slotCount: 54, + windowTitle: JSON.stringify({ + text: `Written Book (${bookTitle})`, + extra: [], + }), + }; + + this.sendContainerOpenPacket(client, fakeOpenPacket); + + this.updateBookGUIContents(client, windowId); + } + + updateBookGUIContents(client, windowId) { + if (!client._bookGUI) return; + + const currentPage = client._bookGUI.currentPage; + const pages = client._bookGUI.pages; + const pageContent = pages[currentPage]; + + const items = []; + for (let i = 0; i < 54; i++) { + items.push({ blockId: -1 }); + } + + if (currentPage > 0) { + items[48] = { + blockId: 35, + itemCount: 1, + itemDamage: 14, + displayName: "Previous Page", + }; + } + + if (currentPage < pages.length - 1) { + items[50] = { + blockId: 35, + itemCount: 1, + itemDamage: 5, + displayName: "Next Page", + }; + } + + try { + const pageText = JSON.parse(pageContent); + + let lines = []; + if (Array.isArray(pageText)) { + lines = pageText; + } else if (pageText.extra) { + lines = pageText.extra; + } else { + lines = [pageText]; + } + + let slotIndex = 0; + for (let i = 0; i < lines.length && slotIndex < 36; i++) { + const line = lines[i]; + let text = ""; + let clickAction = null; + + if (typeof line === "string") { + text = line; + } else if (line && typeof line === "object") { + if (line.text) { + text = line.text; + } + if (line.extra && Array.isArray(line.extra)) { + for (const extraPart of line.extra) { + if (typeof extraPart === "string") { + text += extraPart; + } else if (extraPart.text) { + text += extraPart.text; + } + + if (extraPart.clickEvent) { + clickAction = { + type: extraPart.clickEvent.action, + value: extraPart.clickEvent.value, + }; + } + } + } + } + + text = text.replace(/§[0-9a-fk-or]/gi, "").replace(/\\n/g, "\n"); + + const textLines = text + .split("\n") + .map((l) => l.trim()) + .filter((l) => l.length > 0 && l !== " "); + + for (const textLine of textLines) { + if (slotIndex >= 36) break; + + if (textLine.length > 0 && textLine !== " ") { + let itemId = 339; + let itemDamage = 0; + let isEnchanted = false; + + if (clickAction) { + if (clickAction.type === "open_url") { + itemId = 345; + itemDamage = 0; + } else if (clickAction.type === "run_command") { + itemId = 340; + itemDamage = 0; + } + isEnchanted = true; + } + + const chunks = []; + for (let pos = 0; pos < textLine.length; pos += 32) { + chunks.push(textLine.substring(pos, pos + 32)); + } + + for (const chunk of chunks) { + if (slotIndex >= 36) break; + + items[slotIndex] = { + blockId: itemId, + itemCount: 1, + itemDamage: itemDamage, + displayName: chunk, + enchanted: isEnchanted, + }; + + if (clickAction) { + client._bookGUI.clickActions[slotIndex] = clickAction; + } + + slotIndex++; + } + } + } + } + } catch (err) { + items[0] = { + blockId: 339, + itemCount: 1, + itemDamage: 0, + displayName: "Error loading page", + }; + } + + let itemCount = 0; + for (let i = 0; i < items.length; i++) { + if (items[i].blockId !== -1) { + itemCount++; + } + } + + const PacketWriter = require("./packetwriter"); + const invWriter = new PacketWriter(); + invWriter.writeByte(windowId); + invWriter.writeShort(items.length); + + for (const item of items) { + this.writeItem(invWriter, item); + } + + this.sendPacket(client, 0x68, invWriter.toBuffer()); + } + //debug sendFlatChunk(client, chunkX, chunkZ) { const xs = 16; @@ -1592,6 +1854,7 @@ class LCEProxy { const face = reader.readByte(); const itemId = reader.readShort(); + let itemCount = 0; let itemAux = 0; if (itemId !== -1) { @@ -1976,6 +2239,11 @@ class LCEProxy { const reader = new PacketReader(data.slice(1)); const containerId = reader.readByte(); + if (client.openWindowId === containerId) { + client.openWindowType = null; + client.openWindowId = null; + } + if (client._currentChest && client._currentChest.windowId === containerId) { const posKey = client._currentChest.posKey; const chestData = this.openChests.get(posKey); @@ -1995,6 +2263,11 @@ class LCEProxy { delete client._currentChest; } + if (client._bookGUI && containerId === client.openWindowId) { + delete client._bookGUI; + return; + } + //LCE uses special window IDs //-1=crafting table in inventory //-2=creative inventory @@ -2078,7 +2351,6 @@ class LCEProxy { placeTradeItems(client, windowId, tradeInfo, offerIndex) { //very broken, java requires you to send clicks with the current item in the slot //we have to track inventory and update it after each click, but this is complicated - //maybe in the future we can write a server plugin that handles this if (!client.javaClient) return; if (!client._windowInventories || !client._windowInventories[windowId]) { @@ -2252,9 +2524,16 @@ class LCEProxy { } handleCraftItem(client, data) { + const debugLog = true; + if (client._craftingInProgress) { + if (debugLog) console.log("craft already in progress ignoring"); + return; + } + const reader = new PacketReader(data.slice(1)); const uid = reader.readShort(); const recipeId = reader.readInt(); + //console.log(recipeId); const grid = recipeData[recipeId] || [ "none", @@ -2268,12 +2547,705 @@ class LCEProxy { "none", ]; - //console.log(`recipe id: ${recipeId}`); - //console.log(`${grid[0]}, ${grid[1]}, ${grid[2]}, ${grid[3]}, ${grid[4]}, ${grid[5]}, ${grid[6]}, ${grid[7]}, ${grid[8]}`); + if (!client.inventory) { + if (debugLog) console.log("no inventory"); + client._craftingInProgress = false; + return; + } + + if (debugLog) console.log("id", recipeId); + client._craftingInProgress = true; + this.tryPlaceItemsInCraftingGrid(client, grid, recipeId); } handleJavaCrafting(client, data) { /* do nothing */ } + + getCraftingResult(grid) { + const craftingResults = { + 0: { resultItemId: 5, resultCount: 4 }, + 1: { resultItemId: 5, resultCount: 4 }, + 2: { resultItemId: 5, resultCount: 4 }, + 3: { resultItemId: 5, resultCount: 4 }, + 4: { resultItemId: 280, resultCount: 4 }, + 44: { resultItemId: 58, resultCount: 1 }, + 46: { resultItemId: 54, resultCount: 1 }, + }; + + const recipeStr = grid.join(","); + for (const [recipeId, recipe] of Object.entries(recipeData)) { + if (recipe.join(",") === recipeStr) { + return craftingResults[recipeId]; + } + } + return null; + } + + craftItemDirectly(client, grid, recipeId) { + if (!client.javaClient || !client.javaClient.write) { + return; + } + + const craftingResults = this.getCraftingResult(grid); + if (!craftingResults) { + return; + } + + const { resultItemId, resultCount } = craftingResults; + + const requiredItems = this.findRequiredItems(client, grid); + if (!requiredItems) { + return; + } + + requiredItems.forEach((req) => { + if (!req) return; + const slot = req.sourceSlot; + const item = client.inventory[slot]; + if (item && item.itemCount > 1) { + item.itemCount--; + client.inventory[slot] = item; + } else { + client.inventory[slot] = { blockId: -1, itemCount: 0, itemDamage: 0 }; + } + }); + + let addedToExisting = false; + for (let slot = 9; slot < 45; slot++) { + const item = client.inventory[slot]; + if (item && item.blockId === resultItemId && item.itemCount < 64) { + item.itemCount = Math.min(64, (item.itemCount || 0) + resultCount); + client.inventory[slot] = item; + addedToExisting = true; + break; + } + } + + if (!addedToExisting) { + for (let slot = 9; slot < 45; slot++) { + const item = client.inventory[slot]; + if (!item || item.blockId === -1) { + client.inventory[slot] = { + blockId: resultItemId, + itemCount: resultCount, + itemDamage: 0, + }; + break; + } + } + } + + for (let i = 0; i < 45; i++) { + const item = client.inventory[i] || { + blockId: -1, + itemCount: 0, + itemDamage: 0, + }; + try { + client.javaClient.write("set_slot", { + windowId: 0, + slot: i, + item: item, + }); + } catch (err) { + /* do nothing */ + } + } + } + + tryPlaceItemsInCraftingGrid(client, grid, recipeId) { + const debugLog = true; + if (debugLog) console.log("placing items"); + const itemNameToDamage = { + wool: 0, + orange_wool: 1, + magenta_wool: 2, + light_blue_wool: 3, + yellow_wool: 4, + lime_wool: 5, + pink_wool: 6, + gray_wool: 7, + light_gray_wool: 8, + cyan_wool: 9, + purple_wool: 10, + blue_wool: 11, + brown_wool: 12, + green_wool: 13, + red_wool: 14, + black_wool: 15, + }; + + const itemNameToJavaId = { + oak_log: 17, + birch_log: 17, + spruce_log: 17, + jungle_log: 17, + acacia_log: 162, + dark_oak_log: 162, + any_log: [17, 162], + any_plank: 5, + oak_plank: 5, + birch_planks: 5, + spruce_planks: 5, + jungle_planks: 5, + stick: 280, + cobblestone: 4, + iron_ingot: 265, + diamond: 264, + gold_ingot: 266, + any_wool: 35, + wool: 35, + sand: 12, + sandstone: 24, + sandstone_slab: 44, + quartz_slab: 44, + quartz_block: 155, + stone: 1, + nether_brick: 112, + snowball: 332, + clay: 337, + brick: 336, + nether_quartz: 406, + book: 340, + obsidian: 49, + iron_block: 42, + blaze_rod: 369, + chest: 54, + tripwire_hook: 131, + ender_eye: 381, + mossy_cobblestone: 48, + stonebrick: 98, + brick_block: 45, + charcoal: 263, + coal: 263, + glowstone: 348, + gunpowder: 289, + blaze_powder: 377, + pumpkin: 86, + torch: 50, + redstone: 331, + ender_pearl: 368, + slime_ball: 341, + paper: 339, + compass: 345, + apple: 260, + gold_block: 41, + gold_nugget: 371, + melon: 360, + carrot: 391, + brown_mushroom: 39, + red_mushroom: 40, + bowl: 281, + wheat: 296, + cocoa_beans: 351, + flint: 318, + string: 287, + fishing_rod: 346, + feather: 288, + glass: 20, + any_slab: 44, + inc_sac: 351, + red_dye: 351, + green_dye: 351, + lapis: 351, + purple_dye: 351, + cyan_dye: 351, + light_gray_dye: 351, + gray_dye: 351, + pink_dye: 351, + lime_dye: 351, + yellow_dye: 351, + light_blue_dye: 351, + magenta_dye: 351, + orange_dye: 351, + bone_meal: 351, + dandelion: 37, + rose: 38, + orange_wool: 35, + magenta_wool: 35, + light_blue_wool: 35, + yellow_wool: 35, + lime_wool: 35, + pink_wool: 35, + gray_wool: 35, + light_gray_wool: 35, + cyan_wool: 35, + purple_wool: 35, + blue_wool: 35, + brown_wool: 35, + green_wool: 35, + red_wool: 35, + black_wool: 35, + }; + + const requiredItems = []; + let allItemsFound = true; + const slotUsageCount = new Map(); + + for (let i = 0; i < 9; i++) { + const requiredItem = grid[i]; + if (requiredItem === "none") { + requiredItems[i] = null; + continue; + } + + const javaItemId = itemNameToJavaId[requiredItem]; + if (!javaItemId) { + if (debugLog) console.log("could not find item for", requiredItem); + allItemsFound = false; + continue; + } + + const acceptedIds = Array.isArray(javaItemId) ? javaItemId : [javaItemId]; + if (debugLog) + console.log("looking for", requiredItem, "with id(s)", acceptedIds); + + let foundSlot = null; + const windowId = client.openWindowId || 0; + const isCraftingTable = + client.openWindowType === "minecraft:crafting_table"; + + const inventoryToSearch = + isCraftingTable && + client._windowInventories && + client._windowInventories[windowId] + ? client._windowInventories[windowId] + : client.inventory; + + const startSlot = isCraftingTable ? 10 : 9; + const endSlot = isCraftingTable ? 46 : 45; + + for (let slot = startSlot; slot < endSlot; slot++) { + const item = inventoryToSearch[slot]; + if (item && acceptedIds.includes(item.blockId)) { + const requiredDamage = itemNameToDamage[requiredItem]; + if ( + requiredDamage !== undefined && + item.itemDamage !== requiredDamage + ) { + if (debugLog) + console.log( + "found item at slot", + slot, + "but damage does not match. need", + requiredDamage, + "got", + item.itemDamage, + ); + continue; + } + if (debugLog) console.log("found", requiredItem, "at slot", slot); + + const itemCount = item.itemCount || 1; + const usedCount = slotUsageCount.get(slot) || 0; + + if (usedCount < itemCount) { + foundSlot = slot; + let gridSlot; + if (isCraftingTable) { + gridSlot = i + 1; + } else { + const slot2x2Map = { 0: 1, 1: 2, 3: 3, 4: 4 }; + gridSlot = slot2x2Map[i] || i + 1; + } + + requiredItems[i] = { + sourceSlot: slot, + itemId: item.blockId, + gridSlot: gridSlot, + }; + slotUsageCount.set(slot, usedCount + 1); + break; + } + } + } + + if (!foundSlot) { + if (debugLog) + console.log("could not find", requiredItem, "in inventory"); + allItemsFound = false; + } + } + + if (!allItemsFound) { + if (debugLog) console.log("not all items found"); + client._craftingInProgress = false; + return; + } + + if (debugLog) console.log("all items found, placing"); + this.placeItemsInGrid(client, requiredItems); + } + + placeItemsInGrid(client, requiredItems) { + const debugLog = true; + if (!client.javaClient || !client.javaClient.write) { + client._craftingInProgress = false; + return; + } + if (debugLog) console.log("placing", requiredItems.length, "items"); + + if (!client.windowClickAction) { + client.windowClickAction = 1; + } + + const clicks = []; + const slotGroups = new Map(); + + for (let i = 0; i < requiredItems.length; i++) { + if (!requiredItems[i]) continue; + const { sourceSlot, gridSlot, itemId } = requiredItems[i]; + + if (!slotGroups.has(sourceSlot)) { + slotGroups.set(sourceSlot, []); + } + slotGroups.get(sourceSlot).push({ gridSlot, itemId }); + } + + let lastSourceSlot = null; + let lastSourceItem = null; + + for (const [sourceSlot, gridSlots] of slotGroups) { + const windowId = client.openWindowId || 0; + const isCraftingTable = + client.openWindowType === "minecraft:crafting_table"; + + const inventoryToUse = + isCraftingTable && + client._windowInventories && + client._windowInventories[windowId] + ? client._windowInventories[windowId] + : client.inventory; + + const sourceItem = inventoryToUse[sourceSlot]; + if (!sourceItem) continue; + + lastSourceSlot = sourceSlot; + lastSourceItem = sourceItem; + + clicks.push({ + windowId: windowId, + slot: sourceSlot, + mouseButton: 0, + action: client.windowClickAction++, + mode: 0, + item: sourceItem, + }); + + for (const { gridSlot, itemId } of gridSlots) { + clicks.push({ + windowId: windowId, + slot: gridSlot, + mouseButton: 1, + action: client.windowClickAction++, + mode: 0, + item: { blockId: -1, itemCount: 0, itemDamage: 0 }, + }); + } + + if (gridSlots.length < sourceItem.itemCount) { + clicks.push({ + windowId: windowId, + slot: sourceSlot, + mouseButton: 0, + action: client.windowClickAction++, + mode: 0, + item: { blockId: -1, itemCount: 0, itemDamage: 0 }, + }); + } + } + + let cursorState = { blockId: -1, itemCount: 0 }; + + const tempListener = (packet) => { + if (packet.windowId === 0) { + const slotName = + packet.slot === 0 + ? "RESULT" + : packet.slot >= 1 && packet.slot <= 9 + ? `GRID ${packet.slot}` + : `INV ${packet.slot}`; + } + if (packet.windowId === -1 && packet.slot === -1) { + const oldCursor = `${cursorState.blockId}:${cursorState.itemCount}`; + cursorState = packet.item || { blockId: -1, itemCount: 0 }; + const newCursor = `${cursorState.blockId}:${cursorState.itemCount}`; + } + }; + client.javaClient.on("set_slot", tempListener); + + setTimeout(() => { + client.javaClient.removeListener("set_slot", tempListener); + }, 100); + + let delay = 0; + clicks.forEach((click, index) => { + setTimeout(() => { + try { + client.javaClient.write("window_click", click); + } catch (err) { + /* do nothing */ + } + }, delay); + delay += 1; + }); + + const usedGridSlots = requiredItems.filter((r) => r).map((r) => r.gridSlot); + + setTimeout(() => { + this.checkCraftingResult(client, usedGridSlots); + }, delay + 50); + } + + checkCraftingResult(client, usedGridSlots) { + const debugLog = true; + if (debugLog) console.log("checking crafting result"); + const windowId = client.openWindowId || 0; + + const checkForResult = () => { + const inventoryToCheck = + windowId !== 0 && + client._windowInventories && + client._windowInventories[windowId] + ? client._windowInventories[windowId] + : client.inventory; + + if (debugLog) console.log("slot 0 content", inventoryToCheck[0]); + + if (!inventoryToCheck || !inventoryToCheck[0]) { + if (debugLog) console.log("no result slot found"); + return null; + } + + const resultItem = inventoryToCheck[0]; + const itemId = resultItem.blockId; + + if (itemId === -1 || itemId === null || itemId === undefined) { + if (debugLog) console.log("no valid result item"); + return null; + } + + if (debugLog) console.log("found result item:", itemId); + return resultItem; + }; + + const resultItem = checkForResult(); + if (resultItem) { + this.takeCraftedItemAndClear(client, usedGridSlots); + return; + } + + let handledResult = false; + const resultListener = (packet) => { + if (packet.windowId === windowId && packet.slot === 0) { + if (packet.item && packet.item.blockId !== -1) { + if (client.javaClient) { + client.javaClient.removeListener("set_slot", resultListener); + } + + if (!handledResult) { + handledResult = true; + if (debugLog) + console.log("received set_slot for result, taking item"); + setTimeout(() => { + this.takeCraftedItemAndClear(client, usedGridSlots); + }, 50); + } + } + } + }; + + if (client.javaClient) { + client.javaClient.on("set_slot", resultListener); + + setTimeout(() => { + if (client.javaClient) { + client.javaClient.removeListener("set_slot", resultListener); + } + + if (!handledResult) { + const finalCheck = checkForResult(); + if (finalCheck) { + handledResult = true; + this.takeCraftedItemAndClear(client, usedGridSlots); + } else { + client._craftingInProgress = false; + } + } + }, 150); + } + } + + takeCraftedItemAndClear(client, usedGridSlots) { + const debugLog = true; + if (debugLog) console.log("taking crafted item and clearing grid"); + if (!client.javaClient || !client.javaClient.write) { + if (debugLog) console.log("no java client available"); + client._craftingInProgress = false; + return; + } + + if (!client.windowClickAction) { + client.windowClickAction = 1; + } + + const windowId = client.openWindowId || 0; + const isCraftingTable = windowId !== 0; + const inventoryToCheck = + isCraftingTable && + client._windowInventories && + client._windowInventories[windowId] + ? client._windowInventories[windowId] + : client.inventory; + + const resultItem = inventoryToCheck[0]; + if (!resultItem || resultItem.blockId === -1) { + return; + } + + const resultItemId = resultItem.blockId; + const resultCount = resultItem.itemCount || 1; + + const slotsWithSameItem = []; + const slotRange = isCraftingTable ? [10, 46] : [9, 45]; + for (let slot = slotRange[0]; slot < slotRange[1]; slot++) { + const item = inventoryToCheck[slot]; + if (item && item.blockId === resultItemId) { + slotsWithSameItem.push({ + slot: slot, + count: item.itemCount || 1, + hasSpace: (item.itemCount || 1) < 64, + }); + } + } + + const targetSlots = []; + let remainingCount = resultCount; + + for (const slotInfo of slotsWithSameItem) { + if (slotInfo.hasSpace && remainingCount > 0) { + const spaceAvailable = 64 - slotInfo.count; + const amountToPlace = Math.min(spaceAvailable, remainingCount); + targetSlots.push({ slot: slotInfo.slot, amount: amountToPlace }); + remainingCount -= amountToPlace; + } + } + + if (remainingCount > 0) { + const hotbarSlots = isCraftingTable + ? [37, 38, 39, 40, 41, 42, 43, 44, 45] + : [36, 37, 38, 39, 40, 41, 42, 43, 44]; + for (const slot of hotbarSlots) { + if (remainingCount <= 0) break; + const item = inventoryToCheck[slot]; + if (!item || item.blockId === -1) { + const amountToPlace = Math.min(64, remainingCount); + targetSlots.push({ slot: slot, amount: amountToPlace }); + remainingCount -= amountToPlace; + } + } + } + + if (remainingCount > 0) { + const mainInvSlots = isCraftingTable + ? [ + 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, + 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, + ] + : [ + 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, + ]; + for (const slot of mainInvSlots) { + if (remainingCount <= 0) break; + const item = inventoryToCheck[slot]; + if (!item || item.blockId === -1) { + const amountToPlace = Math.min(64, remainingCount); + targetSlots.push({ slot: slot, amount: amountToPlace }); + remainingCount -= amountToPlace; + } + } + } + + setTimeout(() => { + try { + client.javaClient.write("window_click", { + windowId: windowId, + slot: -999, + mouseButton: 0, + action: client.windowClickAction++, + mode: 0, + item: { blockId: -1, itemCount: 0, itemDamage: 0 }, + }); + if (debugLog) console.log("clicked slot -999"); + } catch (err) {} + + setTimeout(() => { + try { + client.javaClient.write("window_click", { + windowId: windowId, + slot: 0, + mouseButton: 0, + action: client.windowClickAction++, + mode: 1, + item: resultItem, + }); + if (debugLog) console.log("shift clicked result"); + } catch (err) { + /* do nothing */ + } + }, 1); + }, 1); + + setTimeout(() => { + setTimeout(() => { + let foundPlanks = false; + for (let i = 9; i < 45; i++) { + const item = client.inventory[i]; + if (item && item.blockId === 5) { + foundPlanks = true; + } + } + + const inventoryToCheck = + windowId !== 0 && + client._windowInventories && + client._windowInventories[windowId] + ? client._windowInventories[windowId] + : client.inventory; + + if (debugLog) console.log("clearing grid slots", usedGridSlots); + usedGridSlots.forEach((gridSlot, index) => { + setTimeout(() => { + const gridItem = inventoryToCheck[gridSlot]; + if (gridItem && gridItem.blockId !== -1) { + try { + client.javaClient.write("window_click", { + windowId: windowId, + slot: gridSlot, + mouseButton: 0, + action: client.windowClickAction++, + mode: 1, + item: gridItem, + }); + if (debugLog) console.log("shift clicked grid", gridSlot); + } catch (err) { + /* do nothing */ + } + } else { + if (debugLog) console.log("grid slot", gridSlot, "already empty"); + } + }, index * 1); + }); + }, 1); + }, 1); + + setTimeout(() => { + if (debugLog) console.log("craft complete clearing flag"); + client._craftingInProgress = false; + }, 200); + } + placeCraftingItems( client, windowId, @@ -2281,7 +3253,23 @@ class LCEProxy { inventoryWindow, startAction, ) { - /* do nothing */ + /* do nothing - but keep this here so nothing breaks */ + } + + sendInventoryUpdate(client) { + if (!client.inventory || !client.javaClient) { + return; + } + + for (let i = 0; i < 45; i++) { + const item = client.inventory[i]; + const PacketWriter = require("./packetwriter"); + const slotWriter = new PacketWriter(); + slotWriter.writeByte(0); + slotWriter.writeShort(i); + this.writeItem(slotWriter, item); + this.sendPacket(client, 0x67, slotWriter.toBuffer()); + } } //LCE automatically accepts a trade, whilst java requires items in specific slots @@ -2319,6 +3307,54 @@ class LCEProxy { const item = this.readItemWithNBT(reader); + if (client._bookGUI && containerId === client.openWindowId) { + if (slotNum === 48 && client._bookGUI.currentPage > 0) { + client._bookGUI.currentPage--; + this.updateBookGUIContents(client, containerId); + return; + } + + if ( + slotNum === 50 && + client._bookGUI.currentPage < client._bookGUI.pages.length - 1 + ) { + client._bookGUI.currentPage++; + this.updateBookGUIContents(client, containerId); + return; + } + + if ( + client._bookGUI.clickActions && + client._bookGUI.clickActions[slotNum] + ) { + const action = client._bookGUI.clickActions[slotNum]; + + if (action.type === "run_command" && action.value) { + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("chat", { message: action.value }); + } catch (err) { + /* do nothing */ + } + } + + const PacketWriter = require("./packetwriter"); + const writer = new PacketWriter(); + writer.writeByte(containerId & 0xff); + this.sendPacket(client, 0x65, writer.toBuffer()); + delete client._bookGUI; + } + } + + const PacketWriter = require("./packetwriter"); + const rejectWriter = new PacketWriter(); + rejectWriter.writeByte(containerId & 0xff); + rejectWriter.writeShort(uid); + rejectWriter.writeBoolean(false); + this.sendPacket(client, 0x6a, rejectWriter.toBuffer()); + return; + } + //0=Normal click //1=Shift click //2=Number key (hotbar swap) @@ -2363,6 +3399,34 @@ class LCEProxy { } } + handleSignUpdate(client, data) { + const reader = new PacketReader(data.slice(1)); + const x = reader.readInt(); + const y = reader.readShort(); + const z = reader.readInt(); + const verified = reader.readBoolean(); + const censored = reader.readBoolean(); + + const text1 = reader.readUtf(); + const text2 = reader.readUtf(); + const text3 = reader.readUtf(); + const text4 = reader.readUtf(); + + if (client.javaClient && client.javaClient.write) { + try { + client.javaClient.write("update_sign", { + location: { x: x, y: y, z: z }, + text1: JSON.stringify({ text: text1 }), + text2: JSON.stringify({ text: text2 }), + text3: JSON.stringify({ text: text3 }), + text4: JSON.stringify({ text: text4 }), + }); + } catch (err) { + /* do nothing */ + } + } + } + handleSetCreativeModeSlot(client, data) { const reader = new PacketReader(data.slice(1)); const slotNum = reader.readShort(); @@ -2750,8 +3814,8 @@ class LCEProxy { this.udpSocket.close(); } - if (this.tcpServer) { - this.tcpServer.close(); + if (this.tcpServers && this.tcpServers.length > 0) { + this.tcpServers.forEach((server) => server.close()); } this.clients.forEach((client) => { diff --git a/src/mappings/blockmapping.js b/src/mappings/blockmapping.js index 97ca210..d2f2732 100644 --- a/src/mappings/blockmapping.js +++ b/src/mappings/blockmapping.js @@ -167,12 +167,18 @@ function createBlockMapping() { 161: 18, 162: 17, 163: 17, + 165: 95, 170: 170, 171: 171, 172: 171, 173: 171, 174: 171, 175: 31, + 193: 64, + 194: 64, + 195: 64, + 196: 64, + 197: 64, }; } diff --git a/src/mappings/entitymapping.js b/src/mappings/entitymapping.js index 45aacfb..0079768 100644 --- a/src/mappings/entitymapping.js +++ b/src/mappings/entitymapping.js @@ -27,6 +27,7 @@ function createEntityTypeMapping() { Sheep: 91, Cow: 92, Chicken: 93, + Rabbit: 93, Squid: 94, Wolf: 95, MushroomCow: 96, diff --git a/src/mappings/itemmapping.js b/src/mappings/itemmapping.js index 1ba7e8f..9da33e4 100644 --- a/src/mappings/itemmapping.js +++ b/src/mappings/itemmapping.js @@ -133,6 +133,8 @@ function createItemMapping() { 383: 383, //spawn_egg 384: 384, //experience_bottle 385: 385, //fire_charge + 386: 340, //writable_book -> book + 387: 340, //written_book -> book 388: 388, //emerald 389: 389, //item_frame 390: 390, //flower_pot @@ -159,6 +161,20 @@ function createItemMapping() { 419: 419, //diamond_horse_armor 420: 420, //lead 421: 421, //name_tag + 423: 363, //raw_mutton -> raw_beef + 424: 364, //cooked_mutton -> cooked_beef + 411: 363, //raw_rabbit -> raw_beef + 412: 364, //cooked_rabbit -> cooked_beef + 413: 282, //rabbit_stew -> mushroom_stew + 414: 371, //rabbit_foot -> gold_nugget + 415: 334, //rabbit_hide -> leather + 165: 95, //slime_block -> lime_stained_glass + 387: 340, //written_book -> book + 427: 324, //spruce_door -> oak_door + 428: 324, //birch_door -> oak_door + 429: 324, //jungle_door -> oak_door + 430: 324, //acacia_door -> oak_door + 431: 324, //dark_oak_door -> oak_door 2256: 2256, //record_13 2257: 2257, //record_cat 2258: 2258, //record_blocks diff --git a/src/mappings/recipemapping.js b/src/mappings/recipemapping.js index 301e3a8..0be98b9 100644 --- a/src/mappings/recipemapping.js +++ b/src/mappings/recipemapping.js @@ -4,7 +4,43 @@ //all of the crafting recipes that are sent from the client converted into a java recipe grid. //this was absolute fucking torture to write, thanks mojang for not using recipe ids in java edition crafting until 1.12! -//unfinised as of 3/9/2026 (MM/DD/YY) +//DO NOT BEAUTIFY THIS FILE!! +//everything should match 1.8 Java IDs except: + //any_plank + //any_slab + //cocoa_beans + //inc_sac + //red_dye + //green_dye + //lapis + //purple_dye + //cyan_dye + //light_gray_dye + //gray_dye + //pink_dye + //lime_dye + //yellow_dye + //light_blue_dye + //magenta_dye + //orange_dye + //bone_meal + //dandelion + //rose + //orange_wool + //magenta_wool + //light_blue_wool + //yellow_wool + //lime_wool + //pink_wool + //gray_wool + //light_gray_wool + //cyan_wool + //purple_wool + //blue_wool + //brown_wool + //green_wool + //red_wool + //black_wool module.exports = { //page 1 @@ -263,7 +299,65 @@ module.exports = { "quartz_block", "quartz_block", "none", "quartz_block", "quartz_block", "quartz_block" ], - //next: slabs + + + + 162: [ + "sandstone", "sandstone", "sandstone", + "none", "none", "none", + "none", "none", "none" + ], + 163: [ + "stone", "stone", "stone", + "none", "none", "none", + "none", "none", "none" + ], + 164: [ + "cobblestone", "cobblestone", "cobblestone", + "none", "none", "none", + "none", "none", "none" + ], + 165: [ + "brick_block", "brick_block", "brick_block", + "none", "none", "none", + "none", "none", "none" + ], + 166: [ + "stone_bricks", "stone_bricks", "stone_bricks", + "none", "none", "none", + "none", "none", "none" + ], + 167: [ + "nether_brick", "nether_brick", "nether_brick", + "none", "none", "none", + "none", "none", "none" + ], + 168: [ + "quartz_block", "quartz_block", "quartz_block", + "none", "none", "none", + "none", "none", "none" + ], + 169: [ + "oak_planks", "oak_planks", "oak_planks", + "none", "none", "none", + "none", "none", "none" + ], + 170: [ + "birch_planks", "birch_planks", "birch_planks", + "none", "none", "none", + "none", "none", "none" + ], + 171: [ + "spruce_planks", "spruce_planks", "spruce_planks", + "none", "none", "none", + "none", "none", "none" + ], + 172: [ + "jungle_planks", "jungle_planks", "jungle_planks", + "none", "none", "none", + "none", "none", "none" + ], + @@ -581,10 +675,881 @@ module.exports = { "none", "none", "none", "none", "none", "none" ], + + + 31: [ "melon", "melon", "melon", "melon", "melon", "melon", "melon", "melon", "melon" ], + + + + 32: [ + "melon", "none", "none", + "none", "none", "none", + "none", "none", "none" + ], + 33: [ + "pumpkin", "none", "none", + "none", "none", "none", + "none", "none", "none" + ], + + + + 34: [ + "pumkpkin", "sugar", "none", + "egg", "none", "none", + "none", "none", "none" + ], + + + + 36: [ + "spider_eye", "brown_mushroom", "none", + "sugar", "none", "none", + "none", "none", "none" + ], + + + + 37: [ + "blaze_rod", "none", "none", + "none", "none", "none", + "none", "none", "none" + ], + + + + 37: [ + "blaze_powder", "slime_ball", "none", + "none", "none", "none", + "none", "none", "none" + ], + + + + 173: [ + "milk_bucket", "milk_bucket", "milk_bucket", + "sugar", "egg", "sugar", + "wheat", "wheat", "wheat" + ], + + + + 174: [ + "sugar", "none", "none", + "none", "none", "none", + "none", "none", "none" + ], + + + + 188: [ + "wheat", "wheat", "wheat", + "none", "none", "none", + "none", "none", "none" + ], + + + + + + + //page 4 + 77: [ + "leather", "leather", "leather", + "leather", "none", "leather", + "none", "none", "none", + ], + 81: [ + "iron_ingot", "iron_ingot", "iron_ingot", + "iron_ingot", "none", "iron_ingot", + "none", "none", "none", + ], + 85: [ + "diamond", "diamond", "diamond", + "diamond", "none", "diamond", + "none", "none", "none", + ], + 89: [ + "gold_ingot", "gold_ingot", "gold_ingot", + "gold_ingot", "none", "gold_ingot", + "none", "none", "none", + ], + + + + 78: [ + "leather", "none", "leather", + "leather", "leather", "leather", + "leather", "leather", "leather", + ], + 82: [ + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "iron_ingot", "iron_ingot", + "iron_ingot", "iron_ingot", "iron_ingot", + ], + 86: [ + "diamond", "none", "diamond", + "diamond", "diamond", "diamond", + "diamond", "diamond", "diamond", + ], + 90: [ + "gold_ingot", "none", "gold_ingot", + "gold_ingot", "gold_ingot", "gold_ingot", + "gold_ingot", "gold_ingot", "gold_ingot", + ], + + + + 79: [ + "leather", "leather", "leather", + "leather", "none", "leather", + "leather", "none", "leather", + ], + 83: [ + "iron_ingot", "iron_ingot", "iron_ingot", + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "none", "iron_ingot", + ], + 87: [ + "diamond", "diamond", "diamond", + "diamond", "none", "diamond", + "diamond", "none", "diamond", + ], + 91: [ + "gold_ingot", "gold_ingot", "gold_ingot", + "gold_ingot", "none", "gold_ingot", + "gold_ingot", "none", "gold_ingot", + ], + + + + 80: [ + "none", "none", "none", + "leather", "none", "leather", + "leather", "none", "leather", + ], + 84: [ + "none", "none", "none", + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "none", "iron_ingot", + ], + 88: [ + "none", "none", "none", + "diamond", "none", "diamond", + "diamond", "none", "diamond", + ], + 92: [ + "none", "none", "none", + "gold_ingot", "none", "gold_ingot", + "gold_ingot", "none", "gold_ingot", + ], + + + + + + + //page 5 + 52: [ + "none", "redstone", "none", + "redstone", "glowstone", "redstone", + "none", "redstone", "none", + ], + + + + 53: [ + "glass", "glass", "glass", + "glass", "nether_star", "glass", + "obsidian", "obsidian", "obsidian", + ], + + + + 204: [ + "stick", "none", "none", + "cobblestone", "none", "none", + "none", "none", "none", + ], + 205: [ + "iron_ingot", "none", "none", + "stick", "none", "none", + "oak_planks", "none", "none", + ], + + + + 206: [ + "redstone", "none", "none", + "stick", "none", "none", + "none", "none", "none", + ], + + + + 207: [ + "redstone_torch", "redstone", "redstone_torch", + "stone", "stone", "stone", + "none", "none", "none", + ], + + + + 208: [ + "none", "redstone_torch", "none", + "redstone_torch", "quartz", "redstone_torch", + "stone", "stone", "stone", + ], + + + + 209: [ + "glass", "glass", "glass", + "quartz", "quartz", "quartz", + "any_slab", "any_slab", "any_slab", + ], + + + + 210: [ + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "chest", "iron_ingot", + "none", "iron_ingot", "none", + ], + + + + 224: [ + "cobblestone", "cobblestone", "cobblestone", + "cobblestone", "bow", "cobblestone", + "cobblestone", "redstone", "cobblestone", + ], + 225: [ + "cobblestone", "cobblestone", "cobblestone", + "cobblestone", "none", "cobblestone", + "cobblestone", "redstone", "cobblestone", + ], + + + + 218: [ + "stone", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 219: [ + "any_plank", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + + + + 220: [ + "any_plank", "any_plank", "none", + "none", "none", "none", + "none", "none", "none", + ], + 221: [ + "stone", "stone", "none", + "none", "none", "none", + "none", "none", "none", + ], + 222: [ + "iron_ingot", "iron_ingot", "none", + "none", "none", "none", + "none", "none", "none", + ], + 223: [ + "gold_ingot", "gold_ingot", "none", + "none", "none", "none", + "none", "none", "none", + ], + + + + 232: [ + "any_plank", "any_plank", "any_plank", + "any_plank", "redstone", "any_plank", + "any_plank", "any_plank", "any_plank", + ], + + + + 255: [ + "any_plank", "any_plank", "any_plank", + "cobblestone", "iron_ingot", "cobblestone", + "cobblestone", "redstone", "cobblestone", + ], + 256: [ + "slime_ball", "none", "none", + "piston", "none", "none", + "none", "none", "none", + ], + + + + + + + //page 6 + 175: [ + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "stick", "iron_ingot", + "iron_ingot", "none", "iron_ingot", + ], + 176: [ + "gold_ingot", "none", "gold_ingot", + "gold_ingot", "stick", "gold_ingot", + "gold_ingot", "redstone", "gold_ingot", + ], + 178: [ + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "stone_pressure_plate", "iron_ingot", + "iron_ingot", "redstone", "iron_ingot", + ], + + + + 177: [ + "iron_ingot", "stick", "iron_ingot", + "iron_ingot", "redstone_torch", "iron_ingot", + "iron_ingot", "stick", "iron_ingot", + ], + + + + 179: [ + "iron_ingot", "none", "iron_ingot", + "iron_ingot", "iron_ingot", "iron_ingot", + "none", "none", "none", + ], + + + + 180: [ + "chest", "none", "none", + "minecart", "none", "none", + "none", "none", "none", + ], + + + + 181: [ + "furnace", "none", "none", + "minecart", "none", "none", + "none", "none", "none", + ], + + + + 182: [ + "tnt", "none", "none", + "minecart", "none", "none", + "none", "none", "none", + ], + + + + 184: [ + "any_plank", "none", "any_plank", + "any_plank", "any_plank", "any_plank", + "none", "none", "none", + ], + + + + + + + //page 7 + 50: [ + "glass", "glass", "glass", + "glass", "glass", "glass", + "none", "none", "none", + ], + + + + 93: [ + "inc_sac", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 95: [ + "red_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 97: [ + "green_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 99: [ + "cocoa_beans", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 101: [ + "lapis", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 103: [ + "purple_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 105: [ + "cyan_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 105: [ + "cyan_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 107: [ + "light_gray_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 107: [ + "gray_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 111: [ + "pink_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 113: [ + "lime_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 115: [ + "yellow_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 117: [ + "light_blue_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 119: [ + "magenta_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 121: [ + "orange_dye", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 123: [ + "bone_meal", "wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 160: [ + "string", "string", "none", + "string", "string", "none", + "none", "none", "none", + ], + + + + 94: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "inc_sac", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 96: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "red_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 98: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "green_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 100: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "cocoa_beans", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 102: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "lapis", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 104: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "purple_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 106: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "cyan_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 108: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "light_gray_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 110: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "gray_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 112: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "pink_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 114: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "lime_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 116: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "yellow_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 118: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "light_blue_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 120: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "magenta_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 122: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "orange_dye", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + 124: [ + "hardened_clay", "hardened_clay", "hardened_clay", + "hardened_clay", "bone_meal", "hardened_clay", + "hardened_clay", "hardened_clay", "hardened_clay", + ], + + + + 125: [ + "dandelion", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 126: [ + "rose", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 127: [ + "bone", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 128: [ + "red_dye", "bone_meal", "none", + "none", "none", "none", + "none", "none", "none", + ], + 129: [ + "red_dye", "yellow_dye", "none", + "none", "none", "none", + "none", "none", "none", + ], + 130: [ + "green_dye", "bone_meal", "none", + "none", "none", "none", + "none", "none", "none", + ], + 131: [ + "inc_sac", "bone_meal", "none", + "none", "none", "none", + "none", "none", "none", + ], + 132: [ + "gray_dye", "bone_meal", "none", + "none", "none", "none", + "none", "none", "none", + ], + 133: [ + "light_gray_dye", "bone_meal", "none", + "bone_meal", "none", "none", + "none", "none", "none", + ], + 134: [ + "lapis", "bone_meal", "none", + "none", "none", "none", + "none", "none", "none", + ], + 135: [ + "lapis", "green_dye", "none", + "none", "none", "none", + "none", "none", "none", + ], + 136: [ + "lapis", "red_dye", "none", + "none", "none", "none", + "none", "none", "none", + ], + 137: [ + "purple_dye", "pink_dye", "none", + "none", "none", "none", + "none", "none", "none", + ], + 138: [ + "lapis", "red_dye", "none", + "pink_dye", "none", "none", + "none", "none", "none", + ], + 139: [ + "lapis", "red_dye", "none", + "red_dye", "bone_meal", "none", + "none", "none", "none", + ], + 245: [ + "lapis_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + + + + 140: [ + "wool", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 141: [ + "orange_wool", "orange_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 142: [ + "magenta_wool", "magenta_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 143: [ + "light_blue_wool", "light_blue_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 144: [ + "yellow_wool", "yellow_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 145: [ + "lime_wool", "lime_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 146: [ + "pink_wool", "pink_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 147: [ + "gray_wool", "gray_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 148: [ + "light_gray_wool", "light_gray_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 149: [ + "cyan_wool", "cyan_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 150: [ + "purple_wool", "purple_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 151: [ + "blue_wool", "blue_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 152: [ + "brown_wool", "brown_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 153: [ + "green_wool", "green_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 154: [ + "red_wool", "red_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + 155: [ + "black_wool", "black_wool", "none", + "none", "none", "none", + "none", "none", "none", + ], + + + + 199: [ + "brick", "none", "brick", + "none", "brick", "none", + "none", "none", "none", + ], + + + + 229: [ + "any_plank", "any_plank", "any_plank", + "any_plank", "diamond", "any_plank", + "any_plank", "any_plank", "any_plank", + ], + + + + 230: [ + "paper", "paper", "none", + "paper", "leather", "none", + "none", "none", "none", + ], + 231: [ + "sugar_cane", "sugar_cane", "sugar_cane", + "none", "none", "none", + "none", "none", "none", + ], + 233: [ + "any_plank", "any_plank", "any_plank", + "book", "book", "book", + "any_plank", "any_plank", "any_plank", + ], + + + + 234: [ + "stick", "stick", "stick", + "stick", "any_wool", "stick", + "stick", "stick", "stick", + ], + 235: [ + "stick", "stick", "stick", + "stick", "leather", "stick", + "stick", "stick", "stick", + ], + 254: [ + "any_plank", "any_plank", "any_plank", + "any_plank", "any_plank", "any_plank", + "none", "stick", "none", + ], + + + + 236: [ + "gold_ingot", "gold_ingot", "gold_ingot", + "gold_ingot", "gold_ingot", "gold_ingot", + "gold_ingot", "gold_ingot", "gold_ingot", + ], + 238: [ + "iron_ingot", "iron_ingot", "iron_ingot", + "iron_ingot", "iron_ingot", "iron_ingot", + "iron_ingot", "iron_ingot", "iron_ingot", + ], + 240: [ + "diamond", "diamond", "diamond", + "diamond", "diamond", "diamond", + "diamond", "diamond", "diamond", + ], + 242: [ + "emerald", "emerald", "emerald", + "emerald", "emerald", "emerald", + "emerald", "emerald", "emerald", + ], + 244: [ + "lapis", "lapis", "lapis", + "lapis", "lapis", "lapis", + "lapis", "lapis", "none", + ], + 246: [ + "redstone", "redstone", "redstone", + "redstone", "redstone", "redstone", + "redstone", "redstone", "redstone", + ], + 248: [ + "coal", "coal", "coal", + "coal", "coal", "coal", + "coal", "coal", "coal", + ], + 250: [ + "wheat", "wheat", "wheat", + "wheat", "wheat", "wheat", + "wheat", "wheat", "wheat", + ], + + + + 237: [ + "gold_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 239: [ + "iron_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 241: [ + "diamond_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 243: [ + "emerald_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 247: [ + "redstone_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + 251: [ + "hay_block", "none", "none", + "none", "none", "none", + "none", "none", "none", + ], + + + + 257: [ + "none", "paper", "none", + "none", "gunpowder", "none", + "none", "none", "none", + ], }; /* --------------------------------------------------------------- */ diff --git a/src/packetreader.js b/src/packetreader.js index e75da1c..0ad07d9 100644 --- a/src/packetreader.js +++ b/src/packetreader.js @@ -58,6 +58,17 @@ class PacketReader { return str; } + readUtf() { + const length = this.readShort(); + let str = ""; + for (let i = 0; i < length; i++) { + const charCode = this.buffer.readUInt16BE(this.offset); + this.offset += 2; + str += String.fromCharCode(charCode); + } + return str; + } + readDouble() { const value = this.buffer.readDoubleBE(this.offset); this.offset += 8; diff --git a/src/packets/senders/containerpackets.js b/src/packets/senders/containerpackets.js index 9f67591..23abc08 100644 --- a/src/packets/senders/containerpackets.js +++ b/src/packets/senders/containerpackets.js @@ -23,9 +23,21 @@ function sendContainerOpenPacket(proxy, client, packet) { const windowType = packet.inventoryType || packet.windowType; const lceType = windowTypeMapping[windowType] || 0; const containerId = packet.windowId; - const title = packet.windowTitle - ? JSON.parse(packet.windowTitle).text || "" - : ""; + + let title = ""; + if (packet.windowTitle) { + try { + const parsed = JSON.parse(packet.windowTitle); + if (parsed.extra && parsed.extra.length > 0 && parsed.extra[0].text) { + title = parsed.extra[0].text; + } else if (parsed.text) { + title = parsed.text; + } + } catch (err) { + title = packet.windowTitle; + } + } + const size = packet.slotCount || 27; const customName = title.length > 0; @@ -44,7 +56,11 @@ function sendContainerOpenPacket(proxy, client, packet) { writer.writeUtf(title); } - proxy.sendPacket(client, 0x64, writer.toBuffer()); + const buffer = writer.toBuffer(); + const sendTime = Date.now(); + + client._lastContainerOpenTime = sendTime; + proxy.sendPacket(client, 0x64, buffer); } function sendVillagerTrades(proxy, client, windowId, packetData) { diff --git a/src/packets/senders/entitypackets.js b/src/packets/senders/entitypackets.js index bb53d2a..520ed9a 100644 --- a/src/packets/senders/entitypackets.js +++ b/src/packets/senders/entitypackets.js @@ -336,16 +336,9 @@ function sendEntityMetadataPacket(proxy, client, entity, metadata) { for (const item of metadata) { if (!item || item.type === undefined || item.key === undefined) { - console.error( - `[METADATA ERROR] entityId=${entity.entityId} invalid metadata item:`, - JSON.stringify(item), - ); continue; } if (item.type < 0 || item.type > 5) { - console.error( - `[METADATA ERROR] entityId=${entity.entityId} invalid type=${item.type} key=${item.key}`, - ); continue; } if (item.type === 5) { @@ -471,10 +464,27 @@ function sendSetEquippedItemPacket(proxy, client, entity, slot, item) { return; } - const javaItemId = item.blockId; + let javaItemId = item.blockId; const count = item.itemCount || 1; let damage = item.itemDamage || 0; + if (javaItemId === 162) { + javaItemId = 35; + damage = 1; + } + + if (javaItemId === 5 && (damage === 4 || damage === 5)) { + damage = 0; + } + + if (javaItemId === 383 && damage === 101) { + damage = 93; + } + + if (javaItemId === 165) { + damage = 5; + } + const lceItemId = proxy.mapJavaItemToLCE(javaItemId); if (lceItemId === 1 && javaItemId !== 1) { @@ -502,7 +512,7 @@ function sendSetEquippedItemPacket(proxy, client, entity, slot, item) { return; } - writer.writeShort(-1); + proxy.writeItemNBT(writer, item); proxy.sendPacket(client, 0x05, writer.toBuffer()); } @@ -554,7 +564,27 @@ function sendTileUpdatePacket(proxy, client, x, y, z, blockId, metadata) { } function sendSetItemDataPacket(proxy, client, entity, itemData) { - const lceItemId = proxy.mapJavaItemToLCE(itemData.blockId); + let damage = itemData.itemDamage || 0; + let javaItemId = itemData.blockId; + + if (javaItemId === 162) { + javaItemId = 35; + damage = 1; + } + + if (javaItemId === 5 && (damage === 4 || damage === 5)) { + damage = 0; + } + + if (javaItemId === 383 && damage === 101) { + damage = 93; + } + + if (javaItemId === 165) { + damage = 5; + } + + const lceItemId = proxy.mapJavaItemToLCE(javaItemId); if (lceItemId === -1 || lceItemId === 0) { return; @@ -567,9 +597,26 @@ function sendSetItemDataPacket(proxy, client, entity, itemData) { writer.writeShort(lceItemId); writer.writeByte(itemData.itemCount); - writer.writeShort(itemData.itemDamage); + writer.writeShort(damage); - writer.writeShort(-1); + proxy.writeItemNBT(writer, itemData); + + writer.writeByte(0x7f); + + const payload = writer.toBuffer(); + + proxy.sendPacket(client, 0x28, payload); +} + +function sendSetItemFrameDataPacket(proxy, client, entity, itemData, rotation) { + const writer = new PacketWriter(); + writer.writeInt(entity.entityId); + + writer.writeByte((5 << 5) | 2); + proxy.writeItem(writer, itemData); + + writer.writeByte((0 << 5) | 3); + writer.writeByte(rotation & 0xff); writer.writeByte(0x7f); @@ -642,6 +689,7 @@ module.exports = { sendEntityEventPacket, sendSetEquippedItemPacket, sendSetItemDataPacket, + sendSetItemFrameDataPacket, sendSetEntityDataPacket, sendUpdateAttributesPacket, sendSetEntityLinkPacket, diff --git a/src/packetwriter.js b/src/packetwriter.js index 82a3a2d..9a8dec0 100644 --- a/src/packetwriter.js +++ b/src/packetwriter.js @@ -64,6 +64,15 @@ class PacketWriter { this.buffers.push(utf8Buffer); } + writeUtf(str) { + this.writeShort(str.length); + for (let i = 0; i < str.length; i++) { + const buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(str.charCodeAt(i), 0); + this.buffers.push(buf); + } + } + writeString(str) { this.writeShort(str.length); for (let i = 0; i < str.length; i++) { diff --git a/src/utils/items.js b/src/utils/items.js index 2136e28..3768437 100644 --- a/src/utils/items.js +++ b/src/utils/items.js @@ -67,8 +67,52 @@ function readItem(reader) { } function writeItemNBT(writer, item) { - writer.writeShort(-1); - return; + if (!item || (!item.displayName && !item.enchanted)) { + writer.writeShort(-1); + return; + } + + try { + const nbt = require("prismarine-nbt"); + + const nbtValue = {}; + + if (item.displayName && item.displayName.length > 0) { + const cleanedName = item.displayName.replace(/§[0-9a-fk-or]/gi, ""); + nbtValue.display = { + type: "compound", + value: { + Name: { + type: "string", + value: cleanedName, + }, + }, + }; + } + + if (item.enchanted) { + nbtValue.ench = { + type: "list", + value: { + type: "compound", + value: [], + }, + }; + } + + const nbtData = { + type: "compound", + name: "", + value: nbtValue, + }; + + const nbtBuffer = nbt.writeUncompressed(nbtData, "big"); + + writer.writeShort(nbtBuffer.length); + writer.writeBytes(nbtBuffer); + } catch (err) { + writer.writeShort(-1); + } } function writeItem(writer, item, mapJavaItemToLCE) { @@ -94,10 +138,76 @@ function writeItem(writer, item, mapJavaItemToLCE) { return; } - let lceItemId = mapJavaItemToLCE(javaItemId); let auxValue = item.itemDamage !== undefined ? item.itemDamage : item.metadata || 0; + if (javaItemId === 162) { + javaItemId = 35; + auxValue = 1; + if (!item.displayName) { + item.displayName = "Acacia Wood"; + } + } + + let lceItemId = mapJavaItemToLCE(javaItemId); + + if (javaItemId === 5 && auxValue === 4) { + auxValue = 0; + if (!item.displayName) { + item.displayName = "Acacia Wood Planks"; + } + } + + if (javaItemId === 5 && auxValue === 5) { + auxValue = 0; + if (!item.displayName) { + item.displayName = "Dark Oak Wood Planks"; + } + } + + if (javaItemId === 383 && auxValue === 101) { + auxValue = 93; + if (!item.displayName) { + item.displayName = "Rabbit Spawn Egg"; + } + } + + const customItemNames = { + 386: "Book and Quill", + 427: "Spruce Door", + 428: "Birch Door", + 429: "Jungle Door", + 430: "Acacia Door", + 431: "Dark Oak Door", + 423: "Raw Mutton", + 424: "Cooked Mutton", + 411: "Raw Rabbit", + 412: "Cooked Rabbit", + 413: "Rabbit Stew", + 414: "Rabbit Foot", + 415: "Rabbit Hide", + 165: "Slime Block", + }; + + if (customItemNames[javaItemId] && !item.displayName) { + item.displayName = customItemNames[javaItemId]; + } + + if (javaItemId === 165) { + auxValue = 5; + } + + if (javaItemId === 387) { + let authorName = "Unknown"; + if (item.nbtData && item.nbtData.value && item.nbtData.value.author) { + authorName = item.nbtData.value.author.value || "Unknown"; + } + if (!item.displayName) { + item.displayName = `Written Book (by ${authorName})`; + } + item.enchanted = true; + } + if ( lceItemId === undefined || lceItemId === null || diff --git a/src/utils/skins.js b/src/utils/skins.js index a05e07a..fbede0b 100644 --- a/src/utils/skins.js +++ b/src/utils/skins.js @@ -111,9 +111,49 @@ function generateCustomSkinName(playerName) { return `ugcskin${skinId.toString(16).toUpperCase().padStart(8, "0")}.png`; } +function generateCustomCapeName(playerName) { + let hash = 0; + for (let i = 0; i < playerName.length; i++) { + hash = (hash << 5) - hash + playerName.charCodeAt(i); + hash = hash & hash; + } + const capeId = (Math.abs(hash) & 0x7fffffe0) | 0x20; + return `ugccape${capeId.toString(16).toUpperCase().padStart(8, "0")}.png`; +} + +function downloadCape(url) { + return new Promise((resolve, reject) => { + if (skinCache.has(url)) { + resolve(skinCache.get(url)); + return; + } + + const protocol = url.startsWith("https") ? https : http; + + protocol + .get(url, (res) => { + if (res.statusCode !== 200) { + reject(new Error(`HTTP ${res.statusCode}`)); + return; + } + + const chunks = []; + res.on("data", (chunk) => chunks.push(chunk)); + res.on("end", () => { + const capeData = Buffer.concat(chunks); + skinCache.set(url, capeData); + resolve(capeData); + }); + }) + .on("error", reject); + }); +} + module.exports = { downloadSkin, + downloadCape, generateCustomSkinName, + generateCustomCapeName, skinCache, }; /* --------------------------------------------------------------- */