Improve metadata and auxiliary methods of existing packets.

* Add multi-attribute aliases to some packets, for user convenience.
* Add support for writing PlayerListItemPacket.
* Add 'fields' attributes to manually-read/written packet classes,
  implementing 'field_string' where appropriate to allow enable the
  default __repr__ implementation.
* Modify data constructors where appropriate so that __repr__
  implementations match their constructor protocols.
* Improve comments on type aliases within packet classes.
* Add/modify tests to cover the new functionality.
This commit is contained in:
joodicator committed 2019-06-08 15:39:24 +02:00
1 parent 234e57716c
commit e3d2b1a368
14 files changed
+389 -158

No files matched your search

@@ -4,7 +4,8 @@ from minecraft.networking.packets import (
from minecraft.networking.types import (
Integer, FixedPointInteger, Angle, UnsignedByte, Byte, Boolean, UUID,
Short, VarInt, Double, Float, String, Enum, Difficulty, Dimension, GameMode
Short, VarInt, Double, Float, String, Enum, Difficulty, Dimension,
GameMode, Vector, Direction, PositionAndLook, multi_attribute_alias,
)
from .combat_event_packet import CombatEventPacket
@@ -91,13 +92,9 @@ class JoinGamePacket(Packet):
{'reduced_debug_info': Boolean},
])
# JoinGamePacket.Difficulty is an alias for Difficulty
# These aliases declare the Enum type corresponding to each field:
Difficulty = Difficulty
# JoinGamePacket.Gamemode is an alias for Gamemode
GameMode = GameMode
# JoinGamePacket.Dimension is an alias for Dimension
Dimension = Dimension
@@ -115,7 +112,7 @@ class ServerDifficultyPacket(Packet):
{'is_locked': Boolean} if context.protocol_version >= 464 else {},
])
# ServerDifficultyPacket.Difficulty is an alias for Difficulty
# These aliases declare the Enum type corresponding to each field:
Difficulty = Difficulty
@@ -181,10 +178,22 @@ class SpawnPlayerPacket(Packet):
else {'z': FixedPointInteger},
{'yaw': Angle},
{'pitch': Angle},
{'current_item': Short} if context.protocol_version <= 49 else {},
# TODO: read entity metadata
{'current_item': Short} if context.protocol_version <= 49 else {}
])
# Access the 'x', 'y', 'z' fields as a Vector tuple.
position = multi_attribute_alias(Vector, 'x', 'y', 'z')
# Access the 'yaw', 'pitch' fields as a Direction tuple.
look = multi_attribute_alias(Direction, 'yaw', 'pitch')
# Access the 'x', 'y', 'z', 'yaw', 'pitch' fields as a PositionAndLook.
# NOTE: modifying the object retrieved from this property will not change
# the packet; it can only be changed by attribute or property assignment.
position_and_look = multi_attribute_alias(
PositionAndLook, 'x', 'y', 'z', 'yaw', 'pitch')
class EntityVelocityPacket(Packet):
@staticmethod
@@ -258,13 +267,9 @@ class RespawnPacket(Packet):
{'level_type': String},
])
# RespawnPacket.Difficulty is an alias for Difficulty.
# These aliases declare the Enum type corresponding to each field:
Difficulty = Difficulty
# RespawnPacket.Dimension is an alias for Dimension.
Dimension = Dimension
# RespawnPacket.Gamemode is an alias for Gamemode.
GameMode = GameMode
@@ -53,6 +53,11 @@ class MultiBlockChangePacket(Packet):
packet_name = 'multi block change'
fields = 'chunk_x', 'chunk_z', 'records'
# Access the 'chunk_x' and 'chunk_z' fields as a tuple.
chunk_pos = multi_attribute_alias(tuple, 'chunk_x', 'chunk_z')
class Record(MutableRecord):
__slots__ = 'x', 'y', 'z', 'block_state_id'
@@ -22,6 +22,8 @@ class CombatEventPacket(Packet):
packet_name = 'combat event'
fields = 'event',
# The abstract type of the 'event' field of this packet.
class EventType(MutableRecord):
__slots__ = ()
@@ -18,14 +18,19 @@ class ExplosionPacket(Packet):
packet_name = 'explosion'
class Record(Vector):
__slots__ = ()
fields = 'x', 'y', 'z', 'radius', 'records', \
'player_motion_x', 'player_motion_y', 'player_motion_z'
# Access the 'x', 'y', 'z' fields as a Vector tuple.
position = multi_attribute_alias(Vector, 'x', 'y', 'z')
# Access the 'player_motion_{x,y,z}' fields as a Vector tuple.
player_motion = multi_attribute_alias(
Vector, 'player_motion_x', 'player_motion_y', 'player_motion_z')
class Record(Vector):
__slots__ = ()
def read(self, file_object):
self.x = Float.read(file_object)
self.y = Float.read(file_object)
@@ -15,7 +15,13 @@ class FacePlayerPacket(Packet):
packet_name = 'face player'
# Access the 'x', 'y', 'z' fields as a Vector.
@property
def fields(self):
return ('origin', 'x', 'y', 'z', 'entity_id', 'entity_origin') \
if self.context.protocol_version >= 353 else \
('entity_id', 'x', 'y', 'z')
# Access the 'x', 'y', 'z' fields as a Vector tuple.
target = multi_attribute_alias(Vector, 'x', 'y', 'z')
def read(self, file_object):
@@ -17,6 +17,20 @@ class MapPacket(Packet):
packet_name = 'map'
@property
def fields(self):
fields = 'id', 'scale', 'icons', 'width', 'height', 'pixels'
if self.context.protocol_version >= 107:
fields += 'is_tracking_position',
if self.context.protocol_version >= 452:
fields += 'is_locked',
return fields
def field_string(self, field):
if field == 'pixels' and isinstance(self.pixels, bytearray):
return 'bytearray(...)'
return super(MapPacket, self).field_string(field)
class MapIcon(MutableRecord):
__slots__ = 'type', 'direction', 'location', 'display_name'
@@ -43,11 +57,11 @@ class MapPacket(Packet):
class MapSet(object):
__slots__ = 'maps_by_id'
def __init__(self):
self.maps_by_id = dict()
def __init__(self, *maps):
self.maps_by_id = {map.id: map for map in maps}
def __repr__(self):
maps = (str(map) for map in self.maps_by_id.values())
maps = (repr(map) for map in self.maps_by_id.values())
return 'MapSet(%s)' % ', '.join(maps)
def read(self, file_object):
@@ -143,9 +157,3 @@ class MapPacket(Packet):
UnsignedByte.send(self.offset[0], packet_buffer) # x
UnsignedByte.send(self.offset[1], packet_buffer) # z
VarIntPrefixedByteArray.send(self.pixels, packet_buffer)
def __repr__(self):
return '%sMapPacket(%s)' % (
('0x%02X ' % self.id) if self.id is not None else '',
', '.join('%s=%r' % (k, v) for (k, v) in self.__dict__.items()
if k not in ('pixels', '_context', 'id', 'definition')))
@@ -1,7 +1,7 @@
from minecraft.networking.packets import Packet
from minecraft.networking.types import (
String, Boolean, UUID, VarInt,
String, Boolean, UUID, VarInt, MutableRecord,
)
@@ -20,21 +20,24 @@ class PlayerListItemPacket(Packet):
packet_name = "player list item"
fields = 'action_type', 'actions'
def field_string(self, field):
if field == 'action_type':
return self.action_type.__name__
return super(PlayerListItemPacket, self).field_string(field)
class PlayerList(object):
__slots__ = 'players_by_uuid'
def __init__(self):
self.players_by_uuid = dict()
def __init__(self, *items):
self.players_by_uuid = {item.uuid: item for item in items}
class PlayerListItem(object):
class PlayerListItem(MutableRecord):
__slots__ = (
'uuid', 'name', 'properties', 'gamemode', 'ping', 'display_name')
def __init__(self, **kwds):
for key, val in kwds.items():
setattr(self, key, val)
class PlayerProperty(object):
class PlayerProperty(MutableRecord):
__slots__ = 'name', 'value', 'signature'
def read(self, file_object):
@@ -46,33 +49,44 @@ class PlayerListItemPacket(Packet):
else:
self.signature = None
class Action(object):
__slots__ = 'uuid'
def send(self, packet_buffer):
String.send(self.name, packet_buffer)
String.send(self.value, packet_buffer)
if self.signature is not None:
Boolean.send(True, packet_buffer)
String.send(self.signature, packet_buffer)
else:
Boolean.send(False, packet_buffer)
class Action(MutableRecord):
__slots__ = 'uuid',
def read(self, file_object):
self.uuid = UUID.read(file_object)
self._read(file_object)
def send(self, packet_buffer):
UUID.send(self.uuid, packet_buffer)
self._send(packet_buffer)
def _read(self, file_object):
raise NotImplementedError(
'This abstract method must be overridden in a subclass.')
def _send(self, packet_buffer):
raise NotImplementedError(
'This abstract method must be overridden in a subclass.')
@classmethod
def type_from_id(cls, action_id):
subcls = {
0: PlayerListItemPacket.AddPlayerAction,
1: PlayerListItemPacket.UpdateGameModeAction,
2: PlayerListItemPacket.UpdateLatencyAction,
3: PlayerListItemPacket.UpdateDisplayNameAction,
4: PlayerListItemPacket.RemovePlayerAction
}.get(action_id)
if subcls is None:
raise ValueError("Unknown player list action ID: %s."
% action_id)
return subcls
for subcls in cls.__subclasses__():
if subcls.action_id == action_id:
return subcls
raise ValueError("Unknown player list action ID: %s." % action_id)
class AddPlayerAction(Action):
__slots__ = 'name', 'properties', 'gamemode', 'ping', 'display_name'
action_id = 0
def _read(self, file_object):
self.name = String.read(file_object)
@@ -90,6 +104,19 @@ class PlayerListItemPacket(Packet):
else:
self.display_name = None
def _send(self, packet_buffer):
String.send(self.name, packet_buffer)
VarInt.send(len(self.properties), packet_buffer)
for property in self.properties:
property.send(packet_buffer)
VarInt.send(self.gamemode, packet_buffer)
VarInt.send(self.ping, packet_buffer)
if self.display_name is not None:
Boolean.send(True, packet_buffer)
String.send(self.display_name, packet_buffer)
else:
Boolean.send(False, packet_buffer)
def apply(self, player_list):
player = PlayerListItemPacket.PlayerListItem(
uuid=self.uuid,
@@ -102,10 +129,14 @@ class PlayerListItemPacket(Packet):
class UpdateGameModeAction(Action):
__slots__ = 'gamemode'
action_id = 1
def _read(self, file_object):
self.gamemode = VarInt.read(file_object)
def _send(self, packet_buffer):
VarInt.send(self.gamemode, packet_buffer)
def apply(self, player_list):
player = player_list.players_by_uuid.get(self.uuid)
if player:
@@ -113,10 +144,14 @@ class PlayerListItemPacket(Packet):
class UpdateLatencyAction(Action):
__slots__ = 'ping'
action_id = 2
def _read(self, file_object):
self.ping = VarInt.read(file_object)
def _send(self, packet_buffer):
VarInt.send(self.ping, packet_buffer)
def apply(self, player_list):
player = player_list.players_by_uuid.get(self.uuid)
if player:
@@ -124,6 +159,7 @@ class PlayerListItemPacket(Packet):
class UpdateDisplayNameAction(Action):
__slots__ = 'display_name'
action_id = 3
def _read(self, file_object):
has_display_name = Boolean.read(file_object)
@@ -132,15 +168,27 @@ class PlayerListItemPacket(Packet):
else:
self.display_name = None
def _send(self, packet_buffer):
if self.display_name is not None:
Boolean.send(True, packet_buffer)
String.send(self.display_name, packet_buffer)
else:
Boolean.send(False, packet_buffer)
def apply(self, player_list):
player = player_list.players_by_uuid.get(self.uuid)
if player:
player.display_name = self.display_name
class RemovePlayerAction(Action):
action_id = 4
def _read(self, file_object):
pass
def _send(self, packet_buffer):
pass
def apply(self, player_list):
if self.uuid in player_list.players_by_uuid:
del player_list.players_by_uuid[self.uuid]
@@ -155,9 +203,12 @@ class PlayerListItemPacket(Packet):
action.read(file_object)
self.actions.append(action)
def write_fields(self, packet_buffer):
VarInt.send(self.action_type.action_id, packet_buffer)
VarInt.send(len(self.actions), packet_buffer)
for action in self.actions:
action.send(packet_buffer)
def apply(self, player_list):
for action in self.actions:
action.apply(player_list)
def write_fields(self, packet_buffer):
raise NotImplementedError
@@ -1,7 +1,8 @@
from minecraft.networking.packets import Packet
from minecraft.networking.types import (
Double, Float, Byte, VarInt, BitFieldEnum, PositionAndLook
Double, Float, Byte, VarInt, BitFieldEnum, Vector, Direction,
PositionAndLook, multi_attribute_alias,
)
@@ -30,6 +31,18 @@ class PlayerPositionAndLookPacket(Packet, BitFieldEnum):
{'teleport_id': VarInt} if context.protocol_version >= 107 else {},
])
# Access the 'x', 'y', 'z' fields as a Vector tuple.
position = multi_attribute_alias(Vector, 'x', 'y', 'z')
# Access the 'yaw', 'pitch' fields as a Direction tuple.
look = multi_attribute_alias(Direction, 'yaw', 'pitch')
# Access the 'x', 'y', 'z', 'yaw', 'pitch' fields as a PositionAndLook.
# NOTE: modifying the object retrieved from this property will not change
# the packet; it can only be changed by attribute or property assignment.
position_and_look = multi_attribute_alias(
PositionAndLook, 'x', 'y', 'z', 'yaw', 'pitch')
field_enum = classmethod(
lambda cls, field, context: cls if field == 'flags' else None)
@@ -3,7 +3,7 @@ from minecraft.networking.types.utility import descriptor
from minecraft.networking.types import (
VarInt, UUID, Byte, Double, Integer, Angle, Short, Enum, Vector,
PositionAndLook, attribute_alias, multi_attribute_alias,
Direction, PositionAndLook, attribute_alias, multi_attribute_alias,
)
@@ -15,8 +15,8 @@ class SpawnObjectPacket(Packet):
packet_name = 'spawn object'
fields = ('entity_id', 'object_uuid', 'type_id',
'x', 'y', 'z', 'pitch', 'yaw')
fields = ('entity_id', 'object_uuid', 'type_id', 'x', 'y', 'z', 'pitch',
'yaw', 'data', 'velocity_x', 'velocity_y', 'velocity_z')
@descriptor
def EntityType(desc, self, cls): # pylint: disable=no-self-argument
@@ -152,13 +152,19 @@ class SpawnObjectPacket(Packet):
def type(self):
del self.type_id
# Access the 'x', 'y', 'z' fields as a Vector.
position = multi_attribute_alias(Vector, 'x', 'y', 'z')
# Access the 'yaw', 'pitch' fields as a Direction.
look = multi_attribute_alias(Direction, 'yaw', 'pitch')
# Access the 'x', 'y', 'z', 'pitch', 'yaw' fields as a PositionAndLook.
# NOTE: modifying the object retrieved from this property will not change
# the packet; it can only be changed by attribute or property assignment.
position_and_look = multi_attribute_alias(
PositionAndLook, x='x', y='y', z='z', yaw='yaw', pitch='pitch')
# Access the 'velocity_{x,y,z}' fields as a Vector.
velocity = multi_attribute_alias(
Vector, 'velocity_x', 'velocity_y', 'velocity_z')
+3 -2
View File
@@ -112,8 +112,9 @@ class Packet(object):
str = '0x%02X %s' % (self.id, str)
fields = self.fields
if fields is not None:
str = '%s(%s)' % (str, ', '.join('%s=%s' %
(a, self.field_string(a)) for a in fields))
inner_str = ', '.join('%s=%s' % (a, self.field_string(a))
for a in fields if hasattr(self, a))
str = '%s(%s)' % (str, inner_str)
return str
@property
@@ -4,7 +4,8 @@ from minecraft.networking.packets import (
from minecraft.networking.types import (
Double, Float, Boolean, VarInt, String, Byte, Position, Enum,
RelativeHand, BlockFace
RelativeHand, BlockFace, Vector, Direction, PositionAndLook,
multi_attribute_alias
)
from .client_settings_packet import ClientSettingsPacket
@@ -98,6 +99,19 @@ class PositionAndLookPacket(Packet):
{'pitch': Float},
{'on_ground': Boolean}]
# Access the 'x', 'feet_y', 'z' fields as a Vector tuple.
position = multi_attribute_alias(Vector, 'x', 'feet_y', 'z')
# Access the 'yaw', 'pitch' fields as a Direction tuple.
look = multi_attribute_alias(Direction, 'yaw', 'pitch')
# Access the 'x', 'feet_y', 'z', 'yaw', 'pitch' fields as a
# PositionAndLook.
# NOTE: modifying the object retrieved from this property will not change
# the packet; it can only be changed by attribute or property assignment.
position_and_look = multi_attribute_alias(
PositionAndLook, 'x', 'feet_y', 'z', 'yaw', 'pitch')
class TeleportConfirmPacket(Packet):
# Note: added between protocol versions 47 and 107.