Advertisement
alien_fx_fiend

Restore Point Save Before 8-Ball + Foul + CPU Aim/Pocket Bugs Are Fixed Tomorrow !!

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