alien_fx_fiend

2D StickPool Bkp b4 High-Precision Collision Detection

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