aim_session.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. # -*- coding: utf-8 -*-
  2. """测谎出现后:YOLO + ByteTrack 跟踪白形目标,Interception 鼠标跟红准星(预测中心)。"""
  3. from __future__ import annotations
  4. import sys
  5. import threading
  6. import time
  7. from pathlib import Path
  8. from typing import Callable, Optional, Tuple
  9. import cv2
  10. import numpy as np
  11. CH_ROOT = Path(__file__).resolve().parent.parent
  12. if str(CH_ROOT) not in sys.path:
  13. sys.path.insert(0, str(CH_ROOT))
  14. from tracker import mouse_control
  15. from tracker.mot_tracker import MotYoloTracker
  16. from tracker.paths import MODELS_DIR
  17. LogFn = Callable[[str], None]
  18. RegionFn = Callable[[], Optional[Tuple[int, int, int, int]]] # x,y,w,h screen
  19. def _default_log(msg: str) -> None:
  20. print("[%s] %s" % (time.strftime("%H:%M:%S"), msg), flush=True)
  21. def grab_region_bgr(x: int, y: int, w: int, h: int) -> Optional[np.ndarray]:
  22. """按屏幕矩形截 BGR(mss)。"""
  23. try:
  24. import mss
  25. except ImportError:
  26. return None
  27. w, h = max(1, int(w)), max(1, int(h))
  28. with mss.mss() as sct:
  29. shot = sct.grab({"left": int(x), "top": int(y), "width": w, "height": h})
  30. return cv2.cvtColor(np.array(shot), cv2.COLOR_BGRA2BGR)
  31. class AimSession:
  32. """一次测谎瞄准会话:跑满 duration 或连续丢目标就停。"""
  33. def __init__(
  34. self,
  35. *,
  36. weights: Optional[str] = None,
  37. backend: str = "bytetrack",
  38. conf: float = 0.25,
  39. imgsz: int = 640,
  40. duration_seconds: float = 25.0,
  41. miss_stop_frames: int = 45,
  42. gain: float = 1.0,
  43. deadzone: float = 1.5,
  44. min_conf: float = 0.20,
  45. show_overlay: bool = False,
  46. log: Optional[LogFn] = None,
  47. ):
  48. self.weights = str(weights or (MODELS_DIR / "best.pt"))
  49. self.backend = backend
  50. self.conf = float(conf)
  51. self.imgsz = int(imgsz)
  52. self.duration_seconds = float(duration_seconds)
  53. self.miss_stop_frames = max(5, int(miss_stop_frames))
  54. self.gain = float(gain)
  55. self.deadzone = float(deadzone)
  56. self.min_conf = float(min_conf)
  57. self.show_overlay = bool(show_overlay)
  58. self.log = log or _default_log
  59. self._stop = threading.Event()
  60. self._thread: Optional[threading.Thread] = None
  61. self._tracker: Optional[MotYoloTracker] = None
  62. self.running = False
  63. self.frames = 0
  64. self.hits = 0
  65. self.last_conf = 0.0
  66. self.last_center: Optional[Tuple[float, float]] = None
  67. @property
  68. def alive(self) -> bool:
  69. return self._thread is not None and self._thread.is_alive()
  70. def stop(self) -> None:
  71. self._stop.set()
  72. def _build_tracker(self) -> MotYoloTracker:
  73. if self.backend not in ("bytetrack", "deepsort"):
  74. # 瞄准默认 ByteTrack;其它名字也落到 bytetrack
  75. method = "bytetrack"
  76. else:
  77. method = self.backend
  78. return MotYoloTracker(
  79. weights=self.weights,
  80. method=method,
  81. conf=self.conf,
  82. imgsz=self.imgsz,
  83. include_decoy_dets=False, # 瞄准只要主目标,干扰项别抢鼠标
  84. )
  85. def start(self, region_fn: RegionFn) -> bool:
  86. """异步启动。region_fn 每帧返回游戏客户区屏幕矩形。"""
  87. if self.alive:
  88. self.log("瞄准已在跑,忽略重复启动")
  89. return False
  90. if not Path(self.weights).exists():
  91. self.log("找不到 YOLO 权重:%s" % self.weights)
  92. return False
  93. if not mouse_control.ensure_ready():
  94. self.log("Interception 未就绪:%s" % (mouse_control.last_error() or "?"))
  95. return False
  96. self._stop.clear()
  97. self.frames = self.hits = 0
  98. self.last_conf = 0.0
  99. self.last_center = None
  100. self._thread = threading.Thread(
  101. target=self._run, args=(region_fn,), daemon=True, name="aim-session"
  102. )
  103. self._thread.start()
  104. return True
  105. def _run(self, region_fn: RegionFn) -> None:
  106. self.running = True
  107. t0 = time.time()
  108. miss = 0
  109. try:
  110. self.log("瞄准启动:backend=%s conf=%.2f 最长 %.0fs"
  111. % (self.backend, self.conf, self.duration_seconds))
  112. self._tracker = self._build_tracker()
  113. # 先抓一帧做 warmup,避免首帧卡顿
  114. region = region_fn()
  115. if region:
  116. frame = grab_region_bgr(*region)
  117. if frame is not None:
  118. self._tracker.warmup(frame)
  119. self._tracker.reset()
  120. while not self._stop.is_set():
  121. if time.time() - t0 >= self.duration_seconds:
  122. self.log("瞄准结束:到达时长上限")
  123. break
  124. region = region_fn()
  125. if not region or region[2] < 64 or region[3] < 64:
  126. time.sleep(0.05)
  127. continue
  128. rx, ry, rw, rh = region
  129. frame = grab_region_bgr(rx, ry, rw, rh)
  130. if frame is None:
  131. time.sleep(0.03)
  132. continue
  133. det = self._tracker.track(frame)
  134. self.frames += 1
  135. if det.center is None or det.conf < self.min_conf:
  136. miss += 1
  137. self.last_conf = float(det.conf or 0.0)
  138. if miss >= self.miss_stop_frames:
  139. self.log("瞄准结束:连续 %d 帧丢目标" % miss)
  140. break
  141. else:
  142. miss = 0
  143. self.hits += 1
  144. self.last_conf = float(det.conf)
  145. cx, cy = det.center
  146. self.last_center = (cx, cy)
  147. sx, sy = rx + cx, ry + cy
  148. try:
  149. mouse_control.follow_screen_point(
  150. sx, sy, gain=self.gain, deadzone=self.deadzone
  151. )
  152. except Exception as exc:
  153. self.log("鼠标移动失败:%s" % exc)
  154. break
  155. if self.show_overlay and det.center is not None:
  156. vis = frame.copy()
  157. x, y = int(det.center[0]), int(det.center[1])
  158. cv2.drawMarker(vis, (x, y), (0, 0, 255), cv2.MARKER_CROSS, 24, 2)
  159. if det.xyxy:
  160. x1, y1, x2, y2 = map(int, det.xyxy)
  161. cv2.rectangle(vis, (x1, y1), (x2, y2), (0, 140, 255), 2)
  162. cv2.imshow("aim-assist", vis)
  163. if cv2.waitKey(1) & 0xFF == ord("q"):
  164. self.log("瞄准结束:手动关闭预览")
  165. break
  166. else:
  167. # 控制节奏,别把 GPU/CPU 打满;约 30~40 FPS 足够跟准星
  168. time.sleep(0.01)
  169. except Exception as exc:
  170. self.log("瞄准异常:%s" % exc)
  171. finally:
  172. self.running = False
  173. if self.show_overlay:
  174. try:
  175. cv2.destroyWindow("aim-assist")
  176. except Exception:
  177. pass
  178. elapsed = time.time() - t0
  179. self.log("瞄准收工:%.1fs · %d 帧 · 命中 %d · 末置信度 %.2f"
  180. % (elapsed, self.frames, self.hits, self.last_conf))
  181. class AimAssistController:
  182. """给测谎提醒用的薄封装:配置 + 按需起停会话。"""
  183. def __init__(self, cfg: dict, region_fn: RegionFn, log: Optional[LogFn] = None):
  184. self.cfg = cfg or {}
  185. self.region_fn = region_fn
  186. self.log = log or _default_log
  187. self._session: Optional[AimSession] = None
  188. self._lock = threading.Lock()
  189. @property
  190. def enabled(self) -> bool:
  191. return bool(self.cfg.get("enabled", True))
  192. def stop(self) -> None:
  193. with self._lock:
  194. if self._session is not None:
  195. self._session.stop()
  196. def trigger(self, *, manual: bool = False) -> bool:
  197. """测谎报警后调用。返回是否真正启动了会话。"""
  198. if not self.enabled:
  199. return False
  200. if manual and not self.cfg.get("on_manual_test", False):
  201. return False
  202. with self._lock:
  203. if self._session is not None and self._session.alive:
  204. # 已在跟:刷新也不另起,避免两套抢鼠标
  205. return False
  206. weights = self.cfg.get("weights")
  207. if weights:
  208. wpath = Path(weights)
  209. if not wpath.is_absolute():
  210. wpath = CH_ROOT / wpath
  211. else:
  212. wpath = MODELS_DIR / "best.pt"
  213. self._session = AimSession(
  214. weights=str(wpath),
  215. backend=str(self.cfg.get("backend", "bytetrack")),
  216. conf=float(self.cfg.get("conf", 0.25)),
  217. imgsz=int(self.cfg.get("imgsz", 640)),
  218. duration_seconds=float(self.cfg.get("duration_seconds", 25)),
  219. miss_stop_frames=int(self.cfg.get("miss_stop_frames", 45)),
  220. gain=float(self.cfg.get("gain", 1.0)),
  221. deadzone=float(self.cfg.get("deadzone", 1.5)),
  222. min_conf=float(self.cfg.get("min_conf", 0.20)),
  223. show_overlay=bool(self.cfg.get("show_overlay", False)),
  224. log=self.log,
  225. )
  226. return self._session.start(self.region_fn)