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):
+68 -1
View File
@@ -1,4 +1,8 @@
import io
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
from munch import Munch
from mosfet.info import blocks, items
@@ -23,13 +27,50 @@ class CropBatchTests(unittest.TestCase):
self.assertEqual(g.look_at, crop)
self.assertEqual(g.path[-1], crop)
def test_found_crop_log_includes_search_duration(self):
crop = (1, 64, 1)
mature = blocks.MATURE_WHEAT_ID
class FakeWorld:
@staticmethod
def find_blocks_indexed(_center, _block_ids, _distance, sort=True):
return [crop]
@staticmethod
def filter_work_positions(positions):
return list(positions)
@staticmethod
def block_at(*_position):
return mature
state = GatherCropStates(Munch(
world=FakeWorld(), pos=(0, 64, 0)))
output = io.StringIO()
clock = [10.0]
def monotonic():
clock[0] += 0.1
return clock[0]
with patch('mosfet.jobs.gather_crop.time.monotonic',
side_effect=monotonic), redirect_stdout(output):
state.find_new_crop()
self.assertIn('Found crop after 0.90s:', output.getvalue())
self.assertIn('Crop search timings:', output.getvalue())
self.assertIn('ripe-index 0.100s (1/1 allowed)', output.getvalue())
self.assertIn('all-crops+types 0.100s (1/1 allowed)', output.getvalue())
self.assertIn('section-select 0.100s (1 ripe, 1 crops, selected section 1)',
output.getvalue())
def test_selection_rechecks_maturity_after_candidate_search(self):
position = (1, 64, 1)
unripe = blocks.MCD_BLOCKS['wheat']['minStateId']
class FakeWorld:
@staticmethod
def find_blocks_indexed(_center, block_ids, _distance):
def find_blocks_indexed(_center, block_ids, _distance, sort=True):
return [position]
@staticmethod
@@ -75,6 +116,32 @@ class CropBatchTests(unittest.TestCase):
self.assertEqual(game.break_calls, [])
self.assertIs(state.state.__func__, state.find_new_crop.__func__)
def test_already_held_seed_skips_selection_and_places_from_held_hand(self):
position = (1, 64, 1)
seed = items.WHEAT_SEEDS_ID
class FakeGame:
def __init__(self):
self.placements = []
def select_item(self, _item_ids):
raise AssertionError('already-held seed should not be selected')
def place_block(self, location, face, hand=0):
self.placements.append((location, face, hand))
game = FakeGame()
state = GatherCropStates(Munch(
game=game, holding=seed, holding_hand=1))
state.crop = position
state.type_id = blocks.MCD_BLOCKS['wheat']['minStateId']
state.select_seed()
self.assertIs(state.state.__func__, state.place_crop.__func__)
state.place_crop()
self.assertEqual(game.placements, [((1, 63, 1), 1, 1)])
def test_seed_selection_uses_crop_species_for_any_age_state(self):
unripe_wheat = blocks.MCD_BLOCKS['wheat']['minStateId']
+75
View File
@@ -0,0 +1,75 @@
import unittest
from munch import Munch
from mosfet.info import blocks
from mosfet.jobs.gather_crop import GatherCropStates
class CropSectionCacheTests(unittest.TestCase):
def make_world(self, crops):
class FakeWorld:
def __init__(self):
self.crops = dict(crops)
self.index_calls = 0
def find_blocks_indexed(self, _center, block_ids, _distance,
sort=True):
self.index_calls += 1
return [position for position, state in self.crops.items()
if state in block_ids]
@staticmethod
def filter_work_positions(positions):
return list(positions)
def block_at(self, *position):
return self.crops.get(tuple(position), blocks.AIR)
return FakeWorld()
def test_reuses_active_section_without_rebuilding_world_indexes(self):
first = (1, 64, 0)
second = (2, 64, 0)
unripe_wheat = blocks.MCD_BLOCKS['wheat']['minStateId']
world = self.make_world({
first: blocks.MATURE_WHEAT_ID,
second: unripe_wheat,
})
state = GatherCropStates(Munch(world=world, pos=(0, 64, 0)))
state.find_new_crop()
self.assertEqual(state.crop, first)
self.assertEqual(state.active_section_positions, {first, second})
self.assertEqual(world.index_calls, 2)
world.crops[first] = unripe_wheat
world.crops[second] = blocks.MATURE_WHEAT_ID
state.find_new_crop()
self.assertEqual(state.crop, second)
self.assertEqual(world.index_calls, 2)
self.assertEqual(state.active_section_maturity, (1, 2))
def test_rebuilds_cache_when_a_cached_crop_disappears(self):
first = (1, 64, 0)
second = (2, 64, 0)
unripe_wheat = blocks.MCD_BLOCKS['wheat']['minStateId']
world = self.make_world({
first: blocks.MATURE_WHEAT_ID,
second: unripe_wheat,
})
state = GatherCropStates(Munch(world=world, pos=(0, 64, 0)))
state.find_new_crop()
self.assertEqual(world.index_calls, 2)
world.crops.pop(first)
world.crops[second] = blocks.MATURE_WHEAT_ID
state.find_new_crop()
self.assertEqual(state.crop, second)
self.assertEqual(world.index_calls, 4)
self.assertEqual(state.active_section_positions, {second})
if __name__ == '__main__':
unittest.main()
+40
View File
@@ -0,0 +1,40 @@
import unittest
from munch import Munch
from mosfet.info import blocks
from mosfet.world import World
class IndexedSearchTests(unittest.TestCase):
def test_index_deduplication_is_linear_and_sort_is_optional(self):
far = (10, 64, 0)
near = (1, 64, 0)
class FakeChunks:
def __init__(self):
self.reads = {}
@staticmethod
def indexed_positions(_block_ids):
return [far, near, far]
def get_block_at(self, *position):
position = tuple(position)
self.reads[position] = self.reads.get(position, 0) + 1
return blocks.STONE
chunks = FakeChunks()
world = World(Munch(chunks=chunks))
self.assertEqual(world.find_blocks_indexed(
(0, 64, 0), {blocks.STONE}, 50), [near, far])
self.assertEqual(chunks.reads, {far: 1, near: 1})
chunks.reads.clear()
self.assertEqual(world.find_blocks_indexed(
(0, 64, 0), {blocks.STONE}, 50, sort=False), [far, near])
self.assertEqual(chunks.reads, {far: 1, near: 1})
if __name__ == '__main__':
unittest.main()
+2 -1
View File
@@ -13,7 +13,8 @@ class SignWorkTargetTests(unittest.TestCase):
crop_state = blocks.MCD_BLOCKS['wheat']['minStateId']
class FakeWorld:
def find_blocks_indexed(self, _center, _block_ids, _distance):
def find_blocks_indexed(self, _center, _block_ids, _distance,
sort=True):
return [outside]
@staticmethod