Evade ranged weapons and rush target
This commit is contained in:
1 parent
dbd2831dda
commit
0722924263
10 files changed
+474
-14
No files matched your search
+5
-2
@@ -294,8 +294,9 @@ def tick(global_state):
|
||||
|
||||
if d.length() > 0:
|
||||
if g.y_v < 5:
|
||||
p.x -= utils.cap(d.x, 0.2)
|
||||
p.z -= utils.cap(d.z, 0.2)
|
||||
horizontal_step = 0.28 if g.get('sprinting', False) else 0.2
|
||||
p.x -= utils.cap(d.x, horizontal_step)
|
||||
p.z -= utils.cap(d.z, horizontal_step)
|
||||
|
||||
if len(g.path) > 1 and d.length() < 0.2:
|
||||
# removes some jitter in walking
|
||||
@@ -501,6 +502,7 @@ def start_automation(global_state, initialize=True):
|
||||
g.protocol_version = 777
|
||||
if initialize:
|
||||
g.time = 0.0
|
||||
g.sprinting = False
|
||||
g.time_base = None
|
||||
g.time_update_received_at = None
|
||||
g.clock_rate = 1.0
|
||||
@@ -554,6 +556,7 @@ def start_automation(global_state, initialize=True):
|
||||
|
||||
# Preserve active work during hot reloads, but give the worker all fields
|
||||
# introduced by the currently migrated inventory controls.
|
||||
g.setdefault('sprinting', False)
|
||||
g.setdefault('draining', False)
|
||||
g.setdefault('dumping', None)
|
||||
g.setdefault('dump_waiting', None)
|
||||
|
||||
+17
-1
@@ -697,7 +697,7 @@ class Game(LegacyGame):
|
||||
self.g.yaw_target_override = None
|
||||
self.g.unopenable_doors = self.g.get('unopenable_doors') or set()
|
||||
|
||||
from mosfet.protocol.packets import SetHealthPacket
|
||||
from mosfet.protocol.packets import SetEquipmentPacket, SetHealthPacket
|
||||
# Health is a protocol-777 packet, not the legacy UpdateHealthPacket.
|
||||
# Register its decoder on an already-running reactor as well, so a
|
||||
# hot reload can enable health tracking without reconnecting. Rebuild
|
||||
@@ -710,6 +710,7 @@ class Game(LegacyGame):
|
||||
for packet in reactor.__class__.get_clientbound_packets(context)
|
||||
}
|
||||
reactor.clientbound_packets[SetHealthPacket.id] = SetHealthPacket
|
||||
reactor.clientbound_packets[SetEquipmentPacket.id] = SetEquipmentPacket
|
||||
reactor.clientbound_packets[UpdateTimePacket.id] = UpdateTimePacket
|
||||
self.g.connection.register_packet_listener(
|
||||
self.handle_set_health, SetHealthPacket)
|
||||
@@ -721,6 +722,7 @@ class Game(LegacyGame):
|
||||
self.g.setdefault('time_base', None)
|
||||
self.g.setdefault('time_update_received_at', None)
|
||||
self.g.setdefault('clock_rate', 1.0)
|
||||
self.g.setdefault('sprinting', False)
|
||||
|
||||
if not self.g.get('health_update_received', False):
|
||||
self.g.health = None
|
||||
@@ -1084,6 +1086,20 @@ class Game(LegacyGame):
|
||||
self.next_swing_at = now + self.ARM_SWING_INTERVAL
|
||||
return True
|
||||
|
||||
def set_sprinting(self, enabled):
|
||||
"""Tell the server when the bot starts or stops a sprint burst."""
|
||||
enabled = bool(enabled)
|
||||
if self.g.get('sprinting', False) == enabled:
|
||||
return False
|
||||
entity_id = self.g.get('eid')
|
||||
if entity_id is None:
|
||||
return False
|
||||
self._send_action(PlayerCommandPacket(
|
||||
entity_id=entity_id, action_id=1 if enabled else 2,
|
||||
jump_boost=0))
|
||||
self.g.sprinting = enabled
|
||||
return True
|
||||
|
||||
def respawn(self):
|
||||
self.g.respawn_requested_at = time.monotonic()
|
||||
self.g.connection.write_packet(
|
||||
|
||||
@@ -45,6 +45,7 @@ BED_IDS = get_set(BEDS)
|
||||
SHOVEL_IDS = get_set(SHOVELS)
|
||||
AXE_IDS = get_set(AXES)
|
||||
FOOD_IDS = get_set(FOOD)
|
||||
RANGED_WEAPON_IDS = get_set({'bow', 'crossbow', 'trident'})
|
||||
SWORD_IDS = {
|
||||
item['protocol_id'] for name, item in ITEMS.items()
|
||||
if name.endswith('_sword')
|
||||
|
||||
@@ -75,3 +75,26 @@ NON_MOB_ENTITY_IDS = {
|
||||
for name in NON_MOB_ENTITY_NAMES
|
||||
if 'minecraft:' + name in MOBS
|
||||
}
|
||||
|
||||
# Entities known to use ranged attacks even when the equipment packet is not
|
||||
# available yet or the attack is innate rather than item-based.
|
||||
RANGED_ATTACKER_NAMES = {
|
||||
'blaze', 'bogged', 'breeze', 'elder_guardian', 'evoker', 'ghast',
|
||||
'guardian', 'illusioner', 'pillager', 'shulker', 'skeleton', 'stray',
|
||||
'wither', 'witch', 'warden',
|
||||
}
|
||||
RANGED_ATTACKER_IDS = {
|
||||
MOBS['minecraft:' + name]['protocol_id']
|
||||
for name in RANGED_ATTACKER_NAMES if 'minecraft:' + name in MOBS
|
||||
}
|
||||
|
||||
RANGED_PROJECTILE_NAMES = {
|
||||
'arrow', 'dragon_fireball', 'fireball', 'firework_rocket', 'llama_spit',
|
||||
'shulker_bullet', 'small_fireball', 'snowball', 'spectral_arrow',
|
||||
'trident', 'wind_charge',
|
||||
'wither_skull',
|
||||
}
|
||||
RANGED_PROJECTILE_IDS = {
|
||||
MOBS['minecraft:' + name]['protocol_id']
|
||||
for name in RANGED_PROJECTILE_NAMES if 'minecraft:' + name in MOBS
|
||||
}
|
||||
@@ -356,6 +356,8 @@ class JobStates(LegacyJobStates):
|
||||
monitor.cancel_resume()
|
||||
if self.g.get('breaking'):
|
||||
self.g.game.cancel_break()
|
||||
if self.g.get('sprinting') and self.g.get('game'):
|
||||
self.g.game.set_sprinting(False)
|
||||
if self.g.get('window'):
|
||||
self.g.game.close_window()
|
||||
self.g.path = []
|
||||
|
||||
+270
-3
@@ -1,4 +1,5 @@
|
||||
"""Close-range melee combat against loaded mobs."""
|
||||
"""Close-range melee combat against loaded mobs and players."""
|
||||
import math
|
||||
import time
|
||||
|
||||
from mosfet import utils
|
||||
@@ -12,6 +13,14 @@ class CombatStates:
|
||||
PATH_RETRY_INTERVAL = 1.0
|
||||
PATH_SEARCH_TIMEOUT = 0.1
|
||||
TARGET_GROUND_SEARCH_DEPTH = 8
|
||||
EVASION_PATH_TIMEOUT = 0.1
|
||||
EVASION_INTERVAL = 0.9
|
||||
PROJECTILE_LOOKAHEAD = 0.7
|
||||
PROJECTILE_MISS_DISTANCE = 1.35
|
||||
RUSH_DURATION = 1.0
|
||||
RUSH_COOLDOWN = 0.9
|
||||
RECENT_SHOT_WINDOW = 0.8
|
||||
PROJECTILE_SOURCE_RADIUS = 3.0
|
||||
|
||||
def idle(self):
|
||||
return None
|
||||
@@ -47,6 +56,15 @@ class CombatStates:
|
||||
self.best_distance = None
|
||||
self.last_progress_at = None
|
||||
self.last_los_report_at = 0.0
|
||||
self.evading = False
|
||||
self.next_evasion_at = 0.0
|
||||
self.evasion_side = 1
|
||||
self.evasion_count = 0
|
||||
self.rushing = False
|
||||
self.rush_until = 0.0
|
||||
self.next_rush_at = 0.0
|
||||
self.rush_count = 0
|
||||
self.seen_projectile_ids = set()
|
||||
|
||||
main_hand_sword = any(
|
||||
9 <= slot <= 44 and getattr(stack, 'present', False) and
|
||||
@@ -149,6 +167,7 @@ class CombatStates:
|
||||
self.best_distance = distance
|
||||
self.last_progress_at = self.target_started_at
|
||||
self.last_los_report_at = 0.0
|
||||
self.evading = False
|
||||
self.targets_engaged += 1
|
||||
self._log('targeting {}#{} at {:.1f} blocks (scan {:.3f}s)'.format(
|
||||
self.target_name, self.target_id, distance, search_elapsed))
|
||||
@@ -163,6 +182,218 @@ class CombatStates:
|
||||
x, y, z = self._coordinates(target)
|
||||
return check(eye, (x, y + 0.9, z), utils.pint((x, y, z)))
|
||||
|
||||
def _has_ranged_weapon(self, target):
|
||||
if target.get('main_hand_item_id') in items.RANGED_WEAPON_IDS:
|
||||
return True
|
||||
if self.target_players:
|
||||
return any(
|
||||
stack.item_id in items.RANGED_WEAPON_IDS
|
||||
for slot, stack in (target.get('equipment') or {}).items()
|
||||
if slot in (0, 1) and stack.present)
|
||||
return target.get('type') in mobs.RANGED_ATTACKER_IDS
|
||||
|
||||
def _aiming_at_player(self, target):
|
||||
yaw = target.get('yaw')
|
||||
if yaw is None:
|
||||
return False
|
||||
player = self.g.pos
|
||||
dx, dz = player.x - target.x, player.z - target.z
|
||||
if math.hypot(dx, dz) < 0.01:
|
||||
return True
|
||||
desired_yaw = math.degrees(math.atan2(-dx, dz))
|
||||
yaw_delta = (float(yaw) - desired_yaw + 180.0) % 360.0 - 180.0
|
||||
return abs(yaw_delta) <= 40.0
|
||||
|
||||
def _incoming_projectile(self):
|
||||
player = self.g.pos
|
||||
now = time.monotonic()
|
||||
best = None
|
||||
for entity_id, projectile in self.g.get('mobs', {}).items():
|
||||
if projectile.get('type') not in mobs.RANGED_PROJECTILE_IDS:
|
||||
continue
|
||||
px, py, pz = self._coordinates(projectile)
|
||||
relative = (player.x - px, player.y + 0.9 - py, player.z - pz)
|
||||
velocity_time = projectile.get('velocity_updated_at')
|
||||
velocity = tuple(projectile.get('velocity_' + axis)
|
||||
for axis in ('x', 'y', 'z'))
|
||||
if (velocity_time is None or now - velocity_time > 0.5 or
|
||||
any(component is None for component in velocity)):
|
||||
distance = utils.hypot(*relative)
|
||||
if distance <= 2.0:
|
||||
candidate = (projectile, 0.0, distance)
|
||||
if best is None or candidate[2] < best[2]:
|
||||
best = candidate
|
||||
continue
|
||||
|
||||
speed_squared = sum(component * component for component in velocity)
|
||||
if speed_squared < 1e-6:
|
||||
continue
|
||||
time_to_closest = sum(relative[i] * velocity[i]
|
||||
for i in range(3)) / speed_squared
|
||||
if not 0.0 <= time_to_closest <= self.PROJECTILE_LOOKAHEAD:
|
||||
continue
|
||||
miss = utils.hypot(*(
|
||||
relative[i] - velocity[i] * time_to_closest
|
||||
for i in range(3)))
|
||||
if miss <= self.PROJECTILE_MISS_DISTANCE and (
|
||||
best is None or miss < best[2]):
|
||||
best = (projectile, time_to_closest, miss)
|
||||
return best
|
||||
|
||||
def _recent_target_shot(self, target, now):
|
||||
if not self._has_ranged_weapon(target):
|
||||
return None
|
||||
shooter = (target.x, target.y + 1.0, target.z)
|
||||
for entity_id, projectile in self.g.get('mobs', {}).items():
|
||||
if (entity_id in self.seen_projectile_ids or
|
||||
projectile.get('type') not in mobs.RANGED_PROJECTILE_IDS):
|
||||
continue
|
||||
spawned_at = projectile.get('spawned_at')
|
||||
if (spawned_at is None or
|
||||
not 0.0 <= now - spawned_at <= self.RECENT_SHOT_WINDOW):
|
||||
continue
|
||||
spawn = tuple(projectile.get('spawn_' + axis)
|
||||
for axis in ('x', 'y', 'z'))
|
||||
if (any(value is None for value in spawn) or
|
||||
utils.phyp(shooter, spawn) > self.PROJECTILE_SOURCE_RADIUS):
|
||||
continue
|
||||
self.seen_projectile_ids.add(entity_id)
|
||||
return projectile
|
||||
return None
|
||||
|
||||
def _start_rush(self, target, projectile, now):
|
||||
self.rushing = True
|
||||
self.rush_until = now + self.RUSH_DURATION
|
||||
self.next_rush_at = now + self.RUSH_COOLDOWN
|
||||
self.rush_count += 1
|
||||
self.evading = False
|
||||
self.g.path = []
|
||||
self.path_target = None
|
||||
self.next_path_at = 0.0
|
||||
self.g.game.set_sprinting(True)
|
||||
projectile_name = mobs.MOB_NAMES.get(
|
||||
projectile.get('type'), 'projectile')
|
||||
self._log('{}#{} fired {}; rushing for {:.1f}s'.format(
|
||||
self._describe(target), self.target_id, projectile_name,
|
||||
self.RUSH_DURATION))
|
||||
self._path_to_target(target)
|
||||
|
||||
def _stop_rush(self):
|
||||
if not self.rushing:
|
||||
return
|
||||
self.rushing = False
|
||||
self.rush_until = 0.0
|
||||
connection = self.g.get('connection')
|
||||
if connection is not None and connection.connected:
|
||||
self.g.game.set_sprinting(False)
|
||||
else:
|
||||
self.g.sprinting = False
|
||||
self._log('rush window ended')
|
||||
|
||||
def _try_evasion(self, target, now):
|
||||
if self.rushing and now < self.rush_until:
|
||||
return False
|
||||
if self.evading and self.g.path:
|
||||
return False
|
||||
if now < self.next_evasion_at:
|
||||
return False
|
||||
|
||||
projectile = self._incoming_projectile()
|
||||
ranged_weapon = self._has_ranged_weapon(target)
|
||||
facing = ranged_weapon and self._aiming_at_player(target)
|
||||
aiming_with_sight = facing and self._line_of_sight(target)
|
||||
if projectile is None and not aiming_with_sight:
|
||||
return False
|
||||
|
||||
player = self.g.pos
|
||||
if projectile is not None:
|
||||
threat, eta, miss = projectile
|
||||
velocity = (threat.get('velocity_x'), threat.get('velocity_z'))
|
||||
if (any(component is None for component in velocity) or
|
||||
math.hypot(*velocity) < 0.01):
|
||||
velocity = (player.x - threat.x, player.z - threat.z)
|
||||
reason = 'incoming {}#{} in {:.2f}s (closest {:.2f})'.format(
|
||||
mobs.MOB_NAMES.get(threat.get('type'), 'projectile'),
|
||||
threat.get('entity_id', '?'), eta, miss)
|
||||
else:
|
||||
velocity = (player.x - target.x, player.z - target.z)
|
||||
reason = '{}#{} aiming with ranged weapon'.format(
|
||||
self._describe(target), self.target_id)
|
||||
|
||||
magnitude = math.hypot(*velocity)
|
||||
if magnitude < 0.01:
|
||||
return False
|
||||
perpendicular = (-velocity[1] / magnitude, velocity[0] / magnitude)
|
||||
toward = (target.x - player.x, target.z - player.z)
|
||||
toward_length = math.hypot(*toward)
|
||||
if toward_length < 0.01:
|
||||
return False
|
||||
toward = (toward[0] / toward_length, toward[1] / toward_length)
|
||||
start = utils.pint(player)
|
||||
deadline = time.monotonic() + self.EVASION_PATH_TIMEOUT
|
||||
routes = []
|
||||
seen = set()
|
||||
for advance in (2.0, 2.75):
|
||||
for lateral, side in ((2.0, self.evasion_side),
|
||||
(3.5, -self.evasion_side)):
|
||||
x = math.floor(
|
||||
player.x + toward[0] * advance +
|
||||
perpendicular[0] * lateral * side)
|
||||
z = math.floor(
|
||||
player.z + toward[1] * advance +
|
||||
perpendicular[1] * lateral * side)
|
||||
destination = self._grounded_approach_block(
|
||||
x, z, start[1])
|
||||
if destination is None or destination == start or destination in seen:
|
||||
continue
|
||||
seen.add(destination)
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
route = self.g.world.path_to_place(
|
||||
start, destination, timeout=remaining)
|
||||
if not route or len(route) <= 1:
|
||||
continue
|
||||
cover = False
|
||||
check = getattr(
|
||||
self.g.world, '_has_cache_line_of_sight', None)
|
||||
if callable(check):
|
||||
source = (target.x, target.y + 1.5, target.z)
|
||||
endpoint = (destination[0] + 0.5,
|
||||
destination[1] + 1.0,
|
||||
destination[2] + 0.5)
|
||||
cover = not check(source, endpoint, destination)
|
||||
after_distance = math.hypot(
|
||||
target.x - (destination[0] + 0.5),
|
||||
target.z - (destination[2] + 0.5))
|
||||
progress = toward_length - after_distance
|
||||
if progress <= 0.4:
|
||||
continue
|
||||
routes.append((0 if cover else 1, -progress, len(route),
|
||||
destination, route, cover, progress))
|
||||
|
||||
if not routes:
|
||||
self.next_evasion_at = now + 0.5
|
||||
self._log('ranged threat detected ({}) but no advancing dodge '
|
||||
'route found within {:.2f}s'.format(
|
||||
reason, self.EVASION_PATH_TIMEOUT))
|
||||
return False
|
||||
|
||||
(_cover_rank, _progress_rank, _length, destination, route,
|
||||
has_cover, advance) = min(routes)
|
||||
self.g.path = route
|
||||
self.path_target = None
|
||||
self.evading = True
|
||||
self.evasion_count += 1
|
||||
self.evasion_side *= -1
|
||||
self.next_evasion_at = now + self.EVASION_INTERVAL
|
||||
self.best_distance = self._distance(target)
|
||||
self.last_progress_at = now
|
||||
self._log('evasive advance from {} to {} ({} nodes, {:.1f} blocks '
|
||||
'closer, cover={})'.format(
|
||||
reason, destination, len(route), advance, has_cover))
|
||||
return True
|
||||
|
||||
def _path_to_target(self, target):
|
||||
mob_block = utils.pint(self._coordinates(target))
|
||||
target_block = self._grounded_target_block(target)
|
||||
@@ -235,8 +466,10 @@ class CombatStates:
|
||||
target = self._target_entities().get(self.target_id)
|
||||
if target is None:
|
||||
self._log_target_end('lost target entity')
|
||||
self._stop_rush()
|
||||
self.target_id = None
|
||||
self.g.path = []
|
||||
self.evading = False
|
||||
self.state = self.find_target
|
||||
return
|
||||
|
||||
@@ -244,11 +477,21 @@ class CombatStates:
|
||||
now = time.monotonic()
|
||||
if distance > self.ACQUIRE_RADIUS:
|
||||
self._log_target_end('target left the 16-block radius')
|
||||
self._stop_rush()
|
||||
self.target_id = None
|
||||
self.g.path = []
|
||||
self.evading = False
|
||||
self.state = self.find_target
|
||||
return
|
||||
|
||||
if self.rushing and now >= self.rush_until:
|
||||
self._stop_rush()
|
||||
if (distance > self.ATTACK_REACH and now >= self.next_rush_at):
|
||||
shot = self._recent_target_shot(target, now)
|
||||
if shot is not None:
|
||||
self._start_rush(target, shot, now)
|
||||
return
|
||||
|
||||
if self.best_distance is None or distance < self.best_distance - 0.5:
|
||||
self.best_distance = distance
|
||||
self.last_progress_at = now
|
||||
@@ -266,6 +509,7 @@ class CombatStates:
|
||||
if distance <= self.ATTACK_REACH:
|
||||
has_line_of_sight = self._line_of_sight(target)
|
||||
if has_line_of_sight:
|
||||
self._stop_rush()
|
||||
self.g.path = []
|
||||
if now >= self.next_attack_at:
|
||||
self.g.game.attack_entity(self.target_id)
|
||||
@@ -289,6 +533,17 @@ class CombatStates:
|
||||
distance, len(self.g.path)))
|
||||
self.last_los_report_at = now
|
||||
|
||||
if self.evading:
|
||||
if self.g.path:
|
||||
return
|
||||
self.evading = False
|
||||
self.path_target = None
|
||||
self.next_path_at = 0.0
|
||||
|
||||
if (distance > self.ATTACK_REACH and
|
||||
self._try_evasion(target, now)):
|
||||
return
|
||||
|
||||
approach_distance = self._distance_from_path_target(target)
|
||||
if (self.path_target is not None and
|
||||
approach_distance > self.ATTACK_REACH):
|
||||
@@ -306,12 +561,15 @@ class CombatStates:
|
||||
def cleanup(self):
|
||||
total_elapsed = (time.monotonic() - self.started_at
|
||||
if self.started_at is not None else 0.0)
|
||||
self._stop_rush()
|
||||
self._log('combat finished after {:.2f}s: {} targets, {} attack '
|
||||
'attempts'.format(total_elapsed, self.targets_engaged,
|
||||
self.total_attacks))
|
||||
'attempts, {} evasions, {} rushes'.format(
|
||||
total_elapsed, self.targets_engaged,
|
||||
self.total_attacks, self.evasion_count, self.rush_count))
|
||||
self.g.path = []
|
||||
self.g.look_at = None
|
||||
self.target_id = None
|
||||
self.evading = False
|
||||
self.state = self.done
|
||||
job = self.g.get('job')
|
||||
if job is not None and getattr(job.state, '__name__', None) == 'combat':
|
||||
@@ -349,3 +607,12 @@ class CombatStates:
|
||||
self.best_distance = None
|
||||
self.last_progress_at = None
|
||||
self.last_los_report_at = 0.0
|
||||
self.evading = False
|
||||
self.next_evasion_at = 0.0
|
||||
self.evasion_side = 1
|
||||
self.evasion_count = 0
|
||||
self.rushing = False
|
||||
self.rush_until = 0.0
|
||||
self.next_rush_at = 0.0
|
||||
self.rush_count = 0
|
||||
self.seen_projectile_ids = set()
|
||||
@@ -496,6 +496,7 @@ class EntityManager:
|
||||
(SetEntityDataPacket, self.handle_entity_data),
|
||||
(BlockEntityDataPacket, self.handle_block_entity_data),
|
||||
(RemoveEntitiesPacket, self.handle_remove_entities),
|
||||
(packets.SetEquipmentPacket, self.handle_equipment),
|
||||
(MoveEntityPositionPacket, self.handle_move),
|
||||
(MoveEntityPositionRotationPacket, self.handle_move),
|
||||
(MoveEntityRotationPacket, self.handle_rotation),
|
||||
@@ -507,13 +508,17 @@ class EntityManager:
|
||||
|
||||
def handle_add_entity(self, packet):
|
||||
name = mobs.MOB_NAMES.get(packet.entity_type_id, 'unknown')
|
||||
common = dict(entity_id=packet.entity_id, x=packet.x,
|
||||
y=packet.y, z=packet.z)
|
||||
common = dict(
|
||||
entity_id=packet.entity_id, x=packet.x, y=packet.y, z=packet.z,
|
||||
spawn_x=packet.x, spawn_y=packet.y, spawn_z=packet.z,
|
||||
spawned_at=time.monotonic())
|
||||
if name == 'player':
|
||||
player_uuid = str(packet.entity_uuid)
|
||||
self.g.players[packet.entity_id] = Munch(
|
||||
**common, player_uuid=player_uuid,
|
||||
yaw=packet.yaw, pitch=packet.pitch)
|
||||
yaw=packet.yaw, pitch=packet.pitch,
|
||||
equipment={}, main_hand_item_id=None,
|
||||
position_updated_at=time.monotonic())
|
||||
elif name == 'item':
|
||||
self.g.objects[packet.entity_id] = Munch(
|
||||
**common, entity_uuid=str(packet.entity_uuid),
|
||||
@@ -524,7 +529,45 @@ class EntityManager:
|
||||
self.g.mobs[packet.entity_id] = Munch(
|
||||
**common, entity_uuid=str(packet.entity_uuid),
|
||||
type=packet.entity_type_id, yaw=packet.yaw,
|
||||
pitch=packet.pitch)
|
||||
pitch=packet.pitch, equipment={}, main_hand_item_id=None,
|
||||
position_updated_at=time.monotonic(),
|
||||
velocity_x=None, velocity_y=None, velocity_z=None,
|
||||
velocity_updated_at=None)
|
||||
|
||||
def handle_equipment(self, packet):
|
||||
entity = self._entity(packet.entity_id)
|
||||
if entity is None:
|
||||
return
|
||||
equipment = entity.get('equipment') or {}
|
||||
for slot, item in packet.equipment.items():
|
||||
if item.present:
|
||||
equipment[slot] = item
|
||||
else:
|
||||
equipment.pop(slot, None)
|
||||
entity.equipment = equipment
|
||||
main_hand = equipment.get(0)
|
||||
entity.main_hand_item_id = (
|
||||
main_hand.item_id if main_hand and main_hand.present else None)
|
||||
|
||||
def _record_entity_position(self, entity, position):
|
||||
now = time.monotonic()
|
||||
previous_time = entity.get('position_updated_at')
|
||||
previous = (entity.x, entity.y, entity.z)
|
||||
entity.x, entity.y, entity.z = position
|
||||
entity.position_updated_at = now
|
||||
|
||||
if (entity.get('type') not in mobs.RANGED_PROJECTILE_IDS or
|
||||
previous_time is None):
|
||||
return
|
||||
elapsed = now - previous_time
|
||||
if not 0.005 <= elapsed <= 0.5:
|
||||
return
|
||||
velocity = tuple((position[i] - previous[i]) / elapsed
|
||||
for i in range(3))
|
||||
if sum(component * component for component in velocity) > 2500:
|
||||
return
|
||||
entity.velocity_x, entity.velocity_y, entity.velocity_z = velocity
|
||||
entity.velocity_updated_at = now
|
||||
|
||||
def handle_block_entity_data(self, packet):
|
||||
location = packet.location
|
||||
@@ -551,9 +594,10 @@ class EntityManager:
|
||||
entity = self._entity(packet.entity_id)
|
||||
if entity is None:
|
||||
return
|
||||
entity.x += packet.delta_x
|
||||
entity.y += packet.delta_y
|
||||
entity.z += packet.delta_z
|
||||
self._record_entity_position(entity, (
|
||||
entity.x + packet.delta_x,
|
||||
entity.y + packet.delta_y,
|
||||
entity.z + packet.delta_z))
|
||||
if hasattr(packet, 'yaw'):
|
||||
entity.yaw = packet.yaw
|
||||
entity.pitch = packet.pitch
|
||||
@@ -567,7 +611,8 @@ class EntityManager:
|
||||
def handle_position_sync(self, packet):
|
||||
entity = self._entity(packet.entity_id)
|
||||
if entity is not None:
|
||||
entity.x, entity.y, entity.z = packet.x, packet.y, packet.z
|
||||
self._record_entity_position(
|
||||
entity, (packet.x, packet.y, packet.z))
|
||||
entity.yaw = packet.yaw
|
||||
entity.pitch = packet.pitch
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
from math import floor
|
||||
|
||||
from minecraft.networking.packets import Packet, PacketBuffer
|
||||
from minecraft.networking.modern import (
|
||||
UnsupportedItemComponents, read_item_stack,
|
||||
)
|
||||
from minecraft.networking.types import (
|
||||
VarInt, Integer, UnsignedByte, Position, Vector, MutableRecord,
|
||||
attribute_alias, multi_attribute_alias, Long, Boolean, VarLong,
|
||||
@@ -24,6 +27,32 @@ class SetHealthPacket(Packet):
|
||||
]
|
||||
|
||||
|
||||
class SetEquipmentPacket(Packet):
|
||||
"""Decode protocol-777 entity equipment updates."""
|
||||
id = 0x68
|
||||
packet_name = 'set equipment'
|
||||
|
||||
def read(self, file_object):
|
||||
self.entity_id = VarInt.read(file_object)
|
||||
self.equipment = {}
|
||||
self.incomplete = False
|
||||
for _ in range(16):
|
||||
packed_slot = UnsignedByte.read(file_object)
|
||||
slot = packed_slot & 0x7F
|
||||
has_more = bool(packed_slot & 0x80)
|
||||
try:
|
||||
self.equipment[slot] = read_item_stack(
|
||||
file_object, self.context)
|
||||
except UnsupportedItemComponents as exc:
|
||||
self.equipment[slot] = exc.stack
|
||||
self.incomplete = True
|
||||
file_object.read()
|
||||
return
|
||||
if not has_more:
|
||||
return
|
||||
raise ValueError('set equipment contains too many slots')
|
||||
|
||||
|
||||
class ChunkDataPacket(Packet):
|
||||
id = 0x20
|
||||
packet_name = 'chunk data'
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import io
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.packets import PacketBuffer
|
||||
from minecraft.networking.types import UnsignedByte, VarInt
|
||||
|
||||
from mosfet.info import items
|
||||
from mosfet.protocol.packets import SetEquipmentPacket
|
||||
|
||||
|
||||
class SetEquipmentPacketTests(unittest.TestCase):
|
||||
def test_decodes_mainhand_and_offhand_stacks(self):
|
||||
payload = PacketBuffer()
|
||||
VarInt.send(42, payload)
|
||||
UnsignedByte.send(0x80, payload) # main hand, another slot follows
|
||||
VarInt.send(1, payload)
|
||||
VarInt.send(items.get_id('bow'), payload)
|
||||
VarInt.send(0, payload) # no added components
|
||||
VarInt.send(0, payload) # no removed components
|
||||
UnsignedByte.send(1, payload) # off hand, final slot
|
||||
VarInt.send(0, payload) # empty stack
|
||||
|
||||
packet = SetEquipmentPacket(context=Munch(registry_ids={}))
|
||||
packet.read(io.BytesIO(payload.get_writable()))
|
||||
|
||||
self.assertEqual(packet.id, 0x68)
|
||||
self.assertEqual(packet.entity_id, 42)
|
||||
self.assertTrue(packet.equipment[0].present)
|
||||
self.assertEqual(packet.equipment[0].item_id, items.get_id('bow'))
|
||||
self.assertFalse(packet.equipment[1].present)
|
||||
self.assertFalse(packet.incomplete)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,38 @@
|
||||
import unittest
|
||||
|
||||
from munch import Munch
|
||||
from minecraft.networking.modern import ClientTickEnd
|
||||
|
||||
from mosfet.game import Game
|
||||
from mosfet.protocol.modern import PlayerCommandPacket
|
||||
|
||||
|
||||
class FakeConnection:
|
||||
def __init__(self):
|
||||
self.packets = []
|
||||
|
||||
def write_packet(self, packet, force=False):
|
||||
self.packets.append((packet, force))
|
||||
|
||||
|
||||
class SprintControlTests(unittest.TestCase):
|
||||
def test_start_and_stop_sprint_are_sent_once_each(self):
|
||||
connection = FakeConnection()
|
||||
game = Game.__new__(Game)
|
||||
game.g = Munch(connection=connection, eid=23, sprinting=False)
|
||||
|
||||
self.assertTrue(game.set_sprinting(True))
|
||||
self.assertFalse(game.set_sprinting(True))
|
||||
self.assertTrue(game.set_sprinting(False))
|
||||
|
||||
commands = [packet for packet, _force in connection.packets
|
||||
if isinstance(packet, PlayerCommandPacket)]
|
||||
self.assertEqual([packet.action_id for packet in commands], [1, 2])
|
||||
self.assertTrue(all(packet.entity_id == 23 for packet in commands))
|
||||
self.assertTrue(all(isinstance(packet, ClientTickEnd)
|
||||
for packet, _force in connection.packets[1::2]))
|
||||
self.assertFalse(game.g.sprinting)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user