Monitor threats independently of active jobs
This commit is contained in:
1 parent
f799a9ea47
commit
038fc503f0
4 files changed
+320
-8
No files matched your search
+25
-1
@@ -289,7 +289,8 @@ def tick(global_state):
|
|||||||
g.connection.write_packet(packet, force=True)
|
g.connection.write_packet(packet, force=True)
|
||||||
g.connection.write_packet(ClientTickEnd(), force=True)
|
g.connection.write_packet(ClientTickEnd(), force=True)
|
||||||
|
|
||||||
if g.job:
|
monitor = g.get('threat_monitor')
|
||||||
|
if g.job and not (monitor and monitor.suppress_job):
|
||||||
g.job.tick()
|
g.job.tick()
|
||||||
if g.game:
|
if g.game:
|
||||||
g.game.tick() # order important for correction_count
|
g.game.tick() # order important for correction_count
|
||||||
@@ -472,6 +473,10 @@ def start_automation(global_state, initialize=True):
|
|||||||
g.game = Game(g)
|
g.game = Game(g)
|
||||||
g.job = JobStates(g)
|
g.job = JobStates(g)
|
||||||
|
|
||||||
|
if g.get('threat_monitor') is None:
|
||||||
|
from mosfet.jobs.check_threats import ThreatMonitor
|
||||||
|
g.threat_monitor = ThreatMonitor(g)
|
||||||
|
|
||||||
# Preserve active work during hot reloads, but give the worker all fields
|
# Preserve active work during hot reloads, but give the worker all fields
|
||||||
# introduced by the currently migrated inventory controls.
|
# introduced by the currently migrated inventory controls.
|
||||||
g.setdefault('draining', False)
|
g.setdefault('draining', False)
|
||||||
@@ -527,6 +532,25 @@ def start_automation(global_state, initialize=True):
|
|||||||
initial_world_ready = True
|
initial_world_ready = True
|
||||||
else:
|
else:
|
||||||
loaded_since = None
|
loaded_since = None
|
||||||
|
# The monitor runs even with no active job; its own 0.5-second
|
||||||
|
# timer keeps idle threat surveillance cheap and non-blocking.
|
||||||
|
monitor = g.get('threat_monitor')
|
||||||
|
if monitor is not None:
|
||||||
|
try:
|
||||||
|
reload_lock = g.get('reload_lock')
|
||||||
|
if reload_lock is None:
|
||||||
|
monitor.tick()
|
||||||
|
else:
|
||||||
|
with reload_lock:
|
||||||
|
monitor.tick()
|
||||||
|
except Exception:
|
||||||
|
traceback.print_exc()
|
||||||
|
g.movement_error = traceback.format_exc()
|
||||||
|
g.movement_status = 'error'
|
||||||
|
print('[movement] stopped after threat-monitor error',
|
||||||
|
flush=True)
|
||||||
|
return
|
||||||
|
|
||||||
# Wait once for the initial position/chunk batch. After that,
|
# Wait once for the initial position/chunk batch. After that,
|
||||||
# bot.tick() keeps requesting chunks at cache boundaries instead
|
# bot.tick() keeps requesting chunks at cache boundaries instead
|
||||||
# of gating itself forever on a momentary missing column.
|
# of gating itself forever on a momentary missing column.
|
||||||
|
|||||||
+5
-2
@@ -347,10 +347,13 @@ class JobStates(LegacyJobStates):
|
|||||||
|
|
||||||
def loiter(self):
|
def loiter(self):
|
||||||
self.sleep_with_bed_states.silent = True
|
self.sleep_with_bed_states.silent = True
|
||||||
return [self.check_threats_states, self.sleep_with_bed_states,
|
return [self.sleep_with_bed_states, self.eat_food_states]
|
||||||
self.eat_food_states]
|
|
||||||
|
|
||||||
def stop(self):
|
def stop(self):
|
||||||
|
monitor = self.g.get('threat_monitor')
|
||||||
|
if (monitor is not None and
|
||||||
|
not getattr(monitor, 'suspending_job', False)):
|
||||||
|
monitor.cancel_resume()
|
||||||
if self.g.get('breaking'):
|
if self.g.get('breaking'):
|
||||||
self.g.game.cancel_break()
|
self.g.game.cancel_break()
|
||||||
if self.g.get('window'):
|
if self.g.get('window'):
|
||||||
|
|||||||
@@ -16,6 +16,192 @@ from mosfet.info import items
|
|||||||
from mosfet.info import mcdata
|
from mosfet.info import mcdata
|
||||||
from mosfet.info import mobs
|
from mosfet.info import mobs
|
||||||
|
|
||||||
|
class ThreatMonitor:
|
||||||
|
"""Background threat supervisor driven by the movement tick loop."""
|
||||||
|
CHECK_INTERVAL = 0.5
|
||||||
|
THREAT_DISTANCE = 32
|
||||||
|
CLEAR_DISTANCE = 40
|
||||||
|
SAFE_WAIT = 10.0
|
||||||
|
SAFETY_SEARCH_DISTANCE = 80
|
||||||
|
|
||||||
|
@property
|
||||||
|
def suppress_job(self):
|
||||||
|
return self.state != self.watching
|
||||||
|
|
||||||
|
def cancel_resume(self):
|
||||||
|
"""Do not restart a job explicitly stopped during an evacuation."""
|
||||||
|
self.resume_job_name = None
|
||||||
|
|
||||||
|
def _stop_job(self):
|
||||||
|
job = self.g.get('job')
|
||||||
|
if job is None:
|
||||||
|
return
|
||||||
|
self.suspending_job = True
|
||||||
|
try:
|
||||||
|
job.stop()
|
||||||
|
finally:
|
||||||
|
self.suspending_job = False
|
||||||
|
|
||||||
|
def _suspend_job(self):
|
||||||
|
job = self.g.get('job')
|
||||||
|
self.job_suspended = job is not None
|
||||||
|
if job is None or job.state == job.idle:
|
||||||
|
return
|
||||||
|
self.resume_job_name = getattr(job.state, '__name__', None)
|
||||||
|
self._stop_job()
|
||||||
|
|
||||||
|
def _capture_job_change(self):
|
||||||
|
job = self.g.get('job')
|
||||||
|
if (not self.job_suspended or job is None or
|
||||||
|
job.state == job.idle):
|
||||||
|
return
|
||||||
|
self.resume_job_name = getattr(job.state, '__name__', None)
|
||||||
|
print('[threat] queued job change until the area is safe', flush=True)
|
||||||
|
self._stop_job()
|
||||||
|
|
||||||
|
def _find_safety(self):
|
||||||
|
world = self.g.world
|
||||||
|
position = utils.pint(self.g.pos)
|
||||||
|
self.safety = None
|
||||||
|
self.g.path = []
|
||||||
|
|
||||||
|
safety_blocks = world.find_blocks_indexed(
|
||||||
|
position, {blocks.EMERALD_BLOCK}, self.SAFETY_SEARCH_DISTANCE)
|
||||||
|
for block in safety_blocks:
|
||||||
|
spot = utils.padd(block, path.BLOCK_ABOVE)
|
||||||
|
if world.find_threats(spot, self.CLEAR_DISTANCE):
|
||||||
|
continue
|
||||||
|
navpath = world.path_to_place(position, spot)
|
||||||
|
if navpath is not None:
|
||||||
|
self.safety = spot
|
||||||
|
self.g.path = navpath
|
||||||
|
print('[threat] evacuating to safety marker', spot, flush=True)
|
||||||
|
return True
|
||||||
|
|
||||||
|
for spot in world.find_bed_areas(
|
||||||
|
position, self.CLEAR_DISTANCE * 2):
|
||||||
|
if world.find_threats(spot, self.CLEAR_DISTANCE):
|
||||||
|
continue
|
||||||
|
navpath = world.path_to_place(position, spot)
|
||||||
|
if navpath is not None:
|
||||||
|
self.safety = spot
|
||||||
|
self.g.path = navpath
|
||||||
|
print('[threat] fleeing to clear area', spot, flush=True)
|
||||||
|
return True
|
||||||
|
|
||||||
|
print('[threat] no reachable safe area; retrying', flush=True)
|
||||||
|
self.retry_at = time.monotonic() + self.CHECK_INTERVAL
|
||||||
|
return False
|
||||||
|
|
||||||
|
def watching(self):
|
||||||
|
now = time.monotonic()
|
||||||
|
if now < self.next_scan_at:
|
||||||
|
return
|
||||||
|
self.next_scan_at = now + self.CHECK_INTERVAL
|
||||||
|
threats = self.g.world.find_threats(
|
||||||
|
utils.pint(self.g.pos), self.THREAT_DISTANCE)
|
||||||
|
if not threats:
|
||||||
|
return
|
||||||
|
|
||||||
|
self.threats = threats
|
||||||
|
print('[threat] detected {} nearby hostile(s); pausing job: {}'.format(
|
||||||
|
len(threats), threats), flush=True)
|
||||||
|
self._suspend_job()
|
||||||
|
self.g.look_at = None
|
||||||
|
self.safe_since = None
|
||||||
|
self.state = self.evacuating
|
||||||
|
self._find_safety()
|
||||||
|
|
||||||
|
def evacuating(self):
|
||||||
|
self._capture_job_change()
|
||||||
|
now = time.monotonic()
|
||||||
|
if now >= self.next_scan_at:
|
||||||
|
self.next_scan_at = now + self.CHECK_INTERVAL
|
||||||
|
position = utils.pint(self.g.pos)
|
||||||
|
threats = self.g.world.find_threats(
|
||||||
|
position, self.THREAT_DISTANCE)
|
||||||
|
if threats:
|
||||||
|
self.threats = threats
|
||||||
|
if (self.safety is not None and
|
||||||
|
self.g.world.find_threats(
|
||||||
|
self.safety, self.CLEAR_DISTANCE)):
|
||||||
|
print('[threat] planned refuge is no longer clear; '
|
||||||
|
'choosing another', flush=True)
|
||||||
|
self.safety = None
|
||||||
|
self.g.path = []
|
||||||
|
self._find_safety()
|
||||||
|
|
||||||
|
if self.safety is not None and utils.pint(self.g.pos) == self.safety:
|
||||||
|
self.g.path = []
|
||||||
|
self.safe_since = None
|
||||||
|
self.next_scan_at = 0.0
|
||||||
|
self.state = self.waiting
|
||||||
|
print('[threat] reached safety; waiting for patrol to leave',
|
||||||
|
flush=True)
|
||||||
|
return
|
||||||
|
|
||||||
|
if not self.g.path and now >= self.retry_at:
|
||||||
|
self._find_safety()
|
||||||
|
|
||||||
|
def waiting(self):
|
||||||
|
self._capture_job_change()
|
||||||
|
now = time.monotonic()
|
||||||
|
if now < self.next_scan_at:
|
||||||
|
return
|
||||||
|
self.next_scan_at = now + self.CHECK_INTERVAL
|
||||||
|
threats = self.g.world.find_threats(
|
||||||
|
utils.pint(self.g.pos), self.CLEAR_DISTANCE)
|
||||||
|
if threats:
|
||||||
|
print('[threat] hostile still within safety radius; moving again',
|
||||||
|
flush=True)
|
||||||
|
self.threats = threats
|
||||||
|
self.safe_since = None
|
||||||
|
self.safety = None
|
||||||
|
self.state = self.evacuating
|
||||||
|
self._find_safety()
|
||||||
|
return
|
||||||
|
|
||||||
|
if self.safe_since is None:
|
||||||
|
self.safe_since = now
|
||||||
|
elif now - self.safe_since >= self.SAFE_WAIT:
|
||||||
|
self.state = self.resuming
|
||||||
|
|
||||||
|
def resuming(self):
|
||||||
|
job = self.g.get('job')
|
||||||
|
if (self.resume_job_name and job is not None and
|
||||||
|
job.state == job.idle and not self.g.get('dead', False)):
|
||||||
|
resume_state = getattr(job, self.resume_job_name, None)
|
||||||
|
if resume_state is not None:
|
||||||
|
job.state = resume_state
|
||||||
|
print('[threat] resuming job', self.resume_job_name,
|
||||||
|
flush=True)
|
||||||
|
self.resume_job_name = None
|
||||||
|
self.job_suspended = False
|
||||||
|
self.safety = None
|
||||||
|
self.safe_since = None
|
||||||
|
self.next_scan_at = time.monotonic() + self.CHECK_INTERVAL
|
||||||
|
self.state = self.watching
|
||||||
|
|
||||||
|
def tick(self):
|
||||||
|
position = self.g.get('pos')
|
||||||
|
if position is None or position is False:
|
||||||
|
return
|
||||||
|
self._capture_job_change()
|
||||||
|
self.state()
|
||||||
|
|
||||||
|
def __init__(self, global_state):
|
||||||
|
self.g = global_state
|
||||||
|
self.state = self.watching
|
||||||
|
self.next_scan_at = 0.0
|
||||||
|
self.retry_at = 0.0
|
||||||
|
self.safe_since = None
|
||||||
|
self.safety = None
|
||||||
|
self.threats = []
|
||||||
|
self.resume_job_name = None
|
||||||
|
self.job_suspended = False
|
||||||
|
self.suspending_job = False
|
||||||
|
|
||||||
|
|
||||||
class CheckThreatsStates:
|
class CheckThreatsStates:
|
||||||
THREAT_DISTANCE = 20
|
THREAT_DISTANCE = 20
|
||||||
CLEAR_DISTANCE = 30
|
CLEAR_DISTANCE = 30
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import unittest
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
from munch import Munch
|
from munch import Munch
|
||||||
|
|
||||||
from mosfet.commands import Commands
|
from mosfet.commands import Commands
|
||||||
from mosfet.info import blocks, mobs
|
from mosfet.info import blocks, mobs
|
||||||
from mosfet.job import JobStates
|
from mosfet.job import JobStates
|
||||||
from mosfet.jobs.check_threats import CheckThreatsStates
|
from mosfet.jobs.check_threats import CheckThreatsStates, ThreatMonitor
|
||||||
from mosfet.world import World
|
from mosfet.world import World
|
||||||
|
|
||||||
|
|
||||||
@@ -82,16 +83,114 @@ class TestThreatDetection(unittest.TestCase):
|
|||||||
self.assertEqual(state.state, state.wait)
|
self.assertEqual(state.state, state.wait)
|
||||||
self.assertEqual(state.wait_time, 3)
|
self.assertEqual(state.wait_time, 3)
|
||||||
|
|
||||||
def test_loiter_is_enabled_as_a_job(self):
|
def test_threat_monitor_waits_for_valid_spawn_position(self):
|
||||||
check = object()
|
class UnavailableWorld:
|
||||||
|
@staticmethod
|
||||||
|
def find_threats(*_args):
|
||||||
|
raise AssertionError('world queried before player position')
|
||||||
|
|
||||||
|
monitor = ThreatMonitor(Munch(world=UnavailableWorld(), pos=False))
|
||||||
|
|
||||||
|
monitor.tick()
|
||||||
|
|
||||||
|
self.assertIs(monitor.state.__func__, monitor.watching.__func__)
|
||||||
|
|
||||||
|
def test_threat_monitor_polls_every_half_second(self):
|
||||||
|
now = [0.0]
|
||||||
|
scans = []
|
||||||
|
|
||||||
|
class QuietWorld:
|
||||||
|
@staticmethod
|
||||||
|
def find_threats(center, distance):
|
||||||
|
scans.append((center, distance))
|
||||||
|
return []
|
||||||
|
|
||||||
|
monitor = ThreatMonitor(Munch(
|
||||||
|
world=QuietWorld(), pos=(1, 64, 2), job=None))
|
||||||
|
with patch('mosfet.jobs.check_threats.time.monotonic',
|
||||||
|
side_effect=lambda: now[0]):
|
||||||
|
monitor.tick()
|
||||||
|
now[0] = 0.49
|
||||||
|
monitor.tick()
|
||||||
|
self.assertEqual(len(scans), 1)
|
||||||
|
now[0] = 0.5
|
||||||
|
monitor.tick()
|
||||||
|
|
||||||
|
self.assertEqual(len(scans), 2)
|
||||||
|
self.assertEqual(scans, [((1, 64, 2), monitor.THREAT_DISTANCE)] * 2)
|
||||||
|
|
||||||
|
def test_monitor_evacuates_waits_for_clear_area_then_resumes_job(self):
|
||||||
|
threat = Munch(entity_id=7)
|
||||||
|
start = (0, 64, 0)
|
||||||
|
marker = (5, 63, 0)
|
||||||
|
safe = (5, 64, 0)
|
||||||
|
now = [0.0]
|
||||||
|
|
||||||
|
class FakeWorld:
|
||||||
|
@staticmethod
|
||||||
|
def find_threats(center, distance):
|
||||||
|
if tuple(center) == start and distance == ThreatMonitor.THREAT_DISTANCE:
|
||||||
|
return [threat]
|
||||||
|
return []
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def find_blocks_indexed(_center, _block_ids, _distance):
|
||||||
|
return [marker]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def path_to_place(origin, target):
|
||||||
|
return [origin, target]
|
||||||
|
|
||||||
|
class FakeJob:
|
||||||
|
def idle(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def farm_wart(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
self.state = self.farm_wart
|
||||||
|
self.stop_calls = 0
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
self.stop_calls += 1
|
||||||
|
self.state = self.idle
|
||||||
|
|
||||||
|
job = FakeJob()
|
||||||
|
g = Munch(world=FakeWorld(), pos=start, path=[], look_at=None,
|
||||||
|
job=job)
|
||||||
|
monitor = ThreatMonitor(g)
|
||||||
|
with patch('mosfet.jobs.check_threats.time.monotonic',
|
||||||
|
side_effect=lambda: now[0]):
|
||||||
|
monitor.tick()
|
||||||
|
self.assertIs(monitor.state.__func__, monitor.evacuating.__func__)
|
||||||
|
self.assertTrue(monitor.suppress_job)
|
||||||
|
self.assertEqual(job.stop_calls, 1)
|
||||||
|
self.assertEqual(g.path[-1], safe)
|
||||||
|
|
||||||
|
g.pos = safe
|
||||||
|
now[0] = 0.1
|
||||||
|
monitor.tick()
|
||||||
|
self.assertIs(monitor.state.__func__, monitor.waiting.__func__)
|
||||||
|
monitor.tick()
|
||||||
|
now[0] = 10.2
|
||||||
|
monitor.tick()
|
||||||
|
self.assertIs(monitor.state.__func__, monitor.resuming.__func__)
|
||||||
|
now[0] = 10.3
|
||||||
|
monitor.tick()
|
||||||
|
|
||||||
|
self.assertIs(monitor.state.__func__, monitor.watching.__func__)
|
||||||
|
self.assertIs(job.state.__func__, job.farm_wart.__func__)
|
||||||
|
self.assertFalse(monitor.suppress_job)
|
||||||
|
|
||||||
|
def test_loiter_leaves_threat_checks_to_background_monitor(self):
|
||||||
sleep = Munch(silent=False)
|
sleep = Munch(silent=False)
|
||||||
eat = object()
|
eat = object()
|
||||||
job = JobStates.__new__(JobStates)
|
job = JobStates.__new__(JobStates)
|
||||||
job.check_threats_states = check
|
|
||||||
job.sleep_with_bed_states = sleep
|
job.sleep_with_bed_states = sleep
|
||||||
job.eat_food_states = eat
|
job.eat_food_states = eat
|
||||||
|
|
||||||
self.assertEqual(JobStates.loiter(job), [check, sleep, eat])
|
self.assertEqual(JobStates.loiter(job), [sleep, eat])
|
||||||
self.assertTrue(sleep.silent)
|
self.assertTrue(sleep.silent)
|
||||||
|
|
||||||
def test_loiter_command_is_no_longer_rejected(self):
|
def test_loiter_command_is_no_longer_rejected(self):
|
||||||
|
|||||||
Reference in new issue
Block a user