519 lines
21 KiB
Python
519 lines
21 KiB
Python
import re
|
|
import time
|
|
import importlib
|
|
import random
|
|
from itertools import count
|
|
from math import floor
|
|
|
|
from minecraft.networking.types import BlockFace
|
|
|
|
from mosfet.protocol.managers import ChunkNotLoadedException
|
|
|
|
from mosfet import utils
|
|
from mosfet import path
|
|
from mosfet.info import blocks
|
|
from mosfet.info import items
|
|
from mosfet.info import mcdata
|
|
from mosfet.info import mobs
|
|
|
|
class GatherCropStates:
|
|
CROPS_PER_BATCH = 16
|
|
SECTION_MATURITY_WEIGHT = 2.0
|
|
CROP_REACH_DISTANCE = 3.0
|
|
|
|
def idle(self):
|
|
return None
|
|
|
|
def init(self):
|
|
self.state = self.find_new_crop
|
|
|
|
def _select_crop(self, candidates, crop_types, center):
|
|
"""Stay with a connected same-species patch, nearest patch first."""
|
|
adjacent_offsets = ((1, 0, 0), (-1, 0, 0),
|
|
(0, 0, 1), (0, 0, -1))
|
|
remaining = set(crop_types)
|
|
component_for = {}
|
|
component_sizes = {}
|
|
component_id = 0
|
|
|
|
while remaining:
|
|
seed = remaining.pop()
|
|
species = crop_types[seed]
|
|
stack = [seed]
|
|
component = [seed]
|
|
component_for[seed] = component_id
|
|
while stack:
|
|
x, y, z = stack.pop()
|
|
for dx, dy, dz in adjacent_offsets:
|
|
adjacent = (x + dx, y + dy, z + dz)
|
|
if (adjacent in remaining and
|
|
crop_types[adjacent] == species):
|
|
remaining.remove(adjacent)
|
|
component_for[adjacent] = component_id
|
|
component.append(adjacent)
|
|
stack.append(adjacent)
|
|
component_sizes[component_id] = len(component)
|
|
component_id += 1
|
|
|
|
eligible = [position for position in candidates
|
|
if position not in self.bad_crops and
|
|
position in component_for]
|
|
if not eligible:
|
|
self.active_section_maturity = (0, 0)
|
|
self.active_section_anchor = None
|
|
self.active_section_positions = None
|
|
self.active_section_species = None
|
|
return None, 0
|
|
|
|
mature_by_component = {}
|
|
candidates_by_component = {}
|
|
for position in eligible:
|
|
component = component_for[position]
|
|
mature_by_component[component] = (
|
|
mature_by_component.get(component, 0) + 1)
|
|
candidates_by_component.setdefault(component, []).append(position)
|
|
|
|
active_component = component_for.get(self.active_section_anchor)
|
|
active_candidates = candidates_by_component.get(active_component, [])
|
|
if active_candidates:
|
|
section_candidates = active_candidates
|
|
selected_component = active_component
|
|
else:
|
|
# Favor a nearby section if maturity is similar, but allow a
|
|
# farther, substantially more-mature section to win. Once chosen,
|
|
# keep working that connected component until it has no mature
|
|
# crops left, matching the existing patch-stability behavior.
|
|
ranked_sections = []
|
|
for component, positions in candidates_by_component.items():
|
|
nearest_crop = min(positions, key=lambda position: (
|
|
utils.phyp(center, position), position))
|
|
distance = utils.phyp(center, nearest_crop)
|
|
maturity = (mature_by_component[component] /
|
|
component_sizes[component])
|
|
score = distance / (
|
|
1.0 + self.SECTION_MATURITY_WEIGHT * maturity)
|
|
ranked_sections.append((
|
|
score, distance, -mature_by_component[component],
|
|
nearest_crop, component,
|
|
))
|
|
selected_component = min(ranked_sections)[-1]
|
|
section_candidates = candidates_by_component[selected_component]
|
|
|
|
crop = min(section_candidates, key=lambda position: (
|
|
utils.phyp(center, position), position))
|
|
section_size = component_sizes[selected_component]
|
|
self.active_section_anchor = crop
|
|
self.active_section_positions = {
|
|
position for position, component in component_for.items()
|
|
if component == selected_component
|
|
}
|
|
self.active_section_species = crop_types[crop]
|
|
self.active_section_maturity = (
|
|
mature_by_component[selected_component], section_size)
|
|
return crop, section_size
|
|
|
|
def _select_cached_crop(self, world, center, crop_ids, mature_crops,
|
|
distance=50):
|
|
"""Pick a mature crop from the cached active component, if still valid."""
|
|
positions = getattr(self, 'active_section_positions', None)
|
|
species = getattr(self, 'active_section_species', None)
|
|
if not positions or not species:
|
|
return None, 'no-cache', 0
|
|
|
|
cached = set(positions)
|
|
allowed = set(world.filter_work_positions(cached))
|
|
if allowed != cached:
|
|
return None, 'work-policy', 0
|
|
if any(utils.phyp(center, position) > distance
|
|
for position in cached):
|
|
return None, 'out-of-range', 0
|
|
|
|
candidates = []
|
|
for position in cached:
|
|
state_id = world.block_at(*position)
|
|
if (state_id not in crop_ids or
|
|
blocks.BLOCKS.get(state_id) != species):
|
|
return None, 'crop-changed', 0
|
|
if state_id in mature_crops and position not in self.bad_crops:
|
|
candidates.append(position)
|
|
|
|
# If a same-species crop was added next to the cached component, rebuild
|
|
# so the component size and maturity statistics include the extension.
|
|
boundary = set()
|
|
for x, y, z in cached:
|
|
for dx, dz in ((1, 0), (-1, 0), (0, 1), (0, -1)):
|
|
neighbor = (x + dx, y, z + dz)
|
|
if (neighbor not in cached and
|
|
utils.phyp(center, neighbor) <= distance):
|
|
boundary.add(neighbor)
|
|
for neighbor in world.filter_work_positions(boundary):
|
|
if blocks.BLOCKS.get(world.block_at(*neighbor)) == species:
|
|
return None, 'patch-expanded', len(candidates)
|
|
|
|
if not candidates:
|
|
return None, 'exhausted', 0
|
|
|
|
crop = min(candidates, key=lambda position: (
|
|
utils.phyp(center, position), position))
|
|
self.active_section_anchor = crop
|
|
self.active_section_maturity = (len(candidates), len(cached))
|
|
return crop, None, len(candidates)
|
|
|
|
def _finish_crop_travel(self):
|
|
if (self.crop_profile and
|
|
self.crop_profile.get('travel_started_at') is not None and
|
|
utils.pint(self.g.pos) == self.crop):
|
|
self.crop_profile['travel'] = (
|
|
time.monotonic() - self.crop_profile.pop('travel_started_at'))
|
|
|
|
def _crop_interaction_distance(self, target_block, hit_point):
|
|
position = self.g.pos
|
|
player = tuple(
|
|
getattr(position, axis) if hasattr(position, axis) else position[index]
|
|
for index, axis in enumerate(('x', 'y', 'z')))
|
|
eye = (player[0], player[1] + 1.62, player[2])
|
|
distance = utils.hypot(*(eye[i] - hit_point[i] for i in range(3)))
|
|
if distance > self.CROP_REACH_DISTANCE:
|
|
return None
|
|
if not self.g.world._has_cache_line_of_sight(
|
|
eye, hit_point, tuple(target_block)):
|
|
return None
|
|
return distance
|
|
|
|
def _crop_break_distance(self):
|
|
point = tuple(value + 0.5 for value in self.crop)
|
|
return self._crop_interaction_distance(self.crop, point)
|
|
|
|
def find_new_crop(self):
|
|
started_at = time.monotonic()
|
|
print('Finding new crop...')
|
|
w = self.g.world
|
|
p = utils.pint(self.g.pos)
|
|
|
|
mature_crops = {
|
|
blocks.MATURE_WHEAT_ID,
|
|
blocks.MATURE_POTATO_ID,
|
|
blocks.MATURE_CARROT_ID,
|
|
blocks.MATURE_BEETROOT_ID,
|
|
}
|
|
crop_ids = (blocks.WHEAT_IDS | blocks.POTATO_IDS |
|
|
blocks.CARROT_IDS | blocks.BEETROOT_IDS)
|
|
|
|
cache_started_at = time.monotonic()
|
|
crop, cache_status, cached_ripe = self._select_cached_crop(
|
|
w, p, crop_ids, mature_crops, 50)
|
|
cache_time = time.monotonic() - cache_started_at
|
|
if crop is not None:
|
|
section_size = len(self.active_section_positions)
|
|
print('Crop search timings: active-patch {:.3f}s '
|
|
'({}/{} ripe, cache hit)'.format(
|
|
cache_time, cached_ripe, section_size))
|
|
else:
|
|
if cache_status != 'no-cache':
|
|
print('Active crop cache refresh:', cache_status)
|
|
stage_started_at = time.monotonic()
|
|
indexed_candidates = w.find_blocks_indexed(
|
|
p, mature_crops, 50, sort=False)
|
|
candidates = w.filter_work_positions(indexed_candidates)
|
|
mature_scan_time = time.monotonic() - stage_started_at
|
|
|
|
stage_started_at = time.monotonic()
|
|
indexed_crop_positions = w.find_blocks_indexed(
|
|
p, crop_ids, 50, sort=False)
|
|
crop_positions = w.filter_work_positions(indexed_crop_positions)
|
|
crop_types = {
|
|
position: blocks.BLOCKS.get(w.block_at(*position))
|
|
for position in crop_positions
|
|
}
|
|
crop_scan_time = time.monotonic() - stage_started_at
|
|
|
|
stage_started_at = time.monotonic()
|
|
crop, section_size = self._select_crop(candidates, crop_types, p)
|
|
section_time = time.monotonic() - stage_started_at
|
|
print('Crop search timings: ripe-index {:.3f}s ({}/{} allowed), '
|
|
'all-crops+types {:.3f}s ({}/{} allowed), '
|
|
'section-select {:.3f}s ({} ripe, {} crops, selected section {})'.format(
|
|
mature_scan_time, len(candidates), len(indexed_candidates),
|
|
crop_scan_time, len(crop_positions), len(indexed_crop_positions),
|
|
section_time, len(candidates), len(crop_types), section_size))
|
|
|
|
if crop is None:
|
|
self.crop_profile = None
|
|
print('No good crops left; running maintenance after {} harvests'.format(
|
|
self.completed_crops))
|
|
self.completed_crops = 0
|
|
self.state = self.cleanup
|
|
return
|
|
|
|
mature_count, total_count = self.active_section_maturity
|
|
maturity_percent = (100 * mature_count / total_count
|
|
if total_count else 0)
|
|
crop_state = w.block_at(*crop)
|
|
if crop_state not in mature_crops:
|
|
print('Crop changed while selecting; refreshing the crop list')
|
|
self.state = self.find_new_crop
|
|
return
|
|
|
|
elapsed = time.monotonic() - started_at
|
|
print('Found crop after {:.2f}s:'.format(elapsed), crop,
|
|
'(same-species section: {}/{} mature, {:.0f}%)'.format(
|
|
mature_count, total_count, maturity_percent))
|
|
self.crop_profile = {
|
|
'started_at': started_at,
|
|
'search': elapsed,
|
|
'pathfind': 0.0,
|
|
'path_steps': 0,
|
|
'travel': 0.0,
|
|
'break': 0.0,
|
|
'seed': 0.0,
|
|
'plant': 0.0,
|
|
}
|
|
self.crop = crop
|
|
self.type_id = crop_state
|
|
self.state = self.nav_to_crop
|
|
|
|
def nav_to_crop(self):
|
|
w = self.g.world
|
|
p = utils.pint(self.g.pos)
|
|
|
|
pathfind_started_at = time.monotonic()
|
|
navpath = w.path_to_place(p, self.crop)
|
|
pathfind_time = time.monotonic() - pathfind_started_at
|
|
|
|
if navpath:
|
|
if self.crop_profile:
|
|
self.crop_profile['pathfind'] = pathfind_time
|
|
self.crop_profile['path_steps'] = len(navpath)
|
|
self.crop_profile['travel_started_at'] = time.monotonic()
|
|
print('Going to crop', self.crop)
|
|
self.g.path = navpath
|
|
self.g.look_at = self.crop
|
|
self.state = self.going_to_crop
|
|
else:
|
|
print('Cant get to it, blacklisting')
|
|
time.sleep(0.1)
|
|
self.bad_crops.append(self.crop)
|
|
self.state = self.find_new_crop
|
|
|
|
def going_to_crop(self):
|
|
world = self.g.world
|
|
current_state = world.block_at(*self.crop)
|
|
if current_state != self.type_id:
|
|
print('Crop changed while approaching; selecting another crop:',
|
|
self.crop, current_state)
|
|
self.g.path = []
|
|
self.g.look_at = None
|
|
self.state = self.find_new_crop
|
|
return
|
|
|
|
position = utils.pint(self.g.pos)
|
|
distance = self._crop_break_distance()
|
|
if distance is not None:
|
|
if position == self.crop:
|
|
self._finish_crop_travel()
|
|
print('At the crop')
|
|
else:
|
|
print('Crop in reach while approaching ({:.2f} blocks):'.format(
|
|
distance), self.crop)
|
|
if self.crop_profile:
|
|
self.crop_profile['break_started_en_route'] = True
|
|
self.state = self.break_crop
|
|
|
|
def break_crop(self):
|
|
self._finish_crop_travel()
|
|
current_state = self.g.world.block_at(*self.crop)
|
|
mature_crops = {
|
|
blocks.MATURE_WHEAT_ID,
|
|
blocks.MATURE_POTATO_ID,
|
|
blocks.MATURE_CARROT_ID,
|
|
blocks.MATURE_BEETROOT_ID,
|
|
}
|
|
if current_state != self.type_id or current_state not in mature_crops:
|
|
print('Crop changed before break; selecting another crop:',
|
|
self.crop, current_state)
|
|
self.g.path = []
|
|
self.g.look_at = None
|
|
self.state = self.find_new_crop
|
|
return
|
|
distance = self._crop_break_distance()
|
|
if distance is None:
|
|
self.state = self.going_to_crop
|
|
return
|
|
print('Requesting crop break at {}: block={}, mode={}, held={}, '
|
|
'reach={:.2f}'.format(
|
|
self.crop, current_state, self.g.get('game_mode'),
|
|
self.g.get('holding'), distance))
|
|
break_started_at = time.monotonic()
|
|
if self.g.game.break_block(self.crop):
|
|
if self.crop_profile:
|
|
self.crop_profile['break_started_at'] = break_started_at
|
|
print('Started breaking crop {} (state {})'.format(
|
|
self.crop, self.type_id))
|
|
self.break_deadline = time.time() + 5.0
|
|
self.state = self.wait_break
|
|
else:
|
|
print('Break request skipped; current block is',
|
|
self.g.world.block_at(*self.crop))
|
|
self.bad_crops.append(self.crop)
|
|
self.g.path = []
|
|
self.g.look_at = None
|
|
self.state = self.find_new_crop
|
|
|
|
def wait_break(self):
|
|
self._finish_crop_travel()
|
|
current_state = self.g.world.block_at(*self.crop)
|
|
if current_state != self.type_id:
|
|
now = time.monotonic()
|
|
print('Crop break confirmed at {}: {} -> {}'.format(
|
|
self.crop, self.type_id, current_state))
|
|
if self.crop_profile:
|
|
self.crop_profile['break'] = (
|
|
now - self.crop_profile.pop('break_started_at', now))
|
|
self.crop_profile['seed_started_at'] = now
|
|
self.seed_deadline = now + 8.0
|
|
self.seed_wait_logged = False
|
|
self.state = self.select_seed
|
|
elif time.time() > self.break_deadline:
|
|
print('Crop break timed out at {}: expected state {}, server still has {}'.format(
|
|
self.crop, self.type_id, current_state))
|
|
print('Crop did not break; blacklisting', self.crop)
|
|
self.bad_crops.append(self.crop)
|
|
self.state = self.find_new_crop
|
|
|
|
def select_seed(self):
|
|
self._finish_crop_travel()
|
|
crop_seeds = {
|
|
'wheat': items.WHEAT_SEEDS_ID,
|
|
'potatoes': items.POTATO_ID,
|
|
'carrots': items.CARROT_ID,
|
|
'beetroots': items.BEETROOT_SEEDS_ID,
|
|
}
|
|
crop_name = blocks.BLOCKS.get(self.type_id)
|
|
self.target_seed = crop_seeds.get(crop_name)
|
|
if self.target_seed is None:
|
|
print('Cannot select a seed for crop state', self.type_id,
|
|
crop_name)
|
|
self.bad_crops.append(self.crop)
|
|
self.state = self.find_new_crop
|
|
return
|
|
|
|
if self.target_seed == self.g.get('holding'):
|
|
if self.crop_profile:
|
|
self.crop_profile['seed'] = (
|
|
time.monotonic() -
|
|
self.crop_profile.pop('seed_started_at', time.monotonic()))
|
|
self.seed_deadline = None
|
|
self.state = self.place_crop
|
|
elif self.g.game.select_item([self.target_seed]):
|
|
self.seed_deadline = None
|
|
self.state = self.wait_select
|
|
else:
|
|
if (self.seed_deadline is not None and
|
|
time.monotonic() > self.seed_deadline):
|
|
print('No seed collected for crop; skipping', self.crop)
|
|
self.bad_crops.append(self.crop)
|
|
self.seed_deadline = None
|
|
self.state = self.find_new_crop
|
|
elif not getattr(self, 'seed_wait_logged', False):
|
|
print('Waiting for crop seed {} in inventory/hotbar'.format(
|
|
self.target_seed))
|
|
self.seed_wait_logged = True
|
|
return
|
|
|
|
def wait_select(self):
|
|
self._finish_crop_travel()
|
|
if self.target_seed != self.g.holding:
|
|
return
|
|
if self.crop_profile:
|
|
self.crop_profile['seed'] = (
|
|
time.monotonic() -
|
|
self.crop_profile.pop('seed_started_at', time.monotonic()))
|
|
self.state = self.place_crop
|
|
|
|
def place_crop(self):
|
|
self._finish_crop_travel()
|
|
position = self.g.get('pos')
|
|
if position is not None and utils.pint(position) != self.crop:
|
|
return
|
|
p = utils.padd(self.crop, path.BLOCK_BELOW)
|
|
if position is not None and self.g.get('world') is not None:
|
|
hit_point = (p[0] + 0.5, p[1] + 1.0, p[2] + 0.5)
|
|
distance = self._crop_interaction_distance(p, hit_point)
|
|
if distance is None:
|
|
# Keep the existing path moving until the support face is
|
|
# within reach and visible.
|
|
return
|
|
if self.crop_profile:
|
|
self.crop_profile['plant_started_at'] = time.monotonic()
|
|
self.place_deadline = time.time() + 3.0
|
|
self.g.game.place_block(
|
|
p, BlockFace.TOP, hand=self.g.get('holding_hand', 0))
|
|
print('Placed crop')
|
|
self.state = self.wait_place
|
|
|
|
def wait_place(self):
|
|
self._finish_crop_travel()
|
|
w = self.g.world
|
|
current_state = w.block_at(*self.crop)
|
|
crop_name = blocks.BLOCKS.get(self.type_id)
|
|
replanted = (current_state not in (None, blocks.AIR) and
|
|
blocks.BLOCKS.get(current_state) == crop_name and
|
|
current_state != self.type_id)
|
|
if replanted:
|
|
if self.crop_profile:
|
|
now = time.monotonic()
|
|
self.crop_profile['plant'] = (
|
|
now - self.crop_profile.pop('plant_started_at', now))
|
|
print('Crop cycle timings: total={:.3f}s search={:.3f}s '
|
|
'pathfind={:.3f}s/{} steps travel={:.3f}s '
|
|
'break={:.3f}s seed={:.3f}s plant={:.3f}s'.format(
|
|
now - self.crop_profile['started_at'],
|
|
self.crop_profile['search'],
|
|
self.crop_profile['pathfind'],
|
|
self.crop_profile['path_steps'],
|
|
self.crop_profile['travel'],
|
|
self.crop_profile['break'],
|
|
self.crop_profile['seed'],
|
|
self.crop_profile['plant']))
|
|
self.crop_profile = None
|
|
self.completed_crops += 1
|
|
if self.completed_crops >= self.CROPS_PER_BATCH:
|
|
print('Completed {} crop harvests; running maintenance'.format(
|
|
self.completed_crops))
|
|
self.completed_crops = 0
|
|
self.state = self.cleanup
|
|
else:
|
|
self.state = self.find_new_crop
|
|
elif time.time() > getattr(self, 'place_deadline', 0):
|
|
print('Crop did not replant; blacklisting', self.crop)
|
|
self.bad_crops.append(self.crop)
|
|
self.state = self.find_new_crop
|
|
|
|
def cleanup(self):
|
|
self.g.look_at = None
|
|
self.state = self.done
|
|
|
|
def done(self):
|
|
# never gets ran, placeholder
|
|
return None
|
|
|
|
def __init__(self, global_state):
|
|
self.g = global_state
|
|
self.state = self.idle
|
|
|
|
self.crop = None
|
|
self.type_id = None
|
|
self.target_seed = None
|
|
self.seed_deadline = None
|
|
self.seed_wait_logged = False
|
|
self.active_section_anchor = None
|
|
self.active_section_maturity = (0, 0)
|
|
self.active_section_positions = None
|
|
self.active_section_species = None
|
|
self.crop_profile = None
|
|
self.bad_crops = []
|
|
self.completed_crops = 0
|
|
|
|
def run(self):
|
|
self.state()
|