StarRailCopilot/tasks/rogue/route/loader.py

295 lines
11 KiB
Python
Raw Normal View History

2023-10-01 15:03:57 +00:00
from typing import Optional
import numpy as np
2023-10-01 15:03:57 +00:00
from module.base.decorator import cached_property
2023-10-18 05:47:29 +00:00
from module.base.timer import Timer
2023-10-01 15:03:57 +00:00
from module.logger import logger
2023-11-10 13:36:53 +00:00
from tasks.character.switch import CharacterSwitch
2023-10-01 15:03:57 +00:00
from tasks.map.keywords import MapPlane
from tasks.map.keywords.plane import (
Herta_MasterControlZone,
Herta_ParlorCar,
Jarilo_AdministrativeDistrict,
Luofu_AurumAlley,
Luofu_ExaltingSanctum
)
from tasks.map.minimap.minimap import Minimap
2023-10-02 09:14:33 +00:00
from tasks.map.resource.resource import SPECIAL_PLANES
2023-10-01 15:03:57 +00:00
from tasks.map.route.loader import RouteLoader as RouteLoader_
2023-12-18 16:53:33 +00:00
from tasks.rogue.blessing.ui import RogueUI
2023-10-01 15:03:57 +00:00
from tasks.rogue.route.base import RouteBase
from tasks.rogue.route.model import RogueRouteListModel, RogueRouteModel
def model_from_json(model, file: str):
with open(file, 'r', encoding='utf-8') as f:
content = f.read()
data = model.model_validate_json(content)
return data
2023-10-02 09:14:33 +00:00
class MinimapWrapper:
2023-10-01 15:03:57 +00:00
@cached_property
2023-10-07 15:20:28 +00:00
def all_minimap(self) -> dict[str, Minimap]:
2023-10-01 15:03:57 +00:00
"""
Returns:
dict: Key: {world}_{plane}_{floor}, e.g. Jarilo_SilvermaneGuardRestrictedZone_F1
Value: Minimap object
"""
# No enemy spawn at the followings
blacklist = [
Herta_ParlorCar,
Herta_MasterControlZone,
Jarilo_AdministrativeDistrict,
Luofu_ExaltingSanctum,
Luofu_AurumAlley,
]
maps = {}
for plane, floor in SPECIAL_PLANES:
minimap = Minimap()
minimap.set_plane(plane=plane, floor=floor)
maps[f'{plane}_{floor}'] = minimap
2023-10-01 15:03:57 +00:00
for plane in MapPlane.instances.values():
if plane in blacklist:
continue
if not plane.world:
continue
for floor in plane.floors:
minimap = Minimap()
minimap.set_plane(plane=plane, floor=floor)
maps[f'{plane.name}_{floor}'] = minimap
2023-10-02 09:14:33 +00:00
logger.attr('MinimapLoaded', len(maps))
2023-10-01 15:03:57 +00:00
return maps
@cached_property
def all_route(self) -> list[RogueRouteModel]:
routes = model_from_json(RogueRouteListModel, './route/rogue/route.json').root
logger.attr('RouteLoaded', len(routes))
return routes
2023-10-01 15:03:57 +00:00
def get_minimap(self, route: RogueRouteModel):
return self.all_minimap[route.plane_floor]
2023-10-02 09:14:33 +00:00
2023-11-10 13:36:53 +00:00
class RouteLoader(RogueUI, MinimapWrapper, RouteLoader_, CharacterSwitch):
2023-10-18 05:47:29 +00:00
def position_find_known(self, image, force_return=False) -> Optional[RogueRouteModel]:
2023-10-01 15:03:57 +00:00
"""
Try to find from known route spawn point
"""
logger.info('position_find_known')
2023-10-22 17:49:48 +00:00
plane = self.update_plane()
2023-10-01 15:03:57 +00:00
if plane is None:
logger.warning('Unknown rogue domain')
return
visited = []
for route in self.all_route:
if plane.rogue_domain and plane.rogue_domain != route.domain:
2023-11-16 10:43:14 +00:00
if plane.is_rogue_occurrence and route.is_DomainOccurrence:
# Treat as "Occurrence"
2023-10-01 15:03:57 +00:00
pass
2023-11-16 10:43:14 +00:00
elif plane.is_rogue_elite and route.is_DomainElite:
# Treat as "Elite"
2023-10-01 15:03:57 +00:00
pass
else:
continue
minimap = self.get_minimap(route)
minimap.init_position(route.position, show_log=False)
try:
minimap.update_position(image)
except FileNotFoundError as e:
logger.warning(e)
2023-10-01 15:03:57 +00:00
continue
visited.append((route, minimap.position_similarity, minimap.position))
2023-10-01 15:03:57 +00:00
if len(visited) < 3:
logger.warning('Too few routes to search from, not enough to make a prediction')
return
visited = sorted(visited, key=lambda x: x[1], reverse=True)
2023-10-18 05:47:29 +00:00
logger.info(f'Best 3 predictions: {[(r.name, s, p) for r, s, p in visited[:3]]}')
nearby = [
(r, s, p) for r, s, p in visited if np.linalg.norm(np.subtract(r.position, p)) < 5
]
2023-10-18 05:47:29 +00:00
logger.info(f'Best 3 nearby predictions: {[(r.name, s, p) for r, s, p in nearby[:3]]}')
# Check special
for r, s, p in nearby:
if self._position_match_special(r, s, p):
logger.info(f'Route match special: {r.name}')
return r
# Check nearby
if len(nearby) == 1:
if nearby[0][1] > 0.05:
logger.attr('RoutePredict', nearby[0][0].name)
return nearby[0][0]
elif len(nearby) >= 2:
2023-10-18 05:47:29 +00:00
if nearby[0][1] / nearby[1][1] > 0.55:
logger.attr('RoutePredict', nearby[0][0].name)
return nearby[0][0]
# logger.info(f'Best 3 prediction: {[(r.name, s, p) for r, s, p in visited[:3]]}')
# if visited[0][1] / visited[1][1] > 0.75:
# logger.attr('RoutePredict', visited[0][0].name)
# return visited[0][0]
2023-10-18 05:47:29 +00:00
if force_return:
if len(nearby) >= 1:
route = nearby[0][0]
else:
route = visited[0][0]
2023-10-18 13:01:48 +00:00
logger.attr('RoutePredict', route.name)
2023-10-18 05:47:29 +00:00
return route
else:
logger.warning('Similarity too close, not enough to make a prediction')
return None
2023-10-01 15:03:57 +00:00
def _position_match_special(
self,
route: RogueRouteModel,
similarity: float,
position: tuple[float, float]
) -> bool:
# 2023-11-13 23:50:00.470 | INFO | Best 3 predictions: [
# ('Occurrence_Luofu_Cloudford_F1_X241Y947', 0.119, (272.6, 948.5)),
# ('Occurrence_Jarilo_GreatMine_F1_X277Y605', 0.107, (264.4, 645.0)),
# ('Occurrence_Luofu_ArtisanshipCommission_F1_X521Y63', 0.106, (569.8, 34.8))]
# 2023-11-13 23:50:00.472 | INFO | Best 3 nearby predictions: [
# ('Occurrence_Herta_SupplyZone_F2Rogue_X397Y223', 0.102, (393.2, 222.8)),
# ('Occurrence_Herta_StorageZone_F2_X365Y167', 0.094, (363.0, 166.8)),
# ('Occurrence_Herta_StorageZone_F2_X363Y166', 0.094, (363.0, 166.8))]
2023-12-09 16:40:09 +00:00
# if route.name == 'Occurrence_Herta_StorageZone_F2_X363Y166' and similarity > 0.05:
# return True
2023-11-17 16:21:23 +00:00
# Before Combat_Luofu_Cloudford_F1_X281Y873
if route.name == [
'Combat_Herta_StorageZone_F1_X273Y92',
'Occurrence_Herta_StorageZone_F1_X273Y93',
'Occurrence_Jarilo_RivetTown_F1_X289Y97',
'Occurrence_Luofu_DivinationCommission_F2_X425Y791',
'Occurrence_Luofu_ArtisanshipCommission_F1_X169Y491',
2023-11-17 16:21:23 +00:00
] and similarity > 0.1:
return True
# Luofu_Cloudford_F1_X283Y865 and its equivalents
2023-11-16 14:21:04 +00:00
# INFO 21:27:00.816 │ Best 3 nearby predictions: [
# ('Combat_Herta_SupplyZone_F2_X45Y369', 0.184, (41.0, 369.1)),
# ('Combat_Luofu_Cloudford_F1_X281Y873', 0.149, (281.8, 869.6)),
# ('Combat_Luofu_Cloudford_F1_X283Y865', 0.149, (281.8, 869.6))]
# INFO | Best 3 predictions: [('Combat_Herta_SupplyZone_F2_X45Y369', 0.149, (43.4, 369.3)),
# ('Combat_Luofu_Cloudford_F1_X241Y947', 0.138, (198.6, 956.8)),
# ('Combat_Luofu_Cloudford_F1Rogue_X59Y405', 0.134, (81.0, 397.4))]
if route.name in [
'Combat_Luofu_Cloudford_F1_X283Y865',
'Occurrence_Luofu_Cloudford_F1_X283Y865',
'Combat_Luofu_Cloudford_F1_X281Y873',
'Occurrence_Luofu_Cloudford_F1_X281Y873',
] and similarity > 0.05:
2023-11-16 14:21:04 +00:00
return True
return False
2023-10-01 15:03:57 +00:00
def position_find_bruteforce(self, image) -> Minimap:
"""
Fallback method to find from all planes and floors
"""
logger.warning('position_find_bruteforce, this may take a while')
for name, minimap in self.all_minimap.items():
2023-10-02 09:14:33 +00:00
if minimap.is_special_plane:
continue
2023-10-01 15:03:57 +00:00
minimap.init_position((0, 0), show_log=False)
try:
minimap.update_position(image)
except FileNotFoundError:
pass
def get_name(minimap_: Minimap) -> str:
return f'{minimap_.plane.name}_{minimap_.floor}_X{int(minimap_.position[0])}Y{int(minimap_.position[1])}'
visited = sorted(self.all_minimap.values(), key=lambda x: x.position_similarity, reverse=True)
2023-11-16 17:32:32 +00:00
logger.info(f'Best 5 prediction: {[(get_name(m), m.position_similarity) for m in visited[:50]]}')
2023-10-01 15:03:57 +00:00
if visited[1].position_similarity / visited[0].position_similarity > 0.75:
2023-10-18 05:47:29 +00:00
logger.warning('Similarity too close, predictions may go wrong')
2023-10-01 15:03:57 +00:00
logger.attr('RoutePredict', get_name(visited[0]))
return visited[0]
2023-10-18 05:47:29 +00:00
def position_find(self, skip_first_screenshot=True):
timeout = Timer(1, count=3).start()
while 1:
if skip_first_screenshot:
skip_first_screenshot = False
else:
self.device.screenshot()
if timeout.reached():
self.position_find_bruteforce(self.device.image)
logger.warning('Find position timeout, force return route')
return self.position_find_known(self.device.screenshot(), force_return=True)
route = self.position_find_known(self.device.image)
if route is not None:
return route
2023-10-01 15:03:57 +00:00
def route_run(self, route=None):
"""
Run a rogue domain
2023-10-07 15:20:28 +00:00
Returns:
bool: True if success, False if route unknown
2023-10-01 15:03:57 +00:00
Pages:
in: page_main
out: page_main, at another domain
2023-10-07 15:20:28 +00:00
or page_rogue if rogue cleared
2023-10-01 15:03:57 +00:00
"""
# To have a newer image, since previous loadings took some time
route = self.position_find(skip_first_screenshot=False)
2023-12-09 13:39:37 +00:00
self.screenshot_tracking_add()
2023-10-18 05:47:29 +00:00
super().route_run(route)
2023-10-07 15:20:28 +00:00
def rogue_run(self, skip_first_screenshot=True):
"""
Do a complete rogue run, no error handle yet.
Pages:
in: page_rogue, is_page_rogue_launch()
out: page_rogue, is_page_rogue_main()
2023-10-07 15:20:28 +00:00
"""
base = RouteBase(config=self.config, device=self.device, task=self.config.task.command)
count = 1
while 1:
if skip_first_screenshot:
skip_first_screenshot = False
else:
self.device.screenshot()
logger.hr(f'Route run: {count}', level=1)
base.clear_blessing()
2023-11-10 13:36:53 +00:00
if count == 1:
self.character_switch_to_ranged(update=True)
2023-10-18 05:47:29 +00:00
self.route_run()
# if not success:
# self.device.image_save()
# continue
2023-10-07 15:20:28 +00:00
# End
if self.is_page_rogue_main():
2023-10-07 15:20:28 +00:00
break
count += 1
2023-10-01 15:03:57 +00:00
if __name__ == '__main__':
2023-11-19 11:17:07 +00:00
self = RouteLoader('src', task='Rogue')
2023-10-01 15:03:57 +00:00
# self.image_file = r''
self.device.screenshot()
2023-11-17 16:21:23 +00:00
self.position_find()
self.position_find_bruteforce(self.device.image)
# self.device.screenshot()
# self.rogue_run()