Advertisement
alien_fx_fiend

Pool Modification 8BallPocketSelectionIndicator (UNTESTED)

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