1329 lines
49 KiB
Python
1329 lines
49 KiB
Python
"""Incremental protocol support for Java Edition 26.3 (protocol 777).
|
|
|
|
Implemented paths cover offline login/configuration, AuthMe dialogs, chat,
|
|
world/chunk state, basic entity and inventory updates, keepalive, teleports,
|
|
and player movement. Legacy gameplay interactions remain a separate porting
|
|
stage.
|
|
"""
|
|
import io
|
|
import json
|
|
import os
|
|
import struct
|
|
|
|
from minecraft.networking.packets import Packet
|
|
from minecraft.networking.types import (
|
|
Boolean, Byte, Double, Float, Integer, Long, Position, Short, String,
|
|
TrailingByteArray, Type, UUID, UnsignedByte, UnsignedLong, VarInt, VarLong,
|
|
)
|
|
from minecraft.networking.connection import PacketReactor
|
|
|
|
|
|
def trace(message):
|
|
if os.getenv('PYCRAFT_TRACE'):
|
|
print('[pyCraft/777] ' + message, flush=True)
|
|
|
|
|
|
def read_signed_varint(file_object):
|
|
value = VarInt.read(file_object)
|
|
return value - (1 << 32) if value & (1 << 31) else value
|
|
|
|
|
|
def sign_extend(value, bits):
|
|
sign_bit = 1 << (bits - 1)
|
|
return value - (1 << bits) if value & sign_bit else value
|
|
|
|
|
|
def nbt_plain(value):
|
|
raw = getattr(value, 'value', value)
|
|
if hasattr(raw, 'items'):
|
|
return {str(k): nbt_plain(v) for k, v in raw.items()}
|
|
if isinstance(raw, (list, tuple)):
|
|
return [nbt_plain(v) for v in raw]
|
|
return raw
|
|
|
|
|
|
def read_lp_vec3(file_object):
|
|
"""Decode Mojang's compact LpVec3 representation."""
|
|
low = file_object.read(1)
|
|
if not low:
|
|
raise EOFError('truncated LpVec3')
|
|
low = low[0]
|
|
if low == 0:
|
|
return (0.0, 0.0, 0.0)
|
|
middle = file_object.read(1)
|
|
high = file_object.read(4)
|
|
if len(middle) != 1 or len(high) != 4:
|
|
raise EOFError('truncated LpVec3')
|
|
buffer = (struct.unpack('>I', high)[0] << 16) | (middle[0] << 8) | low
|
|
scale = low & 3
|
|
if low & 4:
|
|
scale |= VarInt.read(file_object) << 2
|
|
|
|
def unpack(value):
|
|
value = min(value & 0x7fff, 32766)
|
|
return (value * 2.0 / 32766.0 - 1.0) * scale
|
|
|
|
return (unpack(buffer >> 3), unpack(buffer >> 18),
|
|
unpack(buffer >> 33))
|
|
|
|
|
|
def read_anonymous_nbt(file_object):
|
|
import functools
|
|
import pynbt
|
|
|
|
stream = getattr(file_object, 'bytes', file_object)
|
|
start = stream.tell()
|
|
raw = stream.read()
|
|
if not raw:
|
|
return None
|
|
wrapped = io.BytesIO(raw)
|
|
tag_id = wrapped.read(1)[0]
|
|
if tag_id == 0:
|
|
consumed = 1
|
|
result = None
|
|
else:
|
|
reader = functools.partial(pynbt._read_big, wrapped)
|
|
reader.src = wrapped
|
|
result = pynbt._tags[tag_id].read(reader, has_name=False)
|
|
consumed = wrapped.tell()
|
|
stream.seek(start + consumed)
|
|
return result
|
|
|
|
|
|
class LoginSuccess(Packet):
|
|
id = 0x02
|
|
packet_name = "login success"
|
|
definition = [{'uuid': UUID}, {'username': String}]
|
|
|
|
|
|
class LoginAcknowledged(Packet):
|
|
id = 0x03
|
|
packet_name = "login acknowledged"
|
|
definition = []
|
|
|
|
|
|
class ClientSettings(Packet):
|
|
id = 0x00
|
|
packet_name = "client settings"
|
|
definition = [
|
|
{'locale': String}, {'view_distance': Byte}, {'chat_flags': VarInt},
|
|
{'chat_colors': Boolean}, {'skin_parts': UnsignedByte},
|
|
{'main_hand': VarInt}, {'enable_text_filtering': Boolean},
|
|
{'enable_server_listing': Boolean}, {'particle_status': VarInt},
|
|
]
|
|
|
|
|
|
class CodeOfConduct(Packet):
|
|
id = 0x13
|
|
packet_name = "code of conduct"
|
|
|
|
def read(self, file_object):
|
|
self.payload = file_object.read()
|
|
try:
|
|
self.dialog = read_anonymous_nbt(io.BytesIO(self.payload))
|
|
self.dialog_text = json.dumps(nbt_plain(self.dialog),
|
|
ensure_ascii=False)
|
|
except Exception as exc:
|
|
self.dialog_text = 'could not decode ({})'.format(exc)
|
|
|
|
|
|
class RegistryData(Packet):
|
|
id = 0x07
|
|
packet_name = "registry data"
|
|
|
|
def read(self, file_object):
|
|
self.registry = String.read(file_object)
|
|
self.entries = []
|
|
for _ in range(VarInt.read(file_object)):
|
|
key = String.read(file_object)
|
|
value = AnonymousNBT.read(file_object) if Boolean.read(file_object) else None
|
|
self.entries.append((key, nbt_plain(value) if value is not None else None))
|
|
|
|
|
|
class ConfigurationCustomPayload(Packet):
|
|
id = 0x01
|
|
packet_name = "configuration custom payload"
|
|
definition = [{'channel': String}, {'data': TrailingByteArray}]
|
|
|
|
|
|
class FinishConfiguration(Packet):
|
|
id = 0x03
|
|
packet_name = "finish configuration"
|
|
definition = []
|
|
|
|
|
|
class ConfigurationKeepAlive(Packet):
|
|
id = 0x04
|
|
packet_name = "keep alive"
|
|
definition = [{'keep_alive_id': Long}]
|
|
|
|
|
|
class SelectKnownPacks(Packet):
|
|
id = 0x0F
|
|
packet_name = "select known packs"
|
|
|
|
def read(self, file_object):
|
|
self.packs = []
|
|
for _ in range(VarInt.read(file_object)):
|
|
self.packs.append((String.read(file_object), String.read(file_object),
|
|
String.read(file_object)))
|
|
|
|
|
|
class KnownPacksResponse(Packet):
|
|
id = 0x07
|
|
packet_name = "select known packs response"
|
|
|
|
def write_fields(self, packet_buffer):
|
|
packs = getattr(self, 'packs', ())
|
|
VarInt.send(len(packs), packet_buffer)
|
|
for namespace, pack_id, version in packs:
|
|
String.send(namespace, packet_buffer)
|
|
String.send(pack_id, packet_buffer)
|
|
String.send(version, packet_buffer)
|
|
|
|
|
|
class PlayerLoaded(Packet):
|
|
id = 0x2C
|
|
packet_name = "player loaded"
|
|
definition = []
|
|
|
|
|
|
class EntityAnimationPacket(Packet):
|
|
"""Legacy clientbound entity animation event."""
|
|
id = 0x02
|
|
packet_name = "entity animation"
|
|
definition = [{'entity_id': VarInt}, {'animation': UnsignedByte}]
|
|
|
|
|
|
class EntitySwingAnimationPacket(Packet):
|
|
"""26.3 item-aware swing animation sent to tracking clients."""
|
|
id = 0x7B
|
|
packet_name = "entity swing animation"
|
|
definition = [
|
|
{'entity_id': VarInt}, {'hand': VarInt},
|
|
{'animation_type': VarInt}, {'duration': VarInt},
|
|
]
|
|
|
|
|
|
class PaletteSection:
|
|
"""Decoded paletted container for a 26.3 chunk section."""
|
|
def __init__(self, bits, palette, words, size):
|
|
self.bits = bits
|
|
self.palette = palette
|
|
self.words = words
|
|
self.size = size
|
|
self.overrides = {}
|
|
self.mask = (1 << bits) - 1 if bits else 0
|
|
self.per_word = 64 // bits if bits else 0
|
|
|
|
def get(self, index):
|
|
if index in self.overrides:
|
|
return self.overrides[index]
|
|
if self.bits == 0:
|
|
return self.palette[0]
|
|
word = self.words[index // self.per_word]
|
|
palette_index = (word >> ((index % self.per_word) * self.bits)) & self.mask
|
|
return self.palette[palette_index] if self.palette is not None else palette_index
|
|
|
|
def set(self, index, value):
|
|
self.overrides[index] = value
|
|
|
|
|
|
def read_palette_container(stream, *, size, local_bits_max):
|
|
bits = Byte.read(stream)
|
|
if bits == 0:
|
|
palette = [VarInt.read(stream)]
|
|
elif bits <= local_bits_max:
|
|
palette_size = VarInt.read(stream)
|
|
palette = [VarInt.read(stream) for _ in range(palette_size)]
|
|
else:
|
|
palette = None
|
|
word_count = ((size + (64 // bits) - 1) // (64 // bits)) if bits else 0
|
|
words = [UnsignedLong.read(stream) for _ in range(word_count)]
|
|
return PaletteSection(bits, palette, words, size)
|
|
|
|
|
|
def decode_chunk_sections(data):
|
|
stream = io.BytesIO(data)
|
|
sections = []
|
|
while stream.tell() < len(data):
|
|
start = stream.tell()
|
|
if len(data) - start < 4:
|
|
raise ValueError('truncated chunk section header at byte {}'.format(start))
|
|
non_empty_blocks = Short.read(stream)
|
|
fluid_count = Short.read(stream)
|
|
blocks = read_palette_container(stream, size=4096, local_bits_max=8)
|
|
biomes = read_palette_container(stream, size=64, local_bits_max=3)
|
|
sections.append({
|
|
'non_empty_blocks': non_empty_blocks,
|
|
'fluid_count': fluid_count,
|
|
'blocks': blocks,
|
|
'biomes': biomes,
|
|
})
|
|
if stream.tell() <= start:
|
|
raise ValueError('chunk section decoder made no progress')
|
|
return sections
|
|
|
|
|
|
class ChunkBatchReceived(Packet):
|
|
id = 0x0B
|
|
packet_name = "chunk batch received"
|
|
definition = [{'desired_chunks_per_tick': Float}]
|
|
|
|
|
|
class ClientboundChunkBatchFinished(Packet):
|
|
id = 0x0B
|
|
packet_name = "chunk batch finished"
|
|
definition = [{'batch_size': VarInt}]
|
|
|
|
|
|
class ChunkDataPacket(Packet):
|
|
id = 0x2E
|
|
packet_name = "chunk data"
|
|
|
|
def read(self, file_object):
|
|
self.x = Integer.read(file_object)
|
|
self.z = Integer.read(file_object)
|
|
self.heightmaps = {}
|
|
for _ in range(VarInt.read(file_object)):
|
|
key = VarInt.read(file_object)
|
|
self.heightmaps[key] = [
|
|
Long.read(file_object) for _ in range(VarInt.read(file_object))
|
|
]
|
|
data_size = VarInt.read(file_object)
|
|
self.data = file_object.read(data_size)
|
|
self.sections = decode_chunk_sections(self.data)
|
|
self.block_entities = []
|
|
for _ in range(VarInt.read(file_object)):
|
|
packed_xz = UnsignedByte.read(file_object)
|
|
y = Short.read(file_object)
|
|
block_entity_type = VarInt.read(file_object)
|
|
data = nbt_plain(read_anonymous_nbt(file_object))
|
|
self.block_entities.append({
|
|
'x': self.x * 16 + (packed_xz >> 4),
|
|
'y': y,
|
|
'z': self.z * 16 + (packed_xz & 0x0F),
|
|
'type': block_entity_type,
|
|
'data': data,
|
|
})
|
|
|
|
|
|
class BlockEntityDataPacket(Packet):
|
|
id = 0x06
|
|
packet_name = "block entity data"
|
|
|
|
def read(self, file_object):
|
|
self.location = Position.read_with_context(file_object, self.context)
|
|
self.block_entity_type = VarInt.read(file_object)
|
|
self.data = nbt_plain(read_anonymous_nbt(file_object))
|
|
|
|
|
|
class BlockEventPacket(Packet):
|
|
"""Clientbound block event (chest viewer-count updates, etc.)."""
|
|
id = 0x07
|
|
packet_name = "block event"
|
|
|
|
def read(self, file_object):
|
|
self.location = Position.read_with_context(file_object, self.context)
|
|
self.action = UnsignedByte.read(file_object)
|
|
self.parameter = UnsignedByte.read(file_object)
|
|
self.block_id = VarInt.read(file_object)
|
|
|
|
|
|
class BlockUpdatePacket(Packet):
|
|
id = 0x08
|
|
packet_name = "block update"
|
|
definition = [{'location': Position}, {'block_state_id': VarInt}]
|
|
|
|
|
|
class SectionBlocksUpdatePacket(Packet):
|
|
id = 0x56
|
|
packet_name = "section blocks update"
|
|
|
|
def read(self, file_object):
|
|
packed_section = Long.read(file_object)
|
|
section_x = sign_extend((packed_section >> 42) & 0x3fffff, 22)
|
|
section_z = sign_extend((packed_section >> 20) & 0x3fffff, 22)
|
|
section_y = sign_extend(packed_section & 0xfffff, 20)
|
|
self.changes = []
|
|
for _ in range(VarInt.read(file_object)):
|
|
packed_change = VarLong.read(file_object)
|
|
local = packed_change & 0xFFF
|
|
# Multi-block records pack local coordinates as x:z:y, unlike
|
|
# the x:y:z order used by the chunk-array linear index.
|
|
x = (section_x << 4) + ((local >> 8) & 0xF)
|
|
z = (section_z << 4) + ((local >> 4) & 0xF)
|
|
y = (section_y << 4) + (local & 0xF)
|
|
self.changes.append((x, y, z, packed_change >> 12))
|
|
|
|
|
|
def _read_vec_delta(file_object, step_count):
|
|
from minecraft.networking.types import Short
|
|
if step_count > 1024:
|
|
raise ValueError('entity movement step count too large: {}'.format(step_count))
|
|
deltas = []
|
|
for _ in range(max(1, step_count)):
|
|
if step_count:
|
|
VarInt.read(file_object) # interpolation tick offset
|
|
deltas.append((Short.read(file_object), Short.read(file_object),
|
|
Short.read(file_object)))
|
|
return tuple(sum(delta[i] for delta in deltas) / 4096.0
|
|
for i in range(3))
|
|
|
|
|
|
class AddEntityPacket(Packet):
|
|
id = 0x01
|
|
packet_name = "add entity"
|
|
|
|
def read(self, file_object):
|
|
self.entity_id = VarInt.read(file_object)
|
|
self.entity_uuid = UUID.read(file_object)
|
|
self.entity_type_id = VarInt.read(file_object)
|
|
self.x, self.y, self.z = (Double.read(file_object),
|
|
Double.read(file_object),
|
|
Double.read(file_object))
|
|
self.velocity_x, self.velocity_y, self.velocity_z = read_lp_vec3(file_object)
|
|
self.pitch = Byte.read(file_object) * (360.0 / 256.0)
|
|
self.yaw = Byte.read(file_object) * (360.0 / 256.0)
|
|
self.head_yaw = Byte.read(file_object) * (360.0 / 256.0)
|
|
self.data = VarInt.read(file_object)
|
|
|
|
|
|
class SetEntityDataPacket(Packet):
|
|
"""Decode entity metadata values needed to identify dropped item stacks."""
|
|
id = 0x65
|
|
packet_name = "set entity data"
|
|
|
|
def read(self, file_object):
|
|
self.entity_id = VarInt.read(file_object)
|
|
self.metadata = []
|
|
self.item_stacks = []
|
|
for _ in range(256):
|
|
index = UnsignedByte.read(file_object)
|
|
if index == 0xFF:
|
|
return
|
|
serializer_id = VarInt.read(file_object)
|
|
if serializer_id == 0:
|
|
value = Byte.read(file_object)
|
|
elif serializer_id == 1:
|
|
value = VarInt.read(file_object)
|
|
elif serializer_id == 2:
|
|
value = VarLong.read(file_object)
|
|
elif serializer_id == 3:
|
|
value = Float.read(file_object)
|
|
elif serializer_id == 4:
|
|
value = String.read(file_object)
|
|
elif serializer_id == 5:
|
|
value = read_anonymous_nbt(file_object)
|
|
elif serializer_id == 6:
|
|
value = (read_anonymous_nbt(file_object)
|
|
if Boolean.read(file_object) else None)
|
|
elif serializer_id == 7:
|
|
value = read_item_stack(file_object, self.context)
|
|
self.item_stacks.append(value)
|
|
elif serializer_id == 8:
|
|
value = Boolean.read(file_object)
|
|
else:
|
|
# Unknown serializers are safely contained by this packet's
|
|
# payload; later entries are irrelevant to dropped items.
|
|
return
|
|
self.metadata.append((index, serializer_id, value))
|
|
raise ValueError('entity metadata exceeds 256 entries')
|
|
|
|
|
|
class MoveEntityPositionPacket(Packet):
|
|
id = 0x36
|
|
packet_name = "move entity position"
|
|
|
|
def read(self, file_object):
|
|
self.entity_id = VarInt.read(file_object)
|
|
properties = VarInt.read(file_object)
|
|
self.delta_x, self.delta_y, self.delta_z = _read_vec_delta(
|
|
file_object, properties >> 1)
|
|
self.on_ground = bool(properties & 1)
|
|
|
|
|
|
class MoveEntityPositionRotationPacket(Packet):
|
|
id = 0x37
|
|
packet_name = "move entity position and rotation"
|
|
|
|
def read(self, file_object):
|
|
self.entity_id = VarInt.read(file_object)
|
|
properties = VarInt.read(file_object)
|
|
self.delta_x, self.delta_y, self.delta_z = _read_vec_delta(
|
|
file_object, properties >> 1)
|
|
self.yaw = Byte.read(file_object) * (360.0 / 256.0)
|
|
self.pitch = Byte.read(file_object) * (360.0 / 256.0)
|
|
self.on_ground = bool(properties & 1)
|
|
|
|
|
|
class MoveEntityRotationPacket(Packet):
|
|
id = 0x39
|
|
packet_name = "move entity rotation"
|
|
|
|
def read(self, file_object):
|
|
self.entity_id = VarInt.read(file_object)
|
|
self.on_ground = Boolean.read(file_object)
|
|
self.yaw = Byte.read(file_object) * (360.0 / 256.0)
|
|
self.pitch = Byte.read(file_object) * (360.0 / 256.0)
|
|
|
|
|
|
class EntityPositionSyncPacket(Packet):
|
|
id = 0x23
|
|
packet_name = "entity position sync"
|
|
|
|
def read(self, file_object):
|
|
self.entity_id = VarInt.read(file_object)
|
|
path_type = VarInt.read(file_object)
|
|
if path_type == 0:
|
|
self.x, self.y, self.z = (Double.read(file_object),
|
|
Double.read(file_object),
|
|
Double.read(file_object))
|
|
elif path_type == 1:
|
|
count = VarInt.read(file_object)
|
|
if count <= 0 or count > 1024:
|
|
raise ValueError('invalid stepped entity path length {}'.format(count))
|
|
for _ in range(count):
|
|
position = (Double.read(file_object), Double.read(file_object),
|
|
Double.read(file_object))
|
|
VarInt.read(file_object) # tick offset
|
|
self.x, self.y, self.z = position
|
|
else:
|
|
raise ValueError('unknown entity position path type {}'.format(path_type))
|
|
self.yaw = Float.read(file_object)
|
|
self.pitch = Float.read(file_object)
|
|
self.on_ground = Boolean.read(file_object)
|
|
|
|
|
|
class RemoveEntitiesPacket(Packet):
|
|
id = 0x4E
|
|
packet_name = "remove entities"
|
|
|
|
def read(self, file_object):
|
|
self.entity_ids = [VarInt.read(file_object)
|
|
for _ in range(VarInt.read(file_object))]
|
|
|
|
|
|
class PlayerInfoRemovePacket(Packet):
|
|
id = 0x46
|
|
packet_name = "player info remove"
|
|
|
|
def read(self, file_object):
|
|
self.uuids = [UUID.read(file_object)
|
|
for _ in range(VarInt.read(file_object))]
|
|
|
|
|
|
class PlayerInfoUpdatePacket(Packet):
|
|
id = 0x47
|
|
packet_name = "player info update"
|
|
|
|
def read(self, file_object):
|
|
self.actions = UnsignedByte.read(file_object)
|
|
self.entries = []
|
|
for _ in range(VarInt.read(file_object)):
|
|
profile_uuid = UUID.read(file_object)
|
|
name = None
|
|
if self.actions & 1:
|
|
name = String.read(file_object)
|
|
for _ in range(VarInt.read(file_object)):
|
|
String.read(file_object)
|
|
String.read(file_object)
|
|
if Boolean.read(file_object):
|
|
String.read(file_object)
|
|
if self.actions & 2 and Boolean.read(file_object):
|
|
UUID.read(file_object)
|
|
Long.read(file_object)
|
|
key_size = VarInt.read(file_object)
|
|
file_object.read(key_size)
|
|
signature_size = VarInt.read(file_object)
|
|
file_object.read(signature_size)
|
|
if self.actions & 4:
|
|
VarInt.read(file_object)
|
|
if self.actions & 8:
|
|
Boolean.read(file_object)
|
|
if self.actions & 16:
|
|
VarInt.read(file_object)
|
|
if self.actions & 32 and Boolean.read(file_object):
|
|
read_anonymous_nbt(file_object)
|
|
if self.actions & 64:
|
|
VarInt.read(file_object)
|
|
if self.actions & 128:
|
|
Boolean.read(file_object)
|
|
self.entries.append((profile_uuid, name))
|
|
|
|
|
|
DATA_COMPONENT_TYPES = (
|
|
'custom_data', 'max_stack_size', 'max_damage', 'damage', 'unbreakable',
|
|
'use_effects', 'custom_name', 'minimum_attack_charge', 'damage_type',
|
|
'item_name', 'item_model', 'lore', 'rarity', 'enchantments',
|
|
'can_place_on', 'can_break', 'attribute_modifiers', 'custom_model_data',
|
|
'tooltip_display', 'repair_cost', 'creative_slot_lock',
|
|
'enchantment_glint_override', 'intangible_projectile', 'food',
|
|
'consumable', 'use_remainder', 'use_cooldown', 'damage_resistant',
|
|
'tool', 'weapon', 'attack_range', 'enchantable', 'equippable',
|
|
'repairable', 'glider', 'tooltip_style', 'death_protection',
|
|
'blocks_attacks', 'piercing_weapon', 'kinetic_weapon',
|
|
'attack_animation', 'interact_animation', 'additional_trade_cost',
|
|
'block_transformer', 'villager_food', 'stored_enchantments', 'dye',
|
|
'dyed_color', 'map_id', 'map_decorations', 'map_post_processing',
|
|
'charged_projectiles', 'bundle_contents', 'potion_contents',
|
|
'potion_duration_scale', 'suspicious_stew_effects',
|
|
'writable_book_content', 'written_book_content', 'trim',
|
|
'debug_stick_state', 'entity_data', 'bucket_entity_data',
|
|
'block_entity_data', 'instrument', 'provides_trim_material',
|
|
'ominous_bottle_amplifier', 'jukebox_playable',
|
|
'provides_banner_patterns', 'recipes', 'lodestone_tracker',
|
|
'firework_explosion', 'fireworks', 'profile', 'note_block_sound',
|
|
'banner_patterns', 'base_color', 'pot_decorations', 'container',
|
|
'block_state', 'bees', 'sulfur_cube_content', 'lock', 'container_loot',
|
|
'break_sound', 'compostable', 'cooking_fuel', 'brewing_fuel',
|
|
'mob_visibility', 'villager/variant', 'wolf/variant', 'wolf/sound_variant',
|
|
'wolf/collar', 'fox/variant', 'salmon/size', 'parrot/variant',
|
|
'tropical_fish/pattern', 'tropical_fish/base_color',
|
|
'tropical_fish/pattern_color', 'mooshroom/variant', 'rabbit/variant',
|
|
'pig/variant', 'pig/sound_variant', 'cow/variant', 'cow/sound_variant',
|
|
'chicken/variant', 'chicken/sound_variant', 'zombie_nautilus/variant',
|
|
'frog/variant', 'horse/variant', 'painting/variant', 'llama/variant',
|
|
'axolotl/variant', 'cat/variant', 'cat/sound_variant', 'cat/collar',
|
|
'sheep/color', 'shulker/color', 'provides_pottery_pattern',
|
|
'sign_text_front', 'sign_text_back', 'waxed', 'cushion/color',
|
|
)
|
|
|
|
|
|
class ItemStackData:
|
|
def __init__(self, present=False, item_id=None, item_count=None,
|
|
components_unknown=False, components=None,
|
|
component_ids=None, removed_components=None):
|
|
self.present = present
|
|
self.item_id = item_id
|
|
self.item_count = item_count
|
|
self.components_unknown = components_unknown
|
|
self.components = components or {}
|
|
self.component_ids = component_ids or []
|
|
self.removed_components = removed_components or []
|
|
|
|
|
|
class UnsupportedItemComponents(Exception):
|
|
def __init__(self, stack):
|
|
self.stack = stack
|
|
|
|
|
|
def _component_name(component_id, context):
|
|
registry = getattr(context, 'registry_ids', {}).get(
|
|
'minecraft:data_component_type', {})
|
|
for name, value in registry.items():
|
|
if value == component_id:
|
|
return name.removeprefix('minecraft:')
|
|
return (DATA_COMPONENT_TYPES[component_id]
|
|
if 0 <= component_id < len(DATA_COMPONENT_TYPES) else None)
|
|
|
|
|
|
def _read_filterable(file_object, component=False):
|
|
value = (nbt_plain(read_anonymous_nbt(file_object)) if component
|
|
else String.read(file_object))
|
|
filtered = None
|
|
if Boolean.read(file_object):
|
|
filtered = (nbt_plain(read_anonymous_nbt(file_object)) if component
|
|
else String.read(file_object))
|
|
return {'raw': value, 'filtered': filtered}
|
|
|
|
|
|
def _read_item_template(file_object, context, depth, diagnostic_stack):
|
|
if depth > 8:
|
|
raise ValueError('nested item components exceed depth limit')
|
|
item_id = VarInt.read(file_object)
|
|
count = VarInt.read(file_object)
|
|
stack = ItemStackData(True, item_id, count)
|
|
_read_component_patch(file_object, context, depth, stack,
|
|
diagnostic_stack)
|
|
return stack
|
|
|
|
|
|
def _read_component_value(name, file_object, context, depth, stack,
|
|
diagnostic_stack):
|
|
if name in ('custom_data', 'bucket_entity_data'):
|
|
return nbt_plain(read_anonymous_nbt(file_object))
|
|
if name in ('custom_name', 'item_name'):
|
|
return nbt_plain(read_anonymous_nbt(file_object))
|
|
if name == 'lore':
|
|
count = VarInt.read(file_object)
|
|
if count > 256:
|
|
raise ValueError('item lore has too many lines')
|
|
return [nbt_plain(read_anonymous_nbt(file_object))
|
|
for _ in range(count)]
|
|
if name in ('damage', 'max_damage', 'max_stack_size', 'repair_cost',
|
|
'additional_trade_cost'):
|
|
return VarInt.read(file_object)
|
|
if name in ('enchantments', 'stored_enchantments'):
|
|
count = VarInt.read(file_object)
|
|
if count > 256:
|
|
raise ValueError('item has too many enchantments')
|
|
enchantments = {}
|
|
registry = getattr(context, 'registry_ids', {}).get(
|
|
'minecraft:enchantment', {})
|
|
names = {value: key.removeprefix('minecraft:')
|
|
for key, value in registry.items()}
|
|
for _ in range(count):
|
|
enchantment_id = VarInt.read(file_object)
|
|
level = VarInt.read(file_object)
|
|
enchantments[names.get(enchantment_id, enchantment_id)] = level
|
|
return enchantments
|
|
if name == 'dyed_color':
|
|
return Integer.read(file_object)
|
|
if name == 'enchantment_glint_override':
|
|
return Boolean.read(file_object)
|
|
if name == 'unbreakable':
|
|
return True # Unit stream codec has no payload.
|
|
if name in ('written_book_content', 'writable_book_content'):
|
|
if name == 'writable_book_content':
|
|
count = VarInt.read(file_object)
|
|
if count > 100:
|
|
raise ValueError('writable book has too many pages')
|
|
return [_read_filterable(file_object) for _ in range(count)]
|
|
title = _read_filterable(file_object)
|
|
author = String.read(file_object)
|
|
generation = VarInt.read(file_object)
|
|
count = VarInt.read(file_object)
|
|
if count > 100:
|
|
raise ValueError('written book has too many pages')
|
|
pages = [_read_filterable(file_object, component=True)
|
|
for _ in range(count)]
|
|
return {'title': title, 'author': author,
|
|
'generation': generation, 'pages': pages,
|
|
'resolved': Boolean.read(file_object)}
|
|
if name == 'container':
|
|
count = VarInt.read(file_object)
|
|
if count > 256:
|
|
raise ValueError('container component has too many slots')
|
|
contents = []
|
|
for _ in range(count):
|
|
contents.append(_read_item_template(
|
|
file_object, context, depth + 1, diagnostic_stack)
|
|
if Boolean.read(file_object) else None)
|
|
return contents
|
|
if name in ('creative_slot_lock', 'glider', 'intangible_projectile'):
|
|
return True # Unit stream codec has no payload.
|
|
if name == 'custom_model_data':
|
|
# The modern structure is four independently length-prefixed lists.
|
|
floats = [Float.read(file_object) for _ in range(VarInt.read(file_object))]
|
|
flags = [Boolean.read(file_object) for _ in range(VarInt.read(file_object))]
|
|
strings = [String.read(file_object) for _ in range(VarInt.read(file_object))]
|
|
colors = [Integer.read(file_object) for _ in range(VarInt.read(file_object))]
|
|
return {'floats': floats, 'flags': flags,
|
|
'strings': strings, 'colors': colors}
|
|
return _COMPONENT_UNSUPPORTED
|
|
|
|
|
|
_COMPONENT_UNSUPPORTED = object()
|
|
|
|
|
|
def _read_component_patch(file_object, context, depth=0, stack=None,
|
|
diagnostic_stack=None):
|
|
positive_count = VarInt.read(file_object)
|
|
negative_count = VarInt.read(file_object)
|
|
if positive_count > 256 or negative_count > 256:
|
|
raise ValueError('item component patch is too large')
|
|
components = {}
|
|
removed = []
|
|
for _ in range(positive_count):
|
|
component_id = VarInt.read(file_object)
|
|
name = _component_name(component_id, context)
|
|
if name is None:
|
|
target = diagnostic_stack or stack
|
|
if target is not None:
|
|
target.component_ids.append(component_id)
|
|
target.components_unknown = True
|
|
raise UnsupportedItemComponents(target)
|
|
raise ValueError('unknown data component id {}'.format(component_id))
|
|
if stack is not None:
|
|
stack.component_ids.append(name)
|
|
value = _read_component_value(
|
|
name, file_object, context, depth, stack,
|
|
diagnostic_stack or stack)
|
|
if value is _COMPONENT_UNSUPPORTED:
|
|
target = diagnostic_stack or stack
|
|
if target is not None:
|
|
target.components_unknown = True
|
|
raise UnsupportedItemComponents(target)
|
|
raise ValueError('unsupported data component {}'.format(name))
|
|
components[name] = value
|
|
if stack is not None:
|
|
stack.components[name] = value
|
|
for _ in range(negative_count):
|
|
component_id = VarInt.read(file_object)
|
|
removed.append(_component_name(component_id, context) or component_id)
|
|
if stack is not None:
|
|
stack.removed_components.extend(removed)
|
|
return components, removed
|
|
|
|
|
|
def read_item_stack(file_object, context=None):
|
|
count = VarInt.read(file_object)
|
|
if count == 0:
|
|
return ItemStackData()
|
|
item_id = VarInt.read(file_object)
|
|
stack = ItemStackData(True, item_id, count)
|
|
try:
|
|
stack.components, stack.removed_components = _read_component_patch(
|
|
file_object, context, stack=stack, diagnostic_stack=stack)
|
|
except UnsupportedItemComponents:
|
|
stack.components_unknown = True
|
|
raise
|
|
return stack
|
|
|
|
|
|
class ContainerOpenPacket(Packet):
|
|
id = 0x3C
|
|
packet_name = "container open"
|
|
|
|
def read(self, file_object):
|
|
self.window_id = VarInt.read(file_object)
|
|
self.inventory_type = VarInt.read(file_object)
|
|
self.title = AnonymousNBT.read(file_object)
|
|
|
|
|
|
class ContainerSetContentPacket(Packet):
|
|
id = 0x12
|
|
packet_name = "container set content"
|
|
|
|
def read(self, file_object):
|
|
self.container_id = VarInt.read(file_object)
|
|
self.state_id = VarInt.read(file_object)
|
|
self.items = []
|
|
self.partial = False
|
|
for _ in range(VarInt.read(file_object)):
|
|
try:
|
|
self.items.append(read_item_stack(file_object, self.context))
|
|
except UnsupportedItemComponents as exc:
|
|
self.items.append(exc.stack)
|
|
self.partial = True
|
|
self.carried_item = ItemStackData()
|
|
return
|
|
try:
|
|
self.carried_item = read_item_stack(file_object, self.context)
|
|
except UnsupportedItemComponents as exc:
|
|
self.carried_item = exc.stack
|
|
self.partial = True
|
|
|
|
|
|
class ContainerSetSlotPacket(Packet):
|
|
id = 0x14
|
|
packet_name = "container set slot"
|
|
|
|
def read(self, file_object):
|
|
self.container_id = VarInt.read(file_object)
|
|
self.state_id = VarInt.read(file_object)
|
|
self.slot = Short.read(file_object)
|
|
try:
|
|
self.item = read_item_stack(file_object, self.context)
|
|
except UnsupportedItemComponents as exc:
|
|
self.item = exc.stack
|
|
|
|
|
|
class SetCursorItemPacket(Packet):
|
|
id = 0x62
|
|
packet_name = "set cursor item"
|
|
|
|
def read(self, file_object):
|
|
try:
|
|
self.item = read_item_stack(file_object, self.context)
|
|
except UnsupportedItemComponents as exc:
|
|
self.item = exc.stack
|
|
|
|
|
|
class ForgetChunkPacket(Packet):
|
|
id = 0x26
|
|
packet_name = "forget chunk"
|
|
|
|
def read(self, file_object):
|
|
packed = Long.read(file_object)
|
|
# ChunkPos stores X in the low 32 bits and Z in the high 32 bits.
|
|
raw_x = packed & 0xFFFFFFFF
|
|
raw_z = (packed >> 32) & 0xFFFFFFFF
|
|
self.x = raw_x if raw_x < 0x80000000 else raw_x - 0x100000000
|
|
self.z = raw_z if raw_z < 0x80000000 else raw_z - 0x100000000
|
|
|
|
|
|
class PlayGameEventPacket(Packet):
|
|
id = 0x27
|
|
packet_name = "game event"
|
|
definition = [{'event': UnsignedByte}, {'value': Float}]
|
|
|
|
|
|
class ChunkCacheCenterPacket(Packet):
|
|
id = 0x60
|
|
packet_name = "chunk cache center"
|
|
|
|
def read(self, file_object):
|
|
self.x = read_signed_varint(file_object)
|
|
self.z = read_signed_varint(file_object)
|
|
|
|
|
|
class ChunkCacheRadiusPacket(Packet):
|
|
id = 0x61
|
|
packet_name = "chunk cache radius"
|
|
definition = [{'radius': VarInt}]
|
|
|
|
|
|
class KeepAlive(Packet):
|
|
id = 0x1C
|
|
packet_name = "keep alive"
|
|
definition = [{'keep_alive_id': Long}]
|
|
|
|
|
|
class KeepAliveClientbound(Packet):
|
|
id = 0x2D
|
|
packet_name = "keep alive"
|
|
definition = [{'keep_alive_id': Long}]
|
|
|
|
|
|
class TeleportPosition(Packet):
|
|
id = 0x49
|
|
packet_name = "player position and look"
|
|
definition = [
|
|
{'teleport_id': VarInt},
|
|
{'x': Double}, {'y': Double}, {'z': Double},
|
|
{'velocity_x': Double}, {'velocity_y': Double}, {'velocity_z': Double},
|
|
{'yaw': Float}, {'pitch': Float}, {'relative_flags': Integer},
|
|
]
|
|
|
|
|
|
class TeleportConfirm(Packet):
|
|
id = 0x00
|
|
packet_name = "accept teleportation"
|
|
definition = [
|
|
{'teleport_id': VarInt},
|
|
{'x': Double}, {'y': Double}, {'z': Double},
|
|
{'yaw': Float}, {'pitch': Float},
|
|
]
|
|
|
|
|
|
class ClientTickEnd(Packet):
|
|
id = 0x0D
|
|
packet_name = "client tick end"
|
|
definition = []
|
|
|
|
|
|
class BlockChangedAckPacket(Packet):
|
|
id = 0x04
|
|
packet_name = "block changed acknowledgement"
|
|
definition = [{'sequence': VarInt}]
|
|
|
|
|
|
class PlayerActionPacket(Packet):
|
|
id = 0x29
|
|
packet_name = "player action"
|
|
definition = [
|
|
{'action': VarInt}, {'location': Position}, {'face': Byte},
|
|
{'sequence': VarInt},
|
|
]
|
|
|
|
|
|
class PunchPacket(Packet):
|
|
"""Serverbound punch/arm-swing event (protocol 777)."""
|
|
id = 0x2E
|
|
packet_name = "punch"
|
|
definition = []
|
|
|
|
|
|
class SetCarriedItemPacket(Packet):
|
|
id = 0x36
|
|
packet_name = "set carried item"
|
|
definition = [{'slot': Short}]
|
|
|
|
|
|
class SetHeldSlotPacket(Packet):
|
|
"""Server synchronization of the selected hotbar slot (protocol 777)."""
|
|
id = 0x6B
|
|
packet_name = "set held slot"
|
|
definition = [{'slot': VarInt}]
|
|
|
|
|
|
class ContainerClickSwapPacket(Packet):
|
|
id = 0x12
|
|
packet_name = "container click swap"
|
|
|
|
def write_fields(self, packet_buffer):
|
|
VarInt.send(self.container_id, packet_buffer)
|
|
VarInt.send(self.state_id, packet_buffer)
|
|
Short.send(self.slot, packet_buffer)
|
|
Byte.send(self.button, packet_buffer)
|
|
VarInt.send(2, packet_buffer) # ContainerInput.SWAP
|
|
VarInt.send(0, packet_buffer) # no client-side changed-slot hashes
|
|
Boolean.send(False, packet_buffer) # empty carried stack
|
|
|
|
|
|
class UseItemOnBlockPacket(Packet):
|
|
id = 0x42
|
|
packet_name = "use item on block"
|
|
definition = [
|
|
{'hand': VarInt}, {'location': Position}, {'face': VarInt},
|
|
{'cursor_x': Float}, {'cursor_y': Float}, {'cursor_z': Float},
|
|
{'inside_block': Boolean}, {'world_border_hit': Boolean},
|
|
{'sequence': VarInt},
|
|
]
|
|
|
|
|
|
class PlayerPositionRotation(Packet):
|
|
id = 0x1F
|
|
packet_name = "move player position and rotation"
|
|
definition = [
|
|
{'x': Double}, {'y': Double}, {'z': Double},
|
|
{'yaw': Float}, {'pitch': Float}, {'flags': Byte},
|
|
]
|
|
|
|
def __init__(self, x, y, z, yaw, pitch, on_ground=True,
|
|
horizontal_collision=False):
|
|
flags = (1 if on_ground else 0) | (2 if horizontal_collision else 0)
|
|
super().__init__(x=x, y=y, z=z, yaw=yaw, pitch=pitch, flags=flags)
|
|
|
|
|
|
class AnonymousNBT(Type):
|
|
"""Minecraft's unnamed NBT root used by chat components since 1.20.5."""
|
|
@staticmethod
|
|
def read(file_object):
|
|
return read_anonymous_nbt(file_object)
|
|
|
|
|
|
class SystemChat(Packet):
|
|
id = 0x7C
|
|
packet_name = "system chat"
|
|
definition = [{'content': AnonymousNBT}, {'is_action_bar': Boolean}]
|
|
|
|
|
|
class PlayLogin(Packet):
|
|
id = 0x32
|
|
packet_name = "play login"
|
|
|
|
def read(self, file_object):
|
|
self.player_id = Integer.read(file_object)
|
|
self.hardcore = Boolean.read(file_object)
|
|
self.levels = [String.read(file_object)
|
|
for _ in range(VarInt.read(file_object))]
|
|
self.max_players = VarInt.read(file_object)
|
|
self.chunk_radius = VarInt.read(file_object)
|
|
self.simulation_distance = VarInt.read(file_object)
|
|
self.reduced_debug_info = Boolean.read(file_object)
|
|
self.show_death_screen = Boolean.read(file_object)
|
|
self.do_limited_crafting = Boolean.read(file_object)
|
|
self.dimension_type_id = VarInt.read(file_object)
|
|
self.dimension = String.read(file_object)
|
|
self.hashed_seed = Long.read(file_object)
|
|
self.game_mode = VarInt.read(file_object)
|
|
previous_mode = VarInt.read(file_object)
|
|
self.previous_game_mode = previous_mode - 1 if previous_mode else None
|
|
self.is_debug = Boolean.read(file_object)
|
|
self.is_flat = Boolean.read(file_object)
|
|
if Boolean.read(file_object):
|
|
self.last_death_location = (
|
|
String.read(file_object),
|
|
Position.read_with_context(file_object, self.context))
|
|
else:
|
|
self.last_death_location = None
|
|
self.portal_cooldown = VarInt.read(file_object)
|
|
self.sea_level = VarInt.read(file_object)
|
|
self.online_mode = Boolean.read(file_object)
|
|
self.enforces_secure_chat = Boolean.read(file_object)
|
|
# Names retained by the legacy Game adapter while its packet handlers
|
|
# are migrated to 26.3.
|
|
self.entity_id = self.player_id
|
|
self.world_name = self.dimension
|
|
self.render_distance = self.chunk_radius
|
|
|
|
|
|
class PlayDisconnect(Packet):
|
|
id = 0x20
|
|
packet_name = "disconnect"
|
|
definition = [{'reason': AnonymousNBT}]
|
|
|
|
|
|
class ChatCommand(Packet):
|
|
id = 0x07
|
|
packet_name = "chat command"
|
|
definition = [{'command': String}]
|
|
|
|
|
|
class ClientboundPlayerChatPacket(Packet):
|
|
id = 0x42
|
|
packet_name = "player chat"
|
|
|
|
def read(self, file_object):
|
|
self.global_index = VarInt.read(file_object)
|
|
self.sender = UUID.read(file_object)
|
|
self.index = VarInt.read(file_object)
|
|
if Boolean.read(file_object):
|
|
file_object.read(256)
|
|
self.message = String.read(file_object)
|
|
self.timestamp = Long.read(file_object)
|
|
self.salt = Long.read(file_object)
|
|
for _ in range(VarInt.read(file_object)):
|
|
if VarInt.read(file_object) == 0:
|
|
file_object.read(256)
|
|
self.unsigned_content = (
|
|
AnonymousNBT.read(file_object)
|
|
if Boolean.read(file_object) else None)
|
|
self.filter_type = VarInt.read(file_object)
|
|
if self.filter_type == 2:
|
|
for _ in range(VarInt.read(file_object)):
|
|
Long.read(file_object)
|
|
self.chat_type_id = VarInt.read(file_object)
|
|
self.network_name = AnonymousNBT.read(file_object)
|
|
self.network_target_name_present = Boolean.read(file_object)
|
|
self.network_target_name = (
|
|
AnonymousNBT.read(file_object)
|
|
if self.network_target_name_present else None)
|
|
|
|
|
|
class ServerboundChatPacket(Packet):
|
|
id = 0x09
|
|
packet_name = "chat message"
|
|
|
|
def write_fields(self, packet_buffer):
|
|
String.send(self.message, packet_buffer)
|
|
Long.send(self.timestamp, packet_buffer)
|
|
Long.send(0, packet_buffer) # unsigned-chat salt
|
|
Boolean.send(False, packet_buffer) # no signature
|
|
VarInt.send(0, packet_buffer) # last-seen message offset
|
|
packet_buffer.send(b'\x00\x00\x00') # 20-bit acknowledgement set
|
|
Byte.send(0, packet_buffer) # checksum (ignored with empty acknowledgements)
|
|
|
|
|
|
class AuthMeDialogAction(Packet):
|
|
packet_name = "AuthMe dialog action"
|
|
action_id = None
|
|
password = None
|
|
|
|
def write_fields(self, packet_buffer):
|
|
String.send(self.action_id, packet_buffer)
|
|
if self.password is None:
|
|
# Length-prefixed optional NBT payload: an End tag represents None.
|
|
VarInt.send(1, packet_buffer)
|
|
packet_buffer.send(b'\x00')
|
|
else:
|
|
import pynbt
|
|
nbt = pynbt.TAG_Compound({
|
|
'password': pynbt.TAG_String(self.password),
|
|
})
|
|
stream = io.BytesIO()
|
|
pynbt.NBTFile(value=nbt).save(stream)
|
|
named_nbt = stream.getvalue()
|
|
anonymous_nbt = named_nbt[:1] + named_nbt[3:]
|
|
VarInt.send(len(anonymous_nbt), packet_buffer)
|
|
packet_buffer.send(anonymous_nbt)
|
|
|
|
|
|
class CancelPrejoinDialog(AuthMeDialogAction):
|
|
id = 0x08
|
|
action_id = 'authme:prejoin-register/cancel'
|
|
|
|
|
|
class CancelPostjoinDialog(AuthMeDialogAction):
|
|
id = 0x44
|
|
action_id = 'authme:postjoin-register/cancel'
|
|
|
|
|
|
class CancelPostjoinLoginDialog(AuthMeDialogAction):
|
|
id = 0x44
|
|
action_id = 'authme:postjoin-login/cancel'
|
|
|
|
|
|
class SubmitPrejoinLoginDialog(AuthMeDialogAction):
|
|
id = 0x08
|
|
action_id = 'authme:prejoin-login/submit'
|
|
|
|
|
|
class SubmitPostjoinLoginDialog(AuthMeDialogAction):
|
|
id = 0x44
|
|
action_id = 'authme:postjoin-login/submit'
|
|
|
|
|
|
class PlayShowDialog(Packet):
|
|
id = 0x8F
|
|
packet_name = "show dialog"
|
|
|
|
def read(self, file_object):
|
|
self.payload = file_object.read()
|
|
|
|
|
|
class ModernLoginReactor(PacketReactor):
|
|
@staticmethod
|
|
def get_clientbound_packets(_context):
|
|
from minecraft.networking.packets.clientbound.login import (
|
|
DisconnectPacket, EncryptionRequestPacket, SetCompressionPacket,
|
|
PluginRequestPacket,
|
|
)
|
|
return {DisconnectPacket, EncryptionRequestPacket, SetCompressionPacket,
|
|
PluginRequestPacket, LoginSuccess}
|
|
|
|
def react(self, packet):
|
|
if packet.packet_name == 'base':
|
|
trace('unhandled login packet 0x{:02x}'.format(packet.id))
|
|
# Re-use pyCraft's standard offline encryption/compression behavior.
|
|
from minecraft.networking.connection import LoginReactor
|
|
if packet.packet_name == "login success":
|
|
self.connection.write_packet(LoginAcknowledged(), force=True)
|
|
self.connection.reactor = ModernConfigurationReactor(self.connection)
|
|
self.connection.write_packet(ClientSettings(
|
|
locale='en_us', view_distance=8, chat_flags=0,
|
|
chat_colors=True, skin_parts=0x7f, main_hand=1,
|
|
enable_text_filtering=False, enable_server_listing=True,
|
|
particle_status=0), force=True)
|
|
return
|
|
LoginReactor.react(self, packet)
|
|
|
|
|
|
class ModernConfigurationReactor(PacketReactor):
|
|
@staticmethod
|
|
def get_clientbound_packets(_context):
|
|
return {FinishConfiguration, ConfigurationKeepAlive, SelectKnownPacks,
|
|
ConfigurationCustomPayload, CodeOfConduct, RegistryData}
|
|
|
|
def react(self, packet):
|
|
if packet.packet_name == 'base':
|
|
trace('unhandled configuration packet 0x{:02x}'.format(packet.id))
|
|
elif packet.packet_name == "configuration custom payload":
|
|
trace('configuration payload channel={!r} bytes={}'.format(
|
|
packet.channel, len(packet.data)))
|
|
elif packet.packet_name == "registry data":
|
|
trace('received registry {} ({} entries)'.format(
|
|
packet.registry, len(packet.entries)))
|
|
registry_ids = getattr(self.connection, 'registry_ids', {})
|
|
registry_ids[packet.registry] = {
|
|
key: index for index, (key, _value) in enumerate(packet.entries)
|
|
}
|
|
self.connection.registry_ids = registry_ids
|
|
self.connection.context.registry_ids = registry_ids
|
|
if packet.registry == 'minecraft:dimension_type':
|
|
self.connection.dimension_types_by_id = [
|
|
value or {} for _, value in packet.entries
|
|
]
|
|
elif packet.packet_name == "code of conduct":
|
|
print('[server AuthMe registration dialog] ' + packet.dialog_text, flush=True)
|
|
try:
|
|
dialog = json.loads(packet.dialog_text)
|
|
title = dialog.get('title', {}).get('text', '').lower()
|
|
except (TypeError, ValueError, AttributeError):
|
|
title = 'register'
|
|
self.connection.authme_mode = 'login' if 'login' in title else 'register'
|
|
if self.connection.authme_mode == 'login':
|
|
print('[AuthMe] submitting the pre-join login form.', flush=True)
|
|
self.connection.write_packet(SubmitPrejoinLoginDialog(
|
|
password=self.connection.authme_password), force=True)
|
|
else:
|
|
print('[AuthMe] cancelling the pre-join registration form to use /register.', flush=True)
|
|
self.connection.write_packet(CancelPrejoinDialog(), force=True)
|
|
if packet.packet_name == "keep alive":
|
|
self.connection.write_packet(ConfigurationKeepAlive(
|
|
keep_alive_id=packet.keep_alive_id), force=True)
|
|
elif packet.packet_name == "select known packs":
|
|
trace('negotiating {} known packs'.format(len(packet.packs)))
|
|
self.connection.write_packet(KnownPacksResponse(
|
|
packs=packet.packs), force=True)
|
|
elif packet.packet_name == "finish configuration":
|
|
print('[pyCraft/777] configuration complete', flush=True)
|
|
self.connection.write_packet(FinishConfiguration(), force=True)
|
|
self.connection.reactor = ModernPlayingReactor(self.connection)
|
|
self.connection.spawned = True
|
|
|
|
|
|
class ModernPlayingReactor(PacketReactor):
|
|
@staticmethod
|
|
def get_clientbound_packets(_context):
|
|
return {
|
|
KeepAliveClientbound, SystemChat, PlayDisconnect, TeleportPosition,
|
|
PlayShowDialog, PlayLogin, ChunkDataPacket, BlockUpdatePacket,
|
|
SectionBlocksUpdatePacket, ForgetChunkPacket,
|
|
ChunkCacheCenterPacket, ChunkCacheRadiusPacket,
|
|
PlayGameEventPacket,
|
|
ClientboundChunkBatchFinished, ClientboundPlayerChatPacket,
|
|
EntityAnimationPacket, EntitySwingAnimationPacket,
|
|
BlockChangedAckPacket, AddEntityPacket, SetEntityDataPacket,
|
|
BlockEntityDataPacket, BlockEventPacket, RemoveEntitiesPacket,
|
|
MoveEntityPositionPacket,
|
|
MoveEntityPositionRotationPacket, MoveEntityRotationPacket,
|
|
EntityPositionSyncPacket, PlayerInfoUpdatePacket,
|
|
PlayerInfoRemovePacket, ContainerOpenPacket,
|
|
ContainerSetContentPacket, ContainerSetSlotPacket,
|
|
SetCursorItemPacket, SetHeldSlotPacket,
|
|
}
|
|
|
|
def react(self, packet):
|
|
if packet.packet_name == 'base':
|
|
trace('unhandled play packet 0x{:02x}'.format(packet.id))
|
|
if packet.packet_name == "keep alive":
|
|
self.connection.write_packet(KeepAlive(
|
|
keep_alive_id=packet.keep_alive_id), force=True)
|
|
elif packet.packet_name == "play login":
|
|
self.connection.write_packet(PlayerLoaded(), force=True)
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
world_state.player_id = packet.player_id
|
|
dimension_types = getattr(self.connection,
|
|
'dimension_types_by_id', [])
|
|
dimension_type = (dimension_types[packet.dimension_type_id]
|
|
if packet.dimension_type_id < len(dimension_types)
|
|
else None)
|
|
world_state.set_dimension(packet.dimension, dimension_type)
|
|
elif packet.packet_name == "chunk data":
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
world_state.load_chunk(packet)
|
|
if os.getenv('PYCRAFT_TRACE_CHUNKS'):
|
|
trace('cached chunk {},{} ({} sections, {} total)'.format(
|
|
packet.x, packet.z, len(packet.sections),
|
|
len(world_state.chunks)))
|
|
elif packet.packet_name == "block update":
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
pos = packet.location
|
|
world_state.set_block_at(pos.x, pos.y, pos.z,
|
|
packet.block_state_id)
|
|
elif packet.packet_name == "section blocks update":
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
world_state.handle_section_update(packet)
|
|
elif packet.packet_name == "forget chunk":
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
world_state.unload_chunk(packet.x, packet.z)
|
|
if os.getenv('PYCRAFT_TRACE_CHUNKS'):
|
|
trace('forgot chunk {},{} ({} total)'.format(
|
|
packet.x, packet.z, len(world_state.chunks)))
|
|
elif packet.packet_name == "chunk cache center":
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
world_state.center = (packet.x, packet.z)
|
|
elif packet.packet_name == "chunk cache radius":
|
|
world_state = getattr(self.connection, 'world_state', None)
|
|
if world_state is not None:
|
|
world_state.radius = packet.radius
|
|
elif packet.packet_name == "chunk batch finished":
|
|
self.connection.write_packet(ChunkBatchReceived(
|
|
desired_chunks_per_tick=8.0), force=True)
|
|
elif packet.packet_name == "player chat":
|
|
pass
|
|
elif packet.packet_name == "player position and look":
|
|
previous = getattr(self.connection, 'player_position', None)
|
|
flags = packet.relative_flags
|
|
if previous is None:
|
|
previous = (0.0, 0.0, 0.0, 0.0, 0.0)
|
|
x = packet.x + (previous[0] if flags & 1 else 0.0)
|
|
y = packet.y + (previous[1] if flags & 2 else 0.0)
|
|
z = packet.z + (previous[2] if flags & 4 else 0.0)
|
|
yaw = packet.yaw + (previous[3] if flags & 8 else 0.0)
|
|
pitch = packet.pitch + (previous[4] if flags & 16 else 0.0)
|
|
self.connection.player_position = (x, y, z, yaw, pitch)
|
|
trace('teleport id={} relative=0x{:x} absolute=({:.3f}, {:.3f}, {:.3f}, {:.1f}, {:.1f})'.format(
|
|
packet.teleport_id, flags, x, y, z, yaw, pitch))
|
|
self.connection.write_packet(TeleportConfirm(
|
|
teleport_id=packet.teleport_id, x=x, y=y, z=z,
|
|
yaw=yaw, pitch=pitch), force=True)
|
|
elif packet.packet_name == "show dialog":
|
|
# Dialog actions are handled by the application so it can choose
|
|
# a text command or other AuthMe flow.
|
|
pass
|
|
elif packet.packet_name == "disconnect":
|
|
print('[server disconnect] ' + json.dumps(
|
|
nbt_plain(packet.reason), ensure_ascii=False), flush=True)
|
|
self.connection.disconnect(immediate=True)
|