-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathmain.py
More file actions
425 lines (352 loc) · 11.6 KB
/
main.py
File metadata and controls
425 lines (352 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
"""
CS2 Aimbot entry point
Architecture: [Grab Process] --queue--> [Detection Process] --queue--> [Preview Process]
"""
import logging
import multiprocessing
import signal
import sys
import time
import cv2
import keyboard
from config import (
AppConfig,
CaptureRegion,
Team,
create_default_config,
adjust_region_to_multiple,
)
from grabbers import get_grabber
from controls.mouse import get_mouse_controls
from utils.fps import FPSCounter
from utils.win32 import get_window_rect
from detectors import YOLOv8Detector
from aiming import FOVMouseMovement, TargetSelector
# Logging setup
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("CS2Bot")
class CS2Bot:
"""
Main class.
Manages the multiprocess architecture and coordinates all components.
"""
def __init__(self, config: AppConfig):
self.config = config
# Multiprocessing primitives
self.stop_event = multiprocessing.Event()
self.activated = multiprocessing.Event()
self.frame_queue = multiprocessing.Queue()
self.preview_queue = multiprocessing.Queue()
# Shared state (using Manager for cross-process access)
self.manager = multiprocessing.Manager()
self.shared_state = self.manager.dict({
"team": config.aim.current_team.value,
"fps": 0.0,
})
self.processes = []
def _setup_hotkeys(self) -> None:
"""Set up keyboard hotkeys."""
keyboard.add_hotkey(
self.config.hotkeys.activation,
self._toggle_activation,
)
keyboard.add_hotkey(
self.config.hotkeys.change_team,
self._toggle_team,
)
keyboard.add_hotkey(
self.config.hotkeys.exit,
self._shutdown,
)
def _toggle_activation(self) -> None:
"""Toggle bot activation."""
if self.activated.is_set():
self.activated.clear()
logger.info("Bot DEACTIVATED")
else:
self.activated.set()
logger.info("Bot ACTIVATED")
def _toggle_team(self) -> None:
"""Toggle between CT and T teams."""
current = self.shared_state["team"]
new_team = "t" if current == "ct" else "ct"
self.shared_state["team"] = new_team
logger.info(f"Team changed to: {new_team.upper()}")
def _shutdown(self, *args) -> None:
"""Signal shutdown."""
logger.info("Shutdown requested...")
self.stop_event.set()
def run(self) -> int:
"""
Run the bot.
Returns:
Exit code (0 for success)
"""
logger.info("Starting CS2 Bot...")
# Setup
self._setup_hotkeys()
signal.signal(signal.SIGINT, self._shutdown)
signal.signal(signal.SIGTERM, self._shutdown)
# Start processes
self.processes = [
multiprocessing.Process(
target=grab_process,
args=(self.frame_queue, self.stop_event, self.config),
name="GrabProcess",
),
multiprocessing.Process(
target=detection_process,
args=(
self.frame_queue,
self.preview_queue,
self.stop_event,
self.activated,
self.shared_state,
self.config,
),
name="DetectionProcess",
),
]
if self.config.preview.enabled:
self.processes.append(
multiprocessing.Process(
target=preview_process,
args=(
self.preview_queue,
self.stop_event,
self.shared_state,
self.config,
),
name="PreviewProcess",
)
)
for p in self.processes:
p.daemon = True
p.start()
logger.info(f"Started {p.name}")
# Main loop
try:
while not self.stop_event.is_set():
# Check if any process died
for p in self.processes:
if not p.is_alive():
logger.error(f"{p.name} died unexpectedly")
self.stop_event.set()
break
time.sleep(0.1)
except KeyboardInterrupt:
self.stop_event.set()
# Cleanup
logger.info("Stopping processes...")
for p in self.processes:
p.join(timeout=3)
if p.is_alive():
p.terminate()
logger.info("Shutdown complete")
return 0
def grab_process(
queue: multiprocessing.Queue,
stop_event: multiprocessing.Event,
config: AppConfig,
) -> None:
"""
Screen capture process.
"""
logger = logging.getLogger("GrabProcess")
logger.info("Starting...")
try:
grabber = get_grabber(config.grabber_type, **config.grabber_options)
except Exception as e:
logger.error(f"Failed to initialize grabber: {e}")
stop_event.set()
return
grab_area = config.capture_region.to_dict()
while not stop_event.is_set():
try:
img = grabber.get_image(grab_area)
if img is None:
continue
# drop old frames, keep only latest
while not queue.empty():
try:
queue.get_nowait()
except Exception:
break
queue.put_nowait(img)
except Exception as e:
logger.error(f"Capture error: {e}")
stop_event.set()
break
grabber.cleanup()
logger.info("Stopped")
def detection_process(
frame_queue: multiprocessing.Queue,
preview_queue: multiprocessing.Queue,
stop_event: multiprocessing.Event,
activated: multiprocessing.Event,
shared_state: dict,
config: AppConfig,
) -> None:
"""
Detection and aiming process.
- Receives frames from grab process
- Runs YOLO inference
- Calculates aim movement (hopefully with correct FOV math xD)
- Moves mouse (for now, without windmouse, etc.)
- Sends frames to preview (if enabled)
"""
logger = logging.getLogger("DetectionProcess")
logger.info("Starting...")
# Initialize detector
try:
detector = YOLOv8Detector(
class_names=config.detector.class_names,
weights_path=config.detector.weights_path,
confidence_threshold=config.detector.confidence_threshold,
iou_threshold=config.detector.iou_threshold,
)
detector.set_colors(config.detector.class_colors)
except Exception as e:
logger.error(f"Failed to initialize detector: {e}")
stop_event.set()
return
# Initialize aiming components
fov_mouse = FOVMouseMovement(
screen=config.capture_region,
fov=config.fov,
)
target_selector = TargetSelector(
aim_config=config.aim,
screen=config.capture_region,
)
# Initialize mouse control
try:
mouse = get_mouse_controls("win32")
except Exception as e:
logger.error(f"Failed to initialize mouse control: {e}")
stop_event.set()
return
fps = FPSCounter()
while not stop_event.is_set():
try:
img = frame_queue.get(timeout=0.01)
except Exception:
continue
# Update team from shared state
current_team_str = shared_state.get("team", "ct")
target_selector.config.current_team = Team(current_team_str)
# Run detection
detections = detector.detect(img, verbose=False)
# Process if activated
if activated.is_set() and detections:
# select best target
target = target_selector.select_best_target(
detections,
max_distance=config.aim.max_assist_distance,
)
if target is not None:
aim_result = fov_mouse.get_move(
target.aim_x,
target.aim_y,
smoothing=config.aim.smoothing_factor,
)
# only move if outside ded zone (prevents over-aiming hopefully)
if aim_result.pixel_distance > config.aim.dead_zone:
mouse.move_relative(aim_result.mouse_x, aim_result.mouse_y)
if config.aim.one_shot:
activated.clear()
# draw aim point on preview
if config.preview.enabled:
detector.draw_aim_point(
img,
target.aim_x,
target.aim_y,
color=(0, 255, 0),
)
# Update FPS
current_fps = fps()
shared_state["fps"] = current_fps
# Send to preview
if config.preview.enabled:
# Draw boxes
if config.preview.paint_boxes:
detector.draw_boxes(img, detections)
while not preview_queue.empty():
try:
preview_queue.get_nowait()
except Exception:
break
preview_queue.put_nowait(img)
logger.info("Stopped")
def preview_process(
queue: multiprocessing.Queue,
stop_event: multiprocessing.Event,
shared_state: dict,
config: AppConfig,
) -> None:
"""
Preview window process (for debug purpose).
"""
logger = logging.getLogger("PreviewProcess")
logger.info("Starting...")
font = cv2.FONT_HERSHEY_SIMPLEX
while not stop_event.is_set():
try:
img = queue.get(timeout=0.01)
except Exception:
continue
# Draw FPS
if config.preview.show_fps:
fps_text = f"FPS: {shared_state.get('fps', 0):.1f}"
cv2.putText(
img, fps_text, (20, 50),
font, 1.0, (0, 255, 0), 2, cv2.LINE_AA,
)
# Draw team indicator
if config.preview.show_team:
team = shared_state.get("team", "ct").upper()
color = (245, 185, 115) if team == "CT" else (0, 208, 247)
cv2.putText(
img, f"Team: {team}", (20, 90),
font, 1.0, color, 2, cv2.LINE_AA,
)
# Convert color if needed
if config.preview.convert_rgb_to_bgr:
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
# Resize for display
display = cv2.resize(img, config.preview.size)
cv2.imshow(config.preview.title, display)
key = cv2.waitKey(1) & 0xFF
if key == ord('q'):
stop_event.set()
cv2.destroyAllWindows()
logger.info("Stopped")
def main() -> int:
"""Main entry point."""
# Create configuration
config = create_default_config()
# Try to get window rect
try:
rect = get_window_rect(
config.window_title,
config.border_offsets,
)
config.capture_region = CaptureRegion(
left=rect[0],
top=rect[1],
width=rect[2],
height=rect[3],
)
config.capture_region = adjust_region_to_multiple(config.capture_region, 32)
logger.info(f"Capture region: {config.capture_region}")
except Exception as e:
logger.warning(f"Could not get window rect: {e}")
logger.info("Using default capture region")
# Create and run bot
bot = CS2Bot(config)
return bot.run()
if __name__ == "__main__":
sys.exit(main())