Advertisement
alien_fx_fiend

Gemini's 3rd Attempt - Should Fix (Make Or Break!!)

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