Cache active crop section and streamline harvesting

This commit is contained in:
Tanner committed 2026-11-09 17:37:32 +00:00
1 parent 1b4f32060d
commit 281e90a59f
6 files changed
+356 -22

No files matched your search

+162 -16
View File
@@ -59,6 +59,9 @@ class GatherCropStates:
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 = {}
@@ -99,11 +102,64 @@ class GatherCropStates:
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 find_new_crop(self):
started_at = time.monotonic()
print('Finding new crop...')
w = self.g.world
p = utils.pint(self.g.pos)
@@ -114,20 +170,49 @@ class GatherCropStates:
blocks.MATURE_CARROT_ID,
blocks.MATURE_BEETROOT_ID,
}
candidates = w.filter_work_positions(
w.find_blocks_indexed(p, mature_crops, 50))
crop_ids = (blocks.WHEAT_IDS | blocks.POTATO_IDS |
blocks.CARROT_IDS | blocks.BEETROOT_IDS)
crop_positions = w.filter_work_positions(
w.find_blocks_indexed(p, crop_ids, 50))
crop_types = {
position: blocks.BLOCKS.get(w.block_at(*position))
for position in crop_positions
}
crop, section_size = self._select_crop(candidates, crop_types, p)
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
@@ -143,9 +228,20 @@ class GatherCropStates:
self.state = self.find_new_crop
return
print('Found crop:', crop,
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
@@ -154,9 +250,15 @@ class GatherCropStates:
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
@@ -169,6 +271,10 @@ class GatherCropStates:
def going_to_crop(self):
if utils.pint(self.g.pos) == self.crop:
if self.crop_profile:
self.crop_profile['travel'] = (
time.monotonic() -
self.crop_profile.pop('travel_started_at', time.monotonic()))
print('At the crop')
self.state = self.break_crop
@@ -188,7 +294,10 @@ class GatherCropStates:
print('Requesting crop break at {}: block={}, mode={}, held={}'.format(
self.crop, current_state,
self.g.get('game_mode'), self.g.get('holding')))
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
@@ -202,9 +311,14 @@ class GatherCropStates:
def wait_break(self):
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))
self.seed_deadline = time.monotonic() + 8.0
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:
@@ -230,7 +344,14 @@ class GatherCropStates:
self.state = self.find_new_crop
return
if self.g.game.select_item([self.target_seed]):
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:
@@ -249,13 +370,19 @@ class GatherCropStates:
def wait_select(self):
if self.target_seed != self.g.holding:
return
else:
self.state = self.place_crop
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):
p = utils.padd(self.crop, path.BLOCK_BELOW)
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)
self.g.game.place_block(
p, BlockFace.TOP, hand=self.g.get('holding_hand', 0))
print('Placed crop')
self.state = self.wait_place
@@ -267,6 +394,22 @@ class GatherCropStates:
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(
@@ -299,6 +442,9 @@ class GatherCropStates:
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
+9 -4
View File
@@ -353,7 +353,7 @@ class World:
if self.block_at(*check) in block_ids:
yield check
def find_blocks_indexed(self, center, block_ids, distance=0):
def find_blocks_indexed(self, center, block_ids, distance=0, sort=True):
chunks = self.g.chunks
if hasattr(chunks, 'indexed_positions'):
index = chunks.indexed_positions(block_ids)
@@ -363,15 +363,20 @@ class World:
index.extend(chunks.index.get(bid, []))
result = []
seen = set()
for block in index:
block = tuple(block)
if block in seen:
continue
seen.add(block)
if self.block_at(*block) not in block_ids:
continue
if distance and utils.phyp(center, block) > distance:
continue
if block not in result:
result.append(block)
result.append(block)
result.sort(key=lambda x: utils.phyp(center, x))
if sort:
result.sort(key=lambda x: utils.phyp(center, x))
return result
def find_blocks(self, center, distance, block_ids, limit=0):