alien_fx_fiend

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

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