Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1840 lines (1675 loc) · 77.7 KB
/
Copy pathmain.py
File metadata and controls
1840 lines (1675 loc) · 77.7 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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
CS2 External ESP runtime entry point. Normal launch owns attach/re-attach, feature wiring, overlay/menu orchestration, status IPC and the frame loop;
--qt-menu starts only the PySide6 menu process before GLFW/imgui are imported. Feature logic stays inside cs2esp modules.
"""
import ctypes
import ctypes.wintypes as wt
import math
import os
import sys
from random import uniform
from time import perf_counter, sleep
from cs2esp.crash_logging import configure_crash_logging
configure_crash_logging("menu" if "--qt-menu" in sys.argv else "overlay")
try:
ctypes.windll.winmm.timeBeginPeriod(1)
except Exception:
pass
# Configure PyOpenGL before its first import
try:
import OpenGL
OpenGL.ERROR_CHECKING = bool(os.environ.get("CS2_GL_DEBUG"))
OpenGL.ERROR_LOGGING = False
except Exception:
pass
from cs2esp.ui.hotkeys import KeybindManager, ToggleHotkeyDetector, is_feature_active, is_key_pressed
# Keep Qt startup before glfw/imgui context creation
if "--qt-menu" in sys.argv:
from cs2esp.ui.qt.menu_app import run
raise SystemExit(run())
# Set DPI awareness before any window is painted
from cs2esp.display_info import (
clamp_target_fps, dpi_scale_for_hwnd, enum_monitors, get_display_refresh_hz, is_process_dpi_aware, make_process_dpi_aware, monitor_for_hwnd)
if make_process_dpi_aware():
print("[main] Process marked per-monitor DPI-aware.")
else:
print("[main] WARNING: could not set DPI awareness — overlay may " "render blank/black on high-DPI or duplicate-monitor setups.")
# Select the OpenGL library before GLFW, PyOpenGL or imgui loads it
_startup_render_device_key = "auto"
_gpu_selection_warning = None
try:
from cs2esp.config import DEFAULT_CONFIG as _CFG_PATH
from cs2esp import gpu_devices as _gpu_devices
_startup_render_device_key = _gpu_devices.read_configured_key(_CFG_PATH)
_gpu_devices.apply_render_device(_startup_render_device_key)
_gpu_selection_warning = getattr(_gpu_devices, "SELECTION_WARNING", None)
except Exception as _gpu_exc:
_gpu_selection_warning = f"Render-device setup failed: {_gpu_exc}"
print(f"[gpu] render-device setup skipped: {_gpu_exc!r}")
import glfw
from imgui_bundle import imgui
def _gpu_colorkey_needed() -> bool:
'''Return True when the GPU device setup requires colorkey transparency.'''
try:
from cs2esp import gpu_devices
return bool(gpu_devices.FORCE_COLORKEY)
except Exception:
return False
from cs2esp.config import Config
from cs2esp.memory import MemoryReader
from cs2esp.offsets import (CGlowProperty, Netvars, Offsets, OFFSETS_CACHE_PATH, apply_sigscan, load_offsets_cache,
export_offsets_dict, import_offsets_dict, _live_offsets_readable, verified_offsets_cache_receipt,
save_offsets_cache, update_offsets, verify_netvars, _verify_bone_array)
from cs2esp.entity import EntitySystem
from cs2esp.visuals.skeleton import draw_skeleton, project_players
from cs2esp.state_reader import GameStateReader
from cs2esp.recoil_runtime import HeldWeapon, RecoilRuntime
from cs2esp.input_guard import right_button_guard
from cs2esp.features.recoil_control import RecoilControl
from cs2esp.visuals.math_utils import world_to_screen
from cs2esp.visuals.overlay import Overlay
from cs2esp.visuals.menu_window import MenuWindow
from cs2esp.visuals.esp import draw_crosshair, draw_player_esp
from cs2esp.visuals.radar import Radar
from cs2esp.visuals.overlays import Awareness
from cs2esp.visuals.fps_counter import draw_fps_counter
from cs2esp.features.glow import GlowSystem
from cs2esp.visuals.chams import chams_begin_frame, chams_context_recreated, chams_end_frame, chams_shutdown, draw_chams
from cs2esp.visuals.vpk_chams import renderer as vpk_chams
from cs2esp.visuals.chams_pixel_probe import probe_center_pixel as chams_probe_center_pixel
from cs2esp.features.event_system import EventSystem, EventType
from cs2esp.features.combat_events import CombatEventTracker
from cs2esp.features.combat_telemetry import CombatTelemetry
from cs2esp.visuals.hud_manager import HudPositionManager
from cs2esp.visuals.event_feed import render_event_feed
from cs2esp.visuals.c4_capsule import render_c4_capsule
from cs2esp.visuals.spectator_list import render_spectator_list
from cs2esp.visuals.hotkeys_widget import render_hotkeys_widget
from cs2esp.visuals.status_pills import render_status_pills
from cs2esp.visuals.theme import color_u32
from cs2esp.ui.fonts import set_font_context
from cs2esp.features.triggerbot_vanilla import Triggerbot
from cs2esp.features.triggerbot_feedback import FeedbackTriggerbot
from cs2esp.features.aimbot import WPMAimbot
from cs2esp.features.autoclick import AutoPistol, RapidFire
from cs2esp.features.bhop import BHop
from cs2esp.ui.menu import Menu
from cs2esp.ui.qt_launcher import QtMenuController
from cs2esp.win32_utils import (create_single_instance_mutex, find_window_by_pid,
focus_window, get_client_rect, is_window_minimized, is_window_valid, set_exclusion_region, set_noactivate, windows_covering, user32)
from cs2esp.ipc import StatusPublisher, read_offset_refresh_request, drain_control, send_control, write_instance, write_offset_ack, write_status
def _anti_detect_value(anti_detect, key: str, default):
'''Read optional [anti_detection] keys safely.'''
try:
return getattr(anti_detect, key)
except Exception:
return default
_RENDER_PROFILE_READER_HZ = {"efficient": 90.0, "balanced": 75.0, "low_latency": 120.0, "energy_saving": 60.0}
_GLOW_ADVANCED_DEFAULTS = {"writer_burst": 1, "writer_sleep_ms": 10.0, "write_color": True, "write_type_block": True,
"write_eligible": True, "write_glowing": True, "clear_on_drop": True, "debug_log": False}
def _active_render_profile(overlay_config, active_device_key: str) -> str:
'''Resolve the running device's profile, independently of pending device changes.'''
default = "energy_saving" if active_device_key == "cpu" else "efficient"
if overlay_config is None:
return default
profiles = getattr(overlay_config, "render_profiles", None)
data = profiles if isinstance(profiles, dict) else getattr(profiles, "_data", {})
selected = data.get(active_device_key) if isinstance(data, dict) else None
if selected is None and str(getattr(overlay_config, "render_device", "auto")) == active_device_key:
selected = getattr(overlay_config, "render_profile", default)
selected = str(selected or default)
return selected if selected in _RENDER_PROFILE_READER_HZ else default
def _hud_editor_input_context(overlay, game_hwnd: int, qt_menu=None, menu_window=None, *, enabled: bool) -> tuple[bool, tuple]:
'''Authorize HUD input for owned windows and exclude covered client-space rectangles.'''
if not enabled or not game_hwnd or not getattr(overlay, 'hwnd', 0):
return False, ()
try:
foreground = int(user32.GetForegroundWindow() or 0)
menu_hwnd = int(qt_menu._locate_hwnd() or 0) if qt_menu is not None else 0
external_hwnd = int(getattr(menu_window, 'hwnd', 0) or 0)
trusted = {int(game_hwnd), int(overlay.hwnd)}
trusted.update(handle for handle in (menu_hwnd, external_hwnd) if handle)
ancestor = user32.GetAncestor
ancestor.argtypes = [wt.HWND, wt.UINT]
ancestor.restype = wt.HWND
root_owner = int(ancestor(wt.HWND(foreground), 3) or foreground)
trusted_roots = {int(ancestor(wt.HWND(handle), 3) or handle) for handle in trusted}
if foreground not in trusted and root_owner not in trusted_roots:
return False, ()
covered = list(windows_covering(game_hwnd, skip_hwnds=(overlay.hwnd,)))
for handle in (menu_hwnd, external_hwnd):
if handle and user32.IsWindowVisible(wt.HWND(handle)):
rectangle = get_client_rect(handle)
if rectangle:
covered.append(rectangle)
origin_x, origin_y = overlay._monitor_rect[:2]
return True, tuple((left - origin_x, top - origin_y, width, height) for left, top, width, height in covered if width > 0 and height > 0)
except Exception:
return False, ()
def _precise_sleep(duration: float) -> None:
'''Sleep with a spin tail limited to the last 0.3 ms; the old 1.5 ms tail burned ~18% of a core at 120 fps.'''
if duration <= 0:
return
deadline = perf_counter() + duration
chunk = duration - 0.0003
if chunk > 0:
sleep(chunk)
while perf_counter() < deadline:
pass
def _filter_pawns(pawns: list, predicate, *predicate_args) -> list:
'''Return the entries whose predicate is true, preserving order.'''
filtered = []
for entry in pawns:
if predicate(entry, *predicate_args):
filtered.append(entry)
return filtered
def _within_fov(entry, local_pos, view_dir, min_dot) -> bool:
'''Return True when the pawn centre is within the FOV cone; a near-zero distance is kept.'''
pawn_position = entry[2]
delta_x = pawn_position[0] - local_pos[0]
delta_y = pawn_position[1] - local_pos[1]
delta_z = pawn_position[2] - local_pos[2]
distance = math.sqrt(delta_x*delta_x + delta_y*delta_y + delta_z*delta_z)
if distance < 1e-3:
return True
inverse_distance = 1.0 / distance
dot = (view_dir[0] * delta_x * inverse_distance + view_dir[1] * delta_y * inverse_distance + view_dir[2] * delta_z * inverse_distance)
return dot >= min_dot
def _near_crosshair(entry, view_matrix, screen_w, screen_h, screen_center_x, screen_center_y, crosshair_radius_sq) -> bool:
'''Return True when the projected pawn centre falls inside the crosshair radius.'''
screen_pos = world_to_screen(entry[2], view_matrix, screen_w, screen_h)
if screen_pos is None:
return False
screen_delta_x = screen_pos[0] - screen_center_x
screen_delta_y = screen_pos[1] - screen_center_y
return screen_delta_x * screen_delta_x + screen_delta_y * screen_delta_y <= crosshair_radius_sq
def _on_screen(entry, view_matrix, screen_w, screen_h) -> bool:
'''Return True when the projected pawn centre falls inside the screen bounds.'''
screen_pos = world_to_screen(entry[2], view_matrix, screen_w, screen_h)
if screen_pos is None:
return False
return 0.0 <= screen_pos[0] <= screen_w and 0.0 <= screen_pos[1] <= screen_h
def main() -> int:
'''Run the overlay until exit and return the process exit code.'''
# Defer cyclic collection while rendering; idle frames still collect and reference counting stays active
import gc
gc.collect()
gc.freeze()
gc.set_threshold(100_000, 1000, 1000)
mutex_name = os.environ.get("CS2ESP_MUTEX")
mutex_handle, already_running = (create_single_instance_mutex(mutex_name) if mutex_name else create_single_instance_mutex())
if already_running:
# Second launch = "open the menu", not a second overlay
send_control("show_menu")
print("[main] CS2 ESP is already running — asked it to show the menu. Exiting duplicate.")
return 0
write_instance(os.getpid())
drain_control()
print("[main] CS2 ESP \u2014 research build")
config = Config.load()
launch_render_device = _startup_render_device_key
try:
_bind_list = []
for _name, _section in (
("Triggerbot", getattr(config, "triggerbot", None)), ("Aimbot", getattr(config, "aimbot", None)), ("Rapid-fire", getattr(config, "rapidfire", None)),
("Auto-pistol", getattr(config, "autopistol", None)), ("Recoil control", getattr(config, "recoil_control", None)),
("Bunny Hop", getattr(config, "bhop", None)), ("Wallhack", getattr(config, "wallhack", None)), ("Radar", getattr(config, "radar", None)),
("Awareness", getattr(config, "awareness", None)),
("FPS counter", getattr(config, "fps_counter", None)), ("Snapline", getattr(getattr(config, "visuals", None), "snapline", None)),
("Crosshair", getattr(getattr(config, "visuals", None), "crosshair", None)), ("Names", getattr(getattr(config, "visuals", None), "name", None))):
if _section is None:
continue
for _attr, _mode in (("hotkey", "hold"), ("hotkey_toggle", "toggle")):
_key = str(getattr(_section, _attr, "") or "").strip().lower()
if _key:
_bind_list.append((_key, f"{_name} {_mode}"))
_by_key = {}
for _key, _label in _bind_list:
_by_key.setdefault(_key, []).append(_label)
for _key, _labels in sorted(_by_key.items()):
if len(_labels) > 1:
print(f"[binds] duplicate key {_key!r}: {', '.join(_labels)} " f"(hold and toggle on the same key interact)")
except Exception:
pass
if (sys.platform == "win32" and bool(getattr(config.general, "hide_terminal", True))):
try:
kernel32 = ctypes.windll.kernel32
console_processes = (ctypes.c_ulong * 4)()
attached = int(kernel32.GetConsoleProcessList(console_processes, 4))
if attached > 1:
print(f"[main] hide_terminal=true but console shared with " f"{attached - 1} other process(es); leaving it visible.")
elif attached == 1:
console_hwnd = kernel32.GetConsoleWindow()
if console_hwnd:
ctypes.windll.user32.ShowWindow(console_hwnd, 0)
except Exception as error:
print(f"[main] hide_terminal failed: {error!r}")
anti_detect = config.anti_detection
try:
if bool(getattr(anti_detect, "module_spoof_enabled", False)):
from cs2esp.anti_detect import spoof_python_module_name, module_spoof_supported
if module_spoof_supported():
masquerade_name = getattr(anti_detect, "module_spoof_masquerade_name", None)
unlink_original = bool(getattr(anti_detect, "module_spoof_unlink_from_peb", True))
spoofed_module_name = spoof_python_module_name(masquerade_name=masquerade_name, unlink_original=unlink_original)
if spoofed_module_name:
print(f"[anti-det] interpreter loader display path aliased as {spoofed_module_name!r}; loader basename preserved.")
else:
print("[anti-det] interpreter display-path alias was not applied; runtime identity remains unchanged.")
except Exception as error:
print(f"[anti-det] module-spoof raised: {error!r}")
if not load_offsets_cache():
update_offsets()
else:
try:
update_offsets()
except Exception:
pass
# Save refreshed offsets before runtime validation can reload an older cache
try:
save_offsets_cache()
except Exception as exc:
print(f"[offsets] startup cache save failed: {exc!r}")
qt_menu: QtMenuController | None = None
if bool(getattr(config.general, "qt_menu_enabled", True)):
qt_menu = QtMenuController()
if bool(getattr(config.general, "start_menu_visible", True)):
if not qt_menu.spawn():
print("[main] Qt menu subprocess could not start \u2014 " "falling back to imgui in-overlay menu.")
qt_menu = None
else:
print("[main] start_menu_visible=false \u2014 Qt menu will " "spawn on first toggle-hotkey press.")
else:
print("[main] Qt menu disabled in config; using imgui menu.")
mem = MemoryReader()
attached = mem.attach(quiet=True)
if not attached:
print("[main] Waiting for cs2.exe \u2014 launch the game any time. " "The menu stays open during the wait.")
last_status_at = 0.0
log_attach_failure = True
exit_key = str(getattr(config.general, "exit_key", "ctrl+l"))
menu_toggle_key = str(getattr(config.general, "toggle_menu_key", "ctrl+j"))
master_toggle_key = str(getattr(config.general, "master_toggle_key", "ctrl+k"))
last_menu_toggle_at = 0.0
last_master_toggle_at = 0.0
while not attached:
attached = mem.attach(quiet=not log_attach_failure)
if attached:
break
log_attach_failure = False
try:
if is_key_pressed(exit_key):
print(f"[main] Exit hotkey ({exit_key}) pressed during " "the CS2 wait. Quitting.")
break
except Exception:
pass
now = perf_counter()
try:
if qt_menu is not None and is_key_pressed(menu_toggle_key) and now - last_menu_toggle_at > 0.4:
qt_menu.toggle()
last_menu_toggle_at = now
except Exception:
pass
try:
if (is_key_pressed(master_toggle_key) and now - last_master_toggle_at > 0.4):
was_enabled = bool(getattr(config.general, "master_enabled", True))
config.general.master_enabled = not was_enabled
last_master_toggle_at = now
except Exception:
pass
quit_requested = False
for command in drain_control():
action = command.get("action")
if action == "quit":
quit_requested = True
elif action == "master":
config.general.master_enabled = bool(command.get("value", True))
elif action == "show_menu" and qt_menu is not None:
if not qt_menu.is_alive():
qt_menu.spawn()
if quit_requested:
print("[main] Quit requested from the menu during the CS2 wait.")
break
if qt_menu is not None:
try:
qt_menu.tick_focus()
except Exception:
pass
if now - last_status_at >= 0.25:
try:
write_status(fps=None, cs2_attached=False, master_enabled=bool(getattr(config.general, "master_enabled", True)),
render_device_requested=launch_render_device, render_device_warning=_gpu_selection_warning)
except Exception:
pass
last_status_at = now
sleep(0.2)
if not attached:
if qt_menu is not None:
try:
qt_menu.terminate()
except Exception:
pass
return 0
apply_sigscan(mem.pm)
fixed_netvars = verify_netvars(mem)
if fixed_netvars:
print(f"[main] Auto-corrected {fixed_netvars} netvars from live memory.")
try:
entity_list_addr = mem.read_long(mem.client(Offsets.dwEntityList))
controller_addr = mem.read_long(mem.client(Offsets.dwLocalPlayerController))
if not entity_list_addr and not controller_addr:
print("[main] WARNING: dwEntityList and dwLocalPlayerController "
"both read NULL after dumper + sigscan. Offsets are stale " "for this CS2 build and the sigscan patterns did not match. "
"ESP/aim/trigger will be idle until offsets update. " "(If you're at the main menu this is expected — join a map.)")
except Exception:
pass
try:
if bool(getattr(anti_detect, "read_obfuscator_enabled", False)):
from cs2esp.anti_detect import install_read_obfuscator
bogus_reads_per_real = int(getattr(anti_detect, "read_obfuscator_bogus_per_real", 4))
install_read_obfuscator(mem, bogus_per_real=bogus_reads_per_real)
print(f"[anti-det] read-pattern obfuscator installed " f"(bogus_per_real={bogus_reads_per_real})")
except Exception as error:
print(f"[anti-det] read-obfuscator raised: {error!r}")
cs2_pid = getattr(mem.pm, "process_id", 0) if mem.pm else 0
cs2_hwnd = find_window_by_pid(cs2_pid) if cs2_pid else 0
# Log displays, DPI scale and the client rect to tell clipping apart from projection or adapter faults
try:
monitors = enum_monitors()
print(f"[display] DPI-aware={is_process_dpi_aware()} " f"scale={dpi_scale_for_hwnd(cs2_hwnd):.2f} " f"monitors={len(monitors)}")
for index, monitor in enumerate(monitors):
tag = " [primary]" if monitor.is_primary else ""
print(f"[display] #{index}: {monitor.rect}{tag}")
cs2_monitor = monitor_for_hwnd(cs2_hwnd)
if cs2_monitor is not None:
print(f"[display] CS2 (HWND 0x{cs2_hwnd:X}) is on " f"monitor {cs2_monitor.rect}")
else:
print("[display] CS2 monitor unresolved — overlay will cover " "the largest / primary display.")
client = get_client_rect(cs2_hwnd)
if client is not None:
print(f"[display] CS2 client rect (overlay target) = {client}")
else:
print("[display] CS2 client rect unresolved — falling back to " "monitor rect for overlay sizing.")
except Exception as exc:
print(f"[display] monitor dump failed: {exc!r}")
overlay = Overlay(title=None, randomize_title=_anti_detect_value(anti_detect, "randomize_window_title", False),
hide_from_taskbar=_anti_detect_value(anti_detect, "hide_from_taskbar", True))
overlay_vsync = bool(getattr(getattr(config, "overlay", None), "vsync", False))
if not overlay.create(target_hwnd=cs2_hwnd, colorkey_fallback=bool(getattr(getattr(config, "overlay", None), "colorkey_fallback", False)
or _gpu_colorkey_needed()), vsync=overlay_vsync):
return 1
overlay.bring_to_top()
capture_protect_requested = bool(_anti_detect_value(anti_detect, "hide_overlay_from_capture", False))
capture_applied = overlay.set_capture_protect(capture_protect_requested)
last_capture_reapply_t = perf_counter()
if capture_protect_requested or not capture_applied:
print(f'[anti-det] Overlay capture-affinity request ({"enable" if capture_protect_requested else "disable"}): '
f'{"applied" if capture_applied else "failed; retry pending"}.')
entities = EntitySystem(mem)
state_reader = GameStateReader(entities)
glow = GlowSystem(mem)
trigger_vanilla = Triggerbot(mem, entities, config)
trigger_feedback = FeedbackTriggerbot(mem, entities, config)
aimbot = WPMAimbot(config, mem)
rapidfire = RapidFire(config)
autopistol = AutoPistol(config, mem)
bhop = BHop(mem, entities, config)
recoil_control = RecoilControl(mem, config)
recoil_runtime = RecoilRuntime(mem, entities)
radar = Radar(config)
awareness = Awareness(config)
hud_manager = HudPositionManager(config)
if overlay and overlay.hwnd:
hud_manager.set_overlay_hwnd(overlay.hwnd)
from cs2esp.visuals.edit_backdrop import EditBackdrop
edit_backdrop = EditBackdrop()
from cs2esp.metrics import RealMetrics
real_metrics = RealMetrics()
from cs2esp.features.event_sounds import EventSounds
event_sounds = EventSounds(config)
event_sounds.attach()
menu = Menu(config, overlay, cs2_hwnd=0)
keys = KeybindManager()
def _emit_toggle_event(label: str, key: str, on: bool) -> None:
'''Publish a toggle flip to the shared event feed.'''
EventSystem.get().emit(EventType.HOTKEY_TOGGLED,
title=label.upper(), detail=f"{'ON' if on else 'OFF'} · {key.upper()}", duration=1.8, data={"slot": f"bind:{label}", "active": on, "mode": "toggle"})
toggle_keys = ToggleHotkeyDetector(on_flip=_emit_toggle_event)
menu_window: MenuWindow | None = None
menu_focus_budget: int = 0
if qt_menu is not None:
menu.visible = False
try:
overlay.set_click_through(True)
except Exception:
pass
else:
menu.visible = bool(config.general.start_menu_visible)
try:
overlay.set_click_through(not menu.visible or bool(getattr(config.general, "menu_external_window", False)))
except Exception:
pass
menu.cs2_hwnd = cs2_hwnd
try:
overlay.set_target_hwnd(int(cs2_hwnd or 0))
except Exception:
pass
if getattr(config.general, "focus_cs2_on_launch", True) and cs2_hwnd:
if focus_window(cs2_hwnd):
print(f"[main] Focused cs2.exe (HWND 0x{cs2_hwnd:X}).")
else:
print("[main] Could not auto-focus CS2 \u2014 click the game window once.")
overlay.bring_to_top()
if cs2_hwnd:
try:
window_rect = wt.RECT()
user32.GetWindowRect(ctypes.c_void_p(cs2_hwnd), ctypes.byref(window_rect))
screen_width = user32.GetSystemMetrics(0)
screen_height = user32.GetSystemMetrics(1)
covers_screen = (window_rect.left <= 0
and window_rect.top <= 0 and (window_rect.right - window_rect.left) >= screen_width and (window_rect.bottom - window_rect.top) >= screen_height)
GWL_STYLE = -16
WS_BORDER = 0x00800000
WS_THICKFRAME = 0x00040000
style = user32.GetWindowLongW(ctypes.c_void_p(cs2_hwnd), GWL_STYLE)
chromeless = not (style & (WS_BORDER | WS_THICKFRAME))
if covers_screen and chromeless:
print("[main] WARNING: CS2 looks like EXCLUSIVE FULLSCREEN.")
print("[main] Switch CS2 to 'Fullscreen Windowed' (Borderless),")
print("[main] otherwise CS2 will go BLACK whenever you click the menu.")
except Exception:
pass
def _release_synthetic_inputs():
'''Release owned input and discard partial tap bursts and aim paths on master/focus loss.'''
aimbot.reset()
for clicker in (rapidfire, autopistol):
try:
clicker.release()
except Exception:
pass
try:
bhop.release()
except Exception:
pass
status_publisher: StatusPublisher | None = None
def _apply_master(enabled: bool, source: str):
'''Set master, release synthetic input on OFF and publish the status.'''
enabled = bool(enabled)
was_enabled = bool(getattr(config.general, "master_enabled", True))
if enabled != was_enabled:
config.general.master_enabled = enabled
if not enabled:
_release_synthetic_inputs()
recoil_control.reset()
try:
glow.clear_all()
except Exception:
pass
state_reader.request(enabled=False, bones=False, slab=False, health=False)
state_reader.clear()
try:
publish_status = (status_publisher.publish if status_publisher is not None else write_status)
publish_status(fps=None, cs2_attached=mem.is_process_alive(), master_enabled=enabled, cs2_monitor=overlay._monitor_rect,
renderer=gl_renderer_name, render_device_requested=launch_render_device, render_device_warning=_gpu_selection_warning)
except Exception:
pass
print(f"[main] Master = {'ON' if enabled else 'OFF'} ({source})")
def _toggle_master():
'''Flip master from the hotkey.'''
try:
_apply_master(not bool(getattr(config.general, "master_enabled", True)), "hotkey")
except Exception as error:
print(f"[main] master toggle failed: {error!r}")
try:
menu.set_master_status_provider(lambda: bool(getattr(config.general, "master_enabled", True)))
except Exception:
pass
last_status_write_at = 0.0
last_control_poll_at = 0.0
last_gc_at = perf_counter()
frame_stats = [] if os.environ.get("CS2ESP_FRAME_STATS") else None
frame_stats_at = perf_counter()
pipeline_trace = None
trace_path = os.environ.get("CS2ESP_PIPELINE_TRACE")
if trace_path:
from cs2esp.pipeline_trace import PipelineTrace
pipeline_trace = PipelineTrace(trace_path)
diagnostics_enabled = frame_stats is not None or pipeline_trace is not None
late_visuals_enabled = os.environ.get("CS2ESP_LATE_VISUALS", "1") == "1"
print(f"[perf] early HUD schedule={late_visuals_enabled}; interactive modes retain original order")
frame_id = 0
previous_paced_dt = None
gl_renderer_name: str | None = None
last_master_seen = bool(getattr(config.general, "master_enabled", True))
status_write_interval = 0.25
frame_times: list[float] = []
displayed_fps: float | None = None
last_reattach_attempt_at: float = 0.0
reattach_interval = 1.5
display_hz = get_display_refresh_hz(int(overlay.hwnd or 0))
raw_target = int(getattr(config.general, "target_fps", 144) or 144)
target_fps = clamp_target_fps(raw_target, int(overlay.hwnd or 0))
if target_fps != raw_target:
print(f"[main] Clamping target_fps {raw_target} -> {target_fps} " f"(display reports {display_hz:.2f} Hz)")
try:
config.general.target_fps = target_fps
except Exception:
pass
else:
print(f"[main] target_fps = {target_fps} " f"(display {display_hz:.2f} Hz)")
frame_dt = 1.0 / max(30, target_fps)
active_render_profile = ""
last_frame_started_at = None
print(f"[main] Running. {config.general.toggle_menu_key.upper()} = menu, "
f"{config.general.master_toggle_key.upper()} = master toggle, " f"{config.general.exit_key.upper()} = exit.")
if config.triggerbot.enabled:
print(f"[main] Triggerbot ON (hotkey={config.triggerbot.hotkey!r}, " f"delay={config.triggerbot.delay_ms}\u00b1{config.triggerbot.delay_jitter_ms} ms).")
if config.rapidfire.enabled:
print(f"[main] Rapid-fire ON (hotkey={config.rapidfire.hotkey!r}, " f"{config.rapidfire.cps:.1f} cps \u00b1{int(config.rapidfire.jitter_pct*100)}%).")
if config.autopistol.enabled:
print(f"[main] Auto-pistol ON (hotkey={config.autopistol.hotkey!r}, " f"{config.autopistol.cps:.1f} cps).")
if config.bhop.enabled:
print(f"[main] BHop ON (hotkey={config.bhop.hotkey!r}, " f"min_gap={config.bhop.min_gap_ms} ms, humanize={config.bhop.humanize}).")
taskbar_requested = bool(_anti_detect_value(anti_detect, "hide_from_taskbar", True))
last_taskbar_attempt_t = 0.0
read_only_active = bool(_anti_detect_value(anti_detect, "read_only_mode", False))
bones_diag_logged = False
glow_diag_at = 0.0
spectator_diag_logged = False
last_count_diag_at = 0.0
netvar_reheal_done = False
last_reheal_at = 0.0
last_bone_heal_at = 0.0
last_offset_cmd_ts = 0.0
last_offset_cmd_poll = 0.0
qt_menu_was_alive = False
overlay_sync_warning_logged = False
fps_counter_warning_logged = False
last_topmost_at = 0.0
last_occlusion_at = 0.0
last_metrics_at = 0.0
combat_events = CombatEventTracker(EventSystem.get())
combat_telemetry = CombatTelemetry(mem, entities, EventSystem.get())
spectator_names: list = []
last_spec_poll_at = 0.0
right_column_y = 140.0
def _sync_hud_edit_mode() -> bool:
'''Apply entry and exit immediately, including a toolbar action in the current frame.'''
editing = hud_manager.edit_mode_active()
if editing != getattr(overlay, "_edit_focus_on", False):
overlay._edit_focus_on = editing
try:
set_noactivate(int(overlay.hwnd or 0), not editing)
if editing:
ctypes.windll.user32.ClipCursor(None)
focus_window(int(overlay.hwnd or 0))
elif cs2_hwnd:
focus_window(int(cs2_hwnd))
except Exception as error:
print(f'[edit-mode] focus switch failed: {error!r}')
if editing != getattr(overlay, "_edit_backdrop_on", False):
if not editing:
edit_backdrop.invalidate()
overlay._edit_backdrop_on = editing
return editing
try:
status_publisher = StatusPublisher()
keys.bind(config.general.master_toggle_key, _toggle_master)
while overlay.running:
frame_started_at = perf_counter()
if diagnostics_enabled:
frame_id += 1
frame_interval = (frame_started_at - last_frame_started_at if last_frame_started_at is not None else None)
last_frame_started_at = frame_started_at
snapshot_age_at_draw = None
snapshot_selected_at = None
sync_read_started_at = None
sync_read_completed_at = None
visual_refresh_started_at = None
visual_refresh_at = None
visual_refresh_to_return = None
frame_player_count = 0
frame_visible_player_count = 0
mark_combat = None
mark_esp = None
if keys.just_pressed(config.general.toggle_menu_key):
if qt_menu is not None:
qt_menu.toggle(cs2_hwnd=int(cs2_hwnd or 0))
else:
menu.toggle()
if keys.is_pressed(config.general.exit_key):
break
control_due = frame_started_at - last_control_poll_at >= 0.05
if control_due:
last_control_poll_at = frame_started_at
quit_requested = False
for command in drain_control():
action = command.get("action")
if action == "quit":
quit_requested = True
elif action == "master":
_apply_master(bool(command.get("value", True)), "menu")
elif action == "show_menu":
if qt_menu is not None:
if qt_menu.is_alive():
qt_menu.toggle(cs2_hwnd=int(cs2_hwnd or 0))
else:
qt_menu.spawn()
else:
menu.toggle()
if quit_requested:
print("[main] Quit requested from the menu.")
break
if qt_menu is not None:
if qt_menu.is_alive():
qt_menu_was_alive = True
elif qt_menu_was_alive:
master_on = bool(getattr(config.general, "master_enabled", True))
if not master_on:
print("[main] Qt menu closed and master is OFF " "— exiting.")
break
print("[main] Qt menu closed; master overlay still "
f"active ({config.general.toggle_menu_key.upper()} " "to respawn menu, " f"{config.general.master_toggle_key.upper()} " "to toggle master).")
qt_menu_was_alive = False
try:
qt_menu.tick_focus()
except Exception:
pass
try:
# Poll configuration at 50 ms intervals; master changes also arrive over IPC
if control_due and config.reload_if_changed():
target_fps = int(getattr(config.general, "target_fps", target_fps) or target_fps)
frame_dt = 1.0 / max(30, target_fps)
new_vsync = bool(getattr(getattr(config, "overlay", None), "vsync", False))
overlay.set_vsync(new_vsync)
except Exception:
pass
if control_due:
profile = _active_render_profile(getattr(config, "overlay", None), launch_render_device)
if profile != active_render_profile:
active_render_profile = profile
state_reader.set_target_hz(_RENDER_PROFILE_READER_HZ[profile])
print(f"[perf] render profile={profile}, reader={_RENDER_PROFILE_READER_HZ[profile]:.0f} Hz")
try:
if frame_started_at - last_offset_cmd_poll >= 0.5:
last_offset_cmd_poll = frame_started_at
offset_message = read_offset_refresh_request(last_offset_cmd_ts)
offset_req = offset_message is not None
if offset_message is not None:
last_offset_cmd_ts = offset_message["ts"]
else:
offset_req = False
if offset_req:
print("[main] Live offset update requested via IPC — reloading...")
from hashlib import sha256
applied_cnt = 0
fixed = 0
loaded = saved = succeeded = False
loaded_digest = final_digest = None
refresh_error = None
attached_now = bool(mem and mem.pm and mem.client_base)
previous_offsets = export_offsets_dict()
state_reader.clear()
try:
expected_digest = offset_message.get("cache_sha256")
loaded = load_offsets_cache(expected_sha256=expected_digest)
if not loaded:
raise RuntimeError("cache missing, invalid, or changed since the update request")
loaded_digest = expected_digest or sha256(OFFSETS_CACHE_PATH.read_bytes()).hexdigest()
if attached_now:
applied = apply_sigscan(mem.pm)
applied_cnt = len(applied)
fixed = verify_netvars(mem)
if not _live_offsets_readable(mem):
raise RuntimeError("runtime live global validation failed")
print(f"[main] Live healed in-process: sigscan={len(applied)}, netvars={fixed}")
saved = bool(save_offsets_cache())
if not saved:
raise RuntimeError("runtime could not persist healed offsets")
else:
saved = True
if attached_now:
receipt = verified_offsets_cache_receipt()
if receipt is None:
saved = False
raise RuntimeError("runtime offset cache changed before saved-byte confirmation")
final_digest = receipt["sha256"]
else:
final_digest = loaded_digest
if sha256(OFFSETS_CACHE_PATH.read_bytes()).hexdigest() != final_digest:
saved = False
raise RuntimeError("offset cache changed before application confirmation")
succeeded = True
except Exception as exc:
refresh_error = str(exc)
import_offsets_dict(previous_offsets)
print(f"[main] Offset refresh not applied: {exc!r}")
finally:
state_reader.clear()
try:
write_offset_ack(request_ts=last_offset_cmd_ts, applied=applied_cnt, netvars=fixed, attached=attached_now,
success=succeeded, cache_loaded=loaded, cache_saved=saved, live_verified=True if succeeded and attached_now else None,
applied_cache_sha256=loaded_digest, cache_sha256=final_digest, error=refresh_error)
except Exception as exc:
print(f"[main] offset ack failed: {exc!r}")
if succeeded:
EventSystem.get().emit(
EventType.OFFSETS_UPDATED, title="OFFSETS UPDATED", detail=f"offsets refreshed via GUI ({applied_cnt} sigscans applied)")
netvar_reheal_done = False
bones_diag_logged = False
except Exception:
pass
labels_toggle_key = getattr(config.visuals.name, "hotkey_toggle", "")
toggle_keys.poll([
(getattr(config.triggerbot, "hotkey_toggle", ""), config.triggerbot, "enabled", "Triggerbot"), (getattr(config.rapidfire, "hotkey_toggle", ""),
config.rapidfire, "enabled", "Rapid-fire"), (getattr(config.autopistol, "hotkey_toggle", ""), config.autopistol, "enabled", "Auto-pistol"),
(getattr(config.bhop, "hotkey_toggle", ""), config.bhop, "enabled", "Bunny Hop"), (getattr(config.aimbot, "hotkey_toggle", ""),
config.aimbot, "enabled", "Aimbot"), (getattr(config.recoil_control, "hotkey_toggle", ""), config.recoil_control, "enabled", "Recoil control"),
(getattr(config.radar, "hotkey_toggle", ""), config.radar, "enabled", "Radar"),
(getattr(config.awareness, "hotkey_toggle", ""), config.awareness, "enabled", "Awareness"),
(getattr(config.wallhack, "hotkey_toggle", ""), config.wallhack, "enabled", "Wallhack"), (getattr(config.visuals.snapline, "hotkey_toggle", ""),
config.visuals.snapline, "enabled", "Snapline"), (getattr(config.visuals.crosshair, "hotkey_toggle", ""),
config.visuals.crosshair, "enabled", "Crosshair"), (getattr(config.fps_counter, "hotkey_toggle", ""), config.fps_counter, "enabled", "FPS counter"),
(labels_toggle_key, config.visuals.name, "enabled", "Names"), (labels_toggle_key, config.visuals.distance, "enabled", "Names")])
cs2_alive = mem.is_process_alive()
if not cs2_alive:
recoil_runtime.reset()
recoil_control.reset()
reconnect_now = perf_counter()
if reconnect_now - last_reattach_attempt_at >= reattach_interval:
last_reattach_attempt_at = reconnect_now
# Invalidate any in-flight walk before changing the process handle; a result begun for the old process must not be published
state_reader.request(enabled=False, bones=False, slab=False, health=False)
state_reader.clear()
if mem.pm is not None:
try:
mem.detach()
except Exception:
pass
try:
if mem.attach(quiet=True):
cs2_alive = True
last_status_write_at = 0.0
except Exception:
pass
master_enabled = bool(getattr(config.general, "master_enabled", True))
if master_enabled != last_master_seen:
# Apply the same release/reset path to hotkeys, menu commands and configuration changes
if not master_enabled:
_apply_master(False, "config")
last_master_seen = master_enabled
if cs2_alive and (not cs2_hwnd or not is_window_valid(cs2_hwnd)):
cs2_pid = getattr(mem.pm, "process_id", 0) if mem.pm else 0
new_hwnd = find_window_by_pid(cs2_pid) if cs2_pid else 0
if new_hwnd and new_hwnd != cs2_hwnd:
cs2_hwnd = new_hwnd
try:
overlay.set_target_hwnd(cs2_hwnd)
except Exception:
pass
if cs2_hwnd and not getattr(overlay, "_cs2_focused_once", False):
try:
focus_window(cs2_hwnd)
overlay._cs2_focused_once = True
except Exception:
pass
cs2_window_ready = bool(cs2_hwnd and is_window_valid(cs2_hwnd))
cs2_minimized = is_window_minimized(cs2_hwnd) if cs2_window_ready else False
is_menu_open = bool((qt_menu is not None and qt_menu.is_visible) or (menu is not None and getattr(menu, "visible", False)))
is_imgui_menu_open = bool(qt_menu is None and menu is not None and getattr(menu, "visible", False))
# Overlay only over the active game; the Qt/imgui menu and HUD edit mode keep it alive so widgets stay reachable
fg_hwnd = 0
try:
fg_hwnd = int(user32.GetForegroundWindow() or 0)
except Exception:
pass
cs2_foreground = bool(cs2_hwnd and fg_hwnd == cs2_hwnd)
hud_edit_mode = bool(getattr(getattr(config, "event_visuals", None), "edit_mode", False))
if hud_edit_mode:
try:
if is_key_pressed("esc"):
hud_manager.finish_editing()
hud_edit_mode = False
except Exception:
pass
hud_edit_mode = _sync_hud_edit_mode()
# Clip unrelated windows without hiding the active menu or HUD editor
should_show_overlay = bool(cs2_alive and not cs2_minimized and ((master_enabled and cs2_window_ready) or is_imgui_menu_open))
# Synchronise window-local clipping after geometry changes
try:
context_before_sync = overlay.ctx
overlay.sync_to_monitor()
if overlay.ctx is not context_before_sync:
chams_context_recreated()
vpk_chams().invalidate_context()
menu.invalidate_current_context_state()
edit_backdrop.invalidate()
except Exception as error:
if not overlay_sync_warning_logged:
print(f"[overlay] monitor sync failed: {error!r}")
overlay_sync_warning_logged = True
occlusion_signature = getattr(overlay, "_occlusion_sig", None)
if should_show_overlay and (occlusion_signature is None or frame_started_at - last_occlusion_at >= 0.25):
last_occlusion_at = frame_started_at
try:
holes = [] if hud_edit_mode else windows_covering(cs2_hwnd, skip_hwnds=(overlay.hwnd,))
signature = (int(overlay.hwnd or 0), cs2_hwnd, overlay._monitor_rect, tuple(holes))
if signature != occlusion_signature:
if holes:
applied = set_exclusion_region(overlay.hwnd, list(holes))
else:
applied = set_exclusion_region(overlay.hwnd, [])
# A transient Win32 failure must not cache an unapplied region until a manual toggle
if applied:
overlay._occlusion_sig = signature
except Exception:
pass
try:
overlay_is_visible = bool(glfw.get_window_attrib(overlay.window, glfw.VISIBLE))
if should_show_overlay and not overlay_is_visible:
overlay.show()
elif not should_show_overlay and overlay_is_visible:
overlay.hide()
overlay._occlusion_sig = None
except Exception as error:
print(f"[overlay] visibility sync failed: {error!r}")
if should_show_overlay and frame_started_at - last_topmost_at >= 1.0:
overlay.bring_to_top()
last_topmost_at = frame_started_at
screen_w, screen_h = overlay.width, overlay.height
if overlay and overlay.hwnd:
hud_manager.set_overlay_hwnd(overlay.hwnd)
# Sample process and game metrics outside the per-frame hot path
if frame_started_at - last_metrics_at >= 0.25:
last_metrics_at = frame_started_at
try:
_pids = [os.getpid()]
if qt_menu is not None:
child = getattr(qt_menu, "_proc", None)
if child is not None and child.pid:
_pids.append(child.pid)
real_metrics.set_pids(tuple(_pids))
real_metrics.update(mem if cs2_alive else None)
except Exception:
pass
if not cs2_foreground or not master_enabled or hud_edit_mode or bool(config.anti_detection.read_only_mode):
right_button_guard.configure(config.aimbot, None, int(cs2_hwnd or 0), enabled=False)
if overlay.begin_frame() is False:
continue
hud_manager.begin_frame()
editor_enabled, editor_exclusions = _hud_editor_input_context(