Advertisement
alien_fx_fiend

2D StickPool Game (O3 AI CodeSmell) 3 Bugs Remain !

Jul 9th, 2025
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 197.19 KB | Source Code | 0 0
  1. ==++ Here's the full source code for (File 1\3) "Pool-Game-CloneV18.cpp"::: ++==
  2. ```Pool-Game-CloneV18.cpp
  3. #define WIN32_LEAN_AND_MEAN
  4. #define NOMINMAX
  5. #include <windows.h>
  6. #include <d2d1.h>
  7. #include <dwrite.h>
  8. #include <fstream> // For file I/O
  9. #include <iostream> // For some basic I/O, though not strictly necessary for just file ops
  10. #include <vector>
  11. #include <cmath>
  12. #include <string>
  13. #include <sstream> // Required for wostringstream
  14. #include <algorithm> // Required for std::max, std::min
  15. #include <ctime>    // Required for srand, time
  16. #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  17. #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  18. #include <mmsystem.h> // For PlaySound
  19. #include <tchar.h> //midi func
  20. #include <thread>
  21. #include <atomic>
  22. #include "resource.h"
  23.  
  24. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  25. #pragma comment(lib, "d2d1.lib")
  26. #pragma comment(lib, "dwrite.lib")
  27. #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  28.  
  29. // --- Constants ---
  30. const float PI = 3.1415926535f;
  31. const float BALL_RADIUS = 10.0f;
  32. const float TABLE_LEFT = 100.0f;
  33. const float TABLE_TOP = 100.0f;
  34. const float TABLE_WIDTH = 700.0f;
  35. const float TABLE_HEIGHT = 350.0f;
  36. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  37. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  38. const float CUSHION_THICKNESS = 20.0f;
  39. const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  40. const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  41. const float MAX_SHOT_POWER = 15.0f;
  42. const float FRICTION = 0.985f; // Friction factor per frame
  43. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  44. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  45. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  46. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  47. const UINT ID_TIMER = 1;
  48. const int TARGET_FPS = 60; // Target frames per second for timer
  49.  
  50. // --- Enums ---
  51. // --- MODIFIED/NEW Enums ---
  52. enum GameState {
  53.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  54.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  55.    BREAKING,           // Player is aiming/shooting the break shot
  56.    CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
  57.    CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
  58.    AIMING,             // Player is aiming
  59.    AI_THINKING,        // NEW: AI is calculating its move
  60.    SHOT_IN_PROGRESS,   // Balls are moving
  61.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  62.    PLAYER1_TURN,
  63.    PLAYER2_TURN,
  64.    BALL_IN_HAND_P1,
  65.    BALL_IN_HAND_P2,
  66.    GAME_OVER
  67. };
  68.  
  69. enum BallType {
  70.    NONE,
  71.    SOLID,  // Yellow (1-7)
  72.    STRIPE, // Red (9-15)
  73.    EIGHT_BALL, // Black (8)
  74.    CUE_BALL // White (0)
  75. };
  76.  
  77. // NEW Enums for Game Mode and AI Difficulty
  78. enum GameMode {
  79.    HUMAN_VS_HUMAN,
  80.    HUMAN_VS_AI
  81. };
  82.  
  83. enum AIDifficulty {
  84.    EASY,
  85.    MEDIUM,
  86.    HARD
  87. };
  88.  
  89. enum OpeningBreakMode {
  90.    CPU_BREAK,
  91.    P1_BREAK,
  92.    FLIP_COIN_BREAK
  93. };
  94.  
  95. // --- Structs ---
  96. struct Ball {
  97.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  98.    BallType type;
  99.    float x, y;
  100.    float vx, vy;
  101.    D2D1_COLOR_F color;
  102.    bool isPocketed;
  103. };
  104.  
  105. struct PlayerInfo {
  106.    BallType assignedType;
  107.    int ballsPocketedCount;
  108.    std::wstring name;
  109. };
  110.  
  111. // --- Global Variables ---
  112.  
  113. // Direct2D & DirectWrite
  114. ID2D1Factory* pFactory = nullptr;
  115. //ID2D1Factory* g_pD2DFactory = nullptr;
  116. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  117. IDWriteFactory* pDWriteFactory = nullptr;
  118. IDWriteTextFormat* pTextFormat = nullptr;
  119. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  120.  
  121. // Game State
  122. HWND hwndMain = nullptr;
  123. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  124. std::vector<Ball> balls;
  125. int currentPlayer = 1; // 1 or 2
  126. PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
  127. PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
  128. bool foulCommitted = false;
  129. std::wstring gameOverMessage = L"";
  130. bool firstBallPocketedAfterBreak = false;
  131. std::vector<int> pocketedThisTurn;
  132. // --- NEW: 8-Ball Pocket Call Globals ---
  133. int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
  134. int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
  135. int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
  136. std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
  137.     // --- NEW: Remember which pocket the 8?ball actually went into last shot
  138. int lastEightBallPocketIndex = -1;
  139. //int lastPocketedIndex = -1; // pocket index (0–5) of the last ball pocketed
  140.  
  141. // --- NEW: Foul Tracking Globals ---
  142. int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  143. bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  144. bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  145. // --- End New Foul Tracking Globals ---
  146.  
  147. // NEW Game Mode/AI Globals
  148. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  149. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  150. OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  151. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  152. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  153. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  154. // NEW: Flag to indicate if the current shot is the opening break of the game
  155. bool isOpeningBreakShot = false;
  156.  
  157. // NEW: For AI shot planning and visualization
  158. struct AIPlannedShot {
  159.    float angle;
  160.    float power;
  161.    float spinX;
  162.    float spinY;
  163.    bool isValid; // Is there a valid shot planned?
  164. };
  165. AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  166. bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  167. int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  168. const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  169.  
  170. // Input & Aiming
  171. POINT ptMouse = { 0, 0 };
  172. bool isAiming = false;
  173. bool isDraggingCueBall = false;
  174. // --- ENSURE THIS LINE EXISTS HERE ---
  175. bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  176. // --- End Ensure ---
  177. bool isSettingEnglish = false;
  178. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  179. float cueAngle = 0.0f;
  180. float shotPower = 0.0f;
  181. float cueSpinX = 0.0f; // Range -1 to 1
  182. float cueSpinY = 0.0f; // Range -1 to 1
  183. float pocketFlashTimer = 0.0f;
  184. bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  185. int draggingBallId = -1;
  186. bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  187. MCIDEVICEID midiDeviceID = 0; //midi func
  188. std::atomic<bool> isMusicPlaying(false); //midi func
  189. std::thread musicThread; //midi func
  190. void StartMidi(HWND hwnd, const TCHAR* midiPath);
  191. void StopMidi();
  192.  
  193. // UI Element Positions
  194. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
  195. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  196. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  197. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  198. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  199.  
  200. // Corrected Pocket Center Positions (aligned with table corners/edges)
  201. const D2D1_POINT_2F pocketPositions[6] = {
  202.     {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  203.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  204.     {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  205.     {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  206.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  207.     {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  208. };
  209.  
  210. // Colors
  211. const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.1608f, 0.4000f, 0.1765f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
  212. //const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.0f, 0.5f, 0.1f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
  213. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  214. //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  215. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  216. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  217. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  218. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
  219. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red);   // Stripes = Red
  220. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  221. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  222. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  223. //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  224. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  225. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  226.  
  227. // --- Forward Declarations ---
  228. HRESULT CreateDeviceResources();
  229. void DiscardDeviceResources();
  230. void OnPaint();
  231. void OnResize(UINT width, UINT height);
  232. void InitGame();
  233. void GameUpdate();
  234. void UpdatePhysics();
  235. void CheckCollisions();
  236. bool CheckPockets(); // Returns true if any ball was pocketed
  237. void ProcessShotResults();
  238. void ApplyShot(float power, float angle, float spinX, float spinY);
  239. void RespawnCueBall(bool behindHeadstring);
  240. bool AreBallsMoving();
  241. void SwitchTurns();
  242. bool AssignPlayerBallTypes(BallType firstPocketedType);
  243. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  244. Ball* GetBallById(int id);
  245. Ball* GetCueBall();
  246. //void PlayGameMusic(HWND hwnd); //midi func
  247. void AIBreakShot();
  248.  
  249. // Drawing Functions
  250. void DrawScene(ID2D1RenderTarget* pRT);
  251. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  252. void DrawBalls(ID2D1RenderTarget* pRT);
  253. void DrawCueStick(ID2D1RenderTarget* pRT);
  254. void DrawAimingAids(ID2D1RenderTarget* pRT);
  255. void DrawUI(ID2D1RenderTarget* pRT);
  256. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  257. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  258. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  259. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  260. // NEW
  261. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
  262.  
  263. // Helper Functions
  264. float GetDistance(float x1, float y1, float x2, float y2);
  265. float GetDistanceSq(float x1, float y1, float x2, float y2);
  266. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  267. template <typename T> void SafeRelease(T** ppT);
  268. // --- NEW HELPER FORWARD DECLARATIONS ---
  269. bool IsPlayerOnEightBall(int player);
  270. void CheckAndTransitionToPocketChoice(int playerID);
  271. // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  272. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  273. // --- End Forward Declaration ---
  274. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection); // Keep this if present
  275.  
  276. // --- NEW Forward Declarations ---
  277.  
  278. // AI Related
  279. struct AIShotInfo; // Define below
  280. void TriggerAIMove();
  281. void AIMakeDecision();
  282. void AIPlaceCueBall();
  283. AIShotInfo AIFindBestShot();
  284. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  285. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  286. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  287. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  288. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  289. bool IsValidAIAimAngle(float angle); // Basic check
  290.  
  291. // Dialog Related
  292. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  293. void ShowNewGameDialog(HINSTANCE hInstance);
  294. void LoadSettings(); // For deserialization
  295. void SaveSettings(); // For serialization
  296. const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  297. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  298.  
  299. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  300. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  301.  
  302. // --- NEW Struct for AI Shot Evaluation ---
  303. struct AIShotInfo {
  304.     bool possible = false;          // Is this shot considered viable?
  305.     Ball* targetBall = nullptr;     // Which ball to hit
  306.     int pocketIndex = -1;           // Which pocket to aim for (0-5)
  307.     D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  308.     float angle = 0.0f;             // Calculated shot angle
  309.     float power = 0.0f;             // Calculated shot power
  310.     float score = -1.0f;            // Score for this shot (higher is better)
  311.     bool involves8Ball = false;     // Is the target the 8-ball?
  312. };
  313.  
  314. /*
  315. table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  316. rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  317. gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  318. winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  319. headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  320. bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  321. */
  322.  
  323. // --- NEW Settings Serialization Functions ---
  324. void SaveSettings() {
  325.     std::ofstream outFile(SETTINGS_FILE_NAME);
  326.     if (outFile.is_open()) {
  327.         outFile << static_cast<int>(gameMode) << std::endl;
  328.         outFile << static_cast<int>(aiDifficulty) << std::endl;
  329.         outFile << static_cast<int>(openingBreakMode) << std::endl;
  330.         outFile.close();
  331.     }
  332.     // else: Handle error, e.g., log or silently fail
  333. }
  334.  
  335. void LoadSettings() {
  336.     std::ifstream inFile(SETTINGS_FILE_NAME);
  337.     if (inFile.is_open()) {
  338.         int gm, aid, obm;
  339.         if (inFile >> gm) {
  340.             gameMode = static_cast<GameMode>(gm);
  341.         }
  342.         if (inFile >> aid) {
  343.             aiDifficulty = static_cast<AIDifficulty>(aid);
  344.         }
  345.         if (inFile >> obm) {
  346.             openingBreakMode = static_cast<OpeningBreakMode>(obm);
  347.         }
  348.         inFile.close();
  349.  
  350.         // Validate loaded settings (optional, but good practice)
  351.         if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  352.         if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  353.         if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  354.     }
  355.     // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  356. }
  357. // --- End Settings Serialization Functions ---
  358.  
  359. // --- NEW Dialog Procedure ---
  360. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  361.     switch (message) {
  362.     case WM_INITDIALOG:
  363.     {
  364.         // --- ACTION 4: Center Dialog Box ---
  365. // Optional: Force centering if default isn't working
  366.         RECT rcDlg, rcOwner, rcScreen;
  367.         HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  368.         if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  369.  
  370.         GetWindowRect(hwndOwner, &rcOwner);
  371.         GetWindowRect(hDlg, &rcDlg);
  372.         CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  373.  
  374.         // Offset the owner rect relative to the screen if it's not the desktop
  375.         if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  376.             OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  377.             OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  378.             OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  379.         }
  380.  
  381.  
  382.         // Calculate centered position
  383.         int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  384.         int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  385.  
  386.         // Ensure it stays within screen bounds (optional safety)
  387.         x = std::max(static_cast<int>(rcScreen.left), x);
  388.         y = std::max(static_cast<int>(rcScreen.top), y);
  389.         if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  390.             x = rcScreen.right - (rcDlg.right - rcDlg.left);
  391.         if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  392.             y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  393.  
  394.  
  395.         // Set the dialog position
  396.         SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  397.  
  398.         // --- End Centering Code ---
  399.  
  400.         // Set initial state based on current global settings (or defaults)
  401.         CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  402.  
  403.         CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  404.             (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  405.  
  406.         // Enable/Disable AI group based on initial mode
  407.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  408.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  409.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  410.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  411.         // Set initial state for Opening Break Mode
  412.         CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  413.             (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  414.         // Enable/Disable Opening Break group based on initial mode
  415.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  416.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  417.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  418.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  419.     }
  420.     return (INT_PTR)TRUE;
  421.  
  422.     case WM_COMMAND:
  423.         switch (LOWORD(wParam)) {
  424.         case IDC_RADIO_2P:
  425.         case IDC_RADIO_CPU:
  426.         {
  427.             bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  428.             // Enable/Disable AI group controls based on selection
  429.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  430.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  431.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  432.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  433.             // Also enable/disable Opening Break Mode group
  434.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  435.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  436.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  437.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  438.         }
  439.         return (INT_PTR)TRUE;
  440.  
  441.         case IDOK:
  442.             // Retrieve selected options and store in global variables
  443.             if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  444.                 gameMode = HUMAN_VS_AI;
  445.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  446.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  447.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  448.  
  449.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  450.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  451.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  452.             }
  453.             else {
  454.                 gameMode = HUMAN_VS_HUMAN;
  455.                 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  456.             }
  457.             SaveSettings(); // Save settings when OK is pressed
  458.             EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  459.             return (INT_PTR)TRUE;
  460.  
  461.         case IDCANCEL: // Handle Cancel or closing the dialog
  462.             // Optionally, could reload settings here if you want cancel to revert to previously saved state
  463.             EndDialog(hDlg, IDCANCEL);
  464.             return (INT_PTR)TRUE;
  465.         }
  466.         break; // End WM_COMMAND
  467.     }
  468.     return (INT_PTR)FALSE; // Default processing
  469. }
  470.  
  471. // --- NEW Helper to Show Dialog ---
  472. void ShowNewGameDialog(HINSTANCE hInstance) {
  473.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  474.         // User clicked Start, reset game with new settings
  475.         isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  476.         if (isPlayer2AI) {
  477.             switch (aiDifficulty) {
  478.             case EASY: player2Info.name = L"CPU (Easy)"; break;
  479.             case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  480.             case HARD: player2Info.name = L"CPU (Hard)"; break;
  481.             }
  482.         }
  483.         else {
  484.             player2Info.name = L"Player 2";
  485.         }
  486.         // Update window title
  487.         std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  488.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  489.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  490.         SetWindowText(hwndMain, windowTitle.c_str());
  491.  
  492.         InitGame(); // Re-initialize game logic & board
  493.         InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  494.     }
  495.     else {
  496.         // User cancelled dialog - maybe just resume game? Or exit?
  497.         // For simplicity, we do nothing, game continues as it was.
  498.         // To exit on cancel from F2, would need more complex state management.
  499.     }
  500. }
  501.  
  502. // --- NEW Reset Game Function ---
  503. void ResetGame(HINSTANCE hInstance) {
  504.     // Call the helper function to show the dialog and re-init if OK clicked
  505.     ShowNewGameDialog(hInstance);
  506. }
  507.  
  508. // --- WinMain ---
  509. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  510.     if (FAILED(CoInitialize(NULL))) {
  511.         MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  512.         return -1;
  513.     }
  514.  
  515.     // --- NEW: Load settings at startup ---
  516.     LoadSettings();
  517.  
  518.     // --- NEW: Show configuration dialog FIRST ---
  519.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  520.         // User cancelled the dialog
  521.         CoUninitialize();
  522.         return 0; // Exit gracefully if dialog cancelled
  523.     }
  524.     // Global gameMode and aiDifficulty are now set by the DialogProc
  525.  
  526.     // Set AI flag based on game mode
  527.     isPlayer2AI = (gameMode == HUMAN_VS_AI);
  528.     if (isPlayer2AI) {
  529.         switch (aiDifficulty) {
  530.         case EASY: player2Info.name = L"CPU (Easy)"; break;
  531.         case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
  532.         case HARD: player2Info.name = L"CPU (Hard)"; break;
  533.         }
  534.     }
  535.     else {
  536.         player2Info.name = L"Player 2";
  537.     }
  538.     // --- End of Dialog Logic ---
  539.  
  540.  
  541.     WNDCLASS wc = { };
  542.     wc.lpfnWndProc = WndProc;
  543.     wc.hInstance = hInstance;
  544.     wc.lpszClassName = L"Direct2D_8BallPool";
  545.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  546.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  547.     wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  548.  
  549.     if (!RegisterClass(&wc)) {
  550.         MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  551.         CoUninitialize();
  552.         return -1;
  553.     }
  554.  
  555.     // --- ACTION 4: Calculate Centered Window Position ---
  556.     const int WINDOW_WIDTH = 1000; // Define desired width
  557.     const int WINDOW_HEIGHT = 700; // Define desired height
  558.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  559.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  560.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  561.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  562.  
  563.     // --- Change Window Title based on mode ---
  564.     std::wstring windowTitle = L"Direct2D 8-Ball Pool";
  565.     if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  566.     else windowTitle += L" (Human vs " + player2Info.name + L")";
  567.  
  568.     DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  569.  
  570.     hwndMain = CreateWindowEx(
  571.         0, L"Direct2D_8BallPool", windowTitle.c_str(), dwStyle,
  572.         windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  573.         NULL, NULL, hInstance, NULL
  574.     );
  575.  
  576.     if (!hwndMain) {
  577.         MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  578.         CoUninitialize();
  579.         return -1;
  580.     }
  581.  
  582.     // Initialize Direct2D Resources AFTER window creation
  583.     if (FAILED(CreateDeviceResources())) {
  584.         MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  585.         DestroyWindow(hwndMain);
  586.         CoUninitialize();
  587.         return -1;
  588.     }
  589.  
  590.     InitGame(); // Initialize game state AFTER resources are ready & mode is set
  591.     Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  592.     StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  593.     //PlayGameMusic(hwndMain); //midi func
  594.  
  595.     ShowWindow(hwndMain, nCmdShow);
  596.     UpdateWindow(hwndMain);
  597.  
  598.     if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  599.         MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  600.         DestroyWindow(hwndMain);
  601.         CoUninitialize();
  602.         return -1;
  603.     }
  604.  
  605.     MSG msg = { };
  606.     // --- Modified Main Loop ---
  607.     // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  608.     // or gets reset to it via F2. The main loop runs normally once game starts.
  609.     while (GetMessage(&msg, NULL, 0, 0)) {
  610.         // We might need modeless dialog handling here if F2 shows dialog
  611.         // while window is active, but DialogBoxParam is modal.
  612.         // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  613.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  614.         TranslateMessage(&msg);
  615.         DispatchMessage(&msg);
  616.     }
  617.  
  618.  
  619.     KillTimer(hwndMain, ID_TIMER);
  620.     DiscardDeviceResources();
  621.     SaveSettings(); // Save settings on exit
  622.     CoUninitialize();
  623.  
  624.     return (int)msg.wParam;
  625. }
  626.  
  627. // --- WndProc ---
  628. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  629.     // Declare cueBall pointer once at the top, used in multiple cases
  630.     // For clarity, often better to declare within each case where needed.
  631.     Ball* cueBall = nullptr; // Initialize to nullptr
  632.     switch (msg) {
  633.     case WM_CREATE:
  634.         // Resources are now created in WinMain after CreateWindowEx
  635.         return 0;
  636.  
  637.     case WM_PAINT:
  638.         OnPaint();
  639.         // Validate the entire window region after painting
  640.         ValidateRect(hwnd, NULL);
  641.         return 0;
  642.  
  643.     case WM_SIZE: {
  644.         UINT width = LOWORD(lParam);
  645.         UINT height = HIWORD(lParam);
  646.         OnResize(width, height);
  647.         return 0;
  648.     }
  649.  
  650.     case WM_TIMER:
  651.         if (wParam == ID_TIMER) {
  652.             GameUpdate(); // Update game logic and physics
  653.             InvalidateRect(hwnd, NULL, FALSE); // Request redraw
  654.         }
  655.         return 0;
  656.  
  657.         // --- NEW: Handle F2 Key for Reset ---
  658.         // --- MODIFIED: Handle More Keys ---
  659.     case WM_KEYDOWN:
  660.     { // Add scope for variable declarations
  661.  
  662.         // --- FIX: Get Cue Ball pointer for this scope ---
  663.         cueBall = GetCueBall();
  664.         // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
  665.         // --- End Fix ---
  666.  
  667.         // Check which player can interact via keyboard (Humans only)
  668.         bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  669.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  670.  
  671.         // --- F1 / F2 Keys (Always available) ---
  672.         if (wParam == VK_F2) {
  673.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  674.             ResetGame(hInstance); // Call reset function
  675.             return 0; // Indicate key was processed
  676.         }
  677.         else if (wParam == VK_F1) {
  678.             MessageBox(hwnd,
  679.                 L"Direct2D-based StickPool game made in C++ from scratch (2764+ lines of code)\n" // Update line count if needed
  680.                 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  681.                 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  682.                 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions.\n"
  683.                 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  684.                 L"About This Game", MB_OK | MB_ICONINFORMATION);
  685.             return 0; // Indicate key was processed
  686.         }
  687.  
  688.         // Check for 'M' key (uppercase or lowercase)
  689.             // Toggle music with "M"
  690.         if (wParam == 'M' || wParam == 'm') {
  691.             //static bool isMusicPlaying = false;
  692.             if (isMusicPlaying) {
  693.                 // Stop the music
  694.                 StopMidi();
  695.                 isMusicPlaying = false;
  696.             }
  697.             else {
  698.                 // Build the MIDI file path
  699.                 TCHAR midiPath[MAX_PATH];
  700.                 GetModuleFileName(NULL, midiPath, MAX_PATH);
  701.                 // Keep only the directory part
  702.                 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  703.                 if (lastBackslash != NULL) {
  704.                     *(lastBackslash + 1) = '\0';
  705.                 }
  706.                 // Append the MIDI filename
  707.                 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
  708.  
  709.                 // Start playing MIDI
  710.                 StartMidi(hwndMain, midiPath);
  711.                 isMusicPlaying = true;
  712.             }
  713.         }
  714.  
  715.  
  716.         // --- Player Interaction Keys (Only if allowed) ---
  717.         if (canPlayerControl) {
  718.             // --- Get Shift Key State ---
  719.             bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  720.             float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
  721.             float powerStep = 0.2f; // Power step (Adjust as needed)
  722.  
  723.             switch (wParam) {
  724.             case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
  725.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  726.                     cueAngle -= angleStep;
  727.                     // Normalize angle (keep between 0 and 2*PI)
  728.                     if (cueAngle < 0) cueAngle += 2 * PI;
  729.                     // Ensure state shows aiming visuals if turn just started
  730.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  731.                     isAiming = false; // Keyboard adjust doesn't use mouse aiming state
  732.                     isDraggingStick = false;
  733.                     keyboardAimingActive = true;
  734.                 }
  735.                 break;
  736.  
  737.             case VK_RIGHT: // Rotate Cue Stick Clockwise
  738.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  739.                     cueAngle += angleStep;
  740.                     // Normalize angle (keep between 0 and 2*PI)
  741.                     if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  742.                     // Ensure state shows aiming visuals if turn just started
  743.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  744.                     isAiming = false;
  745.                     isDraggingStick = false;
  746.                     keyboardAimingActive = true;
  747.                 }
  748.                 break;
  749.  
  750.             case VK_UP: // Decrease Shot Power
  751.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  752.                     shotPower -= powerStep;
  753.                     if (shotPower < 0.0f) shotPower = 0.0f;
  754.                     // Ensure state shows aiming visuals if turn just started
  755.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  756.                     isAiming = true; // Keyboard adjust doesn't use mouse aiming state
  757.                     isDraggingStick = false;
  758.                     keyboardAimingActive = true;
  759.                 }
  760.                 break;
  761.  
  762.             case VK_DOWN: // Increase Shot Power
  763.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  764.                     shotPower += powerStep;
  765.                     if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  766.                     // Ensure state shows aiming visuals if turn just started
  767.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  768.                     isAiming = true;
  769.                     isDraggingStick = false;
  770.                     keyboardAimingActive = true;
  771.                 }
  772.                 break;
  773.  
  774.             case VK_SPACE: // Trigger Shot
  775.                 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  776.                     && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  777.                 {
  778.                     if (shotPower > 0.15f) { // Use same threshold as mouse
  779.                        // Reset foul flags BEFORE applying shot
  780.                         firstHitBallIdThisShot = -1;
  781.                         cueHitObjectBallThisShot = false;
  782.                         railHitAfterContact = false;
  783.  
  784.                         // Play sound & Apply Shot
  785.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  786.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  787.  
  788.                         // Update State
  789.                         currentGameState = SHOT_IN_PROGRESS;
  790.                         foulCommitted = false;
  791.                         pocketedThisTurn.clear();
  792.                         shotPower = 0; // Reset power after shooting
  793.                         isAiming = false; isDraggingStick = false; // Reset aiming flags
  794.                         keyboardAimingActive = false;
  795.                     }
  796.                 }
  797.                 break;
  798.  
  799.             case VK_ESCAPE: // Cancel Aim/Shot Setup
  800.                 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  801.                 {
  802.                     shotPower = 0.0f;
  803.                     isAiming = false;
  804.                     isDraggingStick = false;
  805.                     keyboardAimingActive = false;
  806.                     // Revert to basic turn state if not breaking
  807.                     if (currentGameState != BREAKING) {
  808.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  809.                     }
  810.                 }
  811.                 break;
  812.  
  813.             case 'G': // Toggle Cheat Mode
  814.                 cheatModeEnabled = !cheatModeEnabled;
  815.                 if (cheatModeEnabled)
  816.                     MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
  817.                 else
  818.                     MessageBeep(MB_OK); // Play a different beep when disabling
  819.                 break;
  820.  
  821.             default:
  822.                 // Allow default processing for other keys if needed
  823.                 // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
  824.                 break;
  825.             } // End switch(wParam) for player controls
  826.             return 0; // Indicate player control key was processed
  827.         } // End if(canPlayerControl)
  828.     } // End scope for WM_KEYDOWN case
  829.     // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
  830.     // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
  831.     return 0;
  832.  
  833.     case WM_MOUSEMOVE: {
  834.         ptMouse.x = LOWORD(lParam);
  835.         ptMouse.y = HIWORD(lParam);
  836.  
  837.         // --- NEW LOGIC: Handle Pocket Hover ---
  838.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  839.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  840.             int oldHover = currentlyHoveredPocket;
  841.             currentlyHoveredPocket = -1; // Reset
  842.             for (int i = 0; i < 6; ++i) {
  843.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  844.                     currentlyHoveredPocket = i;
  845.                     break;
  846.                 }
  847.             }
  848.             if (oldHover != currentlyHoveredPocket) {
  849.                 InvalidateRect(hwnd, NULL, FALSE);
  850.             }
  851.             // Do NOT return 0 here, allow normal mouse angle update to continue
  852.         }
  853.         // --- END NEW LOGIC ---
  854.  
  855.  
  856.         cueBall = GetCueBall(); // Declare and get cueBall pointer
  857.  
  858.         if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  859.             Ball* ball = GetBallById(draggingBallId);
  860.             if (ball) {
  861.                 ball->x = (float)ptMouse.x;
  862.                 ball->y = (float)ptMouse.y;
  863.                 ball->vx = ball->vy = 0.0f;
  864.             }
  865.             return 0;
  866.         }
  867.  
  868.         if (!cueBall) return 0;
  869.  
  870.         // Update Aiming Logic (Check player turn)
  871.         if (isDraggingCueBall &&
  872.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  873.                 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  874.                 currentGameState == PRE_BREAK_PLACEMENT))
  875.         {
  876.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  877.             // Tentative position update
  878.             cueBall->x = (float)ptMouse.x;
  879.             cueBall->y = (float)ptMouse.y;
  880.             cueBall->vx = cueBall->vy = 0;
  881.         }
  882.         else if ((isAiming || isDraggingStick) &&
  883.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  884.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  885.         {
  886.             //NEW2 MOUSEBOUND CODE = START
  887.                 /*// Clamp mouse inside table bounds during aiming
  888.                 if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
  889.             if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
  890.             if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
  891.             if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
  892.             //NEW2 MOUSEBOUND CODE = END
  893.             // Aiming drag updates angle and power
  894.             float dx = (float)ptMouse.x - cueBall->x;
  895.             float dy = (float)ptMouse.y - cueBall->y;
  896.             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  897.             //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  898.             //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  899.             if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
  900.                 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  901.                 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  902.             }
  903.         }
  904.         else if (isSettingEnglish &&
  905.             ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  906.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  907.         {
  908.             // Setting English
  909.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  910.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  911.             float dist = GetDistance(dx, dy, 0, 0);
  912.             if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  913.             cueSpinX = dx / spinIndicatorRadius;
  914.             cueSpinY = dy / spinIndicatorRadius;
  915.         }
  916.         else {
  917.             //DISABLE PERM AIMING = START
  918.             /*// Update visual angle even when not aiming/dragging (Check player turn)
  919.             bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
  920.                 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
  921.                 currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
  922.  
  923.             if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
  924.             {
  925.                 // NEW MOUSEBOUND CODE = START
  926.                     // Only update cue angle if mouse is inside the playable table area
  927.                 if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
  928.                     ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
  929.                 {
  930.                     // NEW MOUSEBOUND CODE = END
  931.                     Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
  932.                     if (cb) {
  933.                         float dx = (float)ptMouse.x - cb->x;
  934.                         float dy = (float)ptMouse.y - cb->y;
  935.                         if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  936.                     }
  937.                 } //NEW MOUSEBOUND CODE LINE = DISABLE
  938.             }*/
  939.             //DISABLE PERM AIMING = END
  940.         }
  941.         return 0;
  942.     } // End WM_MOUSEMOVE
  943.  
  944.     case WM_LBUTTONDOWN: {
  945.         ptMouse.x = LOWORD(lParam);
  946.         ptMouse.y = HIWORD(lParam);
  947.  
  948.         // --- handle pocket re-selection when choosing 8-ball pocket ---
  949.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1)
  950.             || (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI))
  951.         {
  952.             POINT pt = { LOWORD(lParam), HIWORD(lParam) };
  953.             for (int i = 0; i < 6; ++i) {
  954.                 float dx = pt.x - pocketPositions[i].x;
  955.                 float dy = pt.y - pocketPositions[i].y;
  956.                 if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  957.                     // 1) Record the call
  958.                     if (currentPlayer == 1) calledPocketP1 = i;
  959.                     else                  calledPocketP2 = i;
  960.                     // 2) Clear any prompt text
  961.                     pocketCallMessage.clear();
  962.                     // 3) Return to normal aiming state
  963.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  964.                     // 4) Redraw (arrow stays because calledPocketP* >= 0)
  965.                     InvalidateRect(hwnd, NULL, FALSE);
  966.                     return 0; // consume click
  967.                 }
  968.             }
  969.             return 0; // clicked outside ? stay in pocket?call until a valid pocket is chosen
  970.         }
  971.  
  972.         // … rest of your click?to?aim logic …
  973.  
  974.         //replaced /w new code
  975.         /*
  976.         // --- FIX: Add this entire block at the top of WM_LBUTTONDOWN ---
  977. // This handles input specifically for the pocket selection state.
  978.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  979.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  980.  
  981.             int clickedPocketIndex = -1;
  982.             // Check if the click was on any of the 6 pockets
  983.             for (int i = 0; i < 6; ++i) {
  984.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
  985.                     clickedPocketIndex = i;
  986.                     break;
  987.                 }
  988.             }
  989.  
  990.             if (clickedPocketIndex != -1) {
  991.                 // A pocket was clicked. Update the selection but STAY in the choosing state.
  992.                 // This allows the player to click another pocket to change their mind.
  993.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  994.                 else calledPocketP2 = clickedPocketIndex;
  995.                 InvalidateRect(hwnd, NULL, FALSE); // Redraw to show the arrow has moved.
  996.                 return 0; // Consume the click and wait for the next action.
  997.             }
  998.  
  999.             // If the player clicks the CUE BALL, that confirms their pocket selection.
  1000.             Ball* cueBall = GetCueBall();
  1001.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  1002.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  1003.                 // A pocket has been selected, and the player now clicks the cue ball.
  1004.                 // NOW we transition to the normal aiming state.
  1005.                 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1006.                 pocketCallMessage = L""; // Clear the "Choose a pocket..." message
  1007.                 isAiming = true; // Prepare for aiming
  1008.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y); // Use your existing aim start variable
  1009.                 return 0;
  1010.             }
  1011.  
  1012.             // If they click anywhere else (not a pocket, not the cue ball), do nothing.
  1013.             return 0;
  1014.         }
  1015.         // --- END OF THE NEW BLOCK ---
  1016.         */
  1017.         //new code ends here
  1018.  
  1019.         if (cheatModeEnabled) {
  1020.             // Allow dragging any ball freely
  1021.             for (Ball& ball : balls) {
  1022.                 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  1023.                 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
  1024.                     isDraggingCueBall = true;
  1025.                     draggingBallId = ball.id;
  1026.                     if (ball.id == 0) {
  1027.                         // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
  1028.                         if (currentPlayer == 1)
  1029.                             currentGameState = BALL_IN_HAND_P1;
  1030.                         else if (currentPlayer == 2 && !isPlayer2AI)
  1031.                             currentGameState = BALL_IN_HAND_P2;
  1032.                     }
  1033.                     return 0;
  1034.                 }
  1035.             }
  1036.         }
  1037.  
  1038.         Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer            
  1039.  
  1040.         // Check which player is allowed to interact via mouse click
  1041.         bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  1042.         // Define states where interaction is generally allowed
  1043.         bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  1044.             currentGameState == AIMING || currentGameState == BREAKING ||
  1045.             currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  1046.             currentGameState == PRE_BREAK_PLACEMENT);
  1047.  
  1048.         // Check Spin Indicator first (Allow if player's turn/aim phase)
  1049.         if (canPlayerClickInteract && canInteractState) {
  1050.             float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  1051.             if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  1052.                 isSettingEnglish = true;
  1053.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  1054.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  1055.                 float dist = GetDistance(dx, dy, 0, 0);
  1056.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  1057.                 cueSpinX = dx / spinIndicatorRadius;
  1058.                 cueSpinY = dy / spinIndicatorRadius;
  1059.                 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  1060.                 return 0;
  1061.             }
  1062.         }
  1063.  
  1064.         if (!cueBall) return 0;
  1065.  
  1066.         // Check Ball-in-Hand placement/drag
  1067.         bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1068.         bool isPlayerAllowedToPlace = (isPlacingBall &&
  1069.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1070.                 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1071.                 (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
  1072.  
  1073.         if (isPlayerAllowedToPlace) {
  1074.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1075.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  1076.                 isDraggingCueBall = true;
  1077.                 isAiming = false; isDraggingStick = false;
  1078.             }
  1079.             else {
  1080.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1081.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  1082.                     cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  1083.                     cueBall->vx = 0; cueBall->vy = 0;
  1084.                     isDraggingCueBall = false;
  1085.                     // Transition state
  1086.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1087.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1088.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1089.                     cueAngle = 0.0f;
  1090.                 }
  1091.             }
  1092.             return 0;
  1093.         }
  1094.  
  1095.         // Check for starting Aim (Cue Ball OR Stick)
  1096.         bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  1097.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  1098.  
  1099.         if (canAim) {
  1100.             const float stickDrawLength = 150.0f * 1.4f;
  1101.             float currentStickAngle = cueAngle + PI;
  1102.             D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  1103.             D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  1104.             float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  1105.             float stickClickThresholdSq = 36.0f;
  1106.             float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  1107.             float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  1108.  
  1109.             bool clickedStick = (distToStickSq < stickClickThresholdSq);
  1110.             bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  1111.  
  1112.             if (clickedStick || clickedCueArea) {
  1113.                 isDraggingStick = clickedStick && !clickedCueArea;
  1114.                 isAiming = clickedCueArea;
  1115.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  1116.                 shotPower = 0;
  1117.                 float dx = (float)ptMouse.x - cueBall->x;
  1118.                 float dy = (float)ptMouse.y - cueBall->y;
  1119.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  1120.                 if (currentGameState != BREAKING) currentGameState = AIMING;
  1121.             }
  1122.         }
  1123.         return 0;
  1124.     } // End WM_LBUTTONDOWN
  1125.  
  1126.  
  1127.     case WM_LBUTTONUP: {
  1128.         if (cheatModeEnabled && draggingBallId != -1) {
  1129.             Ball* b = GetBallById(draggingBallId);
  1130.             if (b) {
  1131.                 for (int p = 0; p < 6; ++p) {
  1132.                     float dx = b->x - pocketPositions[p].x;
  1133.                     float dy = b->y - pocketPositions[p].y;
  1134.                     if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1135.                         // --- Assign ball type on first cheat-pocket if table still open ---
  1136.                         if (player1Info.assignedType == BallType::NONE
  1137.                             && player2Info.assignedType == BallType::NONE
  1138.                             && (b->type == BallType::SOLID || b->type == BallType::STRIPE))
  1139.                         {
  1140.                             // In cheat mode, let's just assign to the current player
  1141.                             AssignPlayerBallTypes(b->type);
  1142.                         }
  1143.                         b->isPocketed = true;
  1144.                         pocketedThisTurn.push_back(b->id);
  1145.  
  1146.                         // --- FIX FOR CHEAT MODE SCORING ---
  1147.                         // Immediately increment the correct player's count based on ball type,
  1148.                         // not whose turn it is.
  1149.                         if (b->id != 0 && b->id != 8) {
  1150.                             if (b->type == player1Info.assignedType) {
  1151.                                 player1Info.ballsPocketedCount++;
  1152.                             }
  1153.                             else if (b->type == player2Info.assignedType) {
  1154.                                 player2Info.ballsPocketedCount++;
  1155.                             }
  1156.                         }
  1157.                         // --- END FIX ---
  1158.                         // --- NEW: If this was the 7th ball, trigger the arrow call UI ---
  1159.                         if (b->id != 8) {
  1160.                             PlayerInfo& shooter = (currentPlayer == 1 ? player1Info : player2Info);
  1161.                             if (shooter.ballsPocketedCount >= 7
  1162.                                 && calledPocketP1 < 0
  1163.                                 && calledPocketP2 < 0)
  1164.                             {
  1165.                                 currentGameState = (currentPlayer == 1)
  1166.                                     ? CHOOSING_POCKET_P1
  1167.                                     : CHOOSING_POCKET_P2;
  1168.                             }
  1169.                             else {
  1170.                                 // For any other cheat?pocket, keep the turn so you can continue aiming
  1171.                                 currentGameState = (currentPlayer == 1)
  1172.                                     ? PLAYER1_TURN
  1173.                                     : PLAYER2_TURN;
  1174.                             }
  1175.                         }
  1176.                         // --- NEW: If it was the 8-Ball, award instant victory ---
  1177.                         else {
  1178.                             currentGameState = GAME_OVER;
  1179.                             gameOverMessage = (currentPlayer == 1 ? player1Info.name : player2Info.name)
  1180.                                 + std::wstring(L" Wins!");
  1181.                         }
  1182.                         break;
  1183.                     }
  1184.                 }
  1185.             }
  1186.         }
  1187.  
  1188.         ptMouse.x = LOWORD(lParam);
  1189.         ptMouse.y = HIWORD(lParam);
  1190.  
  1191.         Ball* cueBall = GetCueBall(); // Get cueBall pointer
  1192.  
  1193.         // Check for releasing aim drag (Stick OR Cue Ball)
  1194.         if ((isAiming || isDraggingStick) &&
  1195.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  1196.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  1197.         {
  1198.             bool wasAiming = isAiming;
  1199.             bool wasDraggingStick = isDraggingStick;
  1200.             isAiming = false; isDraggingStick = false;
  1201.  
  1202.             if (shotPower > 0.15f) { // Check power threshold
  1203.                 if (currentGameState != AI_THINKING) {
  1204.                     firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
  1205.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1206.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  1207.                     currentGameState = SHOT_IN_PROGRESS;
  1208.                     foulCommitted = false; pocketedThisTurn.clear();
  1209.                 }
  1210.             }
  1211.             else if (currentGameState != AI_THINKING) { // Revert state if power too low
  1212.                 if (currentGameState == BREAKING) { /* Still breaking */ }
  1213.                 else {
  1214.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  1215.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  1216.                 }
  1217.             }
  1218.             shotPower = 0; // Reset power indicator regardless
  1219.         }
  1220.  
  1221.         // Handle releasing cue ball drag (placement)
  1222.         if (isDraggingCueBall) {
  1223.             isDraggingCueBall = false;
  1224.             // Check player allowed to place
  1225.             bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  1226.             bool isPlayerAllowed = (isPlacingState &&
  1227.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  1228.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  1229.                     (currentGameState == PRE_BREAK_PLACEMENT)));
  1230.  
  1231.             if (isPlayerAllowed && cueBall) {
  1232.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  1233.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  1234.                     // Finalize position already set by mouse move
  1235.                     // Transition state
  1236.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  1237.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  1238.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  1239.                     /* ----------------------------------------------------
  1240.                     If the player who now has the turn is already on the
  1241.                     8-ball, immediately switch to pocket-selection state.
  1242.                     ---------------------------------------------------- */
  1243.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  1244.                     {
  1245.                         CheckAndTransitionToPocketChoice(currentPlayer);
  1246.                     }
  1247.                     cueAngle = 0.0f;
  1248.                 }
  1249.                 else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
  1250.             }
  1251.         }
  1252.  
  1253.         // Handle releasing english setting
  1254.         if (isSettingEnglish) {
  1255.             isSettingEnglish = false;
  1256.         }
  1257.         return 0;
  1258.     } // End WM_LBUTTONUP
  1259.  
  1260.     case WM_DESTROY:
  1261.         isMusicPlaying = false;
  1262.         if (midiDeviceID != 0) {
  1263.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  1264.             midiDeviceID = 0;
  1265.             SaveSettings(); // Save settings on exit
  1266.         }
  1267.         PostQuitMessage(0);
  1268.         return 0;
  1269.  
  1270.     default:
  1271.         return DefWindowProc(hwnd, msg, wParam, lParam);
  1272.     }
  1273.     return 0;
  1274. }
  1275.  
  1276. // --- Direct2D Resource Management ---
  1277.  
  1278. HRESULT CreateDeviceResources() {
  1279.     HRESULT hr = S_OK;
  1280.  
  1281.     // Create Direct2D Factory
  1282.     if (!pFactory) {
  1283.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  1284.         if (FAILED(hr)) return hr;
  1285.     }
  1286.  
  1287.     // Create DirectWrite Factory
  1288.     if (!pDWriteFactory) {
  1289.         hr = DWriteCreateFactory(
  1290.             DWRITE_FACTORY_TYPE_SHARED,
  1291.             __uuidof(IDWriteFactory),
  1292.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  1293.         );
  1294.         if (FAILED(hr)) return hr;
  1295.     }
  1296.  
  1297.     // Create Text Formats
  1298.     if (!pTextFormat && pDWriteFactory) {
  1299.         hr = pDWriteFactory->CreateTextFormat(
  1300.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1301.             16.0f, L"en-us", &pTextFormat
  1302.         );
  1303.         if (FAILED(hr)) return hr;
  1304.         // Center align text
  1305.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  1306.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1307.     }
  1308.     if (!pLargeTextFormat && pDWriteFactory) {
  1309.         hr = pDWriteFactory->CreateTextFormat(
  1310.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  1311.             48.0f, L"en-us", &pLargeTextFormat
  1312.         );
  1313.         if (FAILED(hr)) return hr;
  1314.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  1315.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  1316.     }
  1317.  
  1318.  
  1319.     // Create Render Target (needs valid hwnd)
  1320.     if (!pRenderTarget && hwndMain) {
  1321.         RECT rc;
  1322.         GetClientRect(hwndMain, &rc);
  1323.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  1324.  
  1325.         hr = pFactory->CreateHwndRenderTarget(
  1326.             D2D1::RenderTargetProperties(),
  1327.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  1328.             &pRenderTarget
  1329.         );
  1330.         if (FAILED(hr)) {
  1331.             // If failed, release factories if they were created in this call
  1332.             SafeRelease(&pTextFormat);
  1333.             SafeRelease(&pLargeTextFormat);
  1334.             SafeRelease(&pDWriteFactory);
  1335.             SafeRelease(&pFactory);
  1336.             pRenderTarget = nullptr; // Ensure it's null on failure
  1337.             return hr;
  1338.         }
  1339.     }
  1340.  
  1341.     return hr;
  1342. }
  1343.  
  1344. void DiscardDeviceResources() {
  1345.     SafeRelease(&pRenderTarget);
  1346.     SafeRelease(&pTextFormat);
  1347.     SafeRelease(&pLargeTextFormat);
  1348.     SafeRelease(&pDWriteFactory);
  1349.     // Keep pFactory until application exit? Or release here too? Let's release.
  1350.     SafeRelease(&pFactory);
  1351. }
  1352.  
  1353. void OnResize(UINT width, UINT height) {
  1354.     if (pRenderTarget) {
  1355.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  1356.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  1357.     }
  1358. }
  1359.  
  1360. // --- Game Initialization ---
  1361. void InitGame() {
  1362.     srand((unsigned int)time(NULL)); // Seed random number generator
  1363.     isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  1364.     aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  1365.     aiIsDisplayingAim = false;
  1366.     aiAimDisplayFramesLeft = 0;
  1367.     // ... (rest of InitGame())
  1368.  
  1369.     // --- Ensure pocketed list is clear from the absolute start ---
  1370.     pocketedThisTurn.clear();
  1371.  
  1372.     balls.clear(); // Clear existing balls
  1373.  
  1374.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  1375.     player1Info.assignedType = BallType::NONE;
  1376.     player1Info.ballsPocketedCount = 0;
  1377.     // Player 1 Name usually remains "Player 1"
  1378.     player2Info.assignedType = BallType::NONE;
  1379.     player2Info.ballsPocketedCount = 0;
  1380.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  1381.         // --- Reset any 8?Ball call state on new game ---
  1382.     lastEightBallPocketIndex = -1;
  1383.     calledPocketP1 = -1;
  1384.     calledPocketP2 = -1;
  1385.     pocketCallMessage = L"";
  1386.     aiPlannedShotDetails.isValid = false; // THIS IS THE CRITICAL FIX: Reset the AI's plan.
  1387.  
  1388.     // Create Cue Ball (ID 0)
  1389.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  1390.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
  1391.  
  1392.     // --- Create Object Balls (Temporary List) ---
  1393.     std::vector<Ball> objectBalls;
  1394.     // Solids (1-7, Yellow)
  1395.     for (int i = 1; i <= 7; ++i) {
  1396.         objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  1397.     }
  1398.     // Stripes (9-15, Red)
  1399.     for (int i = 9; i <= 15; ++i) {
  1400.         objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  1401.     }
  1402.     // 8-Ball (ID 8) - Add it to the list to be placed
  1403.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  1404.  
  1405.  
  1406.     // --- Racking Logic (Improved) ---
  1407.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  1408.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  1409.  
  1410.     // Define rack positions (0-14 indices corresponding to triangle spots)
  1411.     D2D1_POINT_2F rackPositions[15];
  1412.     int rackIndex = 0;
  1413.     for (int row = 0; row < 5; ++row) {
  1414.         for (int col = 0; col <= row; ++col) {
  1415.             if (rackIndex >= 15) break;
  1416.             float x = RACK_POS_X + row * spacingX;
  1417.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  1418.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  1419.         }
  1420.     }
  1421.  
  1422.     // Separate 8-ball
  1423.     Ball eightBall;
  1424.     std::vector<Ball> otherBalls; // Solids and Stripes
  1425.     bool eightBallFound = false;
  1426.     for (const auto& ball : objectBalls) {
  1427.         if (ball.id == 8) {
  1428.             eightBall = ball;
  1429.             eightBallFound = true;
  1430.         }
  1431.         else {
  1432.             otherBalls.push_back(ball);
  1433.         }
  1434.     }
  1435.     // Ensure 8 ball was actually created (should always be true)
  1436.     if (!eightBallFound) {
  1437.         // Handle error - perhaps recreate it? For now, proceed.
  1438.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  1439.     }
  1440.  
  1441.  
  1442.     // Shuffle the other 14 balls
  1443.     // Use std::shuffle if available (C++11 and later) for better randomness
  1444.     // std::random_device rd;
  1445.     // std::mt19937 g(rd());
  1446.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  1447.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  1448.  
  1449.     // --- Place balls into the main 'balls' vector in rack order ---
  1450.     // Important: Add the cue ball (already created) first.
  1451.     // (Cue ball added at the start of the function now)
  1452.  
  1453.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  1454.     int eightBallRackIndex = 4;
  1455.     eightBall.x = rackPositions[eightBallRackIndex].x;
  1456.     eightBall.y = rackPositions[eightBallRackIndex].y;
  1457.     eightBall.vx = 0;
  1458.     eightBall.vy = 0;
  1459.     eightBall.isPocketed = false;
  1460.     balls.push_back(eightBall); // Add 8 ball to the main vector
  1461.  
  1462.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  1463.     size_t otherBallIdx = 0;
  1464.     //int otherBallIdx = 0;
  1465.     for (int i = 0; i < 15; ++i) {
  1466.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  1467.  
  1468.         if (otherBallIdx < otherBalls.size()) {
  1469.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  1470.             ballToPlace.x = rackPositions[i].x;
  1471.             ballToPlace.y = rackPositions[i].y;
  1472.             ballToPlace.vx = 0;
  1473.             ballToPlace.vy = 0;
  1474.             ballToPlace.isPocketed = false;
  1475.             balls.push_back(ballToPlace); // Add to the main game vector
  1476.         }
  1477.     }
  1478.     // --- End Racking Logic ---
  1479.  
  1480.  
  1481.     // --- Determine Who Breaks and Initial State ---
  1482.     if (isPlayer2AI) {
  1483.         /*// AI Mode: Randomly decide who breaks
  1484.         if ((rand() % 2) == 0) {
  1485.             // AI (Player 2) breaks
  1486.             currentPlayer = 2;
  1487.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  1488.             aiTurnPending = true; // Trigger AI logic
  1489.         }
  1490.         else {
  1491.             // Player 1 (Human) breaks
  1492.             currentPlayer = 1;
  1493.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  1494.             aiTurnPending = false;*/
  1495.         switch (openingBreakMode) {
  1496.         case CPU_BREAK:
  1497.             currentPlayer = 2; // AI breaks
  1498.             currentGameState = PRE_BREAK_PLACEMENT;
  1499.             aiTurnPending = true;
  1500.             break;
  1501.         case P1_BREAK:
  1502.             currentPlayer = 1; // Player 1 breaks
  1503.             currentGameState = PRE_BREAK_PLACEMENT;
  1504.             aiTurnPending = false;
  1505.             break;
  1506.         case FLIP_COIN_BREAK:
  1507.             if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  1508.                 currentPlayer = 2; // AI breaks
  1509.                 currentGameState = PRE_BREAK_PLACEMENT;
  1510.                 aiTurnPending = true;
  1511.             }
  1512.             else {
  1513.                 currentPlayer = 1; // Player 1 breaks
  1514.                 currentGameState = PRE_BREAK_PLACEMENT;
  1515.                 aiTurnPending = false;
  1516.             }
  1517.             break;
  1518.         default: // Fallback to CPU break
  1519.             currentPlayer = 2;
  1520.             currentGameState = PRE_BREAK_PLACEMENT;
  1521.             aiTurnPending = true;
  1522.             break;
  1523.         }
  1524.     }
  1525.     else {
  1526.         // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  1527.         currentPlayer = 1;
  1528.         currentGameState = PRE_BREAK_PLACEMENT;
  1529.         aiTurnPending = false; // No AI involved
  1530.     }
  1531.  
  1532.     // Reset other relevant game state variables
  1533.     foulCommitted = false;
  1534.     gameOverMessage = L"";
  1535.     firstBallPocketedAfterBreak = false;
  1536.     // pocketedThisTurn cleared at start
  1537.     // Reset shot parameters and input flags
  1538.     shotPower = 0.0f;
  1539.     cueSpinX = 0.0f;
  1540.     cueSpinY = 0.0f;
  1541.     isAiming = false;
  1542.     isDraggingCueBall = false;
  1543.     isSettingEnglish = false;
  1544.     cueAngle = 0.0f; // Reset aim angle
  1545. }
  1546.  
  1547.  
  1548. // --------------------------------------------------------------------------------
  1549. // Full GameUpdate(): integrates AI call?pocket ? aim ? shoot (no omissions)
  1550. // --------------------------------------------------------------------------------
  1551. void GameUpdate() {
  1552.     // --- 1) Handle an in?flight shot ---
  1553.     if (currentGameState == SHOT_IN_PROGRESS) {
  1554.         UpdatePhysics();
  1555.         // ? clear old 8?ball pocket info before any new pocket checks
  1556.         //lastEightBallPocketIndex = -1;
  1557.         CheckCollisions();
  1558.         CheckPockets(); // FIX: This line was missing. It's essential to check for pocketed balls every frame.
  1559.  
  1560.         if (AreBallsMoving()) {
  1561.             isAiming = false;
  1562.             aiIsDisplayingAim = false;
  1563.         }
  1564.  
  1565.         if (!AreBallsMoving()) {
  1566.             ProcessShotResults();
  1567.         }
  1568.         return;
  1569.     }
  1570.  
  1571.     // --- 2) CPU’s turn (table is static) ---
  1572.     if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  1573.         // ??? If we've just auto?entered AI_THINKING for the 8?ball call, actually make the decision ???
  1574.         if (currentGameState == AI_THINKING && aiTurnPending) {
  1575.             aiTurnPending = false;        // consume the pending flag
  1576.             AIMakeDecision();             // CPU calls its pocket or plans its shot
  1577.             return;                       // done this tick
  1578.         }
  1579.  
  1580.         // ??? Automate the AI pocket?selection click ???
  1581.         if (currentGameState == CHOOSING_POCKET_P2) {
  1582.             // AI immediately confirms its call and moves to thinking/shooting
  1583.             currentGameState = AI_THINKING;
  1584.             aiTurnPending = true;
  1585.             return; // process on next tick
  1586.         }
  1587.         // 2A) If AI is displaying its aim line, count down then shoot
  1588.         if (aiIsDisplayingAim) {
  1589.             aiAimDisplayFramesLeft--;
  1590.             if (aiAimDisplayFramesLeft <= 0) {
  1591.                 aiIsDisplayingAim = false;
  1592.                 if (aiPlannedShotDetails.isValid) {
  1593.                     firstHitBallIdThisShot = -1;
  1594.                     cueHitObjectBallThisShot = false;
  1595.                     railHitAfterContact = false;
  1596.                     std::thread([](const TCHAR* soundName) {
  1597.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  1598.                         }, TEXT("cue.wav")).detach();
  1599.  
  1600.                         ApplyShot(
  1601.                             aiPlannedShotDetails.power,
  1602.                             aiPlannedShotDetails.angle,
  1603.                             aiPlannedShotDetails.spinX,
  1604.                             aiPlannedShotDetails.spinY
  1605.                         );
  1606.                         aiPlannedShotDetails.isValid = false;
  1607.                 }
  1608.                 currentGameState = SHOT_IN_PROGRESS;
  1609.                 foulCommitted = false;
  1610.                 pocketedThisTurn.clear();
  1611.             }
  1612.             return;
  1613.         }
  1614.  
  1615.         // 2B) Immediately after calling pocket, transition into AI_THINKING
  1616.         if (currentGameState == CHOOSING_POCKET_P2 && aiTurnPending) {
  1617.             // Start thinking/shooting right away—no human click required
  1618.             currentGameState = AI_THINKING;
  1619.             aiTurnPending = false;
  1620.             AIMakeDecision();
  1621.             return;
  1622.         }
  1623.  
  1624.         // 2C) If AI has pending actions (break, ball?in?hand, or normal turn)
  1625.         if (aiTurnPending) {
  1626.             if (currentGameState == BALL_IN_HAND_P2) {
  1627.                 AIPlaceCueBall();
  1628.                 currentGameState = AI_THINKING;
  1629.                 aiTurnPending = false;
  1630.                 AIMakeDecision();
  1631.             }
  1632.             else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  1633.                 AIBreakShot();
  1634.             }
  1635.             else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  1636.                 currentGameState = AI_THINKING;
  1637.                 aiTurnPending = false;
  1638.                 AIMakeDecision();
  1639.             }
  1640.             return;
  1641.         }
  1642.     }
  1643. }
  1644.  
  1645.  
  1646. // --- Physics and Collision ---
  1647. void UpdatePhysics() {
  1648.     for (size_t i = 0; i < balls.size(); ++i) {
  1649.         Ball& b = balls[i];
  1650.         if (!b.isPocketed) {
  1651.             b.x += b.vx;
  1652.             b.y += b.vy;
  1653.  
  1654.             // Apply friction
  1655.             b.vx *= FRICTION;
  1656.             b.vy *= FRICTION;
  1657.  
  1658.             // Stop balls if velocity is very low
  1659.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  1660.                 b.vx = 0;
  1661.                 b.vy = 0;
  1662.             }
  1663.  
  1664.             /* -----------------------------------------------------------------
  1665.    Additional clamp to guarantee the ball never escapes the table.
  1666.    The existing wall–collision code can momentarily disable the
  1667.    reflection test while the ball is close to a pocket mouth;
  1668.    that rare case allowed it to ‘slide’ through the cushion and
  1669.    leave the board.  We therefore enforce a final boundary check
  1670.    after the normal physics step.
  1671.    ----------------------------------------------------------------- */
  1672.             const float leftBound = TABLE_LEFT + BALL_RADIUS;
  1673.             const float rightBound = TABLE_RIGHT - BALL_RADIUS;
  1674.             const float topBound = TABLE_TOP + BALL_RADIUS;
  1675.             const float bottomBound = TABLE_BOTTOM - BALL_RADIUS;
  1676.  
  1677.             if (b.x < leftBound) { b.x = leftBound;   b.vx = fabsf(b.vx); }
  1678.             if (b.x > rightBound) { b.x = rightBound;  b.vx = -fabsf(b.vx); }
  1679.             if (b.y < topBound) { b.y = topBound;    b.vy = fabsf(b.vy); }
  1680.             if (b.y > bottomBound) { b.y = bottomBound; b.vy = -fabsf(b.vy); }
  1681.         }
  1682.     }
  1683. }
  1684.  
  1685. void CheckCollisions() {
  1686.     float left = TABLE_LEFT;
  1687.     float right = TABLE_RIGHT;
  1688.     float top = TABLE_TOP;
  1689.     float bottom = TABLE_BOTTOM;
  1690.     const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
  1691.  
  1692.     // --- Reset Per-Frame Sound Flags ---
  1693.     bool playedWallSoundThisFrame = false;
  1694.     bool playedCollideSoundThisFrame = false;
  1695.     // ---
  1696.  
  1697.     for (size_t i = 0; i < balls.size(); ++i) {
  1698.         Ball& b1 = balls[i];
  1699.         if (b1.isPocketed) continue;
  1700.  
  1701.         bool nearPocket[6];
  1702.         for (int p = 0; p < 6; ++p) {
  1703.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
  1704.         }
  1705.         bool nearTopLeftPocket = nearPocket[0];
  1706.         bool nearTopMidPocket = nearPocket[1];
  1707.         bool nearTopRightPocket = nearPocket[2];
  1708.         bool nearBottomLeftPocket = nearPocket[3];
  1709.         bool nearBottomMidPocket = nearPocket[4];
  1710.         bool nearBottomRightPocket = nearPocket[5];
  1711.  
  1712.         bool collidedWallThisBall = false;
  1713.  
  1714.         // --- Ball-Wall Collisions ---
  1715.         // (Check logic unchanged, added sound calls and railHitAfterContact update)
  1716.         // Left Wall
  1717.         if (b1.x - BALL_RADIUS < left) {
  1718.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  1719.                 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1720.                 if (!playedWallSoundThisFrame) {
  1721.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1722.                     playedWallSoundThisFrame = true;
  1723.                 }
  1724.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1725.             }
  1726.         }
  1727.         // Right Wall
  1728.         if (b1.x + BALL_RADIUS > right) {
  1729.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  1730.                 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  1731.                 if (!playedWallSoundThisFrame) {
  1732.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1733.                     playedWallSoundThisFrame = true;
  1734.                 }
  1735.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1736.             }
  1737.         }
  1738.         // Top Wall
  1739.         if (b1.y - BALL_RADIUS < top) {
  1740.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  1741.                 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1742.                 if (!playedWallSoundThisFrame) {
  1743.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1744.                     playedWallSoundThisFrame = true;
  1745.                 }
  1746.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1747.             }
  1748.         }
  1749.         // Bottom Wall
  1750.         if (b1.y + BALL_RADIUS > bottom) {
  1751.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  1752.                 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  1753.                 if (!playedWallSoundThisFrame) {
  1754.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  1755.                     playedWallSoundThisFrame = true;
  1756.                 }
  1757.                 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
  1758.             }
  1759.         }
  1760.  
  1761.         // Spin effect (Unchanged)
  1762.         if (collidedWallThisBall) {
  1763.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  1764.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  1765.             cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  1766.         }
  1767.  
  1768.  
  1769.         // --- Ball-Ball Collisions ---
  1770.         for (size_t j = i + 1; j < balls.size(); ++j) {
  1771.             Ball& b2 = balls[j];
  1772.             if (b2.isPocketed) continue;
  1773.  
  1774.             float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  1775.             float distSq = dx * dx + dy * dy;
  1776.             float minDist = BALL_RADIUS * 2.0f;
  1777.  
  1778.             if (distSq > 1e-6 && distSq < minDist * minDist) {
  1779.                 float dist = sqrtf(distSq);
  1780.                 float overlap = minDist - dist;
  1781.                 float nx = dx / dist; float ny = dy / dist;
  1782.  
  1783.                 // Separation (Unchanged)
  1784.                 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  1785.                 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  1786.  
  1787.                 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  1788.                 float velAlongNormal = rvx * nx + rvy * ny;
  1789.  
  1790.                 if (velAlongNormal > 0) { // Colliding
  1791.                     // --- Play Ball Collision Sound ---
  1792.                     if (!playedCollideSoundThisFrame) {
  1793.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  1794.                         playedCollideSoundThisFrame = true; // Set flag
  1795.                     }
  1796.                     // --- End Sound ---
  1797.  
  1798.                     // --- NEW: Track First Hit and Cue/Object Collision ---
  1799.                     if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
  1800.                         if (b1.id == 0) { // Cue ball hit b2 first
  1801.                             firstHitBallIdThisShot = b2.id;
  1802.                             cueHitObjectBallThisShot = true;
  1803.                         }
  1804.                         else if (b2.id == 0) { // Cue ball hit b1 first
  1805.                             firstHitBallIdThisShot = b1.id;
  1806.                             cueHitObjectBallThisShot = true;
  1807.                         }
  1808.                         // If neither is cue ball, doesn't count as first hit for foul purposes
  1809.                     }
  1810.                     else if (b1.id == 0 || b2.id == 0) {
  1811.                         // Track subsequent cue ball collisions with object balls
  1812.                         cueHitObjectBallThisShot = true;
  1813.                     }
  1814.                     // --- End First Hit Tracking ---
  1815.  
  1816.  
  1817.                     // Impulse (Unchanged)
  1818.                     float impulse = velAlongNormal;
  1819.                     b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  1820.                     b2.vx += impulse * nx; b2.vy += impulse * ny;
  1821.  
  1822.                     // Spin Transfer (Unchanged)
  1823.                     if (b1.id == 0 || b2.id == 0) {
  1824.                         float spinEffectFactor = 0.08f;
  1825.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1826.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1827.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  1828.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  1829.                         cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  1830.                     }
  1831.                 }
  1832.             }
  1833.         } // End ball-ball loop
  1834.     } // End ball loop
  1835. } // End CheckCollisions
  1836.  
  1837.  
  1838. bool CheckPockets() {
  1839.     bool anyPocketed = false;
  1840.     // For each ball not already pocketed:
  1841.     for (auto& b : balls) {
  1842.         if (b.isPocketed)
  1843.             continue;
  1844.  
  1845.         // Check against each pocket
  1846.         for (int p = 0; p < 6; ++p) {
  1847.             float dx = b.x - pocketPositions[p].x;
  1848.             float dy = b.y - pocketPositions[p].y;
  1849.             if (dx * dx + dy * dy <= POCKET_RADIUS * POCKET_RADIUS) {
  1850.                 // It's in the pocket—remove it from play
  1851.                 // If it's the 8?ball, remember which pocket it went into
  1852.                 if (b.id == 8) {
  1853.                     lastEightBallPocketIndex = p;   // <-- Must set here!
  1854.                 }
  1855.                 b.isPocketed = true;
  1856.                 b.vx = b.vy = 0.0f;           // kill any movement
  1857.                 pocketedThisTurn.push_back(b.id);                
  1858.                 anyPocketed = true;
  1859.                 break;  // no need to check other pockets for this ball
  1860.             }
  1861.         }
  1862.     }
  1863.     return anyPocketed;
  1864. }
  1865.  
  1866. bool AreBallsMoving() {
  1867.     for (size_t i = 0; i < balls.size(); ++i) {
  1868.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  1869.             return true;
  1870.         }
  1871.     }
  1872.     return false;
  1873. }
  1874.  
  1875. void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
  1876.     Ball* cueBall = GetCueBall();
  1877.     if (cueBall) {
  1878.         // Reset position to a default
  1879.         //disabled for behind headstring (now move anywhere)
  1880.         /*cueBall->x = HEADSTRING_X * 0.5f;
  1881.         cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;*/
  1882.         // Reset position to a default:
  1883.         if (behindHeadstring) {
  1884.             // Opening break: kitchen center
  1885.             cueBall->x = HEADSTRING_X * 0.5f;
  1886.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1887.         }
  1888.         else {
  1889.             // Ball-in-hand (foul): center of full table
  1890.             cueBall->x = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  1891.             cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  1892.         }
  1893.         cueBall->vx = 0;
  1894.         cueBall->vy = 0;
  1895.         cueBall->isPocketed = false;
  1896.  
  1897.         // Set state based on who gets ball-in-hand
  1898.         /*// 'currentPlayer' already reflects who's turn it is NOW (switched before calling this)*/
  1899.         // 'currentPlayer' has already been switched to the player whose turn it will be.
  1900.         // The 'behindHeadstring' parameter to RespawnCueBall is mostly for historical reasons / initial setup.
  1901.         if (currentPlayer == 1) { // Player 2 (AI/Human) fouled, Player 1 (Human) gets ball-in-hand
  1902.             currentGameState = BALL_IN_HAND_P1;
  1903.             aiTurnPending = false; // Ensure AI flag off
  1904.         }
  1905.         else { // Player 1 (Human) fouled, Player 2 gets ball-in-hand
  1906.             if (isPlayer2AI) {
  1907.                 // --- CONFIRMED FIX: Set correct state for AI Ball-in-Hand ---
  1908.                 currentGameState = BALL_IN_HAND_P2; // AI now needs to place the ball
  1909.                 aiTurnPending = true; // Trigger AI logic (will call AIPlaceCueBall first)
  1910.             }
  1911.             else { // Human Player 2
  1912.                 currentGameState = BALL_IN_HAND_P2;
  1913.                 aiTurnPending = false; // Ensure AI flag off
  1914.             }
  1915.         }
  1916.         // Handle initial placement state correctly if called from InitGame
  1917.         /*if (behindHeadstring && currentGameState != PRE_BREAK_PLACEMENT) {
  1918.             // This case might need review depending on exact initial setup flow,
  1919.             // but the foul logic above should now be correct.
  1920.             // Let's ensure initial state is PRE_BREAK_PLACEMENT if behindHeadstring is true.*/
  1921.             //currentGameState = PRE_BREAK_PLACEMENT;
  1922.     }
  1923. }
  1924. //}
  1925.  
  1926.  
  1927. // --- Game Logic ---
  1928.  
  1929. void ApplyShot(float power, float angle, float spinX, float spinY) {
  1930.     Ball* cueBall = GetCueBall();
  1931.     if (cueBall) {
  1932.  
  1933.         // --- Play Cue Strike Sound (Threaded) ---
  1934.         if (power > 0.1f) { // Only play if it's an audible shot
  1935.             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  1936.         }
  1937.         // --- End Sound ---
  1938.  
  1939.         cueBall->vx = cosf(angle) * power;
  1940.         cueBall->vy = sinf(angle) * power;
  1941.  
  1942.         // Apply English (Spin) - Simplified effect (Unchanged)
  1943.         cueBall->vx += sinf(angle) * spinY * 0.5f;
  1944.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  1945.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  1946.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  1947.  
  1948.         // Store spin (Unchanged)
  1949.         cueSpinX = spinX;
  1950.         cueSpinY = spinY;
  1951.  
  1952.         // --- Reset Foul Tracking flags for the new shot ---
  1953.         // (Also reset in LBUTTONUP, but good to ensure here too)
  1954.         firstHitBallIdThisShot = -1;      // No ball hit yet
  1955.         cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  1956.         railHitAfterContact = false;     // No rail hit after contact yet
  1957.         // --- End Reset ---
  1958.  
  1959.                 // If this was the opening break shot, clear the flag
  1960.         if (isOpeningBreakShot) {
  1961.             isOpeningBreakShot = false; // Mark opening break as taken
  1962.         }
  1963.     }
  1964. }
  1965.  
  1966.  
  1967. // ---------------------------------------------------------------------
  1968. //  ProcessShotResults()
  1969. // ---------------------------------------------------------------------
  1970. void ProcessShotResults()
  1971. {
  1972.     // ---------------------------------------------------------------
  1973.     //  0.  Gather shot information
  1974.     // ---------------------------------------------------------------
  1975.     bool cueBallPocketed = false;
  1976.     bool eightBallPocketed = false;
  1977.     int  ownBallsPocketedThisTurn = 0;
  1978.     bool didAssignThisTurn = false;
  1979.  
  1980.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  1981.     bool isBreakShot = isOpeningBreakShot;
  1982.  
  1983.     for (int id : pocketedThisTurn)
  1984.     {
  1985.         if (id == 0)            cueBallPocketed = true;
  1986.         else if (id == 8)       eightBallPocketed = true;
  1987.         else                    // ordinary object ball
  1988.         {
  1989.             Ball* b = GetBallById(id);
  1990.             if (b && b->type == shootingPlayer.assignedType)
  1991.                 ++ownBallsPocketedThisTurn;
  1992.         }
  1993.     }
  1994.  
  1995.     // update counters for already-assigned balls
  1996.     for (int id : pocketedThisTurn)
  1997.     {
  1998.         if (id == 0 || id == 8) continue;
  1999.  
  2000.         Ball* bb = GetBallById(id);
  2001.         if (!bb) continue;
  2002.  
  2003.         if (bb->type == player1Info.assignedType) ++player1Info.ballsPocketedCount;
  2004.         if (bb->type == player2Info.assignedType) ++player2Info.ballsPocketedCount;
  2005.     }
  2006.  
  2007.     // ---------------------------------------------------------------
  2008.     //  1.  Determine foul
  2009.     // ---------------------------------------------------------------
  2010.     bool anyObjectPocketed = !pocketedThisTurn.empty() && !cueBallPocketed;
  2011.     bool turnFoul = false;
  2012.  
  2013.     if (!anyObjectPocketed)
  2014.     {
  2015.         if (cueBallPocketed)                          turnFoul = true;
  2016.         else
  2017.         {
  2018.             Ball* fh = GetBallById(firstHitBallIdThisShot);
  2019.             if (!fh)                                  turnFoul = true;
  2020.             else
  2021.             {
  2022.                 bool tableOpen = player1Info.assignedType == BallType::NONE &&
  2023.                     player2Info.assignedType == BallType::NONE;
  2024.                 bool mustHit8 = !tableOpen && (shootingPlayer.ballsPocketedCount >= 7);
  2025.  
  2026.                 if (!tableOpen)
  2027.                 {
  2028.                     if (mustHit8 && fh->id != 8)                      turnFoul = true;
  2029.                     else if (!mustHit8 && fh->type != shootingPlayer.assignedType)
  2030.                         turnFoul = true;
  2031.                 }
  2032.             }
  2033.         }
  2034.     }
  2035.  
  2036.     foulCommitted = turnFoul;
  2037.     if (isBreakShot)              // break fouls handled further below
  2038.         foulCommitted = false;
  2039.  
  2040.     // ---------------------------------------------------------------
  2041.     //  2. “Free turn” after a LEGAL BREAK
  2042.     // ---------------------------------------------------------------
  2043.     if (isBreakShot)
  2044.     {
  2045.         isOpeningBreakShot = false;   // break has now happened
  2046.  
  2047.         bool legalBreak = anyObjectPocketed && !cueBallPocketed && !foulCommitted;
  2048.  
  2049.         if (legalBreak)
  2050.         {
  2051.             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2052.             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  2053.             pocketedThisTurn.clear();
  2054.             return;
  2055.         }
  2056.     }
  2057.  
  2058.     // ---------------------------------------------------------------
  2059.     //  3.  Handle foul (ball-in-hand for opponent)
  2060.     // ---------------------------------------------------------------
  2061.     if (foulCommitted)
  2062.     {
  2063.         SwitchTurns();
  2064.         RespawnCueBall(false);
  2065.         pocketedThisTurn.clear();
  2066.         return;
  2067.     }
  2068.  
  2069.     // ---------------------------------------------------------------
  2070.     //  4.  Assign colours if table was open
  2071.     // ---------------------------------------------------------------
  2072.     if (player1Info.assignedType == BallType::NONE &&
  2073.         !pocketedThisTurn.empty() &&
  2074.         !cueBallPocketed)
  2075.     {
  2076.         for (int id : pocketedThisTurn)
  2077.         {
  2078.             Ball* b = GetBallById(id);
  2079.             if (!b || b->type == BallType::EIGHT_BALL) continue;
  2080.  
  2081.             AssignPlayerBallTypes(b->type);
  2082.             didAssignThisTurn = true;
  2083.  
  2084.             if (currentPlayer == 1) player1Info.ballsPocketedCount = 1;
  2085.             else                    player2Info.ballsPocketedCount = 1;
  2086.             break;      // colours decided – stop looking
  2087.         }
  2088.     }
  2089.  
  2090.     // ---------------------------------------------------------------
  2091.     //  5.  FREE TURN immediately after colour assignment
  2092.     // ---------------------------------------------------------------
  2093.     if (didAssignThisTurn)
  2094.     {
  2095.         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2096.         if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  2097.         pocketedThisTurn.clear();
  2098.         return;
  2099.     }
  2100.  
  2101.     // ---------------------------------------------------------------
  2102.     //  6.  Handle ordinary continuation logic
  2103.     // ---------------------------------------------------------------
  2104.     if (ownBallsPocketedThisTurn > 0)
  2105.     {
  2106.         // check 7-ball clearance ? choose pocket for 8-ball
  2107.         PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2108.         if (!eightBallPocketed && shooter.ballsPocketedCount >= 7)
  2109.         {
  2110.             if (currentPlayer == 1) calledPocketP1 = -1;
  2111.             else                    calledPocketP2 = -1;
  2112.  
  2113.             currentGameState = (currentPlayer == 1)
  2114.                 ? CHOOSING_POCKET_P1
  2115.                 : CHOOSING_POCKET_P2;
  2116.             return;
  2117.         }
  2118.  
  2119.         // shooter keeps the table
  2120.         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2121.         if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  2122.     }
  2123.     else
  2124.     {
  2125.         SwitchTurns();   // nothing went in – pass the table
  2126.     }
  2127.  
  2128.     // ---------------------------------------------------------------
  2129.     //  7.  8-ball pocketed  (use your existing helper)
  2130.     // ---------------------------------------------------------------
  2131.     if (eightBallPocketed)
  2132.     {
  2133.         CheckGameOverConditions(true, cueBallPocketed);
  2134.         pocketedThisTurn.clear();
  2135.         return;
  2136.     }
  2137.  
  2138.     // ---------------------------------------------------------------
  2139.     //  8.  housekeeping
  2140.     // ---------------------------------------------------------------
  2141.     pocketedThisTurn.clear();
  2142.     if (currentGameState == PLAYER1_TURN)      calledPocketP2 = -1;
  2143.     if (currentGameState == PLAYER2_TURN)      calledPocketP1 = -1;
  2144. }
  2145.  
  2146.     /*
  2147.     // --- Step 3: Final State Transition ---
  2148.     if (foulCommitted) {
  2149.         SwitchTurns();
  2150.         RespawnCueBall(false);
  2151.     }
  2152.     else if (playerContinuesTurn) {
  2153.         CheckAndTransitionToPocketChoice(currentPlayer);
  2154.     }
  2155.     else {
  2156.         SwitchTurns();
  2157.     }
  2158.  
  2159.     pocketedThisTurn.clear();
  2160. } */
  2161.  
  2162. bool AssignPlayerBallTypes(BallType firstPocketedType) {
  2163.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  2164.         if (currentPlayer == 1) {
  2165.             player1Info.assignedType = firstPocketedType;
  2166.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2167.         }
  2168.         else {
  2169.             player2Info.assignedType = firstPocketedType;
  2170.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  2171.         }
  2172.         return true; // Assignment was successful
  2173.     }
  2174.     return false; // No assignment made (e.g., 8-ball was pocketed on break)
  2175. }
  2176.     // If 8-ball was first (illegal on break generally), rules vary.
  2177.     // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  2178.     // Or assign based on what *else* was pocketed, if anything.
  2179.     // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  2180.  
  2181. // ????????????????????????????????????????????????????????????????
  2182. //  CheckGameOverConditions()
  2183. //     – Called when the 8-ball has fallen.
  2184. //     – Decides who wins and builds the gameOverMessage.
  2185. // ????????????????????????????????????????????????????????????????
  2186. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  2187. {
  2188.     if (!eightBallPocketed) return;                     // safety
  2189.  
  2190.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2191.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2192.  
  2193.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2194.     int actualPocket = lastEightBallPocketIndex;
  2195.  
  2196.     bool clearedSeven = (shooter.ballsPocketedCount >= 7);
  2197.     bool noScratch = !cueBallPocketed;
  2198.     bool callMade = (calledPocket >= 0);
  2199.  
  2200.     // helper ? turn “-1” into "None" for readability
  2201.     auto pocketToStr = [](int idx) -> std::wstring
  2202.     {
  2203.         return (idx >= 0) ? std::to_wstring(idx) : L"None";
  2204.     };
  2205.  
  2206.     if (clearedSeven && noScratch && callMade && actualPocket == calledPocket)
  2207.     {
  2208.         // legitimate win
  2209.         gameOverMessage =
  2210.             shooter.name +
  2211.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  2212.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  2213.     }
  2214.     else
  2215.     {
  2216.         // wrong pocket, scratch, or early 8-ball
  2217.         gameOverMessage =
  2218.             opponent.name +
  2219.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  2220.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  2221.     }
  2222.  
  2223.     currentGameState = GAME_OVER;
  2224. }
  2225.  
  2226. /* void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  2227.     if (!eightBallPocketed) return; // Only when 8-ball actually pocketed
  2228.  
  2229.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  2230.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  2231.     bool      onEightRoll = IsPlayerOnEightBall(currentPlayer);
  2232.     int       calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2233.     int       actualPocket = -1;
  2234.     Ball* bEight = GetBallById(8);
  2235.  
  2236.     // locate which hole the 8-ball went into
  2237.     if (bEight) {
  2238.         for (int i = 0; i < 6; ++i) {
  2239.             if (GetDistanceSq(bEight->x, bEight->y,
  2240.                 pocketPositions[i].x, pocketPositions[i].y)
  2241.                 < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  2242.                 actualPocket = i; break;
  2243.             }
  2244.         }
  2245.     }
  2246.  
  2247.     // 1) On break / pre-assignment: re-spot & continue
  2248.     if (player1Info.assignedType == BallType::NONE) {
  2249.         if (bEight) {
  2250.             bEight->isPocketed = false;
  2251.             bEight->x = RACK_POS_X; bEight->y = RACK_POS_Y;
  2252.             bEight->vx = bEight->vy = 0;
  2253.         }
  2254.         if (cueBallPocketed) foulCommitted = true;
  2255.         return;
  2256.     }
  2257.  
  2258.     // 2) Loss if pocketed 8 early
  2259.     if (!onEightRoll) {
  2260.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" pocketed 8-ball early)";
  2261.     }
  2262.     // 3) Loss if scratched
  2263.     else if (cueBallPocketed) {
  2264.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" scratched on 8-ball)";
  2265.     }
  2266.     // 4) Loss if no pocket call
  2267.     else if (calledPocket < 0) {
  2268.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" did not call a pocket)";
  2269.     }
  2270.     // 5) Loss if in wrong pocket
  2271.     else if (actualPocket != calledPocket) {
  2272.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" 8-ball in wrong pocket)";
  2273.     }
  2274.     // 6) Otherwise, valid win
  2275.     else {
  2276.         gameOverMessage = shooter.name + L" Wins!";
  2277.     }
  2278.  
  2279.     currentGameState = GAME_OVER;
  2280. } */
  2281.  
  2282.  
  2283.  
  2284. void SwitchTurns() {
  2285.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  2286.     isAiming = false;
  2287.     shotPower = 0;
  2288.  
  2289.     /* ---------------------------------------------------------------
  2290.        If the PREVIOUS turn ended with a foul we must first give the
  2291.        incoming player BALL-IN-HAND and clear any pocket calls; if
  2292.        we immediately ask for a pocket-choice the state machine can
  2293.        get stuck (arrow shown while cue-ball not yet placed).
  2294.        --------------------------------------------------------------- */
  2295.     if (foulCommitted)
  2296.     {
  2297.         /*  clear any outstanding 8-ball “called pocket” information   */
  2298.         calledPocketP1 = -1;
  2299.         calledPocketP2 = -1;
  2300.         pocketCallMessage.clear();
  2301.  
  2302.         /*  give the new player ball-in-hand                           */
  2303.         if (currentPlayer == 1)
  2304.         {
  2305.             currentGameState = BALL_IN_HAND_P1;
  2306.             aiTurnPending = false;
  2307.         }
  2308.         else
  2309.         {
  2310.             currentGameState = BALL_IN_HAND_P2;
  2311.             aiTurnPending = isPlayer2AI;     // AI will auto-place
  2312.         }
  2313.  
  2314.         /*  this foul has been handled – reset the flag                */
  2315.         foulCommitted = false;
  2316.         return;              // skip pocket–choice for now
  2317.     }
  2318.  
  2319.     /*  normal (non-foul) turn switch                                 */
  2320.     CheckAndTransitionToPocketChoice(currentPlayer);
  2321. }
  2322.  
  2323. void AIBreakShot() {
  2324.     Ball* cueBall = GetCueBall();
  2325.     if (!cueBall) return;
  2326.  
  2327.     // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  2328.     // AI will place the cue ball and then plan the shot.
  2329.     if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2330.         // Place cue ball in the kitchen randomly
  2331.         /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  2332.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  2333.         float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  2334.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  2335.  
  2336.         // --- AI Places Cue Ball for Break ---
  2337. // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  2338. // towards one side for a more angled break, or center for direct apex hit.
  2339. // A common strategy is to hit the second ball of the rack.
  2340.  
  2341.         float placementY = RACK_POS_Y; // Align vertically with the rack center
  2342.         float placementX;
  2343.  
  2344.         // Randomly choose a side or center-ish placement for variation.
  2345.         int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  2346.  
  2347.         if (placementChoice == 0) { // Left-ish
  2348.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  2349.         }
  2350.         else if (placementChoice == 2) { // Right-ish
  2351.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  2352.         }
  2353.         else { // Center-ish
  2354.             placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  2355.         }
  2356.         placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  2357.  
  2358.         bool validPos = false;
  2359.         int attempts = 0;
  2360.         while (!validPos && attempts < 100) {
  2361.             /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  2362.             cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  2363.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  2364.                 validPos = true; // [cite: 1591]*/
  2365.                 // Try the chosen X, but vary Y slightly to find a clear spot
  2366.             cueBall->x = placementX;
  2367.             cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  2368.             cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  2369.  
  2370.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  2371.                 validPos = true;
  2372.             }
  2373.             attempts++; // [cite: 1592]
  2374.         }
  2375.         if (!validPos) {
  2376.             // Fallback position
  2377.             /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  2378.             cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  2379.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  2380.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  2381.                 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  2382.             }
  2383.         }
  2384.         cueBall->vx = 0; // [cite: 1595]
  2385.         cueBall->vy = 0; // [cite: 1596]
  2386.  
  2387.         // Plan a break shot: aim at the center of the rack (apex ball)
  2388.         float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  2389.         float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  2390.  
  2391.         float dx = targetX - cueBall->x; // [cite: 1599]
  2392.         float dy = targetY - cueBall->y; // [cite: 1600]
  2393.         float shotAngle = atan2f(dy, dx); // [cite: 1600]
  2394.         float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  2395.  
  2396.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  2397.             cueBall->y = RACK_POS_Y;
  2398.         }
  2399.         cueBall->vx = 0; cueBall->vy = 0;
  2400.  
  2401.         // --- AI Plans the Break Shot ---
  2402.         float targetX, targetY;
  2403.         // If cue ball is near center of kitchen width, aim for apex.
  2404.         // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  2405.         float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  2406.         if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  2407.             // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  2408.             targetX = RACK_POS_X; // Apex ball X
  2409.             targetY = RACK_POS_Y; // Apex ball Y
  2410.         }
  2411.         else {
  2412.             // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  2413.             // This is a simplification. A more robust way is to find the actual second ball.
  2414.             // For now, aim slightly off the apex towards the side the cue ball is on.
  2415.             targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  2416.             targetY = RACK_POS_Y + ((cueBall->y > RACK_POS_Y) ? -BALL_RADIUS : BALL_RADIUS); // Aim at the upper or lower of the two second-row balls
  2417.         }
  2418.  
  2419.         float dx = targetX - cueBall->x;
  2420.         float dy = targetY - cueBall->y;
  2421.         float shotAngle = atan2f(dy, dx);
  2422.         float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  2423.  
  2424.         // Store planned shot details for the AI
  2425.         /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  2426.         aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  2427.         aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  2428.         aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  2429.         aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  2430.  
  2431.         aiPlannedShotDetails.angle = shotAngle;
  2432.         aiPlannedShotDetails.power = shotPowerValue;
  2433.         aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  2434.         aiPlannedShotDetails.spinY = 0.0f;
  2435.         aiPlannedShotDetails.isValid = true;
  2436.  
  2437.         // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  2438.         /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  2439.         ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  2440.         ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  2441.         ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  2442.  
  2443.         ::cueAngle = aiPlannedShotDetails.angle;
  2444.         ::shotPower = aiPlannedShotDetails.power;
  2445.         ::cueSpinX = aiPlannedShotDetails.spinX;
  2446.         ::cueSpinY = aiPlannedShotDetails.spinY;
  2447.  
  2448.         // Set up for AI display via GameUpdate
  2449.         /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  2450.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  2451.  
  2452.         currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  2453.                                         // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  2454.                                         // and then execute the shot using aiPlannedShotDetails.
  2455.                                         // isOpeningBreakShot will be set to false within ApplyShot.
  2456.  
  2457.         // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  2458.  
  2459.         aiIsDisplayingAim = true;
  2460.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2461.         currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  2462.         aiTurnPending = false;
  2463.  
  2464.         return; // The break shot is now planned and will be executed by GameUpdate
  2465.     }
  2466.  
  2467.     // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  2468.     //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  2469.     //    This part can be extended if AIBreakShot needs to handle other scenarios.
  2470.     //    For now, the primary logic is above.
  2471. }
  2472.  
  2473. // --- Helper Functions ---
  2474.  
  2475. Ball* GetBallById(int id) {
  2476.     for (size_t i = 0; i < balls.size(); ++i) {
  2477.         if (balls[i].id == id) {
  2478.             return &balls[i];
  2479.         }
  2480.     }
  2481.     return nullptr;
  2482. }
  2483.  
  2484. Ball* GetCueBall() {
  2485.     return GetBallById(0);
  2486. }
  2487.  
  2488. float GetDistance(float x1, float y1, float x2, float y2) {
  2489.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  2490. }
  2491.  
  2492. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  2493.     float dx = x2 - x1;
  2494.     float dy = y2 - y1;
  2495.     return dx * dx + dy * dy;
  2496. }
  2497.  
  2498. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  2499.     // Basic bounds check (inside cushions)
  2500.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  2501.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  2502.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  2503.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  2504.  
  2505.     if (x < left || x > right || y < top || y > bottom) {
  2506.         return false;
  2507.     }
  2508.  
  2509.     // Check headstring restriction if needed
  2510.     if (checkHeadstring && x >= HEADSTRING_X) {
  2511.         return false;
  2512.     }
  2513.  
  2514.     // Check overlap with other balls
  2515.     for (size_t i = 0; i < balls.size(); ++i) {
  2516.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  2517.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  2518.                 return false; // Overlapping another ball
  2519.             }
  2520.         }
  2521.     }
  2522.  
  2523.     return true;
  2524. }
  2525.  
  2526. // --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
  2527.  
  2528. // Checks if a player has pocketed all their balls and is now on the 8-ball.
  2529. bool IsPlayerOnEightBall(int player) {
  2530.     PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
  2531.     if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
  2532.         Ball* eightBall = GetBallById(8);
  2533.         return (eightBall && !eightBall->isPocketed);
  2534.     }
  2535.     return false;
  2536. }
  2537.  
  2538. // Centralized logic to enter the "choosing pocket" state. This fixes the indicator bugs.
  2539. void CheckAndTransitionToPocketChoice(int playerID) {
  2540.     bool needsToCall = IsPlayerOnEightBall(playerID);
  2541.  
  2542.     if (needsToCall) {
  2543.         if (playerID == 1) { // Human Player 1
  2544.             currentGameState = CHOOSING_POCKET_P1;
  2545.             pocketCallMessage = player1Info.name + L": Choose a pocket for the 8-Ball...";
  2546.             if (calledPocketP1 == -1) calledPocketP1 = 5; // Default to bottom-right
  2547.         }
  2548.         else { // Player 2
  2549.             if (isPlayer2AI) {
  2550.                 // FOOLPROOF FIX: AI doesn't choose here. It transitions to a thinking state.
  2551.                 // AIMakeDecision will handle the choice and the pocket call.
  2552.                 currentGameState = AI_THINKING;
  2553.                 aiTurnPending = true; // Signal the main loop to run AIMakeDecision
  2554.             }
  2555.             else { // Human Player 2
  2556.                 currentGameState = CHOOSING_POCKET_P2;
  2557.                 pocketCallMessage = player2Info.name + L": Choose a pocket for the 8-Ball...";
  2558.                 if (calledPocketP2 == -1) calledPocketP2 = 5; // Default to bottom-right
  2559.             }
  2560.         }
  2561.     }
  2562.     else {
  2563.         // Player does not need to call a pocket, proceed to normal turn.
  2564.         pocketCallMessage = L"";
  2565.         currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2566.         if (playerID == 2 && isPlayer2AI) {
  2567.             aiTurnPending = true;
  2568.         }
  2569.     }
  2570. }
  2571.  
  2572. template <typename T>
  2573. void SafeRelease(T** ppT) {
  2574.     if (*ppT) {
  2575.         (*ppT)->Release();
  2576.         *ppT = nullptr;
  2577.     }
  2578. }
  2579.  
  2580. // --- CPU Ball?in?Hand Placement --------------------------------
  2581. // Moves the cue ball to a legal "ball in hand" position for the AI.
  2582. void AIPlaceCueBall() {
  2583.     Ball* cue = GetCueBall();
  2584.     if (!cue) return;
  2585.  
  2586.     // Simple strategy: place back behind the headstring at the standard break spot
  2587.     cue->x = TABLE_LEFT + TABLE_WIDTH * 0.15f;
  2588.     cue->y = RACK_POS_Y;
  2589.     cue->vx = cue->vy = 0.0f;
  2590. }
  2591.  
  2592. // --- Helper Function for Line Segment Intersection ---
  2593. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  2594. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  2595. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  2596. {
  2597.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  2598.  
  2599.     // Check if lines are parallel or collinear
  2600.     if (fabs(denominator) < 1e-6) {
  2601.         return false;
  2602.     }
  2603.  
  2604.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  2605.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  2606.  
  2607.     // Check if intersection point lies on both segments
  2608.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  2609.         intersection.x = p1.x + ua * (p2.x - p1.x);
  2610.         intersection.y = p1.y + ua * (p2.y - p1.y);
  2611.         return true;
  2612.     }
  2613.  
  2614.     return false;
  2615. }
  2616.  
  2617. // --- INSERT NEW HELPER FUNCTION HERE ---
  2618. // Calculates the squared distance from point P to the line segment AB.
  2619. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  2620.     float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  2621.     if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  2622.     // Consider P projecting onto the line AB infinite line
  2623.     // t = [(P-A) . (B-A)] / |B-A|^2
  2624.     float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  2625.     t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  2626.     // Projection falls on the segment
  2627.     D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  2628.     return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  2629. }
  2630. // --- End New Helper ---
  2631.  
  2632. // --- NEW AI Implementation Functions ---
  2633.  
  2634. // --------------------------------------------------------------------------------
  2635. // Full AIMakeDecision(): CPU pocket?calling & shot planning (no omissions)
  2636. // --------------------------------------------------------------------------------
  2637. void AIMakeDecision() {
  2638.     aiPlannedShotDetails.isValid = false; // Always start with a clean plan.
  2639.     Ball* cueBall = GetCueBall();
  2640.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return;
  2641.  
  2642.     // Ask the "expert" (AIFindBestShot) for the best possible shot.
  2643.     AIShotInfo bestShot = AIFindBestShot();
  2644.  
  2645.     if (bestShot.possible) {
  2646.         // A good shot was found.
  2647.         if (bestShot.involves8Ball) {
  2648.             //  ??? Call exactly the pocket we're about to shoot into ???
  2649.             calledPocketP2 = bestShot.pocketIndex;
  2650.         }
  2651.         /*// A good shot was found.
  2652.         if (bestShot.involves8Ball) {
  2653.             // THE CRITICAL FIX: The AI officially "calls" the pocket it's aiming for.
  2654.                 // 1) Remember which pocket we're "calling"
  2655.             calledPocketP2 = bestShot.pocketIndex;
  2656.  
  2657.             // 2) Force the UI into the pocket?selection state
  2658.             currentGameState = CHOOSING_POCKET_P2;
  2659.  
  2660.             // 3) Clear any lingering hover
  2661.             currentlyHoveredPocket = -1;
  2662.  
  2663.             // 4) Immediately redraw so the arrow appears for one frame
  2664.             InvalidateRect(hwndMain, NULL, FALSE);
  2665.  
  2666.             // 5) Now we can go back to AIMING and let our “AI click” fire
  2667.             currentGameState = AIMING;
  2668.         }*/
  2669.         // Commit to the shot plan.
  2670.         aiPlannedShotDetails.angle = bestShot.angle;
  2671.         aiPlannedShotDetails.power = bestShot.power;
  2672.         aiPlannedShotDetails.spinX = 0.0f; // AI plays center ball for now
  2673.         aiPlannedShotDetails.spinY = 0.0f;
  2674.         aiPlannedShotDetails.isValid = true;
  2675.     }
  2676.     else {
  2677.         // No good offensive shot found, must play a safe defensive shot.
  2678.         Ball* ballToNudge = nullptr;
  2679.         if (IsPlayerOnEightBall(2)) {
  2680.             ballToNudge = GetBallById(8);
  2681.             // Even on a safety, the AI must call a pocket. Default to one far away.
  2682.             calledPocketP2 = 5;
  2683.         }
  2684.         else {
  2685.             // Add logic here to find the closest of your own balls to tap safely.
  2686.             // For now, we'll just handle the 8-ball case.
  2687.         }
  2688.  
  2689.         if (ballToNudge) {
  2690.             aiPlannedShotDetails.angle = atan2f(ballToNudge->y - cueBall->y, ballToNudge->x - cueBall->x);
  2691.             aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.15f; // Gentle tap
  2692.             aiPlannedShotDetails.isValid = true;
  2693.         }
  2694.     }
  2695.  
  2696.     // If any valid plan was made, prepare to show the aim and shoot.
  2697.     if (aiPlannedShotDetails.isValid) {
  2698.         cueAngle = aiPlannedShotDetails.angle;
  2699.         shotPower = aiPlannedShotDetails.power;
  2700.         aiIsDisplayingAim = true;
  2701.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  2702.     }
  2703.     else {
  2704.         // Absolute fallback: If no plan could be made, switch turns to prevent a freeze.
  2705.         SwitchTurns();
  2706.     }
  2707. }
  2708.  
  2709.  
  2710.  
  2711. AIShotInfo AIFindBestShot() {
  2712.     AIShotInfo bestShotOverall = { false };
  2713.     Ball* cueBall = GetCueBall();
  2714.     if (!cueBall) return bestShotOverall;
  2715.  
  2716.     bool mustShoot8Ball = IsPlayerOnEightBall(2);
  2717.  
  2718.     for (auto& potentialTarget : balls) {
  2719.         if (potentialTarget.isPocketed || potentialTarget.id == 0) continue;
  2720.  
  2721.         // Determine if this ball is a valid target for this turn
  2722.         bool isValidTarget = false;
  2723.         if (mustShoot8Ball) {
  2724.             // 8-BALL MODE: The only valid target is the 8-ball.
  2725.             isValidTarget = (potentialTarget.id == 8);
  2726.         }
  2727.         else {
  2728.             // NORMAL MODE: The only valid targets are the AI's own assigned balls.
  2729.             isValidTarget = (potentialTarget.type == player2Info.assignedType && potentialTarget.id != 8);
  2730.         }
  2731.  
  2732.         if (!isValidTarget) continue;
  2733.  
  2734.         // Evaluate shooting this valid target into all 6 pockets
  2735.         for (int p = 0; p < 6; ++p) {
  2736.             AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
  2737.             if (currentShot.possible) {
  2738.                 // A shot is only truly viable if the first ball it hits is the one we're aiming for.
  2739.                 float firstHitDistSq;
  2740.                 Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), currentShot.angle, firstHitDistSq);
  2741.  
  2742.                 if (firstHit && firstHit->id == currentShot.targetBall->id) {
  2743.                     // This is a legal, viable shot. Is it better than the best one we've found so far?
  2744.                     if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
  2745.                         bestShotOverall = currentShot;
  2746.                     }
  2747.                 }
  2748.             }
  2749.         }
  2750.     }
  2751.     return bestShotOverall;
  2752. }
  2753.  
  2754.  
  2755. // Evaluate a potential shot at a specific target ball towards a specific pocket
  2756. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
  2757.     AIShotInfo shotInfo; // Defaults to not possible
  2758.     shotInfo.targetBall = targetBall;
  2759.     shotInfo.pocketIndex = pocketIndex;
  2760.     shotInfo.involves8Ball = (targetBall && targetBall->id == 8);
  2761.  
  2762.     Ball* cueBall = GetCueBall();
  2763.     if (!cueBall || !targetBall) return shotInfo;
  2764.  
  2765.     // 1. Calculate Ghost Ball position (where cue must hit target)
  2766.     shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  2767.  
  2768.     // 2. Check Path: Cue Ball -> Ghost Ball Position
  2769.     if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
  2770.         return shotInfo; // Path blocked, shot is impossible.
  2771.     }
  2772.  
  2773.     // 3. Calculate Angle and Power
  2774.     float dx = shotInfo.ghostBallPos.x - cueBall->x;
  2775.     float dy = shotInfo.ghostBallPos.y - cueBall->y;
  2776.     shotInfo.angle = atan2f(dy, dx);
  2777.  
  2778.     float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
  2779.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
  2780.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
  2781.  
  2782.     // 4. Score the shot (simple scoring: closer and straighter is better)
  2783.     shotInfo.score = 1000.0f - (cueToGhostDist + targetToPocketDist);
  2784.  
  2785.     // If we reached here, the shot is geometrically possible.
  2786.     shotInfo.possible = true;
  2787.     return shotInfo;
  2788. }
  2789.  
  2790.  
  2791. // Calculates required power (simplified)
  2792. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
  2793.     // Basic model: Power needed increases with total distance the balls need to travel.
  2794.     // Need enough power for cue ball to reach target AND target to reach pocket.
  2795.     float totalDist = cueToGhostDist + targetToPocketDist;
  2796.  
  2797.     // Map distance to power (needs tuning)
  2798.     // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
  2799.     float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
  2800.  
  2801.     float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
  2802.     float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
  2803.  
  2804.     // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
  2805.     return std::min(MAX_SHOT_POWER, basePower + variablePower);
  2806. }
  2807.  
  2808. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  2809. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
  2810.     float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
  2811.     float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
  2812.     float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
  2813.  
  2814.     if (dist < 1.0f) { // Target is basically in the pocket
  2815.         // Aim slightly off-center to avoid weird physics? Or directly at center?
  2816.         // For simplicity, return a point slightly behind center along the reverse line.
  2817.         return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
  2818.     }
  2819.  
  2820.     // Normalize direction vector from target to pocket
  2821.     float nx = targetToPocketX / dist;
  2822.     float ny = targetToPocketY / dist;
  2823.  
  2824.     // Ghost ball position is diameter distance *behind* the target ball along this line
  2825.     float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
  2826.     float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
  2827.  
  2828.     return D2D1::Point2F(ghostX, ghostY);
  2829. }
  2830.  
  2831. // Checks if line segment is clear of obstructing balls
  2832. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
  2833.     float dx = end.x - start.x;
  2834.     float dy = end.y - start.y;
  2835.     float segmentLenSq = dx * dx + dy * dy;
  2836.  
  2837.     if (segmentLenSq < 0.01f) return true; // Start and end are same point
  2838.  
  2839.     for (const auto& ball : balls) {
  2840.         if (ball.isPocketed) continue;
  2841.         if (ball.id == ignoredBallId1) continue;
  2842.         if (ball.id == ignoredBallId2) continue;
  2843.  
  2844.         // Check distance from ball center to the line segment
  2845.         float ballToStartX = ball.x - start.x;
  2846.         float ballToStartY = ball.y - start.y;
  2847.  
  2848.         // Project ball center onto the line defined by the segment
  2849.         float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
  2850.  
  2851.         D2D1_POINT_2F closestPointOnLine;
  2852.         if (dot < 0) { // Closest point is start point
  2853.             closestPointOnLine = start;
  2854.         }
  2855.         else if (dot > 1) { // Closest point is end point
  2856.             closestPointOnLine = end;
  2857.         }
  2858.         else { // Closest point is along the segment
  2859.             closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
  2860.         }
  2861.  
  2862.         // Check if the closest point is within collision distance (ball radius + path radius)
  2863.         if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
  2864.             // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
  2865.             // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
  2866.             return false; // Path is blocked
  2867.         }
  2868.     }
  2869.     return true; // No obstructions found
  2870. }
  2871.  
  2872. // Finds the first ball hit along a path (simplified)
  2873. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
  2874.     Ball* hitBall = nullptr;
  2875.     hitDistSq = -1.0f; // Initialize hit distance squared
  2876.     float minCollisionDistSq = -1.0f;
  2877.  
  2878.     float cosA = cosf(angle);
  2879.     float sinA = sinf(angle);
  2880.  
  2881.     for (auto& ball : balls) {
  2882.         if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
  2883.  
  2884.         float dx = ball.x - start.x;
  2885.         float dy = ball.y - start.y;
  2886.  
  2887.         // Project vector from start->ball onto the aim direction vector
  2888.         float dot = dx * cosA + dy * sinA;
  2889.  
  2890.         if (dot > 0) { // Ball is generally in front
  2891.             // Find closest point on aim line to the ball's center
  2892.             float closestPointX = start.x + dot * cosA;
  2893.             float closestPointY = start.y + dot * sinA;
  2894.             float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
  2895.  
  2896.             // Check if the aim line passes within the ball's radius
  2897.             if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
  2898.                 // Calculate distance from start to the collision point on the ball's circumference
  2899.                 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
  2900.                 float collisionDist = dot - backDist; // Distance along aim line to collision
  2901.  
  2902.                 if (collisionDist > 0) { // Ensure collision is in front
  2903.                     float collisionDistSq = collisionDist * collisionDist;
  2904.                     if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
  2905.                         minCollisionDistSq = collisionDistSq;
  2906.                         hitBall = &ball; // Found a closer hit ball
  2907.                     }
  2908.                 }
  2909.             }
  2910.         }
  2911.     }
  2912.     hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
  2913.     return hitBall;
  2914. }
  2915.  
  2916. // Basic check for reasonable AI aim angles (optional)
  2917. bool IsValidAIAimAngle(float angle) {
  2918.     // Placeholder - could check for NaN or infinity if calculations go wrong
  2919.     return isfinite(angle);
  2920. }
  2921.  
  2922. //midi func = start
  2923. void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  2924.     while (isMusicPlaying) {
  2925.         MCI_OPEN_PARMS mciOpen = { 0 };
  2926.         mciOpen.lpstrDeviceType = TEXT("sequencer");
  2927.         mciOpen.lpstrElementName = midiPath;
  2928.  
  2929.         if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  2930.             midiDeviceID = mciOpen.wDeviceID;
  2931.  
  2932.             MCI_PLAY_PARMS mciPlay = { 0 };
  2933.             mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  2934.  
  2935.             // Wait for playback to complete
  2936.             MCI_STATUS_PARMS mciStatus = { 0 };
  2937.             mciStatus.dwItem = MCI_STATUS_MODE;
  2938.  
  2939.             do {
  2940.                 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  2941.                 Sleep(100); // adjust as needed
  2942.             } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  2943.  
  2944.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  2945.             midiDeviceID = 0;
  2946.         }
  2947.     }
  2948. }
  2949.  
  2950. void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  2951.     if (isMusicPlaying) {
  2952.         StopMidi();
  2953.     }
  2954.     isMusicPlaying = true;
  2955.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  2956. }
  2957.  
  2958. void StopMidi() {
  2959.     if (isMusicPlaying) {
  2960.         isMusicPlaying = false;
  2961.         if (musicThread.joinable()) musicThread.join();
  2962.         if (midiDeviceID != 0) {
  2963.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  2964.             midiDeviceID = 0;
  2965.         }
  2966.     }
  2967. }
  2968.  
  2969. /*void PlayGameMusic(HWND hwnd) {
  2970.     // Stop any existing playback
  2971.     if (isMusicPlaying) {
  2972.         isMusicPlaying = false;
  2973.         if (musicThread.joinable()) {
  2974.             musicThread.join();
  2975.         }
  2976.         if (midiDeviceID != 0) {
  2977.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  2978.             midiDeviceID = 0;
  2979.         }
  2980.     }
  2981.  
  2982.     // Get the path of the executable
  2983.     TCHAR exePath[MAX_PATH];
  2984.     GetModuleFileName(NULL, exePath, MAX_PATH);
  2985.  
  2986.     // Extract the directory path
  2987.     TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  2988.     if (lastBackslash != NULL) {
  2989.         *(lastBackslash + 1) = '\0';
  2990.     }
  2991.  
  2992.     // Construct the full path to the MIDI file
  2993.     static TCHAR midiPath[MAX_PATH];
  2994.     _tcscpy_s(midiPath, MAX_PATH, exePath);
  2995.     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  2996.  
  2997.     // Start the background playback
  2998.     isMusicPlaying = true;
  2999.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  3000. }*/
  3001. //midi func = end
  3002.  
  3003. // --- Drawing Functions ---
  3004.  
  3005. void OnPaint() {
  3006.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  3007.  
  3008.     if (SUCCEEDED(hr)) {
  3009.         pRenderTarget->BeginDraw();
  3010.         DrawScene(pRenderTarget); // Pass render target
  3011.         hr = pRenderTarget->EndDraw();
  3012.  
  3013.         if (hr == D2DERR_RECREATE_TARGET) {
  3014.             DiscardDeviceResources();
  3015.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  3016.             // But the timer loop will trigger redraw anyway.
  3017.         }
  3018.     }
  3019.     // If CreateDeviceResources failed, EndDraw might not be called.
  3020.     // Consider handling this more robustly if needed.
  3021. }
  3022.  
  3023. void DrawScene(ID2D1RenderTarget* pRT) {
  3024.     if (!pRT) return;
  3025.  
  3026.     //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  3027.     // Set background color to #ffffcd (RGB: 255, 255, 205)
  3028.     pRT->Clear(D2D1::ColorF(0.3686f, 0.5333f, 0.3882f)); // Clear with light yellow background NEWCOLOR 1.0f, 1.0f, 0.803f => (0.3686f, 0.5333f, 0.3882f)
  3029.     //pRT->Clear(D2D1::ColorF(1.0f, 1.0f, 0.803f)); // Clear with light yellow background NEWCOLOR 1.0f, 1.0f, 0.803f => (0.3686f, 0.5333f, 0.3882f)
  3030.  
  3031.     DrawTable(pRT, pFactory);
  3032.     DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
  3033.     DrawBalls(pRT);
  3034.     DrawAimingAids(pRT); // Includes cue stick if aiming
  3035.     DrawUI(pRT);
  3036.     DrawPowerMeter(pRT);
  3037.     DrawSpinIndicator(pRT);
  3038.     DrawPocketedBallsIndicator(pRT);
  3039.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  3040.  
  3041.      // Draw Game Over Message
  3042.     if (currentGameState == GAME_OVER && pTextFormat) {
  3043.         ID2D1SolidColorBrush* pBrush = nullptr;
  3044.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  3045.         if (pBrush) {
  3046.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  3047.             pRT->DrawText(
  3048.                 gameOverMessage.c_str(),
  3049.                 (UINT32)gameOverMessage.length(),
  3050.                 pTextFormat, // Use large format maybe?
  3051.                 &layoutRect,
  3052.                 pBrush
  3053.             );
  3054.             SafeRelease(&pBrush);
  3055.         }
  3056.     }
  3057.  
  3058. }
  3059.  
  3060. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  3061.     ID2D1SolidColorBrush* pBrush = nullptr;
  3062.  
  3063.     // === Draw Full Orange Frame (Table Border) ===
  3064.     ID2D1SolidColorBrush* pFrameBrush = nullptr;
  3065.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3066.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
  3067.     if (pFrameBrush) {
  3068.         D2D1_RECT_F outerRect = D2D1::RectF(
  3069.             TABLE_LEFT - CUSHION_THICKNESS,
  3070.             TABLE_TOP - CUSHION_THICKNESS,
  3071.             TABLE_RIGHT + CUSHION_THICKNESS,
  3072.             TABLE_BOTTOM + CUSHION_THICKNESS
  3073.         );
  3074.         pRT->FillRectangle(&outerRect, pFrameBrush);
  3075.         SafeRelease(&pFrameBrush);
  3076.     }
  3077.  
  3078.     // Draw Table Bed (Green Felt)
  3079.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  3080.     if (!pBrush) return;
  3081.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  3082.     pRT->FillRectangle(&tableRect, pBrush);
  3083.     SafeRelease(&pBrush);
  3084.  
  3085.     // Draw Cushions (Red Border)
  3086.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  3087.     if (!pBrush) return;
  3088.     // Top Cushion (split by middle pocket)
  3089.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
  3090.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
  3091.     // Bottom Cushion (split by middle pocket)
  3092.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
  3093.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
  3094.     // Left Cushion
  3095.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3096.     // Right Cushion
  3097.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
  3098.     SafeRelease(&pBrush);
  3099.  
  3100.  
  3101.     // Draw Pockets (Black Circles)
  3102.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
  3103.     if (!pBrush) return;
  3104.     for (int i = 0; i < 6; ++i) {
  3105.         D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
  3106.         pRT->FillEllipse(&ellipse, pBrush);
  3107.     }
  3108.     SafeRelease(&pBrush);
  3109.  
  3110.     // Draw Headstring Line (White)
  3111.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3112.     //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
  3113.     if (!pBrush) return;
  3114.     pRT->DrawLine(
  3115.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  3116.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  3117.         pBrush,
  3118.         1.0f // Line thickness
  3119.     );
  3120.     SafeRelease(&pBrush);
  3121.  
  3122.     // Draw Semicircle facing West (flat side East)
  3123.     // Draw Semicircle facing East (curved side on the East, flat side on the West)
  3124.     ID2D1PathGeometry* pGeometry = nullptr;
  3125.     HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  3126.     if (SUCCEEDED(hr) && pGeometry)
  3127.     {
  3128.         ID2D1GeometrySink* pSink = nullptr;
  3129.         hr = pGeometry->Open(&pSink);
  3130.         if (SUCCEEDED(hr) && pSink)
  3131.         {
  3132.             float radius = 60.0f; // Radius for the semicircle
  3133.             D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  3134.  
  3135.             // For a semicircle facing East (curved side on the East), use the top and bottom points.
  3136.             D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
  3137.  
  3138.             pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  3139.  
  3140.             D2D1_ARC_SEGMENT arc = {};
  3141.             arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
  3142.             arc.size = D2D1::SizeF(radius, radius);
  3143.             arc.rotationAngle = 0.0f;
  3144.             // Use the correct identifier with the extra underscore:
  3145.             arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  3146.             arc.arcSize = D2D1_ARC_SIZE_SMALL;
  3147.  
  3148.             pSink->AddArc(&arc);
  3149.             pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  3150.             pSink->Close();
  3151.             SafeRelease(&pSink);
  3152.  
  3153.             ID2D1SolidColorBrush* pArcBrush = nullptr;
  3154.             //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
  3155.             pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
  3156.             if (pArcBrush)
  3157.             {
  3158.                 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
  3159.                 SafeRelease(&pArcBrush);
  3160.             }
  3161.         }
  3162.         SafeRelease(&pGeometry);
  3163.     }
  3164.  
  3165.  
  3166.  
  3167.  
  3168. }
  3169.  
  3170.  
  3171. void DrawBalls(ID2D1RenderTarget* pRT) {
  3172.     ID2D1SolidColorBrush* pBrush = nullptr;
  3173.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  3174.  
  3175.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  3176.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3177.  
  3178.     if (!pBrush || !pStripeBrush) {
  3179.         SafeRelease(&pBrush);
  3180.         SafeRelease(&pStripeBrush);
  3181.         return;
  3182.     }
  3183.  
  3184.  
  3185.     for (size_t i = 0; i < balls.size(); ++i) {
  3186.         const Ball& b = balls[i];
  3187.         if (!b.isPocketed) {
  3188.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  3189.  
  3190.             // Set main ball color
  3191.             pBrush->SetColor(b.color);
  3192.             pRT->FillEllipse(&ellipse, pBrush);
  3193.  
  3194.             // Draw Stripe if applicable
  3195.             if (b.type == BallType::STRIPE) {
  3196.                 // Draw a white band across the middle (simplified stripe)
  3197.                 D2D1_RECT_F stripeRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS * 0.4f, b.x + BALL_RADIUS, b.y + BALL_RADIUS * 0.4f);
  3198.                 // Need to clip this rectangle to the ellipse bounds - complex!
  3199.                 // Alternative: Draw two colored arcs leaving a white band.
  3200.                 // Simplest: Draw a white circle inside, slightly smaller.
  3201.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  3202.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  3203.                 pBrush->SetColor(b.color); // Set back to stripe color
  3204.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  3205.  
  3206.                 // Let's try drawing a thick white line across
  3207.                 // This doesn't look great. Just drawing solid red for stripes for now.
  3208.             }
  3209.  
  3210.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  3211.             // if (b.id != 0 && pTextFormat) {
  3212.             //     std::wstring numStr = std::to_wstring(b.id);
  3213.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  3214.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  3215.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  3216.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  3217.             //     // Create a smaller text format...
  3218.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  3219.             //     SafeRelease(&pNumBrush);
  3220.             // }
  3221.         }
  3222.     }
  3223.  
  3224.     SafeRelease(&pBrush);
  3225.     SafeRelease(&pStripeBrush);
  3226. }
  3227.  
  3228.  
  3229. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  3230.     // Condition check at start (Unchanged)
  3231.     //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  3232.         //currentGameState != BREAKING && currentGameState != AIMING)
  3233.     //{
  3234.         //return;
  3235.     //}
  3236.         // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  3237.     // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  3238.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  3239.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  3240.             currentGameState == BREAKING || currentGameState == AIMING);
  3241.     // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  3242.     // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  3243.         // NEW Condition: AI is displaying its aim
  3244.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  3245.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  3246.  
  3247.     if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  3248.         return;
  3249.     }
  3250.  
  3251.     Ball* cueBall = GetCueBall();
  3252.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  3253.  
  3254.     ID2D1SolidColorBrush* pBrush = nullptr;
  3255.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  3256.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  3257.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  3258.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  3259.  
  3260.     // Ensure render target is valid
  3261.     if (!pRT) return;
  3262.  
  3263.     // Create Brushes and Styles (check for failures)
  3264.     HRESULT hr;
  3265.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  3266.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  3267.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  3268.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  3269.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  3270.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  3271.     // Create reflection brush (e.g., lighter shade or different color)
  3272.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  3273.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  3274.     // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  3275.     D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  3276.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  3277.     hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  3278.     if (FAILED(hr)) {
  3279.         SafeRelease(&pCyanBrush);
  3280.         // handle error if needed
  3281.     }
  3282.     // Create a Purple brush for primary and secondary lines
  3283.     D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  3284.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  3285.     hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  3286.     if (FAILED(hr)) {
  3287.         SafeRelease(&pPurpleBrush);
  3288.         // handle error if needed
  3289.     }
  3290.  
  3291.     if (pFactory) {
  3292.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  3293.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  3294.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  3295.         if FAILED(hr) { pDashedStyle = nullptr; }
  3296.     }
  3297.  
  3298.  
  3299.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  3300.     const float baseStickLength = 150.0f;
  3301.     const float baseStickThickness = 4.0f;
  3302.     float stickLength = baseStickLength * 1.4f;
  3303.     float stickThickness = baseStickThickness * 1.5f;
  3304.     float stickAngle = cueAngle + PI;
  3305.     float powerOffset = 0.0f;
  3306.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  3307.         // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  3308.     if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  3309.         powerOffset = shotPower * 5.0f;
  3310.     }
  3311.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  3312.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  3313.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  3314.  
  3315.  
  3316.     // --- Projection Line Calculation ---
  3317.     float cosA = cosf(cueAngle);
  3318.     float sinA = sinf(cueAngle);
  3319.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  3320.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  3321.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  3322.  
  3323.     // Find the first ball hit by the aiming ray
  3324.     Ball* hitBall = nullptr;
  3325.     float firstHitDistSq = -1.0f;
  3326.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  3327.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  3328.  
  3329.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  3330.     if (hitBall) {
  3331.         // Calculate the point on the target ball's circumference
  3332.         float collisionDist = sqrtf(firstHitDistSq);
  3333.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  3334.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  3335.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  3336.     }
  3337.  
  3338.     // Find the first rail hit by the aiming ray
  3339.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  3340.     float minRailDistSq = rayLength * rayLength;
  3341.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  3342.  
  3343.     // Define table edge segments for intersection checks
  3344.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  3345.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  3346.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  3347.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  3348.  
  3349.     D2D1_POINT_2F currentIntersection;
  3350.  
  3351.     // Check Left Rail
  3352.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  3353.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3354.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  3355.     }
  3356.     // Check Right Rail
  3357.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  3358.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3359.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  3360.     }
  3361.     // Check Top Rail
  3362.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  3363.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3364.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  3365.     }
  3366.     // Check Bottom Rail
  3367.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  3368.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  3369.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  3370.     }
  3371.  
  3372.  
  3373.     // --- Determine final aim line end point ---
  3374.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  3375.     bool aimingAtRail = true;
  3376.  
  3377.     if (hitBall && firstHitDistSq < minRailDistSq) {
  3378.         // Ball collision is closer than rail collision
  3379.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  3380.         aimingAtRail = false;
  3381.     }
  3382.  
  3383.     // --- Draw Primary Aiming Line ---
  3384.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3385.  
  3386.     // --- Draw Target Circle/Indicator ---
  3387.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  3388.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  3389.  
  3390.     // --- Draw Projection/Reflection Lines ---
  3391.     if (!aimingAtRail && hitBall) {
  3392.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  3393.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  3394.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3395.  
  3396.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  3397.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  3398.         // Clamp angle calculation if distance is tiny
  3399.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  3400.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  3401.         }
  3402.  
  3403.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  3404.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  3405.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  3406.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  3407.         );
  3408.         // Draw solid line for target projection
  3409.         //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  3410.  
  3411.     //new code start
  3412.  
  3413.                 // Dual trajectory with edge-aware contact simulation
  3414.         D2D1_POINT_2F dir = {
  3415.             targetProjectionEnd.x - targetStartPoint.x,
  3416.             targetProjectionEnd.y - targetStartPoint.y
  3417.         };
  3418.         float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  3419.         dir.x /= dirLen;
  3420.         dir.y /= dirLen;
  3421.  
  3422.         D2D1_POINT_2F perp = { -dir.y, dir.x };
  3423.  
  3424.         // Approximate cue ball center by reversing from tip
  3425.         D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  3426.             targetStartPoint.x - dir.x * BALL_RADIUS,
  3427.             targetStartPoint.y - dir.y * BALL_RADIUS
  3428.         };
  3429.  
  3430.         // REAL contact-ball center - use your physics object's center:
  3431.         // (replace 'objectBallPos' with whatever you actually call it)
  3432.         // (targetStartPoint is already hitBall->x, hitBall->y)
  3433.         D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  3434.         //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  3435.  
  3436.        // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  3437.        // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  3438.        // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  3439.        // and 'perp' is perpendicular to 'dir'.
  3440.        // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  3441.         /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  3442.             (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  3443.             /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  3444.                 (targetStartPoint.y - cueBallCenter.y) * perp.y);
  3445.             float absOffset = fabsf(offset);
  3446.             float side = (offset >= 0 ? 1.0f : -1.0f);*/
  3447.  
  3448.             // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  3449.         D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  3450.  
  3451.         // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  3452.         float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  3453.             (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  3454.         float absOffset = fabsf(offset);
  3455.         float side = (offset >= 0 ? 1.0f : -1.0f);
  3456.  
  3457.  
  3458.         // Actual contact point on target ball edge
  3459.         D2D1_POINT_2F contactPoint = {
  3460.         contactBallCenter.x + perp.x * BALL_RADIUS * side,
  3461.         contactBallCenter.y + perp.y * BALL_RADIUS * side
  3462.         };
  3463.  
  3464.         // Tangent (cut shot) path from contact point
  3465.             // Tangent (cut shot) path: from contact point to contact ball center
  3466.         D2D1_POINT_2F objectBallDir = {
  3467.             contactBallCenter.x - contactPoint.x,
  3468.             contactBallCenter.y - contactPoint.y
  3469.         };
  3470.         float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  3471.         if (oLen != 0.0f) {
  3472.             objectBallDir.x /= oLen;
  3473.             objectBallDir.y /= oLen;
  3474.         }
  3475.  
  3476.         const float PRIMARY_LEN = 150.0f; //default=150.0f
  3477.         const float SECONDARY_LEN = 150.0f; //default=150.0f
  3478.         const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  3479.  
  3480.         D2D1_POINT_2F primaryEnd = {
  3481.             targetStartPoint.x + dir.x * PRIMARY_LEN,
  3482.             targetStartPoint.y + dir.y * PRIMARY_LEN
  3483.         };
  3484.  
  3485.         // Secondary line starts from the contact ball's center
  3486.         D2D1_POINT_2F secondaryStart = contactBallCenter;
  3487.         D2D1_POINT_2F secondaryEnd = {
  3488.             secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  3489.             secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  3490.         };
  3491.  
  3492.         if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  3493.         {
  3494.             // Straight: secondary behind primary
  3495.                     // secondary behind primary {pDashedStyle param at end}
  3496.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  3497.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  3498.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  3499.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  3500.         }
  3501.         else
  3502.         {
  3503.             // Cut shot: both visible
  3504.                     // both visible for cut shot
  3505.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  3506.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  3507.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  3508.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  3509.         }
  3510.         // End improved trajectory logic
  3511.  
  3512.     //new code end
  3513.  
  3514.         // -- Cue Ball Path after collision (Optional, requires physics) --
  3515.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  3516.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  3517.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  3518.         // D2D1_POINT_2F cueProjectionEnd = ...
  3519.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3520.  
  3521.         // --- Accuracy Comment ---
  3522.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  3523.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  3524.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  3525.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  3526.  
  3527.     }
  3528.     else if (aimingAtRail && hitRailIndex != -1) {
  3529.         // Aiming at a rail: Draw reflection line
  3530.         float reflectAngle = cueAngle;
  3531.         // Reflect angle based on which rail was hit
  3532.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  3533.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  3534.         }
  3535.         else { // Top or Bottom rail
  3536.             reflectAngle = -cueAngle; // Reflect vertical component
  3537.         }
  3538.         // Normalize angle if needed (atan2 usually handles this)
  3539.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  3540.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  3541.  
  3542.  
  3543.         float reflectionLength = 60.0f; // Length of the reflection line
  3544.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  3545.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  3546.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  3547.         );
  3548.  
  3549.         // Draw the reflection line (e.g., using a different color/style)
  3550.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  3551.     }
  3552.  
  3553.     // Release resources
  3554.     SafeRelease(&pBrush);
  3555.     SafeRelease(&pGhostBrush);
  3556.     SafeRelease(&pCueBrush);
  3557.     SafeRelease(&pReflectBrush); // Release new brush
  3558.     SafeRelease(&pCyanBrush);
  3559.     SafeRelease(&pPurpleBrush);
  3560.     SafeRelease(&pDashedStyle);
  3561. }
  3562.  
  3563.  
  3564. void DrawUI(ID2D1RenderTarget* pRT) {
  3565.     if (!pTextFormat || !pLargeTextFormat) return;
  3566.  
  3567.     ID2D1SolidColorBrush* pBrush = nullptr;
  3568.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  3569.     if (!pBrush) return;
  3570.  
  3571.     //new code
  3572.     // --- Always draw AI's 8?Ball call arrow when it's Player?2's turn and AI has called ---
  3573.     //if (isPlayer2AI && currentPlayer == 2 && calledPocketP2 >= 0) {
  3574.         // FIX: This condition correctly shows the AI's called pocket arrow.
  3575.     if (isPlayer2AI && IsPlayerOnEightBall(2) && calledPocketP2 >= 0) {
  3576.         // pocket index that AI called
  3577.         int idx = calledPocketP2;
  3578.         // draw large blue arrow
  3579.         ID2D1SolidColorBrush* pArrow = nullptr;
  3580.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  3581.         if (pArrow) {
  3582.             auto P = pocketPositions[idx];
  3583.             D2D1_POINT_2F tri[3] = {
  3584.                 { P.x - 15.0f, P.y - 40.0f },
  3585.                 { P.x + 15.0f, P.y - 40.0f },
  3586.                 { P.x       , P.y - 10.0f }
  3587.             };
  3588.             ID2D1PathGeometry* geom = nullptr;
  3589.             pFactory->CreatePathGeometry(&geom);
  3590.             ID2D1GeometrySink* sink = nullptr;
  3591.             geom->Open(&sink);
  3592.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  3593.             sink->AddLines(&tri[1], 2);
  3594.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3595.             sink->Close();
  3596.             pRT->FillGeometry(geom, pArrow);
  3597.             SafeRelease(&sink);
  3598.             SafeRelease(&geom);
  3599.             SafeRelease(&pArrow);
  3600.         }
  3601.         // draw “Choose a pocket...” prompt
  3602.         D2D1_RECT_F txt = D2D1::RectF(
  3603.             TABLE_LEFT,
  3604.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  3605.             TABLE_RIGHT,
  3606.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  3607.         );
  3608.         pRT->DrawText(
  3609.             L"AI has called this pocket",
  3610.             (UINT32)wcslen(L"AI has called this pocket"),
  3611.             pTextFormat,
  3612.             &txt,
  3613.             pBrush
  3614.         );
  3615.         // note: no return here — we still draw fouls/turn text underneath
  3616.     }
  3617.     //end new code
  3618.  
  3619.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  3620.     float uiTop = TABLE_TOP - 80;
  3621.     float uiHeight = 60;
  3622.     float p1Left = TABLE_LEFT;
  3623.     float p1Width = 150;
  3624.     float p2Left = TABLE_RIGHT - p1Width;
  3625.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  3626.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  3627.  
  3628.     // Player 1 Info Text (Unchanged)
  3629.     std::wostringstream oss1;
  3630.     oss1 << player1Info.name.c_str() << L"\n";
  3631.     if (player1Info.assignedType != BallType::NONE) {
  3632.         oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  3633.         oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  3634.     }
  3635.     else {
  3636.         oss1 << L"(Undecided)";
  3637.     }
  3638.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  3639.     // Draw Player 1 Side Ball
  3640.     if (player1Info.assignedType != BallType::NONE)
  3641.     {
  3642.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  3643.         D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  3644.             D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  3645.         pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  3646.         if (pBallBrush)
  3647.         {
  3648.             D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 10.0f, p1Rect.top + 20.0f);
  3649.             float radius = 10.0f;
  3650.             D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  3651.             pRT->FillEllipse(&ball, pBallBrush);
  3652.             SafeRelease(&pBallBrush);
  3653.             // Draw border around the ball
  3654.             ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3655.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3656.             if (pBorderBrush)
  3657.             {
  3658.                 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  3659.                 SafeRelease(&pBorderBrush);
  3660.             }
  3661.  
  3662.             // If stripes, draw a stripe band
  3663.             if (player1Info.assignedType == BallType::STRIPE)
  3664.             {
  3665.                 ID2D1SolidColorBrush* pStripeBrush = nullptr;
  3666.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3667.                 if (pStripeBrush)
  3668.                 {
  3669.                     D2D1_RECT_F stripeRect = D2D1::RectF(
  3670.                         ballCenter.x - radius,
  3671.                         ballCenter.y - 3.0f,
  3672.                         ballCenter.x + radius,
  3673.                         ballCenter.y + 3.0f
  3674.                     );
  3675.                     pRT->FillRectangle(&stripeRect, pStripeBrush);
  3676.                     SafeRelease(&pStripeBrush);
  3677.                 }
  3678.             }
  3679.         }
  3680.     }
  3681.  
  3682.  
  3683.     // Player 2 Info Text (Unchanged)
  3684.     std::wostringstream oss2;
  3685.     oss2 << player2Info.name.c_str() << L"\n";
  3686.     if (player2Info.assignedType != BallType::NONE) {
  3687.         oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
  3688.         oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  3689.     }
  3690.     else {
  3691.         oss2 << L"(Undecided)";
  3692.     }
  3693.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  3694.     // Draw Player 2 Side Ball
  3695.     if (player2Info.assignedType != BallType::NONE)
  3696.     {
  3697.         ID2D1SolidColorBrush* pBallBrush = nullptr;
  3698.         D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  3699.             D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  3700.         pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  3701.         if (pBallBrush)
  3702.         {
  3703.             D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.right + 10.0f, p2Rect.top + 20.0f);
  3704.             float radius = 10.0f;
  3705.             D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  3706.             pRT->FillEllipse(&ball, pBallBrush);
  3707.             SafeRelease(&pBallBrush);
  3708.             // Draw border around the ball
  3709.             ID2D1SolidColorBrush* pBorderBrush = nullptr;
  3710.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  3711.             if (pBorderBrush)
  3712.             {
  3713.                 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
  3714.                 SafeRelease(&pBorderBrush);
  3715.             }
  3716.  
  3717.             // If stripes, draw a stripe band
  3718.             if (player2Info.assignedType == BallType::STRIPE)
  3719.             {
  3720.                 ID2D1SolidColorBrush* pStripeBrush = nullptr;
  3721.                 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  3722.                 if (pStripeBrush)
  3723.                 {
  3724.                     D2D1_RECT_F stripeRect = D2D1::RectF(
  3725.                         ballCenter.x - radius,
  3726.                         ballCenter.y - 3.0f,
  3727.                         ballCenter.x + radius,
  3728.                         ballCenter.y + 3.0f
  3729.                     );
  3730.                     pRT->FillRectangle(&stripeRect, pStripeBrush);
  3731.                     SafeRelease(&pStripeBrush);
  3732.                 }
  3733.             }
  3734.         }
  3735.     }
  3736.  
  3737.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  3738.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3739.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3740.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  3741.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  3742.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  3743.         float arrowTipX, arrowBackX;
  3744.  
  3745.         D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  3746.         arrowBackX = playerBox.left - 25.0f;
  3747.         arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  3748.  
  3749.         float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  3750.         float notchWidth = 10.0f;
  3751.  
  3752.         float cx = arrowBackX;
  3753.         float cy = arrowCenterY;
  3754.  
  3755.         // Define triangle + rectangle tail shape
  3756.         D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  3757.         D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  3758.         D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  3759.  
  3760.         // Rectangle coordinates for the tail portion:
  3761.         D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  3762.         D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  3763.         D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  3764.         D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  3765.  
  3766.         ID2D1PathGeometry* pPath = nullptr;
  3767.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3768.             ID2D1GeometrySink* pSink = nullptr;
  3769.             if (SUCCEEDED(pPath->Open(&pSink))) {
  3770.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  3771.                 pSink->AddLine(baseTop);
  3772.                 pSink->AddLine(r2); // transition from triangle into rectangle
  3773.                 pSink->AddLine(r1);
  3774.                 pSink->AddLine(r4);
  3775.                 pSink->AddLine(r3);
  3776.                 pSink->AddLine(baseBot);
  3777.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3778.                 pSink->Close();
  3779.                 SafeRelease(&pSink);
  3780.                 pRT->FillGeometry(pPath, pArrowBrush);
  3781.             }
  3782.             SafeRelease(&pPath);
  3783.         }
  3784.  
  3785.  
  3786.         SafeRelease(&pArrowBrush);
  3787.     }
  3788.  
  3789.     //original
  3790. /*
  3791.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  3792.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  3793.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  3794.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  3795.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  3796.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  3797.         float arrowTipX, arrowBackX;
  3798.  
  3799.         if (currentPlayer == 1) {
  3800. arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  3801.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  3802.             // Define points for right-pointing arrow
  3803.             //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3804.             //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3805.             //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3806.             // Enhanced arrow with base rectangle intersection
  3807.     float notchDepth = 6.0f; // Depth of square base "stem"
  3808.     float notchWidth = 4.0f; // Thickness of square part
  3809.  
  3810.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3811.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3812.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  3813.     D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  3814.     D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3815.  
  3816.  
  3817.     ID2D1PathGeometry* pPath = nullptr;
  3818.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3819.         ID2D1GeometrySink* pSink = nullptr;
  3820.         if (SUCCEEDED(pPath->Open(&pSink))) {
  3821.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  3822.             pSink->AddLine(pt2);
  3823.             pSink->AddLine(pt3);
  3824.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3825.             pSink->Close();
  3826.             SafeRelease(&pSink);
  3827.             pRT->FillGeometry(pPath, pArrowBrush);
  3828.         }
  3829.         SafeRelease(&pPath);
  3830.     }
  3831.         }
  3832.  
  3833.  
  3834.         //==================else player 2
  3835.         else { // Player 2
  3836.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  3837.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  3838. // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  3839. arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  3840. arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  3841. // Define points for right-pointing arrow
  3842. D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  3843. D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  3844. D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  3845.  
  3846. ID2D1PathGeometry* pPath = nullptr;
  3847. if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  3848.     ID2D1GeometrySink* pSink = nullptr;
  3849.     if (SUCCEEDED(pPath->Open(&pSink))) {
  3850.         pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  3851.         pSink->AddLine(pt2);
  3852.         pSink->AddLine(pt3);
  3853.         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3854.         pSink->Close();
  3855.         SafeRelease(&pSink);
  3856.         pRT->FillGeometry(pPath, pArrowBrush);
  3857.     }
  3858.     SafeRelease(&pPath);
  3859. }
  3860.         }
  3861.         */
  3862.  
  3863.  
  3864.         // --- Persistent Blue 8?Ball Call Arrow & Prompt ---
  3865.     /*if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  3866.     {
  3867.         // determine index (default top?right)
  3868.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  3869.         if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  3870.         if (idx < 0) idx = 2;
  3871.  
  3872.         // draw large blue arrow
  3873.         ID2D1SolidColorBrush* pArrow = nullptr;
  3874.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  3875.         if (pArrow) {
  3876.             auto P = pocketPositions[idx];
  3877.             D2D1_POINT_2F tri[3] = {
  3878.                 {P.x - 15.0f, P.y - 40.0f},
  3879.                 {P.x + 15.0f, P.y - 40.0f},
  3880.                 {P.x       , P.y - 10.0f}
  3881.             };
  3882.             ID2D1PathGeometry* geom = nullptr;
  3883.             pFactory->CreatePathGeometry(&geom);
  3884.             ID2D1GeometrySink* sink = nullptr;
  3885.             geom->Open(&sink);
  3886.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  3887.             sink->AddLines(&tri[1], 2);
  3888.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3889.             sink->Close();
  3890.             pRT->FillGeometry(geom, pArrow);
  3891.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  3892.         }
  3893.  
  3894.         // draw prompt
  3895.         D2D1_RECT_F txt = D2D1::RectF(
  3896.             TABLE_LEFT,
  3897.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  3898.             TABLE_RIGHT,
  3899.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  3900.         );
  3901.         pRT->DrawText(
  3902.             L"Choose a pocket...",
  3903.             (UINT32)wcslen(L"Choose a pocket..."),
  3904.             pTextFormat,
  3905.             &txt,
  3906.             pBrush
  3907.         );
  3908.     }*/
  3909.  
  3910.         // --- Persistent Blue 8?Ball Pocket Arrow & Prompt (once called) ---
  3911.     /* if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  3912.     {
  3913.         // 1) Determine pocket index
  3914.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  3915.         // If the other player had called but it's now your turn, still show that call
  3916.         if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  3917.         if (idx < 0) idx = 2; // default to top?right if somehow still unset
  3918.  
  3919.         // 2) Draw large blue arrow
  3920.         ID2D1SolidColorBrush* pArrow = nullptr;
  3921.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  3922.         if (pArrow) {
  3923.             auto P = pocketPositions[idx];
  3924.             D2D1_POINT_2F tri[3] = {
  3925.                 { P.x - 15.0f, P.y - 40.0f },
  3926.                 { P.x + 15.0f, P.y - 40.0f },
  3927.                 { P.x       , P.y - 10.0f }
  3928.             };
  3929.             ID2D1PathGeometry* geom = nullptr;
  3930.             pFactory->CreatePathGeometry(&geom);
  3931.             ID2D1GeometrySink* sink = nullptr;
  3932.             geom->Open(&sink);
  3933.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  3934.             sink->AddLines(&tri[1], 2);
  3935.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  3936.             sink->Close();
  3937.             pRT->FillGeometry(geom, pArrow);
  3938.             SafeRelease(&sink);
  3939.             SafeRelease(&geom);
  3940.             SafeRelease(&pArrow);
  3941.         }
  3942.  
  3943.         // 3) Draw persistent prompt text
  3944.         D2D1_RECT_F txt = D2D1::RectF(
  3945.             TABLE_LEFT,
  3946.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  3947.             TABLE_RIGHT,
  3948.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  3949.         );
  3950.         pRT->DrawText(
  3951.             L"Choose a pocket...",
  3952.             (UINT32)wcslen(L"Choose a pocket..."),
  3953.             pTextFormat,
  3954.             &txt,
  3955.             pBrush
  3956.         );
  3957.         // Note: no 'return'; allow foul/turn text to draw beneath if needed
  3958.     } */
  3959.  
  3960.     // new code ends here
  3961.  
  3962.         // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  3963.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  3964.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  3965.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  3966.         if (pFoulBrush && pLargeTextFormat) {
  3967.             // Calculate Rect for bottom-middle area
  3968.             float foulWidth = 200.0f; // Adjust width as needed
  3969.             float foulHeight = 60.0f;
  3970.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  3971.             // Position below the pocketed balls bar
  3972.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  3973.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  3974.  
  3975.             // --- Set text alignment to center for foul text ---
  3976.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  3977.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  3978.  
  3979.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  3980.  
  3981.             // --- Restore default alignment for large text if needed elsewhere ---
  3982.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  3983.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  3984.  
  3985.             SafeRelease(&pFoulBrush);
  3986.         }
  3987.     }
  3988.  
  3989.     // --- Blue Arrow & Prompt for 8?Ball Call (while choosing or after called) ---
  3990.     if ((currentGameState == CHOOSING_POCKET_P1
  3991.         || currentGameState == CHOOSING_POCKET_P2)
  3992.         || (calledPocketP1 >= 0 || calledPocketP2 >= 0))
  3993.     {
  3994.         // determine index:
  3995.         //  - if a call exists, use it
  3996.         //  - if still choosing, use hover if any
  3997.         // determine index: use only the clicked call; default to top?right if unset
  3998.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  3999.         if (idx < 0) idx = 2;
  4000.  
  4001.         // draw large blue arrow
  4002.         ID2D1SolidColorBrush* pArrow = nullptr;
  4003.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  4004.         if (pArrow) {
  4005.             auto P = pocketPositions[idx];
  4006.             D2D1_POINT_2F tri[3] = {
  4007.                 {P.x - 15.0f, P.y - 40.0f},
  4008.                 {P.x + 15.0f, P.y - 40.0f},
  4009.                 {P.x       , P.y - 10.0f}
  4010.             };
  4011.             ID2D1PathGeometry* geom = nullptr;
  4012.             pFactory->CreatePathGeometry(&geom);
  4013.             ID2D1GeometrySink* sink = nullptr;
  4014.             geom->Open(&sink);
  4015.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4016.             sink->AddLines(&tri[1], 2);
  4017.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4018.             sink->Close();
  4019.             pRT->FillGeometry(geom, pArrow);
  4020.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  4021.         }
  4022.  
  4023.         // draw prompt below pockets
  4024.         D2D1_RECT_F txt = D2D1::RectF(
  4025.             TABLE_LEFT,
  4026.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4027.             TABLE_RIGHT,
  4028.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4029.         );
  4030.         pRT->DrawText(
  4031.             L"Choose a pocket...",
  4032.             (UINT32)wcslen(L"Choose a pocket..."),
  4033.             pTextFormat,
  4034.             &txt,
  4035.             pBrush
  4036.         );
  4037.         // do NOT return here; allow foul/turn text to display under the arrow
  4038.     }
  4039.  
  4040.     // Removed Obsolete
  4041.     /*
  4042.     // --- 8-Ball Pocket Selection Arrow & Prompt ---
  4043.     if (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2) {
  4044.         // Determine which pocket to highlight (default to Top-Right if unset)
  4045.         int idx = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4046.         if (idx < 0) idx = 2;
  4047.  
  4048.         // Draw the downward arrow
  4049.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4050.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  4051.         if (pArrowBrush) {
  4052.             D2D1_POINT_2F P = pocketPositions[idx];
  4053.             D2D1_POINT_2F tri[3] = {
  4054.                 {P.x - 10.0f, P.y - 30.0f},
  4055.                 {P.x + 10.0f, P.y - 30.0f},
  4056.                 {P.x        , P.y - 10.0f}
  4057.             };
  4058.             ID2D1PathGeometry* geom = nullptr;
  4059.             pFactory->CreatePathGeometry(&geom);
  4060.             ID2D1GeometrySink* sink = nullptr;
  4061.             geom->Open(&sink);
  4062.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  4063.             sink->AddLines(&tri[1], 2);
  4064.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4065.             sink->Close();
  4066.             pRT->FillGeometry(geom, pArrowBrush);
  4067.             SafeRelease(&sink);
  4068.             SafeRelease(&geom);
  4069.             SafeRelease(&pArrowBrush);
  4070.         }
  4071.  
  4072.         // Draw “Choose a pocket...” text under the table
  4073.         D2D1_RECT_F prompt = D2D1::RectF(
  4074.             TABLE_LEFT,
  4075.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  4076.             TABLE_RIGHT,
  4077.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  4078.         );
  4079.         pRT->DrawText(
  4080.             L"Choose a pocket...",
  4081.             (UINT32)wcslen(L"Choose a pocket..."),
  4082.             pTextFormat,
  4083.             &prompt,
  4084.             pBrush
  4085.         );
  4086.  
  4087.         return; // Skip normal turn/foul text
  4088.     }
  4089.     */
  4090.  
  4091.  
  4092.     // Show AI Thinking State (Unchanged from previous step)
  4093.     if (currentGameState == AI_THINKING && pTextFormat) {
  4094.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  4095.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  4096.         if (pThinkingBrush) {
  4097.             D2D1_RECT_F thinkingRect = p2Rect;
  4098.             thinkingRect.top += 20; // Offset within P2 box
  4099.             // Ensure default text alignment for this
  4100.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4101.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  4102.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  4103.             SafeRelease(&pThinkingBrush);
  4104.         }
  4105.     }
  4106.  
  4107.     SafeRelease(&pBrush);
  4108.  
  4109.     // --- Draw CHEAT MODE label if active ---
  4110.     if (cheatModeEnabled) {
  4111.         ID2D1SolidColorBrush* pCheatBrush = nullptr;
  4112.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  4113.         if (pCheatBrush && pTextFormat) {
  4114.             D2D1_RECT_F cheatTextRect = D2D1::RectF(
  4115.                 TABLE_LEFT + 10.0f,
  4116.                 TABLE_TOP + 10.0f,
  4117.                 TABLE_LEFT + 200.0f,
  4118.                 TABLE_TOP + 40.0f
  4119.             );
  4120.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  4121.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  4122.             pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
  4123.         }
  4124.         SafeRelease(&pCheatBrush);
  4125.     }
  4126. }
  4127.  
  4128. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  4129.     // Draw Border
  4130.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  4131.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4132.     if (!pBorderBrush) return;
  4133.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  4134.     SafeRelease(&pBorderBrush);
  4135.  
  4136.     // Create Gradient Fill
  4137.     ID2D1GradientStopCollection* pGradientStops = nullptr;
  4138.     ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  4139.     D2D1_GRADIENT_STOP gradientStops[4];
  4140.     gradientStops[0].position = 0.0f;
  4141.     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  4142.     gradientStops[1].position = 0.45f;
  4143.     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  4144.     gradientStops[2].position = 0.7f;
  4145.     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  4146.     gradientStops[3].position = 1.0f;
  4147.     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  4148.  
  4149.     pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  4150.     if (pGradientStops) {
  4151.         D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  4152.         props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  4153.         props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  4154.         pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  4155.         SafeRelease(&pGradientStops);
  4156.     }
  4157.  
  4158.     // Calculate Fill Height
  4159.     float fillRatio = 0;
  4160.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  4161.         // Determine if power meter should reflect shot power (human aiming or AI preparing)
  4162.     bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  4163.     // NEW Condition: AI is displaying its aim, so show its chosen power
  4164.     bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  4165.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  4166.  
  4167.     if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  4168.         fillRatio = shotPower / MAX_SHOT_POWER;
  4169.     }
  4170.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  4171.     D2D1_RECT_F fillRect = D2D1::RectF(
  4172.         powerMeterRect.left,
  4173.         powerMeterRect.bottom - fillHeight,
  4174.         powerMeterRect.right,
  4175.         powerMeterRect.bottom
  4176.     );
  4177.  
  4178.     if (pGradientBrush) {
  4179.         pRT->FillRectangle(&fillRect, pGradientBrush);
  4180.         SafeRelease(&pGradientBrush);
  4181.     }
  4182.  
  4183.     // Draw scale notches
  4184.     ID2D1SolidColorBrush* pNotchBrush = nullptr;
  4185.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  4186.     if (pNotchBrush) {
  4187.         for (int i = 0; i <= 8; ++i) {
  4188.             float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  4189.             pRT->DrawLine(
  4190.                 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  4191.                 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  4192.                 pNotchBrush,
  4193.                 1.5f
  4194.             );
  4195.         }
  4196.         SafeRelease(&pNotchBrush);
  4197.     }
  4198.  
  4199.     // Draw "Power" Label Below Meter
  4200.     if (pTextFormat) {
  4201.         ID2D1SolidColorBrush* pTextBrush = nullptr;
  4202.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  4203.         if (pTextBrush) {
  4204.             D2D1_RECT_F textRect = D2D1::RectF(
  4205.                 powerMeterRect.left - 20.0f,
  4206.                 powerMeterRect.bottom + 8.0f,
  4207.                 powerMeterRect.right + 20.0f,
  4208.                 powerMeterRect.bottom + 38.0f
  4209.             );
  4210.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  4211.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  4212.             pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  4213.             SafeRelease(&pTextBrush);
  4214.         }
  4215.     }
  4216.  
  4217.     // Draw Glow Effect if fully charged or fading out
  4218.     static float glowPulse = 0.0f;
  4219.     static bool glowIncreasing = true;
  4220.     static float glowFadeOut = 0.0f; // NEW: tracks fading out
  4221.  
  4222.     if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  4223.         // While fully charged, keep pulsing normally
  4224.         if (glowIncreasing) {
  4225.             glowPulse += 0.02f;
  4226.             if (glowPulse >= 1.0f) glowIncreasing = false;
  4227.         }
  4228.         else {
  4229.             glowPulse -= 0.02f;
  4230.             if (glowPulse <= 0.0f) glowIncreasing = true;
  4231.         }
  4232.         glowFadeOut = 1.0f; // Reset fade out to full
  4233.     }
  4234.     else if (glowFadeOut > 0.0f) {
  4235.         // If shot fired, gradually fade out
  4236.         glowFadeOut -= 0.02f;
  4237.         if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  4238.     }
  4239.  
  4240.     if (glowFadeOut > 0.0f) {
  4241.         ID2D1SolidColorBrush* pGlowBrush = nullptr;
  4242.         float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  4243.         pRT->CreateSolidColorBrush(
  4244.             D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  4245.             &pGlowBrush
  4246.         );
  4247.         if (pGlowBrush) {
  4248.             float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  4249.             float glowCenterY = powerMeterRect.top;
  4250.             D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  4251.                 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  4252.                 12.0f + 3.0f * glowPulse,
  4253.                 6.0f + 2.0f * glowPulse
  4254.             );
  4255.             pRT->FillEllipse(&glowEllipse, pGlowBrush);
  4256.             SafeRelease(&pGlowBrush);
  4257.         }
  4258.     }
  4259. }
  4260.  
  4261. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  4262.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  4263.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  4264.  
  4265.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  4266.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  4267.  
  4268.     if (!pWhiteBrush || !pRedBrush) {
  4269.         SafeRelease(&pWhiteBrush);
  4270.         SafeRelease(&pRedBrush);
  4271.         return;
  4272.     }
  4273.  
  4274.     // Draw White Ball Background
  4275.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  4276.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  4277.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  4278.  
  4279.  
  4280.     // Draw Red Dot for Spin Position
  4281.     float dotRadius = 4.0f;
  4282.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  4283.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  4284.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  4285.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  4286.  
  4287.     SafeRelease(&pWhiteBrush);
  4288.     SafeRelease(&pRedBrush);
  4289. }
  4290.  
  4291.  
  4292. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  4293.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  4294.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  4295.  
  4296.     // Ensure render target is valid before proceeding
  4297.     if (!pRT) return;
  4298.  
  4299.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  4300.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  4301.  
  4302.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  4303.     if (FAILED(hr)) {
  4304.         SafeRelease(&pBgBrush);
  4305.         SafeRelease(&pBallBrush);
  4306.         return; // Exit if brush creation fails
  4307.     }
  4308.  
  4309.     // Draw the background bar (rounded rect)
  4310.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  4311.     float baseAlpha = 0.8f;
  4312.     float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  4313.     float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  4314.     pBgBrush->SetOpacity(finalAlpha);
  4315.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  4316.     pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  4317.  
  4318.     // --- Draw small circles for pocketed balls inside the bar ---
  4319.  
  4320.     // Calculate dimensions based on the bar's height for better scaling
  4321.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  4322.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  4323.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  4324.     float padding = spacing * 0.75f; // Add padding from the edges
  4325.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  4326.  
  4327.     // Starting X positions with padding
  4328.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  4329.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  4330.  
  4331.     int p1DrawnCount = 0;
  4332.     int p2DrawnCount = 0;
  4333.     const int maxBallsToShow = 7; // Max balls per player in the bar
  4334.  
  4335.     for (const auto& b : balls) {
  4336.         if (b.isPocketed) {
  4337.             // Skip cue ball and 8-ball in this indicator
  4338.             if (b.id == 0 || b.id == 8) continue;
  4339.  
  4340.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  4341.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  4342.  
  4343.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  4344.                 pBallBrush->SetColor(b.color);
  4345.                 // Draw P1 balls from left to right
  4346.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4347.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  4348.                 p1DrawnCount++;
  4349.             }
  4350.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  4351.                 pBallBrush->SetColor(b.color);
  4352.                 // Draw P2 balls from right to left
  4353.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  4354.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  4355.                 p2DrawnCount++;
  4356.             }
  4357.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  4358.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  4359.         }
  4360.     }
  4361.  
  4362.     SafeRelease(&pBgBrush);
  4363.     SafeRelease(&pBallBrush);
  4364. }
  4365.  
  4366. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  4367.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  4368.         return; // Only show when placing/dragging
  4369.     }
  4370.  
  4371.     Ball* cueBall = GetCueBall();
  4372.     if (!cueBall) return;
  4373.  
  4374.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  4375.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  4376.  
  4377.     if (pGhostBrush) {
  4378.         D2D1_POINT_2F drawPos;
  4379.         if (isDraggingCueBall) {
  4380.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  4381.         }
  4382.         else {
  4383.             // If not dragging but in placement state, show at current ball pos
  4384.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  4385.         }
  4386.  
  4387.         // Check if the placement is valid before drawing differently?
  4388.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  4389.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  4390.  
  4391.         if (!isValid) {
  4392.             // Maybe draw red outline if invalid placement?
  4393.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  4394.         }
  4395.  
  4396.  
  4397.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  4398.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  4399.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  4400.  
  4401.         SafeRelease(&pGhostBrush);
  4402.     }
  4403. }
  4404.  
  4405. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
  4406.     /*  Never show the arrow while the player is still placing the
  4407.     cue-ball (ball-in-hand) – it otherwise hides behind the
  4408.     ghost-ball and can lock the UI.                               */
  4409.     if (currentGameState == BALL_IN_HAND_P1 ||
  4410.         currentGameState == BALL_IN_HAND_P2 ||
  4411.         currentGameState == PRE_BREAK_PLACEMENT)
  4412.     {
  4413.         return;
  4414.     }
  4415.  
  4416.     int pocketToIndicate = -1;
  4417.     // Whenever EITHER player has pocketed their first 7 and has called (human or AI),
  4418.     // we forcibly show their arrow—regardless of currentGameState.
  4419.     if ((currentPlayer == 1 && player1Info.ballsPocketedCount >= 7 && calledPocketP1 >= 0) ||
  4420.         (currentPlayer == 2 && player2Info.ballsPocketedCount >= 7 && calledPocketP2 >= 0))
  4421.     {
  4422.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4423.     }
  4424.     /*// A human player is actively choosing if they are in the CHOOSING_POCKET state.
  4425.     bool isHumanChoosing = (currentGameState == CHOOSING_POCKET_P1 || (currentGameState == CHOOSING_POCKET_P2 && !isPlayer2AI));
  4426.  
  4427.     if (isHumanChoosing) {
  4428.         // When choosing, show the currently selected pocket (which has a default).
  4429.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4430.     }
  4431.     else if (IsPlayerOnEightBall(currentPlayer)) {
  4432.         // If it's a normal turn but the player is on the 8-ball, show their called pocket as a reminder.
  4433.         pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  4434.     }*/
  4435.  
  4436.     if (pocketToIndicate < 0 || pocketToIndicate > 5) {
  4437.         return; // Don't draw if no pocket is selected or relevant.
  4438.     }
  4439.  
  4440.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  4441.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
  4442.     if (!pArrowBrush) return;
  4443.  
  4444.     // ... The rest of your arrow drawing geometry logic remains exactly the same ...
  4445.     // (No changes needed to the points/path drawing, only the logic above)
  4446.     D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
  4447.     float arrowHeadSize = HOLE_VISUAL_RADIUS * 0.5f;
  4448.     float arrowShaftLength = HOLE_VISUAL_RADIUS * 0.3f;
  4449.     float arrowShaftWidth = arrowHeadSize * 0.4f;
  4450.     float verticalOffsetFromPocketCenter = HOLE_VISUAL_RADIUS * 1.6f;
  4451.     D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
  4452.  
  4453.     if (targetPocketCenter.y == TABLE_TOP) {
  4454.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
  4455.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  4456.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  4457.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  4458.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  4459.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
  4460.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
  4461.     }
  4462.     else {
  4463.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
  4464.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  4465.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  4466.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
  4467.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
  4468.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  4469.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  4470.     }
  4471.  
  4472.     ID2D1PathGeometry* pPath = nullptr;
  4473.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  4474.         ID2D1GeometrySink* pSink = nullptr;
  4475.         if (SUCCEEDED(pPath->Open(&pSink))) {
  4476.             pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  4477.             pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
  4478.             pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
  4479.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4480.             pSink->Close();
  4481.             SafeRelease(&pSink);
  4482.             pRT->FillGeometry(pPath, pArrowBrush);
  4483.         }
  4484.         SafeRelease(&pPath);
  4485.     }
  4486.     SafeRelease(&pArrowBrush);
  4487. }
  4488. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement