alien_fx_fiend

2D StickPool C++ D2D Ball Collision-Movement Rotation+ Bolded Current Player's PlayerInfoText

Aug 16th, 2025
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 295.84 KB | Source Code | 0 0
  1. ==++ Here's the full source code for (file 1\3) "Pool-Game-CloneV18"::: ++== cf. Github.com/alienfxfiend/Prelude-in-C/
  2. ```Pool-Game-CloneV18
  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 <array>
  11. #include <vector>
  12. #include <cmath>
  13. #include <string>
  14. #include <sstream> // Required for wostringstream
  15. #include <algorithm> // Required for std::max, std::min
  16. #include <ctime>    // Required for srand, time
  17. #include <cstdlib> // Required for srand, rand (often included by others, but good practice)
  18. #include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
  19. #include <mmsystem.h> // For PlaySound
  20. #include <tchar.h> //midi func
  21. #include <thread>
  22. #include <atomic>
  23. #include <wincodec.h>   // WIC
  24. #include "resource.h"
  25.  
  26. #ifndef HAS_STD_CLAMP
  27. template <typename T>
  28. T clamp(const T& v, const T& lo, const T& hi)
  29. {
  30.    return (v < lo) ? lo : (v > hi) ? hi : v;
  31. }
  32. namespace std { using ::clamp; }   // inject into std:: for seamless use
  33. #define HAS_STD_CLAMP
  34. #endif
  35.  
  36. #pragma comment(lib, "Comctl32.lib") // Link against common controls library
  37. #pragma comment(lib, "d2d1.lib")
  38. #pragma comment(lib, "dwrite.lib")
  39. #pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
  40. #pragma comment(lib, "windowscodecs.lib")
  41.  
  42. // --- Constants ---
  43. const float PI = 3.1415926535f;
  44. const float BALL_RADIUS = 10.0f;
  45. const float TABLE_LEFT = 100.0f;
  46. const float TABLE_TOP = 100.0f;
  47. const float TABLE_WIDTH = 700.0f;
  48. const float TABLE_HEIGHT = 350.0f;
  49. const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
  50. const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
  51. const float CUSHION_THICKNESS = 20.0f;
  52. // --- WITH these new constants ---
  53. const float CORNER_HOLE_VISUAL_RADIUS = 22.0f;
  54. const float MIDDLE_HOLE_VISUAL_RADIUS = 26.0f; // Middle pockets are now ~18% bigger
  55. //const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
  56. //const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
  57. const float MAX_SHOT_POWER = 15.0f;
  58. const float FRICTION = 0.985f; // Friction factor per frame
  59. const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
  60. const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
  61. const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
  62. const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  63. const UINT ID_TIMER = 1;
  64. const int TARGET_FPS = 60; // Target frames per second for timer
  65.  
  66. // --- Enums ---
  67. // --- MODIFIED/NEW Enums ---
  68. enum GameState {
  69.    SHOWING_DIALOG,     // NEW: Game is waiting for initial dialog input
  70.    PRE_BREAK_PLACEMENT,// Player placing cue ball for break
  71.    BREAKING,           // Player is aiming/shooting the break shot
  72.    CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
  73.    CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
  74.    AIMING,             // Player is aiming
  75.    AI_THINKING,        // NEW: AI is calculating its move
  76.    SHOT_IN_PROGRESS,   // Balls are moving
  77.    ASSIGNING_BALLS,    // Turn after break where ball types are assigned
  78.    PLAYER1_TURN,
  79.    PLAYER2_TURN,
  80.    BALL_IN_HAND_P1,
  81.    BALL_IN_HAND_P2,
  82.    GAME_OVER
  83. };
  84.  
  85. enum BallType {
  86.    NONE,
  87.    SOLID,  // Yellow (1-7)
  88.    STRIPE, // Red (9-15)
  89.    EIGHT_BALL, // Black (8)
  90.    CUE_BALL // White (0)
  91. };
  92.  
  93. // NEW Enums for Game Mode and AI Difficulty
  94. enum GameMode {
  95.    HUMAN_VS_HUMAN,
  96.    HUMAN_VS_AI
  97. };
  98.  
  99. enum AIDifficulty {
  100.    EASY,
  101.    MEDIUM,
  102.    HARD
  103. };
  104.  
  105. enum OpeningBreakMode {
  106.    CPU_BREAK,
  107.    P1_BREAK,
  108.    FLIP_COIN_BREAK
  109. };
  110.  
  111. // NEW: Enum and arrays for table color options
  112. enum TableColor {
  113.    INDIGO,
  114.    TAN,
  115.    TEAL,
  116.    GREEN,
  117.    RED
  118. };
  119.  
  120. // --- Structs ---
  121. struct Ball {
  122.    int id;             // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
  123.    BallType type;
  124.    float x, y;
  125.    float vx, vy;
  126.    D2D1_COLOR_F color;
  127.    bool isPocketed;
  128.    float rotationAngle; // radians, used for drawing rotation (visual spin)
  129.    float rotationAxis;  // direction (radians) perpendicular to travel - used to offset highlight
  130. };
  131.  
  132. struct PlayerInfo {
  133.    BallType assignedType;
  134.    int ballsPocketedCount;
  135.    std::wstring name;
  136. };
  137.  
  138. // --- Global Variables ---
  139.  
  140. // Direct2D & DirectWrite
  141. ID2D1Factory* pFactory = nullptr;
  142. //ID2D1Factory* g_pD2DFactory = nullptr;
  143. ID2D1HwndRenderTarget* pRenderTarget = nullptr;
  144. IDWriteFactory* pDWriteFactory = nullptr;
  145. IDWriteTextFormat* pTextFormat = nullptr;
  146. IDWriteTextFormat* pTextFormatBold = nullptr;
  147. IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
  148. IDWriteTextFormat* pBallNumFormat = nullptr;
  149. // -------------------- Globals for mask creation --------------------
  150. static IWICImagingFactory* g_pWICFactory_masks = nullptr;
  151. static std::vector<std::vector<uint8_t>> pocketMasks; // 6 masks, each maskWidth*maskHeight bytes (0/1)
  152. static int pocketMaskWidth = 0;
  153. static int pocketMaskHeight = 0;
  154. static float pocketMaskOriginX = TABLE_LEFT;
  155. static float pocketMaskOriginY = TABLE_TOP;
  156. static float pocketMaskScale = 1.0f; // pixels per world unit
  157. static const uint8_t POCKET_ALPHA_THRESHOLD = 48; // same idea as earlier
  158.  
  159. // Game State
  160. HWND hwndMain = nullptr;
  161. GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
  162. std::vector<Ball> balls;
  163. int currentPlayer = 1; // 1 or 2
  164. PlayerInfo player1Info = { BallType::NONE, 0, L"Vince Woods"/*"Player 1"*/ };
  165. PlayerInfo player2Info = { BallType::NONE, 0, L"Virtus Pro"/*"CPU"*/ }; // Default P2 name
  166. bool foulCommitted = false;
  167. std::wstring gameOverMessage = L"";
  168. bool firstBallPocketedAfterBreak = false;
  169. std::vector<int> pocketedThisTurn;
  170. // --- NEW: 8-Ball Pocket Call Globals ---
  171. int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
  172. int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
  173. int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
  174. std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
  175.     // --- NEW: Remember which pocket the 8?ball actually went into last shot
  176. int lastEightBallPocketIndex = -1;
  177. //int lastPocketedIndex = -1; // pocket index (0–5) of the last ball pocketed
  178. int called = -1;
  179. bool cueBallPocketed = false;
  180.  
  181. // --- NEW: Foul Tracking Globals ---
  182. int firstHitBallIdThisShot = -1;      // ID of the first object ball hit by cue ball (-1 if none)
  183. bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
  184. bool railHitAfterContact = false;     // Did any ball hit a rail AFTER cue hit an object ball?
  185. // --- End New Foul Tracking Globals ---
  186.  
  187. // NEW Game Mode/AI Globals
  188. GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
  189. AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
  190. OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
  191. bool isPlayer2AI = false;           // Is Player 2 controlled by AI?
  192. bool aiTurnPending = false;         // Flag: AI needs to take its turn when possible
  193. // bool aiIsThinking = false;       // Replaced by AI_THINKING game state
  194. // NEW: Flag to indicate if the current shot is the opening break of the game
  195. bool isOpeningBreakShot = false;
  196.  
  197. // NEW: For AI shot planning and visualization
  198. struct AIPlannedShot {
  199.    float angle;
  200.    float power;
  201.    float spinX;
  202.    float spinY;
  203.    bool isValid; // Is there a valid shot planned?
  204. };
  205. AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
  206. bool aiIsDisplayingAim = false;    // True when AI has decided a shot and is in "display aim" mode
  207. int aiAimDisplayFramesLeft = 0;  // How many frames left to display AI aim
  208. const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
  209.  
  210. // Input & Aiming
  211. POINT ptMouse = { 0, 0 };
  212. bool isAiming = false;
  213. bool isDraggingCueBall = false;
  214. // --- ENSURE THIS LINE EXISTS HERE ---
  215. bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
  216. // --- End Ensure ---
  217. bool isSettingEnglish = false;
  218. D2D1_POINT_2F aimStartPoint = { 0, 0 };
  219. float cueAngle = 0.0f;
  220. float shotPower = 0.0f;
  221. float cueSpinX = 0.0f; // Range -1 to 1
  222. float cueSpinY = 0.0f; // Range -1 to 1
  223. float pocketFlashTimer = 0.0f;
  224. bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
  225. int draggingBallId = -1;
  226. bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
  227. MCIDEVICEID midiDeviceID = 0; //midi func
  228. std::atomic<bool> isMusicPlaying(false); //midi func
  229. std::thread musicThread; //midi func
  230. void StartMidi(HWND hwnd, const TCHAR* midiPath);
  231. void StopMidi();
  232.  
  233. // NEW: Global for selected table color and definitions
  234. TableColor selectedTableColor = INDIGO; // Default color
  235. const WCHAR* tableColorNames[] = { L"Indigo", L"Tan", L"Teal", L"Green", L"Red" };
  236. const D2D1_COLOR_F tableColorValues[] = {
  237. D2D1::ColorF(0.05f, 0.09f, 0.28f),       // Indigo
  238. D2D1::ColorF(0.3529f, 0.3137f, 0.2196f), // Tan
  239. 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)
  240. D2D1::ColorF(0.1608f, 0.4000f, 0.1765f), // Green
  241. D2D1::ColorF(0.3882f, 0.1059f, 0.10196f) // Red
  242. };
  243.  
  244. // UI Element Positions
  245. D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 20, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 50, TABLE_BOTTOM };
  246. D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
  247. D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
  248. float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
  249. D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
  250.  
  251. // Corrected Pocket Center Positions (aligned with table corners/edges)
  252. const D2D1_POINT_2F pocketPositions[6] = {
  253.     {TABLE_LEFT, TABLE_TOP},                           // Top-Left
  254.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP},      // Top-Middle
  255.     {TABLE_RIGHT, TABLE_TOP},                          // Top-Right
  256.     {TABLE_LEFT, TABLE_BOTTOM},                        // Bottom-Left
  257.     {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM},   // Bottom-Middle
  258.     {TABLE_RIGHT, TABLE_BOTTOM}                        // Bottom-Right
  259. };
  260.  
  261. // Colors
  262. //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)
  263. // This is now a variable that can be changed, not a constant.
  264. D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.05f, 0.09f, 0.28f); // Default to Indigo
  265. //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)
  266. /*
  267. 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);
  268. Hex: Teal=#00abc2 Tan=#7c6d53 Teal2=#03adc2 xPurple=#314b69 ?Tan=#88785b Red=#631b1a
  269. */
  270. const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  271. //const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
  272. const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  273. const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
  274. const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  275. const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Goldenrod); // Solids = Yellow Goldenrod
  276. const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::DarkOrchid);   // Stripes = Red DarkOrchid
  277. const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
  278. const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  279. const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
  280. //const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
  281. const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
  282. const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
  283.  
  284. // --------------------------------------------------------------------
  285. //  Realistic colours for each id (0-15)
  286. //  0 = cue-ball (white) | 1-7 solids | 8 = eight-ball | 9-15 stripes
  287. // --------------------------------------------------------------------
  288. static const D2D1_COLOR_F BALL_COLORS[16] =
  289. {
  290.     D2D1::ColorF(D2D1::ColorF::White),          // 0  cue
  291.     D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 1  yellow
  292.     D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 2  blue
  293.     D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 3  red
  294.     D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 4  purple
  295.     D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 5  orange
  296.     D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 6  green
  297.     D2D1::ColorF(0.50f, 0.05f, 0.05f),          // 7  maroon / burgundy
  298.     D2D1::ColorF(D2D1::ColorF::Black),          // 8  black
  299.     D2D1::ColorF(1.00f, 0.85f, 0.00f),          // 9  (yellow stripe)
  300.     D2D1::ColorF(0.05f, 0.30f, 1.00f),          // 10 blue stripe
  301.     D2D1::ColorF(0.90f, 0.10f, 0.10f),          // 11 red stripe
  302.     D2D1::ColorF(0.55f, 0.25f, 0.85f),          // 12 purple stripe
  303.     D2D1::ColorF(1.00f, 0.55f, 0.00f),          // 13 orange stripe
  304.     D2D1::ColorF(0.00f, 0.60f, 0.30f),          // 14 green stripe
  305.     D2D1::ColorF(0.50f, 0.05f, 0.05f)           // 15 maroon stripe
  306. };
  307.  
  308. // Quick helper
  309. inline D2D1_COLOR_F GetBallColor(int id)
  310. {
  311.     return (id >= 0 && id < 16) ? BALL_COLORS[id]
  312.         : D2D1::ColorF(D2D1::ColorF::White);
  313. }
  314.  
  315. // --- Forward Declarations ---
  316. HRESULT CreateDeviceResources();
  317. void DiscardDeviceResources();
  318. void OnPaint();
  319. void OnResize(UINT width, UINT height);
  320. void InitGame();
  321. void GameUpdate();
  322. void UpdatePhysics();
  323. void CheckCollisions();
  324. bool CheckPockets(); // Returns true if any ball was pocketed
  325. void ProcessShotResults();
  326. void ApplyShot(float power, float angle, float spinX, float spinY);
  327. void RespawnCueBall(bool behindHeadstring);
  328. bool AreBallsMoving();
  329. void SwitchTurns();
  330. //bool AssignPlayerBallTypes(BallType firstPocketedType);
  331. bool AssignPlayerBallTypes(BallType firstPocketedType,
  332.     bool creditShooter = true);
  333. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
  334. Ball* GetBallById(int id);
  335. Ball* GetCueBall();
  336. //void PlayGameMusic(HWND hwnd); //midi func
  337. void AIBreakShot();
  338.  
  339. // Drawing Functions
  340. void DrawScene(ID2D1RenderTarget* pRT);
  341. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
  342. void DrawBalls(ID2D1RenderTarget* pRT);
  343. void DrawCueStick(ID2D1RenderTarget* pRT);
  344. void DrawAimingAids(ID2D1RenderTarget* pRT);
  345. void DrawUI(ID2D1RenderTarget* pRT);
  346. void DrawPowerMeter(ID2D1RenderTarget* pRT);
  347. void DrawSpinIndicator(ID2D1RenderTarget* pRT);
  348. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
  349. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
  350. // NEW
  351. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
  352.  
  353. // Helper Functions
  354. float GetDistance(float x1, float y1, float x2, float y2);
  355. float GetDistanceSq(float x1, float y1, float x2, float y2);
  356. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
  357. //template <typename T> void SafeRelease(T** ppT);
  358. template <typename T>
  359. void SafeRelease(T** ppT) {
  360.     if (*ppT) {
  361.         (*ppT)->Release();
  362.         *ppT = nullptr;
  363.     }
  364. }
  365. static bool IsBallInPocketBlackArea(const Ball& b, int p);
  366. static std::vector<std::vector<std::array<D2D1_POINT_2F, 4>>> g_pocketBezierCache;
  367. static bool g_pocketBezierCacheInitialized = false;
  368.  
  369. // --- NEW HELPER FORWARD DECLARATIONS ---
  370. bool IsPlayerOnEightBall(int player);
  371. void CheckAndTransitionToPocketChoice(int playerID);
  372. // --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
  373. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
  374. // --- End Forward Declaration ---
  375. 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
  376.  
  377. // Return the visual pocket radius for pocket index p
  378. inline float GetPocketVisualRadius(int p)
  379. {
  380.     // Middle pockets are larger; corners use the corner radius
  381.     return (p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  382. }
  383. // -----------------------------
  384. // Pocket / capsule collision helper
  385. // -----------------------------
  386. static inline float Dot(const D2D1_POINT_2F& a, const D2D1_POINT_2F& b) {
  387.     return a.x * b.x + a.y * b.y;
  388. }
  389. static inline float Clampf(float v, float a, float b) {
  390.     return (v < a) ? a : (v > b ? b : v);
  391. }
  392.  
  393. // Ensure WIC factory (call once)
  394. bool EnsureWICFactory_Masks()
  395. {
  396.     if (g_pWICFactory_masks) return true;
  397.     HRESULT hr = CoCreateInstance(
  398.         CLSID_WICImagingFactory,
  399.         nullptr,
  400.         CLSCTX_INPROC_SERVER,
  401.         IID_PPV_ARGS(&g_pWICFactory_masks));
  402.     return SUCCEEDED(hr);
  403. }
  404.  
  405. // Cleanup
  406. void ShutdownPocketMasks_D2D()
  407. {
  408.     pocketMasks.clear();
  409.     pocketMaskWidth = pocketMaskHeight = 0;
  410.     pocketMaskOriginX = pocketMaskOriginY = 0.0f;
  411.     pocketMaskScale = 1.0f;
  412.     if (g_pWICFactory_masks) { g_pWICFactory_masks->Release(); g_pWICFactory_masks = nullptr; }
  413. }
  414.  
  415. // ----------------------------------------------------------------------
  416. // CreatePocketMasks_D2D  (uses your pocket path geometry)
  417. // ----------------------------------------------------------------------
  418. void CreatePocketMasks_D2D(int pixelWidth, int pixelHeight, float originX, float originY, float scale)
  419. {
  420.     if (!EnsureWICFactory_Masks()) return;
  421.     if (!pFactory) return;
  422.  
  423.     pocketMaskWidth = pixelWidth;
  424.     pocketMaskHeight = pixelHeight;
  425.     pocketMaskOriginX = originX;
  426.     pocketMaskOriginY = originY;
  427.     pocketMaskScale = scale;
  428.  
  429.     pocketMasks.clear();
  430.     pocketMasks.resize(6);
  431.  
  432.     // Create WIC bitmap + D2D render target
  433.     IWICBitmap* pWicBitmap = nullptr;
  434.     HRESULT hr = g_pWICFactory_masks->CreateBitmap(
  435.         pocketMaskWidth, pocketMaskHeight,
  436.         GUID_WICPixelFormat32bppPBGRA,
  437.         WICBitmapCacheOnLoad,
  438.         &pWicBitmap);
  439.     if (FAILED(hr) || !pWicBitmap) {
  440.         SafeRelease(&pWicBitmap);
  441.         return;
  442.     }
  443.  
  444.     D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
  445.     rtProps.dpiX = 96.0f;
  446.     rtProps.dpiY = 96.0f;
  447.  
  448.     ID2D1RenderTarget* pWicRT = nullptr;
  449.     hr = pFactory->CreateWicBitmapRenderTarget(pWicBitmap, rtProps, &pWicRT);
  450.     if (FAILED(hr) || !pWicRT) {
  451.         SafeRelease(&pWicBitmap);
  452.         return;
  453.     }
  454.  
  455.     // Create pocket brush + rim brush (you provided both; mask uses pocket brush)
  456.     ID2D1SolidColorBrush* pPocketBrush = nullptr;
  457.     //ID2D1SolidColorBrush* pRimBrush = nullptr;
  458.     pWicRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  459.     //pWicRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  460.  
  461.     // Set transform so world -> mask pixels mapping is consistent:
  462.     //D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-pocketMaskOriginX, -pocketMaskOriginY) *
  463.         //D2D1::Matrix3x2F::Scale(pocketMaskScale, pocketMaskScale);
  464.     //pWicRT->SetTransform(transform);
  465.  
  466.     // For each pocket: clear, draw exact pocket path (your code), EndDraw, lock & read pixels
  467.     for (int i = 0; i < 6; ++i) {
  468.         pWicRT->BeginDraw();
  469.         pWicRT->Clear(D2D1::ColorF(0, 0.0f)); // fully transparent background
  470.  
  471.                 // --- FOOLPROOF FIX: Apply a unique transform for EACH pocket ---
  472.         // This ensures the pocket shape is drawn correctly on its mask regardless of its position.
  473.         D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-pocketPositions[i].x, -pocketPositions[i].y) *
  474.             D2D1::Matrix3x2F::Scale(pocketMaskScale, pocketMaskScale) *
  475.             D2D1::Matrix3x2F::Translation(pocketMaskWidth / 2.0f, pocketMaskHeight / 2.0f);
  476.         pWicRT->SetTransform(transform);
  477.  
  478.         // --- Your pocket geometry (copied verbatim, using pPocketBrush) ---
  479.         if (pPocketBrush) {
  480.         //if (pPocketBrush && pRimBrush) {
  481.             ID2D1PathGeometry* pPath = nullptr;
  482.             if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath)) && pPath) {
  483.                 ID2D1GeometrySink* pSink = nullptr;
  484.                 if (SUCCEEDED(pPath->Open(&pSink)) && pSink) {
  485.                     float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  486.                     // FIX: Increase the multipliers for corner pockets to make them larger. default= 1.5 :1.7 (1.5) | 1.1 :1.3 (1.1)=>1.0:2.0[1.7]|1.1:1.3
  487.                     float mouthRadius = currentVisualRadius * ((i == 1 || i == 4) ? 1.0f : 2.7f); // Corners are now 1.7x
  488.                     float backRadius = currentVisualRadius * ((i == 1 || i == 4) ? 1.1f : 2.0f);  // Corners are now 1.3x
  489.                     //float mouthRadius = currentVisualRadius * 1.5f;
  490.                     //float backRadius = currentVisualRadius * 1.1f;
  491.                     D2D1_POINT_2F center = pocketPositions[i];
  492.                     D2D1_POINT_2F p1, p2;
  493.                     D2D1_SWEEP_DIRECTION sweep;
  494.  
  495.                     if (i == 0) {
  496.                         p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  497.                         p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  498.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  499.                     }
  500.                     else if (i == 2) {
  501.                         p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  502.                         p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  503.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  504.                     }
  505.                     else if (i == 3) {
  506.                         p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  507.                         p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  508.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  509.                     }
  510.                     else if (i == 5) {
  511.                         p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  512.                         p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  513.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  514.                     }
  515.                     else if (i == 1) { // top-middle
  516.                         p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  517.                         p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  518.                         // FIX: The arc must sweep counter-clockwise to open into the table.
  519.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  520.                         //sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  521.                     }
  522.                     else { // i == 4 bottom-middle
  523.                         p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  524.                         p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  525.                         // FIX: The arc must sweep counter-clockwise to open into the table.
  526.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  527.                         //sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  528.                     }
  529.  
  530.                     pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  531.                     pSink->AddLine(p1);
  532.                     pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  533.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  534.                     pSink->Close();
  535.                     SafeRelease(&pSink);
  536.  
  537.                     // Fill the pocket geometry using pocket brush (black hole area)
  538.                     pWicRT->FillGeometry(pPath, pPocketBrush);
  539.                 }
  540.                 SafeRelease(&pPath);
  541.             }
  542.         }
  543.         // --- end pocket geometry ---
  544.  
  545.         hr = pWicRT->EndDraw();
  546.         (void)hr; // continue even if EndDraw fails
  547.  
  548.         // Lock the WIC bitmap and extract alpha => build mask
  549.         WICRect lockRect = { 0, 0, pocketMaskWidth, pocketMaskHeight };
  550.         IWICBitmapLock* pLock = nullptr;
  551.         hr = pWicBitmap->Lock(&lockRect, WICBitmapLockRead, &pLock);
  552.         if (SUCCEEDED(hr) && pLock) {
  553.             UINT cbStride = 0;
  554.             UINT cbBufferSize = 0;
  555.             BYTE* pv = nullptr;
  556.             hr = pLock->GetDataPointer(&cbBufferSize, &pv);
  557.             pLock->GetStride(&cbStride);
  558.  
  559.             if (SUCCEEDED(hr) && pv) {
  560.                 pocketMasks[i].assign(pocketMaskWidth * pocketMaskHeight, 0);
  561.                 for (int y = 0; y < pocketMaskHeight; ++y) {
  562.                     BYTE* row = pv + y * cbStride;
  563.                     int base = y * pocketMaskWidth;
  564.                     for (int x = 0; x < pocketMaskWidth; ++x) {
  565.                         BYTE a = row[x * 4 + 3]; // premultiplied BGRA alpha at offset 3
  566.                         pocketMasks[i][base + x] = (a > POCKET_ALPHA_THRESHOLD) ? 1 : 0;
  567.                     }
  568.                 }
  569.             }
  570.             pLock->Release();
  571.         }
  572.     } // end for pockets
  573.  
  574.     // cleanup
  575.     SafeRelease(&pPocketBrush);
  576.     //SafeRelease(&pRimBrush);
  577.     SafeRelease(&pWicRT);
  578.     SafeRelease(&pWicBitmap);
  579. }
  580.  
  581. // Create six per-pocket masks by rendering each pocket individually into a WIC bitmap.
  582. // pixelWidth/Height = resolution for the masks
  583. // originX/originY = world coordinate mapping for mask pixel (0,0) -> these world coords
  584. // scale = pixels per world unit (1.0f = 1 pixel per D2D unit)
  585. /*void CreatePocketMasks_D2D(int pixelWidth, int pixelHeight, float originX, float originY, float scale)
  586. {
  587.     if (!EnsureWICFactory_Masks()) return;
  588.     if (!pFactory) return; // requires your ID2D1Factory*
  589.  
  590.     pocketMaskWidth = pixelWidth;
  591.     pocketMaskHeight = pixelHeight;
  592.     pocketMaskOriginX = originX;
  593.     pocketMaskOriginY = originY;
  594.     pocketMaskScale = scale;
  595.  
  596.     pocketMasks.clear();
  597.     pocketMasks.resize(6); // six pockets
  598.  
  599.     // Create a WIC bitmap and a D2D render-target that draws into it.
  600.     IWICBitmap* pWicBitmap = nullptr;
  601.     HRESULT hr = g_pWICFactory_masks->CreateBitmap(
  602.         pocketMaskWidth, pocketMaskHeight,
  603.         GUID_WICPixelFormat32bppPBGRA,
  604.         WICBitmapCacheOnLoad,
  605.         &pWicBitmap);
  606.     if (FAILED(hr) || !pWicBitmap) {
  607.         SafeRelease(&pWicBitmap);
  608.         return;
  609.     }
  610.  
  611.     D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
  612.     rtProps.dpiX = 96.0f;
  613.     rtProps.dpiY = 96.0f;
  614.  
  615.     ID2D1RenderTarget* pWicRT = nullptr;
  616.     hr = pFactory->CreateWicBitmapRenderTarget(pWicBitmap, rtProps, &pWicRT);
  617.     if (FAILED(hr) || !pWicRT) {
  618.         SafeRelease(&pWicBitmap);
  619.         return;
  620.     }
  621.  
  622.     // Create a brush for drawing the pocket shape (solid black)
  623.     ID2D1SolidColorBrush* pBrush = nullptr;
  624.     pWicRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 1.0f), &pBrush);
  625.  
  626.     // Set transform: world -> pixel = (world - origin) * scale
  627.     D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-pocketMaskOriginX, -pocketMaskOriginY) *
  628.         D2D1::Matrix3x2F::Scale(pocketMaskScale, pocketMaskScale);
  629.     pWicRT->SetTransform(transform);
  630.  
  631.     // For each pocket: clear, draw that pocket's black area, EndDraw, lock & read pixels into pocketMasks[i]
  632.     for (int p = 0; p < 6; ++p) {
  633.         pWicRT->BeginDraw();
  634.         // Clear to transparent
  635.         pWicRT->Clear(D2D1::ColorF(0, 0.0f));
  636.  
  637.         // Draw only the pocket p — use the same geometry you use for on-screen pockets.
  638.         // Example draws a filled ellipse of the visual pocket radius; if you draw semicircles
  639.         // or a path on screen, replicate that exact path here for pixel-perfect masks.
  640.         float visualRadius = GetPocketVisualRadius(p); // uses your helper (MIDDLE vs CORNER)
  641.         D2D1_ELLIPSE e = D2D1::Ellipse(D2D1::Point2F(pocketPositions[p].x, pocketPositions[p].y), visualRadius, visualRadius);
  642.         pWicRT->FillEllipse(&e, pBrush);
  643. */
  644.         /*ID2D1SolidColorBrush* pPocketBrush = nullptr;
  645.         ID2D1SolidColorBrush* pRimBrush = nullptr;
  646.         pWicRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  647.         pWicRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  648.         if (pPocketBrush && pRimBrush) {
  649.             for (int i = 0; i < 6; ++i) {
  650.                 ID2D1PathGeometry* pPath = nullptr;
  651.                 pFactory->CreatePathGeometry(&pPath);
  652.                 if (pPath) {
  653.                     ID2D1GeometrySink* pSink = nullptr;
  654.                     if (SUCCEEDED(pPath->Open(&pSink))) {
  655.                         float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  656.                         float mouthRadius = currentVisualRadius * 1.5f;
  657.                         float backRadius = currentVisualRadius * 1.1f;
  658.                         D2D1_POINT_2F center = pocketPositions[i];
  659.                         D2D1_POINT_2F p1, p2;
  660.                         D2D1_SWEEP_DIRECTION sweep;
  661.                         if (i == 0) {
  662.                             p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  663.                             p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  664.                             sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  665.                         }
  666.                         else if (i == 2) {
  667.                             p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  668.                             p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  669.                             sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  670.                         }
  671.                         else if (i == 3) {
  672.                             p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  673.                             p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  674.                             sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  675.                         }
  676.                         else if (i == 5) {
  677.                             p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  678.                             p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  679.                             sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  680.                         }
  681.                         else if (i == 1) {
  682.                             p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  683.                             p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  684.                             sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  685.                         }
  686.                         else {
  687.                             p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  688.                             p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  689.                             sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  690.                         }
  691.                         pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  692.                         pSink->AddLine(p1);
  693.                         pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  694.                         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  695.                         pSink->Close();
  696.                         SafeRelease(&pSink);
  697.                         pWicRT->FillGeometry(pPath, pPocketBrush);
  698.                         // Draw the inner rim for a beveled effect (Start)
  699.                         D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(0.8f, 0.8f, center);
  700.                         ID2D1TransformedGeometry* pTransformedGeo = nullptr;
  701.                         pFactory->CreateTransformedGeometry(pPath, &scale, &pTransformedGeo);
  702.                         if (pTransformedGeo) {
  703.                             pWicRT->FillGeometry(pTransformedGeo, pRimBrush);
  704.                             SafeRelease(&pTransformedGeo);
  705.                         } //End
  706.                     }
  707.                     SafeRelease(&pPath);
  708.                 }
  709.             }
  710.         }
  711.         SafeRelease(&pPocketBrush);
  712.         SafeRelease(&pRimBrush);*/
  713. /*
  714.         // If your on-screen pocket is a semicircle / capsule / complex path,
  715.         // create & fill the same path geometry here instead of FillEllipse.
  716.  
  717.         hr = pWicRT->EndDraw();
  718.         if (FAILED(hr)) {
  719.             // continue but mask may be invalid
  720.         }
  721.  
  722.         // Lock WIC bitmap and read pixels
  723.         WICRect lockRect = { 0, 0, pocketMaskWidth, pocketMaskHeight };
  724.         IWICBitmapLock* pLock = nullptr;
  725.         hr = pWicBitmap->Lock(&lockRect, WICBitmapLockRead, &pLock);
  726.         if (SUCCEEDED(hr) && pLock) {
  727.             UINT cbStride = 0;
  728.             UINT cbBufferSize = 0;
  729.             BYTE* pv = nullptr;
  730.             hr = pLock->GetDataPointer(&cbBufferSize, &pv);
  731.             pLock->GetStride(&cbStride);
  732.  
  733.             if (SUCCEEDED(hr) && pv) {
  734.                 pocketMasks[p].assign(pocketMaskWidth * pocketMaskHeight, 0);
  735.                 for (int y = 0; y < pocketMaskHeight; ++y) {
  736.                     BYTE* row = pv + y * cbStride;
  737.                     int base = y * pocketMaskWidth;
  738.                     for (int x = 0; x < pocketMaskWidth; ++x) {
  739.                         BYTE a = row[x * 4 + 3]; // premultiplied BGRA -> alpha at offset 3
  740.                         pocketMasks[p][base + x] = (a > POCKET_ALPHA_THRESHOLD) ? 1 : 0;
  741.                     }
  742.                 }
  743.             }
  744.             pLock->Release();
  745.         }
  746.     } // end loop pockets
  747.  
  748.     // cleanup
  749.     SafeRelease(&pBrush);
  750.     SafeRelease(&pWicRT);
  751.     SafeRelease(&pWicBitmap);
  752. }*/
  753.  
  754. //orig function
  755. /*
  756. // Create pixel mask by rendering pocket shapes into a WIC bitmap via Direct2D
  757. // pixelWidth/height = desired mask resolution in pixels
  758. // originX/originY = world coordinate representing pixel (0,0) origin of mask
  759. // scale = pixels per world unit (use 1.0f for 1 pixel per D2D unit; >1 for supersampling)
  760. void CreatePocketMask_D2D(int pixelWidth, int pixelHeight, float originX, float originY, float scale)
  761. {
  762.     if (!EnsureWICFactory()) return;
  763.     if (!pFactory) return; // requires your ID2D1Factory* (global in your code)
  764.  
  765.     maskWidth = pixelWidth;
  766.     maskHeight = pixelHeight;
  767.     maskOriginX = originX;
  768.     maskOriginY = originY;
  769.     maskScale = scale;
  770.     pocketMask.assign(maskWidth * maskHeight, 0);
  771.  
  772.     // Create a WIC bitmap (32bpp premultiplied BGRA) to be the render target surface
  773.     IWICBitmap* pWicBitmap = nullptr;
  774.     HRESULT hr = g_pWICFactory->CreateBitmap(
  775.         maskWidth, maskHeight,
  776.         GUID_WICPixelFormat32bppPBGRA,
  777.         WICBitmapCacheOnLoad,
  778.         &pWicBitmap);
  779.     if (FAILED(hr) || !pWicBitmap) {
  780.         if (pWicBitmap) pWicBitmap->Release();
  781.         return;
  782.     }
  783.  
  784.     // Create a Direct2D render target that draws into the WIC bitmap
  785.     // Use default D2D render target properties but ensure DPI = 96 (pixels align)
  786.     D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
  787.     rtProps.dpiX = 96.0f;
  788.     rtProps.dpiY = 96.0f;
  789.     ID2D1RenderTarget* pWicRT = nullptr;
  790.     hr = pFactory->CreateWicBitmapRenderTarget(
  791.         pWicBitmap,
  792.         rtProps,
  793.         &pWicRT);
  794.     if (FAILED(hr) || !pWicRT) {
  795.         pWicBitmap->Release();
  796.         return;
  797.     }
  798.  
  799.     // Create a black brush for pocket fill
  800.     ID2D1SolidColorBrush* pBlackBrush = nullptr;
  801.     pWicRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 1.0f), &pBlackBrush);
  802.  
  803.     // Set transform: scale then translate so we can draw in world coords.
  804.     // world -> pixel: (world - origin) * scale
  805.     D2D1::Matrix3x2F transform = D2D1::Matrix3x2F::Translation(-maskOriginX, -maskOriginY) *
  806.         D2D1::Matrix3x2F::Scale(maskScale, maskScale);
  807.     pWicRT->SetTransform(transform);
  808.  
  809.     // Begin drawing
  810.     pWicRT->BeginDraw();
  811.     pWicRT->Clear(D2D1::ColorF(0, 0.0f)); // transparent
  812.  
  813.     // ---- Draw pocket shapes (use your exact same Direct2D math here) ----
  814.     // For pixel-perfect match you MUST draw the *same* shapes/paths you use in the screen render.
  815.     // The example below draws filled circles at pocketPositions; replace with your path code if needed.
  816. */
  817. /*    for (int i = 0; i < 6; ++i) {
  818.         float visualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  819.         // Draw as an ellipse centered at pocketPositions[i] in *world* coords — transform handles scale/origin.
  820.         D2D1_ELLIPSE e = D2D1::Ellipse(D2D1::Point2F(pocketPositions[i].x, pocketPositions[i].y), visualRadius, visualRadius);
  821.         pWicRT->FillEllipse(&e, pBlackBrush);
  822. */
  823. /*
  824. ID2D1SolidColorBrush* pPocketBrush = nullptr;
  825. ID2D1SolidColorBrush* pRimBrush = nullptr;
  826. pWicRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  827. pWicRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  828. if (pPocketBrush && pRimBrush) {
  829.     for (int i = 0; i < 6; ++i) {
  830.         ID2D1PathGeometry* pPath = nullptr;
  831.         pFactory->CreatePathGeometry(&pPath);
  832.         if (pPath) {
  833.             ID2D1GeometrySink* pSink = nullptr;
  834.             if (SUCCEEDED(pPath->Open(&pSink))) {
  835.                 float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  836.                 float mouthRadius = currentVisualRadius * 1.5f;
  837.                 float backRadius = currentVisualRadius * 1.1f;
  838.                 D2D1_POINT_2F center = pocketPositions[i];
  839.                 D2D1_POINT_2F p1, p2;
  840.                 D2D1_SWEEP_DIRECTION sweep;
  841.                 if (i == 0) {
  842.                     p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  843.                     p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  844.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  845.                 }
  846.                 else if (i == 2) {
  847.                     p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  848.                     p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  849.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  850.                 }
  851.                 else if (i == 3) {
  852.                     p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  853.                     p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  854.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  855.                 }
  856.                 else if (i == 5) {
  857.                     p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  858.                     p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  859.                     sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  860.                 }
  861.                 else if (i == 1) {
  862.                     p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  863.                     p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  864.                     sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  865.                 }
  866.                 else {
  867.                     p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  868.                     p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  869.                     sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  870.                 }
  871.                 pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  872.                 pSink->AddLine(p1);
  873.                 pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  874.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  875.                 pSink->Close();
  876.                 SafeRelease(&pSink);
  877.                 pWicRT->FillGeometry(pPath, pPocketBrush);
  878.                 // Draw the inner rim for a beveled effect (Start)
  879.                 D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(0.8f, 0.8f, center);
  880.                 ID2D1TransformedGeometry* pTransformedGeo = nullptr;
  881.                 pFactory->CreateTransformedGeometry(pPath, &scale, &pTransformedGeo);
  882.                 if (pTransformedGeo) {
  883.                     pWicRT->FillGeometry(pTransformedGeo, pRimBrush);
  884.                     SafeRelease(&pTransformedGeo);
  885.                 } //End
  886.             }
  887.             SafeRelease(&pPath);
  888.         }
  889.     }
  890. }
  891. SafeRelease(&pPocketBrush);
  892. SafeRelease(&pRimBrush);
  893.  
  894. // If your visual is a semicircle or a complex path, create + fill a path geometry here:
  895. // ID2D1PathGeometry* pPath; pFactory->CreatePathGeometry(&pPath); ... FillGeometry ...
  896. //}
  897.  
  898. // End drawing
  899. pWicRT->EndDraw();
  900.  
  901. // Release brush & render target (we still have the WIC bitmap to lock/read)
  902. //SafeRelease(&pBlackBrush);
  903. SafeRelease(&pWicRT);
  904.  
  905. // Lock WIC bitmap and read pixel data (32bppPBGRA -> bytes: B G R A premultiplied)
  906. WICRect lockRect = { 0, 0, maskWidth, maskHeight };
  907. IWICBitmapLock* pLock = nullptr;
  908. hr = pWicBitmap->Lock(&lockRect, WICBitmapLockRead, &pLock);
  909. if (SUCCEEDED(hr) && pLock) {
  910.     UINT cbStride = 0;
  911.     UINT cbBufferSize = 0;
  912.     BYTE* pv = nullptr;
  913.     hr = pLock->GetDataPointer(&cbBufferSize, &pv);
  914.     pLock->GetStride(&cbStride);
  915.  
  916.     if (SUCCEEDED(hr) && pv) {
  917.         // Iterate rows -> columns; pixel is 4 bytes (B,G,R,A) premultiplied
  918.         for (int y = 0; y < maskHeight; ++y) {
  919.             BYTE* row = pv + y * cbStride;
  920.             int base = y * maskWidth;
  921.             for (int x = 0; x < maskWidth; ++x) {
  922.                 BYTE a = row[x * 4 + 3]; // alpha channel
  923.                 pocketMask[base + x] = (a > ALPHA_THRESHOLD) ? 1 : 0;
  924.             }
  925.         }
  926.     }
  927.     pLock->Release();
  928. }
  929.  
  930. pWicBitmap->Release();
  931. }
  932. */
  933.  
  934. // Helper: world coords -> mask pixel coords (rounded). returns false if outside mask bounds.
  935. inline bool WorldToMaskPixel_Masks(float worldX, float worldY, int& outX, int& outY)
  936. {
  937.     float px = (worldX - pocketMaskOriginX) * pocketMaskScale;
  938.     float py = (worldY - pocketMaskOriginY) * pocketMaskScale;
  939.     int ix = (int)floorf(px + 0.5f);
  940.     int iy = (int)floorf(py + 0.5f);
  941.     if (ix < 0 || iy < 0 || ix >= pocketMaskWidth || iy >= pocketMaskHeight) return false;
  942.     outX = ix; outY = iy; return true;
  943. }
  944.  
  945. // ----------------------------------------------------------------------
  946. // IsBallTouchingPocketMask_D2D (unchanged pixel-perfect test)
  947. // ----------------------------------------------------------------------
  948. bool IsBallTouchingPocketMask_D2D(const Ball& b, int pocketIndex)
  949. {
  950.     if (pocketIndex < 0 || pocketIndex >= (int)pocketMasks.size()) return false;
  951.     if (pocketMaskWidth <= 0 || pocketMaskHeight <= 0) return false;
  952.     const std::vector<uint8_t>& mask = pocketMasks[pocketIndex];
  953.     if (mask.empty()) return false;
  954.  
  955.     // --- FOOLPROOF FIX: Transform the ball's center into the mask's local space ---
  956.     float ballMaskX = (b.x - pocketPositions[pocketIndex].x) * pocketMaskScale + (pocketMaskWidth / 2.0f);
  957.     float ballMaskY = (b.y - pocketPositions[pocketIndex].y) * pocketMaskScale + (pocketMaskHeight / 2.0f);
  958.     float radiusInPixels = BALL_RADIUS * pocketMaskScale;
  959.  
  960.     // Ball bounding box in world coords
  961.     /*float leftW = b.x - BALL_RADIUS;
  962.     float rightW = b.x + BALL_RADIUS;
  963.     float topW = b.y - BALL_RADIUS;
  964.     float bottomW = b.y + BALL_RADIUS;
  965.  
  966.     int leftPx = (int)floorf((leftW - pocketMaskOriginX) * pocketMaskScale);
  967.     int topPx = (int)floorf((topW - pocketMaskOriginY) * pocketMaskScale);
  968.     int rightPx = (int)ceilf((rightW - pocketMaskOriginX) * pocketMaskScale);
  969.     int bottomPx = (int)ceilf((bottomW - pocketMaskOriginY) * pocketMaskScale);
  970.  
  971.     // clamp to mask bounds
  972.     leftPx = std::max(0, leftPx);
  973.     topPx = std::max(0, topPx);
  974.     rightPx = std::min(pocketMaskWidth - 1, rightPx);
  975.     bottomPx = std::min(pocketMaskHeight - 1, bottomPx);
  976.  
  977.     // ball center and radius in pixels
  978.     float cx = (b.x - pocketMaskOriginX) * pocketMaskScale;
  979.     float cy = (b.y - pocketMaskOriginY) * pocketMaskScale;
  980.     float rPx = BALL_RADIUS * pocketMaskScale;
  981.     float rPx2 = rPx * rPx;*/
  982.  
  983.     // Define a search area around the ball's transformed position
  984.     int startX = std::max(0, static_cast<int>(ballMaskX - radiusInPixels));
  985.     int endX = std::min(pocketMaskWidth - 1, static_cast<int>(ballMaskX + radiusInPixels));
  986.     int startY = std::max(0, static_cast<int>(ballMaskY - radiusInPixels));
  987.     int endY = std::min(pocketMaskHeight - 1, static_cast<int>(ballMaskY + radiusInPixels));
  988.  
  989.     // Check each pixel within the search area
  990.     for (int y = startY; y <= endY; ++y) {
  991.         int rowBase = y * pocketMaskWidth;
  992.         for (int x = startX; x <= endX; ++x) {
  993.             // Check if this mask pixel is "solid" (part of the pocket)
  994.             if (mask[rowBase + x] > 0) {
  995.                 // Check if the distance from the pixel to the ball's center is within the ball's radius
  996.                 float dx = (float)x - ballMaskX;
  997.                 float dy = (float)y - ballMaskY;
  998.                 if (dx * dx + dy * dy < radiusInPixels * radiusInPixels) {
  999.                     return true; // Collision detected!
  1000.                 }
  1001.  
  1002.     /*for (int yy = topPx; yy <= bottomPx; ++yy) {
  1003.         int rowBase = yy * pocketMaskWidth;
  1004.         for (int xx = leftPx; xx <= rightPx; ++xx) {
  1005.             float px = (float)xx + 0.5f;
  1006.             float py = (float)yy + 0.5f;
  1007.             float dx = px - cx;
  1008.             float dy = py - cy;
  1009.             if (dx * dx + dy * dy <= rPx2) {
  1010.                 if (mask[rowBase + xx]) return true;*/
  1011.             }
  1012.         }
  1013.     }
  1014.     return false;
  1015. }
  1016.  
  1017. /*
  1018. // Pixel-perfect test using the selected pocket mask
  1019. bool IsBallTouchingPocketMask_D2D(const Ball& b, int pocketIndex)
  1020. {
  1021.     if (pocketIndex < 0 || pocketIndex >= (int)pocketMasks.size()) return false;
  1022.     if (pocketMaskWidth <= 0 || pocketMaskHeight <= 0) return false;
  1023.     const std::vector<uint8_t>& mask = pocketMasks[pocketIndex];
  1024.     if (mask.empty()) return false;
  1025.  
  1026.     // Ball bounding box in world coords
  1027.     float leftW = b.x - BALL_RADIUS;
  1028.     float rightW = b.x + BALL_RADIUS;
  1029.     float topW = b.y - BALL_RADIUS;
  1030.     float bottomW = b.y + BALL_RADIUS;
  1031.  
  1032.     int leftPx = (int)floorf((leftW - pocketMaskOriginX) * pocketMaskScale);
  1033.     int topPx = (int)floorf((topW - pocketMaskOriginY) * pocketMaskScale);
  1034.     int rightPx = (int)ceilf((rightW - pocketMaskOriginX) * pocketMaskScale);
  1035.     int bottomPx = (int)ceilf((bottomW - pocketMaskOriginY) * pocketMaskScale);
  1036.  
  1037.     // clamp to mask bounds
  1038.     leftPx = std::max(0, leftPx);
  1039.     topPx = std::max(0, topPx);
  1040.     rightPx = std::min(pocketMaskWidth - 1, rightPx);
  1041.     bottomPx = std::min(pocketMaskHeight - 1, bottomPx);
  1042.  
  1043.     // ball center and radius in pixels
  1044.     float cx = (b.x - pocketMaskOriginX) * pocketMaskScale;
  1045.     float cy = (b.y - pocketMaskOriginY) * pocketMaskScale;
  1046.     float rPx = BALL_RADIUS * pocketMaskScale;
  1047.     float rPx2 = rPx * rPx;
  1048.  
  1049.     for (int yy = topPx; yy <= bottomPx; ++yy) {
  1050.         int rowBase = yy * pocketMaskWidth;
  1051.         for (int xx = leftPx; xx <= rightPx; ++xx) {
  1052.             float px = (float)xx + 0.5f;
  1053.             float py = (float)yy + 0.5f;
  1054.             float dx = px - cx;
  1055.             float dy = py - cy;
  1056.             if (dx * dx + dy * dy <= rPx2) {
  1057.                 if (mask[rowBase + xx]) return true;
  1058.             }
  1059.         }
  1060.     }
  1061.     return false;
  1062. }*/
  1063.  
  1064. //new polygon mask helpers
  1065. // -----------------------------
  1066. // Polygon-based pocket hit test
  1067. // -----------------------------
  1068. // Add these helper functions near your other geometry helpers.
  1069. // This implementation approximates pocket curves with a sampled polygon
  1070. // then does precise point-in-polygon and point-to-segment checks.
  1071. // This avoids any Direct2D FillContainsPoint incompatibility and
  1072. // gives deterministic shape-based results (not circle-based).
  1073. //
  1074. // Tweak SAMPLE_PER_QUARTER_CIRCLE if you want finer resolution.
  1075.  
  1076. static const int SAMPLE_PER_QUARTER_CIRCLE = 24; // controls polygon smoothness (increase = more precise) (default=14)
  1077.  
  1078. static float Sq(float v) { return v * v; }
  1079.  
  1080. static float DistancePointSegmentSq(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b)
  1081. {
  1082.     // compute squared distance from p to segment ab
  1083.     D2D1_POINT_2F ab = { b.x - a.x, b.y - a.y };
  1084.     D2D1_POINT_2F ap = { p.x - a.x, p.y - a.y };
  1085.     float abLen2 = ab.x * ab.x + ab.y * ab.y;
  1086.     if (abLen2 <= 1e-8f) {
  1087.         return (p.x - a.x) * (p.x - a.x) + (p.y - a.y) * (p.y - a.y);
  1088.     }
  1089.     float t = (ap.x * ab.x + ap.y * ab.y) / abLen2;
  1090.     if (t < 0.0f) t = 0.0f;
  1091.     else if (t > 1.0f) t = 1.0f;
  1092.     D2D1_POINT_2F proj = { a.x + ab.x * t, a.y + ab.y * t };
  1093.     return (p.x - proj.x) * (p.x - proj.x) + (p.y - proj.y) * (p.y - proj.y);
  1094. }
  1095.  
  1096. // Winding/ray-cast point-in-polygon (non-zero winding). Returns true if inside.
  1097. static bool PointInPolygon(const std::vector<D2D1_POINT_2F>& poly, const D2D1_POINT_2F& pt)
  1098. {
  1099.     bool inside = false;
  1100.     size_t n = poly.size();
  1101.     if (n < 3) return false;
  1102.     for (size_t i = 0, j = n - 1; i < n; j = i++) {
  1103.         const D2D1_POINT_2F& pi = poly[i], & pj = poly[j];
  1104.         bool intersect = ((pi.y > pt.y) != (pj.y > pt.y)) &&
  1105.             (pt.x < (pj.x - pi.x)* (pt.y - pi.y) / (pj.y - pi.y + 1e-12f) + pi.x);
  1106.         if (intersect) inside = !inside;
  1107.     }
  1108.     return inside;
  1109. }
  1110.  
  1111. // build an approximated polygon describing the black/inner pocket area (the "hole")
  1112. // pIndex: 0..5
  1113. // output poly is in the same coordinate space as your table (pixel coordinates)
  1114. static void BuildPocketPolygon(int pIndex, std::vector<D2D1_POINT_2F>& outPoly)
  1115. {
  1116.     outPoly.clear();
  1117.     D2D1_POINT_2F center = pocketPositions[pIndex];
  1118.  
  1119.     // choose inner black radius for the pocket (this should match the drawn 'black' mouth)
  1120.     float vis = GetPocketVisualRadius(pIndex);
  1121.     float innerRadius = vis * 0.55f; // tweak multiplier to match your drawn black area exactly (default=0.85)
  1122.  
  1123.     int samples = SAMPLE_PER_QUARTER_CIRCLE * 2; // semi-circle uses half circle of samples
  1124.  
  1125.     // Middle pockets (top-middle index 1, bottom-middle index 4) -> semicircle opening into table
  1126.     if (pIndex == 1 || pIndex == 4) {
  1127.         // top-middle (1): semicircle opening downward => angles [0..PI]
  1128.         // bottom-middle (4): semicircle opening upward => angles [PI..2PI]
  1129.         float a0 = (pIndex == 1) ? 0.0f : PI;
  1130.         float a1 = a0 + PI;
  1131.         for (int i = 0; i <= samples; ++i) {
  1132.             float t = float(i) / float(samples);
  1133.             float a = a0 + (a1 - a0) * t;
  1134.             float x = center.x + cosf(a) * innerRadius;
  1135.             float y = center.y + sinf(a) * innerRadius;
  1136.             outPoly.push_back(D2D1::Point2F(x, y));
  1137.         }
  1138.         // close polygon by adding the center "mouth" edge (slightly inside) to make a filled shape
  1139.         // we insert two small points inside the semicircle to make the polygon closed and reasonable
  1140.         outPoly.push_back(D2D1::Point2F(center.x + innerRadius * 0.25f, center.y)); // inner mid-right
  1141.         outPoly.push_back(D2D1::Point2F(center.x - innerRadius * 0.25f, center.y)); // inner mid-left
  1142.         return;
  1143.     }
  1144.  
  1145.     // Corner pockets: quarter-circle interior where black area is inside the table corner.
  1146.     // Create a quarter-arc polygon oriented depending on which corner.
  1147.     float startAngle = 0.0f, endAngle = 0.0f;
  1148.     // p0 TL, p2 TR, p3 BL, p5 BR
  1149.     // angle mapping:
  1150.     // 0 -> right (0), PI/2 -> down, PI -> left, 3PI/2 -> up
  1151.     if (pIndex == 0) { // top-left: interior down-right => angles [0 .. PI/2]
  1152.         startAngle = 0.0f; endAngle = PI / 2.0f;
  1153.     }
  1154.     else if (pIndex == 2) { // top-right: interior down-left => angles [PI/2 .. PI]
  1155.         startAngle = PI / 2.0f; endAngle = PI;
  1156.     }
  1157.     else if (pIndex == 3) { // bottom-left: interior up-right => angles [3PI/2 .. 2PI]
  1158.         startAngle = 3.0f * PI / 2.0f; endAngle = 2.0f * PI;
  1159.     }
  1160.     else if (pIndex == 5) { // bottom-right: interior up-left => angles [PI .. 3PI/2]
  1161.         startAngle = PI; endAngle = 3.0f * PI / 2.0f;
  1162.     }
  1163.     else {
  1164.         // fallback: full circle
  1165.         startAngle = 0.0f; endAngle = 2.0f * PI;
  1166.     }
  1167.  
  1168.     int quarterSamples = SAMPLE_PER_QUARTER_CIRCLE;
  1169.     for (int i = 0; i <= quarterSamples; ++i) {
  1170.         float t = float(i) / float(quarterSamples);
  1171.         float a = startAngle + (endAngle - startAngle) * t;
  1172.         float x = center.x + cosf(a) * innerRadius;
  1173.         float y = center.y + sinf(a) * innerRadius;
  1174.         outPoly.push_back(D2D1::Point2F(x, y));
  1175.     }
  1176.     // add a small interior chord to close polygon toward table inside
  1177.     // determine inward direction (table interior)
  1178.     D2D1_POINT_2F innerOffset = { 0, 0 };
  1179.     if (pIndex == 0) innerOffset = { innerRadius * 0.35f, innerRadius * 0.35f }; // down-right
  1180.     if (pIndex == 2) innerOffset = { -innerRadius * 0.35f, innerRadius * 0.35f }; // down-left
  1181.     if (pIndex == 3) innerOffset = { innerRadius * 0.35f, -innerRadius * 0.35f }; // up-right
  1182.     if (pIndex == 5) innerOffset = { -innerRadius * 0.35f, -innerRadius * 0.35f }; // up-left
  1183.  
  1184.     outPoly.push_back(D2D1::Point2F(center.x + innerOffset.x, center.y + innerOffset.y));
  1185. }
  1186.  
  1187. // Main high precision pocket test using polygon
  1188. // returns true if ball overlaps or touches the polygonal black area
  1189. bool IsBallInPocketPolygon(const Ball& b, int pIndex)
  1190. {
  1191.     if (pIndex < 0 || pIndex > 5) return false;
  1192.  
  1193.     // Build polygon describing pocket black area
  1194.     std::vector<D2D1_POINT_2F> poly;
  1195.     BuildPocketPolygon(pIndex, poly);
  1196.     if (poly.size() < 3) return false;
  1197.  
  1198.     D2D1_POINT_2F center = D2D1::Point2F(b.x, b.y);
  1199.  
  1200.     // Quick bounding-box reject (cheap)
  1201.     float minx = FLT_MAX, miny = FLT_MAX, maxx = -FLT_MAX, maxy = -FLT_MAX;
  1202.     for (auto& pt : poly) {
  1203.         if (pt.x < minx) minx = pt.x;
  1204.         if (pt.y < miny) miny = pt.y;
  1205.         if (pt.x > maxx) maxx = pt.x;
  1206.         if (pt.y > maxy) maxy = pt.y;
  1207.     }
  1208.     // expand by BALL_RADIUS
  1209.     minx -= BALL_RADIUS; miny -= BALL_RADIUS; maxx += BALL_RADIUS; maxy += BALL_RADIUS;
  1210.     if (center.x < minx || center.x > maxx || center.y < miny || center.y > maxy) {
  1211.         // center outside expanded bounds; not enough to intersect
  1212.         // but still we should check if the ball edge could overlap an extended corner -> we've expanded by BALL_RADIUS so safe
  1213.         return false;
  1214.     }
  1215.  
  1216.     // 1) If ball center is inside the polygon -> pocketed
  1217.     if (PointInPolygon(poly, center)) {
  1218.         // Table side check: ensure ball is approaching from table side (avoid false positives from below/above)
  1219.         bool topPocket = (pIndex == 0 || pIndex == 1 || pIndex == 2);
  1220.         if (topPocket) {
  1221.             if (b.y < pocketPositions[pIndex].y - BALL_RADIUS) return false;
  1222.         }
  1223.         else {
  1224.             if (b.y > pocketPositions[pIndex].y + BALL_RADIUS) return false;
  1225.         }
  1226.         return true;
  1227.     }
  1228.  
  1229.     // 2) Otherwise, check distance from ball center to any polygon edge
  1230.     float rr = BALL_RADIUS * BALL_RADIUS;
  1231.     for (size_t i = 0, n = poly.size(); i < n; ++i) {
  1232.         const D2D1_POINT_2F& a = poly[i];
  1233.         const D2D1_POINT_2F& bb = poly[(i + 1) % n];
  1234.         float d2 = DistancePointSegmentSq(center, a, bb);
  1235.         if (d2 <= rr + 1e-6f) {
  1236.             // edge-touch candidate -> verify table side (avoid outside approach)
  1237.             bool topPocket = (pIndex == 0 || pIndex == 1 || pIndex == 2);
  1238.             if (topPocket) {
  1239.                 if (b.y < pocketPositions[pIndex].y - BALL_RADIUS) return false;
  1240.             }
  1241.             else {
  1242.                 if (b.y > pocketPositions[pIndex].y + BALL_RADIUS) return false;
  1243.             }
  1244.             return true;
  1245.         }
  1246.     }
  1247.  
  1248.     return false;
  1249. }
  1250.  
  1251. // Backwards-compatible alias: some places in the code call IsBallInPocket(...)
  1252. // so provide a thin wrapper that uses the precise black-area test.
  1253. bool IsBallInPocket(const Ball& b, int pIndex)
  1254. {
  1255.     return IsBallInPocketPolygon(b, pIndex);
  1256. }
  1257.  
  1258. // Backwards-compatible wrapper (if your code calls IsBallInPocket(...))
  1259. bool IsBallInPocket(const Ball* ball, int p)
  1260. {
  1261.     if (!ball) return false;
  1262.     return IsBallInPocketPolygon(*ball, p);
  1263. } //end
  1264.  
  1265.  
  1266. // Flatten one cubic bezier into a polyline (uniform sampling).
  1267. static void FlattenCubicBezier(const std::array<D2D1_POINT_2F, 4>& bz, std::vector<D2D1_POINT_2F>& outPts, int steps = 16)
  1268. {
  1269.     outPts.clear();
  1270.     outPts.reserve(steps + 1);
  1271.     for (int i = 0; i <= steps; ++i) {
  1272.         float t = (float)i / (float)steps;
  1273.         float mt = 1.0f - t;
  1274.         // De Casteljau cubic
  1275.         float x =
  1276.             mt * mt * mt * bz[0].x +
  1277.             3.0f * mt * mt * t * bz[1].x +
  1278.             3.0f * mt * t * t * bz[2].x +
  1279.             t * t * t * bz[3].x;
  1280.         float y =
  1281.             mt * mt * mt * bz[0].y +
  1282.             3.0f * mt * mt * t * bz[1].y +
  1283.             3.0f * mt * t * t * bz[2].y +
  1284.             t * t * t * bz[3].y;
  1285.         outPts.push_back(D2D1::Point2F(x, y));
  1286.     }
  1287. }
  1288.  
  1289. // squared distance point -> segment
  1290. static inline float PointSegDistSq(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b)
  1291. {
  1292.     float vx = b.x - a.x, vy = b.y - a.y;
  1293.     float wx = p.x - a.x, wy = p.y - a.y;
  1294.     float c1 = vx * wx + vy * wy;
  1295.     if (c1 <= 0.0f) {
  1296.         float dx = p.x - a.x, dy = p.y - a.y;
  1297.         return dx * dx + dy * dy;
  1298.     }
  1299.     float c2 = vx * vx + vy * vy;
  1300.     if (c2 <= c1) {
  1301.         float dx = p.x - b.x, dy = p.y - b.y;
  1302.         return dx * dx + dy * dy;
  1303.     }
  1304.     float t = c1 / c2;
  1305.     float projx = a.x + vx * t;
  1306.     float projy = a.y + vy * t;
  1307.     float dx = p.x - projx, dy = p.y - projy;
  1308.     return dx * dx + dy * dy;
  1309. }
  1310.  
  1311. // Point-in-polygon (winding rule). flattened polyline is assumed closed.
  1312. static bool PointInPolygonWinding(const D2D1_POINT_2F& pt, const std::vector<D2D1_POINT_2F>& poly)
  1313. {
  1314.     int wn = 0;
  1315.     size_t n = poly.size();
  1316.     if (n < 3) return false;
  1317.     for (size_t i = 0; i < n; ++i) {
  1318.         const D2D1_POINT_2F& a = poly[i];
  1319.         const D2D1_POINT_2F& b = poly[(i + 1) % n];
  1320.         if (a.y <= pt.y) {
  1321.             if (b.y > pt.y) { // upward crossing
  1322.                 float isLeft = (b.x - a.x) * (pt.y - a.y) - (pt.x - a.x) * (b.y - a.y);
  1323.                 if (isLeft > 0.0f) ++wn;
  1324.             }
  1325.         }
  1326.         else {
  1327.             if (b.y <= pt.y) { // downward crossing
  1328.                 float isLeft = (b.x - a.x) * (pt.y - a.y) - (pt.x - a.x) * (b.y - a.y);
  1329.                 if (isLeft < 0.0f) --wn;
  1330.             }
  1331.         }
  1332.     }
  1333.     return wn != 0;
  1334. }
  1335.  
  1336. // Add a circular arc (possibly >90deg) approximated by cubic beziers.
  1337. // center, radius, startAngle (radians), sweepAngle (radians). Sweep may be > PI/2,
  1338. // so we subdivide into <= PI/2 segments.
  1339. static void AddArcAsCubics(std::vector<std::array<D2D1_POINT_2F, 4>>& out, D2D1_POINT_2F center, float radius, float startAngle, float sweep)
  1340. {
  1341.     // normalize sweep sign and break into pieces of max 90 degrees
  1342.     const float MAXSEG = PI / 2.0f; // 90deg
  1343.     int segs = (int)ceilf(fabsf(sweep) / MAXSEG);
  1344.     float segAngle = sweep / segs;
  1345.     float a0 = startAngle;
  1346.     for (int i = 0; i < segs; ++i) {
  1347.         float a1 = a0 + segAngle;
  1348.         float theta = a1 - a0;
  1349.         float alpha = (4.0f / 3.0f) * tanf(theta / 4.0f); // control length factor
  1350.         D2D1_POINT_2F p0 = { center.x + radius * cosf(a0), center.y + radius * sinf(a0) };
  1351.         D2D1_POINT_2F p3 = { center.x + radius * cosf(a1), center.y + radius * sinf(a1) };
  1352.         D2D1_POINT_2F t0 = { -sinf(a0), cosf(a0) }; // unit tangent at p0
  1353.         D2D1_POINT_2F t1 = { -sinf(a1), cosf(a1) }; // unit tangent at p3
  1354.         D2D1_POINT_2F p1 = { p0.x + alpha * radius * t0.x, p0.y + alpha * radius * t0.y };
  1355.         D2D1_POINT_2F p2 = { p3.x - alpha * radius * t1.x, p3.y - alpha * radius * t1.y };
  1356.         out.push_back({ p0, p1, p2, p3 });
  1357.         a0 = a1;
  1358.     }
  1359. }
  1360.  
  1361. // Build the pocket black-area bezier description (semicircles for middles,
  1362. // quarter/rounded for corners). Caches results in g_pocketBezierCache.
  1363. static void EnsurePocketBezierCache()
  1364. {
  1365.     if (g_pocketBezierCacheInitialized) return;
  1366.     g_pocketBezierCacheInitialized = true;
  1367.     g_pocketBezierCache.clear();
  1368.     g_pocketBezierCache.resize(6);
  1369.  
  1370.     for (int p = 0; p < 6; ++p) {
  1371.         D2D1_POINT_2F c = pocketPositions[p];
  1372.         float pocketVis = GetPocketVisualRadius(p); // uses your existing helper
  1373.         float inner = pocketVis * 0.88f; // base for the 'black' mouth. tweak if needed
  1374.  
  1375.         // decide arc angles (y increases downward)
  1376.         // Top-left (0): quarter arc from angle 0 (right) to PI/2 (down)
  1377.         // Top-middle (1): semicircle from angle 0 (right) to PI (left) - lower half
  1378.         // Top-right (2): quarter arc from PI/2 (down) to PI (left)
  1379.         // Bottom-left (3): quarter arc from 3PI/2 (up) to 2PI (right)
  1380.         // Bottom-middle (4): semicircle from PI (left) to 2PI (right) - upper half
  1381.         // Bottom-right (5): quarter arc from PI (left) to 3PI/2 (up)
  1382.         const float TWO_PI = 2.0f * PI;
  1383.         if (p == 1) {
  1384.             // top middle -> semicircle opening downward (angles 0 -> PI)
  1385.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, 0.0f, PI);
  1386.         }
  1387.         else if (p == 4) {
  1388.             // bottom middle -> semicircle opening upward (angles PI -> 2PI)
  1389.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, PI, PI);
  1390.         }
  1391.         else if (p == 0) {
  1392.             // top-left quarter: right -> down (0 -> PI/2)
  1393.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, 0.0f, PI / 2.0f);
  1394.         }
  1395.         else if (p == 2) {
  1396.             // top-right quarter: down -> left (PI/2 -> PI)
  1397.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, PI / 2.0f, PI / 2.0f);
  1398.         }
  1399.         else if (p == 3) {
  1400.             // bottom-left quarter: up -> right (3PI/2 -> 2PI)
  1401.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, 3.0f * PI / 2.0f, PI / 2.0f);
  1402.         }
  1403.         else if (p == 5) {
  1404.             // bottom-right quarter: left -> up (PI -> 3PI/2)
  1405.             AddArcAsCubics(g_pocketBezierCache[p], c, inner, PI, PI / 2.0f);
  1406.         }
  1407.     }
  1408. }
  1409. //above are bezier mask helpers
  1410.  
  1411. //below are pixel-perfect bezier matching helpers
  1412.  
  1413.  
  1414. // -------------------------------------------------------------------------
  1415. // Geometry helpers for precise pocket shape hit-testing
  1416. // -------------------------------------------------------------------------
  1417. static float DistPointToSegment(const D2D1_POINT_2F& p, const D2D1_POINT_2F& a, const D2D1_POINT_2F& b)
  1418. {
  1419.     // squared distance project of p onto segment ab
  1420.     D2D1_POINT_2F ab = { b.x - a.x, b.y - a.y };
  1421.     D2D1_POINT_2F ap = { p.x - a.x, p.y - a.y };
  1422.     float ab2 = ab.x * ab.x + ab.y * ab.y;
  1423.     if (ab2 <= 1e-8f) {
  1424.         float dx = p.x - a.x, dy = p.y - a.y;
  1425.         return sqrtf(dx*dx + dy*dy);
  1426.     }
  1427.     float t = (ap.x * ab.x + ap.y * ab.y) / ab2;
  1428.     if (t < 0.0f) t = 0.0f;
  1429.     if (t > 1.0f) t = 1.0f;
  1430.     D2D1_POINT_2F proj = { a.x + ab.x * t, a.y + ab.y * t };
  1431.     float dx = p.x - proj.x, dy = p.y - proj.y;
  1432.     return sqrtf(dx*dx + dy*dy);
  1433. }
  1434.  
  1435. static float NormalizeAngle(float a)
  1436. {
  1437.     // normalize to [0, 2PI)
  1438.     const float TWO_PI = 2.0f * PI;
  1439.     while (a < 0.0f) a += TWO_PI;
  1440.     while (a >= TWO_PI) a -= TWO_PI;
  1441.     return a;
  1442. }
  1443.  
  1444. // return true if angle `ang` is inside sector starting at startAngle
  1445. // sweeping `sweep` (sweep >= 0). Handles wrap-around.
  1446. static bool AngleInRange(float ang, float startAngle, float sweep)
  1447. {
  1448.     ang = NormalizeAngle(ang);
  1449.     startAngle = NormalizeAngle(startAngle);
  1450.     float endAngle = NormalizeAngle(startAngle + sweep);
  1451.     if (sweep >= 2.0f * PI - 1e-6f) return true;
  1452.     if (startAngle <= endAngle) {
  1453.         return (ang >= startAngle - 1e-6f && ang <= endAngle + 1e-6f);
  1454.     } else {
  1455.         // wrapped around
  1456.         return (ang >= startAngle - 1e-6f || ang <= endAngle + 1e-6f);
  1457.     }
  1458. }
  1459.  
  1460. // minimal distance from point `p` to a circular arc (centered at c, radius r,
  1461. // starting at startAngle for sweepAngle radians). Also returns if point is
  1462. // inside the filled sector (i.e., r0 <= r and angle in sector).
  1463. static float DistPointToArc(const D2D1_POINT_2F& p, const D2D1_POINT_2F& c, float r, float startAngle, float sweepAngle, bool &outInsideSector)
  1464. {
  1465.     float dx = p.x - c.x;
  1466.     float dy = p.y - c.y;
  1467.     float r0 = sqrtf(dx*dx + dy*dy);
  1468.     float ang = atan2f(dy, dx);
  1469.     ang = NormalizeAngle(ang);
  1470.  
  1471.     // endpoints of the arc
  1472.     float a1 = NormalizeAngle(startAngle);
  1473.     float a2 = NormalizeAngle(startAngle + sweepAngle);
  1474.  
  1475.     // is the point angle within sector?
  1476.     bool inSector = AngleInRange(ang, a1, sweepAngle);
  1477.     outInsideSector = (inSector && (r0 <= r + 1e-6f));
  1478.  
  1479.     if (inSector) {
  1480.         // distance to arc circle
  1481.         return fabsf(r0 - r);
  1482.     } else {
  1483.         // distance to arc endpoints
  1484.         D2D1_POINT_2F ep1 = { c.x + r * cosf(a1), c.y + r * sinf(a1) };
  1485.         D2D1_POINT_2F ep2 = { c.x + r * cosf(a2), c.y + r * sinf(a2) };
  1486.         float dx1 = p.x - ep1.x, dy1 = p.y - ep1.y;
  1487.         float dx2 = p.x - ep2.x, dy2 = p.y - ep2.y;
  1488.         float d1 = sqrtf(dx1*dx1 + dy1*dy1);
  1489.         float d2 = sqrtf(dx2*dx2 + dy2*dy2);
  1490.         return (d1 < d2) ? d1 : d2;
  1491.     }
  1492. }
  1493.  
  1494. // -------------------------------------------------------------------------
  1495. // High-precision pocket test: returns true when any part of the BALL
  1496. // overlaps the black pocket area (semicircle for middle pockets or
  1497. // corner pocket interior). Uses BALL_RADIUS so touching counts.
  1498. // Insert this function in the Helpers section (near other helpers).
  1499. // -------------------------------------------------------------------------
  1500. // -------------------------------------------------------------------------
  1501. // Precise test whether any part of the ball overlaps the black pocket shape
  1502. // (quarter/semicircle filled area). This function *replaces* the older loose
  1503. // radius/capsule approach and matches the actual black mouth shape.
  1504. // -------------------------------------------------------------------------
  1505. bool IsBallInPocketBlackArea(const Ball& b, int pIndex)
  1506. {
  1507.     if (pIndex < 0 || pIndex > 5) return false;
  1508.  
  1509.     D2D1_POINT_2F pc = pocketPositions[pIndex];
  1510.     // Use pocket visual radius converted to a conservative black-mouth radius
  1511.     float pocketVis = GetPocketVisualRadius(pIndex);
  1512.     // `blackRadius` controls how big the black area is relative to visual.
  1513.     // Reduce if you want more strictness.
  1514.     const float blackRadius = pocketVis * 0.55f; //0.88f(default) => 75 =>65=>55    
  1515.  
  1516.     // For top middle (1): semicircle opening downward (angles 0..PI),
  1517.     // for bottom middle (4): semicircle opening upward (angles PI..2PI).
  1518.     // For corners, quarter-circle angles depend on pocket index:
  1519.     // 0 (top-left): angles 0..PI/2  (right -> down)
  1520.     // 2 (top-right): angles PI/2..PI (down -> left)
  1521.     // 3 (bottom-left): angles 3PI/2..2PI (up -> right)
  1522.     // 5 (bottom-right): angles PI..3PI/2 (left -> up)
  1523.  
  1524.     D2D1_POINT_2F ballCenter = { b.x, b.y };
  1525.  
  1526.     // --- Middle pockets: semicircle + diameter segment ---
  1527.     if (pIndex == 1 || pIndex == 4) {
  1528.         // semicircle params
  1529.         float startAngle, sweep;
  1530.         if (pIndex == 1) {
  1531.             // top middle: arc from angle 0 (right) to pi (left) -> opening downward into table
  1532.             startAngle = 0.0f;
  1533.             sweep = PI;
  1534.             // require ball to be on table side (below center) when checking "inside"
  1535.             // we handle this orientation implicitly with the semicircle sector and diameter.
  1536.         }
  1537.         else {
  1538.             // bottom middle: arc from PI to 2PI (opening upward)
  1539.             startAngle = PI;
  1540.             sweep = PI;
  1541.         }
  1542.  
  1543.         // 1) If ball center is inside semicircular sector (r0 <= blackRadius and angle in sector)
  1544.         bool insideSector = false;
  1545.         float dx = ballCenter.x - pc.x;
  1546.         float dy = ballCenter.y - pc.y;
  1547.         float r0 = sqrtf(dx * dx + dy * dy);
  1548.         float ang = NormalizeAngle(atan2f(dy, dx));
  1549.         if (AngleInRange(ang, startAngle, sweep) && r0 <= blackRadius + 1e-6f) {
  1550.             // ball center lies strictly inside semicircle -> definitely overlaps
  1551.             return true;
  1552.         }
  1553.  
  1554.         // 2) if not, compute minimal distance to the semicircle filled shape boundary:
  1555.         //    boundary = arc (circular curve) + diameter segment (straight line between arc endpoints)
  1556.         bool tmpInsideArcSector = false;
  1557.         float distToArc = DistPointToArc(ballCenter, pc, blackRadius, startAngle, sweep, tmpInsideArcSector);
  1558.         // diameter endpoints
  1559.         D2D1_POINT_2F ep1 = { pc.x + blackRadius * cosf(startAngle), pc.y + blackRadius * sinf(startAngle) };
  1560.         D2D1_POINT_2F ep2 = { pc.x + blackRadius * cosf(startAngle + sweep), pc.y + blackRadius * sinf(startAngle + sweep) };
  1561.         float distToDiameter = DistPointToSegment(ballCenter, ep1, ep2);
  1562.  
  1563.         float minDist = (distToArc < distToDiameter) ? distToArc : distToDiameter;
  1564.  
  1565.         // If any part of the ball (circle radius) reaches into the filled semicircle -> collision
  1566.         return (minDist <= BALL_RADIUS + 1e-6f);
  1567.     }
  1568.     else {
  1569.         // --- Corner pockets: treat as filled quarter-circles ---
  1570.         float startAngle = 0.0f;
  1571.         // assign angles for each corner pocket (w/ y increasing downwards)
  1572.         if (pIndex == 0) {             // top-left: right->down (0 -> PI/2)
  1573.             startAngle = 0.0f;
  1574.         }
  1575.         else if (pIndex == 2) {      // top-right: down->left (PI/2 -> PI)
  1576.             startAngle = 0.5f * PI;
  1577.         }
  1578.         else if (pIndex == 5) {      // bottom-right: left->up (PI -> 3PI/2)
  1579.             startAngle = PI;
  1580.         }
  1581.         else if (pIndex == 3) {      // bottom-left: up->right (3PI/2 -> 2PI)
  1582.             startAngle = 1.5f * PI;
  1583.         }
  1584.         float sweep = 0.5f * PI; // 90 degrees
  1585.  
  1586.         // center-inside test (is ball center inside the quarter sector)
  1587.         float dx = ballCenter.x - pc.x;
  1588.         float dy = ballCenter.y - pc.y;
  1589.         float r0 = sqrtf(dx * dx + dy * dy);
  1590.         float ang = NormalizeAngle(atan2f(dy, dx));
  1591.         if (AngleInRange(ang, startAngle, sweep) && r0 <= blackRadius + 1e-6f) {
  1592.             return true;
  1593.         }
  1594.  
  1595.         // Otherwise compute minimal distance to arc OR to the two radial segments (center->endpoint)
  1596.         bool tmpInsideArcSector = false;
  1597.         float distToArc = DistPointToArc(ballCenter, pc, blackRadius, startAngle, sweep, tmpInsideArcSector);
  1598.  
  1599.         // radial endpoints
  1600.         D2D1_POINT_2F ep1 = { pc.x + blackRadius * cosf(startAngle), pc.y + blackRadius * sinf(startAngle) };
  1601.         D2D1_POINT_2F ep2 = { pc.x + blackRadius * cosf(startAngle + sweep), pc.y + blackRadius * sinf(startAngle + sweep) };
  1602.         float distToRadial1 = DistPointToSegment(ballCenter, pc, ep1);
  1603.         float distToRadial2 = DistPointToSegment(ballCenter, pc, ep2);
  1604.  
  1605.         float minDist = distToArc;
  1606.         if (distToRadial1 < minDist) minDist = distToRadial1;
  1607.         if (distToRadial2 < minDist) minDist = distToRadial2;
  1608.  
  1609.         return (minDist <= BALL_RADIUS + 1e-6f);
  1610.     }
  1611.  
  1612.     // fallback
  1613.     return false;
  1614. }
  1615. /*
  1616. // Backwards-compatible alias: some places in the code call IsBallInPocket(...)
  1617. // so provide a thin wrapper that uses the precise black-area test.
  1618. bool IsBallInPocket(const Ball& b, int pIndex)
  1619. {
  1620.     return IsBallInPocketBlackArea(b, pIndex);
  1621. }
  1622.  
  1623. // Return true if the ball circle intersects the pocket black area.
  1624. // Middle pockets (indexes 1 and 4) use a horizontal capsule; corners use a circle.
  1625. bool IsBallInPocket(const Ball* ball, int p)
  1626. {
  1627.     if (!ball) return false;
  1628.     D2D1_POINT_2F center = pocketPositions[p];
  1629.  
  1630.     // Get the visual radius appropriate for this pocket (corner vs middle)
  1631.     const float pocketVis = GetPocketVisualRadius(p);
  1632.     // black mouth visual radius (tweak these multipliers to get the feel you want)
  1633.     const float blackRadius = pocketVis * 0.9f;
  1634.     // When testing collision of a ball's **edge**, include BALL_RADIUS so the test is between centers:
  1635.     const float testRadius = blackRadius + BALL_RADIUS;
  1636.  
  1637.     // Middle pockets: treat as a horizontal capsule (line segment + circular end-caps)
  1638.     if (p == 1 || p == 4) {
  1639.         const float mouthHalfLength = pocketVis * 1.2f; // half-length of opening
  1640.         D2D1_POINT_2F a = { center.x - mouthHalfLength, center.y };
  1641.         D2D1_POINT_2F b = { center.x + mouthHalfLength, center.y };
  1642.  
  1643.         D2D1_POINT_2F ab = { b.x - a.x, b.y - a.y };
  1644.         D2D1_POINT_2F ap = { ball->x - a.x, ball->y - a.y };
  1645.         float abLen2 = ab.x * ab.x + ab.y * ab.y;
  1646.         if (abLen2 <= 1e-6f) { // degenerate fallback to circle
  1647.             float dx = ball->x - center.x;
  1648.             float dy = ball->y - center.y;
  1649.             return (dx * dx + dy * dy) <= (testRadius * testRadius);
  1650.         }
  1651.  
  1652.         float t = Dot(ap, ab) / abLen2;
  1653.         t = Clampf(t, 0.0f, 1.0f);
  1654.         D2D1_POINT_2F closest = { a.x + ab.x * t, a.y + ab.y * t };
  1655.         float dx = ball->x - closest.x;
  1656.         float dy = ball->y - closest.y;
  1657.         float dist2 = dx * dx + dy * dy;
  1658.  
  1659.         // Ensure ball is coming from the table side (not from outside)
  1660.         const float verticalTolerance = BALL_RADIUS * 0.35f;
  1661.         bool tableSideOk = true;
  1662.         if (p == 1) { // top middle; table interior is below center
  1663.             if (ball->y + verticalTolerance < center.y) tableSideOk = false;
  1664.         }
  1665.         else { // p == 4 bottom middle; table interior is above center
  1666.             if (ball->y - verticalTolerance > center.y) tableSideOk = false;
  1667.         }
  1668.  
  1669.         return tableSideOk && (dist2 <= (testRadius * testRadius));
  1670.     }
  1671.     else {
  1672.         // Corner pocket: simple circle test around pocket center (black mouth)
  1673.         float dx = ball->x - center.x;
  1674.         float dy = ball->y - center.y;
  1675.         float dist2 = dx * dx + dy * dy;
  1676.         return (dist2 <= (testRadius * testRadius));
  1677.     }
  1678. }
  1679. */
  1680. // --- NEW Forward Declarations ---
  1681.  
  1682. // AI Related
  1683. struct AIShotInfo; // Define below
  1684. void TriggerAIMove();
  1685. void AIMakeDecision();
  1686. void AIPlaceCueBall();
  1687. AIShotInfo AIFindBestShot();
  1688. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
  1689. bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
  1690. Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
  1691. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
  1692. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
  1693. bool IsValidAIAimAngle(float angle); // Basic check
  1694.  
  1695. // Dialog Related
  1696. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
  1697. void ShowNewGameDialog(HINSTANCE hInstance);
  1698. void LoadSettings(); // For deserialization
  1699. void SaveSettings(); // For serialization
  1700. const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
  1701. void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
  1702.  
  1703. // --- Forward Declaration for Window Procedure --- <<< Add this line HERE
  1704. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
  1705.  
  1706. // --- NEW Struct for AI Shot Evaluation ---
  1707. struct AIShotInfo {
  1708.     bool possible = false;          // Is this shot considered viable?
  1709.     Ball* targetBall = nullptr;     // Which ball to hit
  1710.     int pocketIndex = -1;           // Which pocket to aim for (0-5)
  1711.     D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
  1712.     D2D1_POINT_2F predictedCueEndPos = { 0,0 }; // For positional play
  1713.     float angle = 0.0f;             // Calculated shot angle
  1714.     float power = 0.0f;             // Calculated shot power
  1715.     float score = -9999.0f; // Use a very low initial score
  1716.     //float score = -1.0f;            // Score for this shot (higher is better)
  1717.     //bool involves8Ball = false;     // Is the target the 8-ball?
  1718.     float spinX = 0.0f;
  1719.     float spinY = 0.0f;
  1720.     bool isBankShot = false;
  1721.     bool involves8Ball = false;
  1722. };
  1723.  
  1724. /*
  1725. table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
  1726. rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
  1727. gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
  1728. winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
  1729. headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
  1730. bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
  1731. */
  1732.  
  1733. // --- NEW Settings Serialization Functions ---
  1734. void SaveSettings() {
  1735.     std::ofstream outFile(SETTINGS_FILE_NAME);
  1736.     if (outFile.is_open()) {
  1737.         outFile << static_cast<int>(gameMode) << std::endl;
  1738.         outFile << static_cast<int>(aiDifficulty) << std::endl;
  1739.         outFile << static_cast<int>(openingBreakMode) << std::endl;
  1740.         outFile << static_cast<int>(selectedTableColor) << std::endl;
  1741.         outFile.close();
  1742.     }
  1743.     // else: Handle error, e.g., log or silently fail
  1744. }
  1745.  
  1746. void LoadSettings() {
  1747.     std::ifstream inFile(SETTINGS_FILE_NAME);
  1748.     if (inFile.is_open()) {
  1749.         int gm, aid, obm;
  1750.         if (inFile >> gm) {
  1751.             gameMode = static_cast<GameMode>(gm);
  1752.         }
  1753.         if (inFile >> aid) {
  1754.             aiDifficulty = static_cast<AIDifficulty>(aid);
  1755.         }
  1756.         if (inFile >> obm) {
  1757.             openingBreakMode = static_cast<OpeningBreakMode>(obm);
  1758.         }
  1759.         int tc;
  1760.         if (inFile >> tc) {
  1761.             selectedTableColor = static_cast<TableColor>(tc);
  1762.         }
  1763.         inFile.close();
  1764.  
  1765.         // Validate loaded settings (optional, but good practice)
  1766.         if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
  1767.         if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
  1768.         if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
  1769.     }
  1770.     // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
  1771. }
  1772. // --- End Settings Serialization Functions ---
  1773.  
  1774. // --- NEW Dialog Procedure ---
  1775. INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
  1776.     switch (message) {
  1777.     case WM_INITDIALOG:
  1778.     {
  1779.         // --- ACTION 4: Center Dialog Box ---
  1780. // Optional: Force centering if default isn't working
  1781.         RECT rcDlg, rcOwner, rcScreen;
  1782.         HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
  1783.         if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
  1784.  
  1785.         GetWindowRect(hwndOwner, &rcOwner);
  1786.         GetWindowRect(hDlg, &rcDlg);
  1787.         CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
  1788.  
  1789.         // Offset the owner rect relative to the screen if it's not the desktop
  1790.         if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
  1791.             OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
  1792.             OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
  1793.             OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
  1794.         }
  1795.  
  1796.  
  1797.         // Calculate centered position
  1798.         int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
  1799.         int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
  1800.  
  1801.         // Ensure it stays within screen bounds (optional safety)
  1802.         x = std::max(static_cast<int>(rcScreen.left), x);
  1803.         y = std::max(static_cast<int>(rcScreen.top), y);
  1804.         if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
  1805.             x = rcScreen.right - (rcDlg.right - rcDlg.left);
  1806.         if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
  1807.             y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
  1808.  
  1809.  
  1810.         // Set the dialog position
  1811.         SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
  1812.  
  1813.         // --- End Centering Code ---
  1814.  
  1815.         // Set initial state based on current global settings (or defaults)
  1816.         CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
  1817.  
  1818.         CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
  1819.             (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
  1820.  
  1821.         // Enable/Disable AI group based on initial mode
  1822.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
  1823.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
  1824.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
  1825.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
  1826.         // Set initial state for Opening Break Mode
  1827.         CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
  1828.             (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
  1829.         // Enable/Disable Opening Break group based on initial mode
  1830.         EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
  1831.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
  1832.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
  1833.         EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
  1834.         // --- NEW: Populate the Table Color ComboBox ---
  1835.         HWND hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  1836.         for (int i = 0; i < 5; ++i) {
  1837.             SendMessage(hCombo, CB_ADDSTRING, 0, (LPARAM)tableColorNames[i]);
  1838.         }
  1839.         // Set the initial selection based on the loaded/default setting
  1840.         SendMessage(hCombo, CB_SETCURSEL, (WPARAM)selectedTableColor, 0);
  1841.     }
  1842.     return (INT_PTR)TRUE;
  1843.  
  1844.     case WM_COMMAND:
  1845.     { // Add an opening brace to create a new scope for the entire case.
  1846.         HWND hCombo;
  1847.         int selectedIndex;
  1848.         switch (LOWORD(wParam)) {
  1849.         case IDC_RADIO_2P:
  1850.         case IDC_RADIO_CPU:
  1851.         {
  1852.             bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
  1853.             // Enable/Disable AI group controls based on selection
  1854.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
  1855.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
  1856.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
  1857.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
  1858.             // Also enable/disable Opening Break Mode group
  1859.             EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
  1860.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
  1861.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
  1862.             EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
  1863.         }
  1864.         return (INT_PTR)TRUE;
  1865.  
  1866.         case IDOK:
  1867.             // Retrieve selected options and store in global variables
  1868.             if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
  1869.                 gameMode = HUMAN_VS_AI;
  1870.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
  1871.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
  1872.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
  1873.  
  1874.                 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
  1875.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
  1876.                 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
  1877.             }
  1878.             else {
  1879.                 gameMode = HUMAN_VS_HUMAN;
  1880.                 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
  1881.             }
  1882.  
  1883.             // --- NEW: Retrieve selected table color ---
  1884.             hCombo = GetDlgItem(hDlg, IDC_COMBO_TABLECOLOR);
  1885.             selectedIndex = (int)SendMessage(hCombo, CB_GETCURSEL, 0, 0);
  1886.             if (selectedIndex != CB_ERR) {
  1887.                 selectedTableColor = static_cast<TableColor>(selectedIndex);
  1888.             }
  1889.  
  1890.             SaveSettings(); // Save settings when OK is pressed
  1891.             EndDialog(hDlg, IDOK); // Close dialog, return IDOK
  1892.             return (INT_PTR)TRUE;
  1893.  
  1894.         case IDCANCEL: // Handle Cancel or closing the dialog
  1895.             // Optionally, could reload settings here if you want cancel to revert to previously saved state
  1896.             EndDialog(hDlg, IDCANCEL);
  1897.             return (INT_PTR)TRUE;
  1898.         }
  1899.     } // Add a closing brace for the new scope.
  1900.     break; // End WM_COMMAND
  1901.     }
  1902.     return (INT_PTR)FALSE; // Default processing
  1903. }
  1904.  
  1905. // --- NEW Helper to Show Dialog ---
  1906. void ShowNewGameDialog(HINSTANCE hInstance) {
  1907.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
  1908.         // User clicked Start, reset game with new settings
  1909.         isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
  1910.         if (isPlayer2AI) {
  1911.             switch (aiDifficulty) {
  1912.             case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  1913.             case MEDIUM: player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  1914.             case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  1915.             }
  1916.         }
  1917.         else {
  1918.             player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  1919.         }
  1920.         // Update window title
  1921.         std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  1922.         if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  1923.         else windowTitle += L" (Human vs " + player2Info.name + L")";
  1924.         SetWindowText(hwndMain, windowTitle.c_str());
  1925.  
  1926.         // --- NEW: Apply the selected table color ---
  1927.         TABLE_COLOR = tableColorValues[selectedTableColor];
  1928.  
  1929.         InitGame(); // Re-initialize game logic & board
  1930.         InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
  1931.     }
  1932.     else {
  1933.         // User cancelled dialog - maybe just resume game? Or exit?
  1934.         // For simplicity, we do nothing, game continues as it was.
  1935.         // To exit on cancel from F2, would need more complex state management.
  1936.     }
  1937. }
  1938.  
  1939. // --- NEW Reset Game Function ---
  1940. void ResetGame(HINSTANCE hInstance) {
  1941.     // Call the helper function to show the dialog and re-init if OK clicked
  1942.     ShowNewGameDialog(hInstance);
  1943. }
  1944.  
  1945. // --- WinMain ---
  1946. int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
  1947.     if (FAILED(CoInitialize(NULL))) {
  1948.         MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
  1949.         return -1;
  1950.     }
  1951.  
  1952.     // --- NEW: Load settings at startup ---
  1953.     LoadSettings();
  1954.  
  1955.     // --- NEW: Show configuration dialog FIRST ---
  1956.     if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
  1957.         // User cancelled the dialog
  1958.         CoUninitialize();
  1959.         return 0; // Exit gracefully if dialog cancelled
  1960.     }
  1961.     // Global gameMode and aiDifficulty are now set by the DialogProc
  1962.  
  1963.     // --- Apply the selected table color to the global before anything else draws ---
  1964.     TABLE_COLOR = tableColorValues[selectedTableColor];
  1965.  
  1966.     // Set AI flag based on game mode
  1967.     isPlayer2AI = (gameMode == HUMAN_VS_AI);
  1968.     if (isPlayer2AI) {
  1969.         switch (aiDifficulty) {
  1970.         case EASY: player2Info.name = L"Virtus Pro (Easy)"/*"CPU (Easy)"*/; break;
  1971.         case MEDIUM:player2Info.name = L"Virtus Pro (Medium)"/*"CPU (Medium)"*/; break;
  1972.         case HARD: player2Info.name = L"Virtus Pro (Hard)"/*"CPU (Hard)"*/; break;
  1973.         }
  1974.     }
  1975.     else {
  1976.         player2Info.name = L"Billy Ray Cyrus"/*"Player 2"*/;
  1977.     }
  1978.     // --- End of Dialog Logic ---
  1979.  
  1980.  
  1981.     WNDCLASS wc = { };
  1982.     wc.lpfnWndProc = WndProc;
  1983.     wc.hInstance = hInstance;
  1984.     wc.lpszClassName = L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/;
  1985.     wc.hCursor = LoadCursor(NULL, IDC_ARROW);
  1986.     wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
  1987.     wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
  1988.  
  1989.     if (!RegisterClass(&wc)) {
  1990.         MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
  1991.         CoUninitialize();
  1992.         return -1;
  1993.     }
  1994.  
  1995.     // --- ACTION 4: Calculate Centered Window Position ---
  1996.     const int WINDOW_WIDTH = 1000; // Define desired width
  1997.     const int WINDOW_HEIGHT = 700; // Define desired height
  1998.     int screenWidth = GetSystemMetrics(SM_CXSCREEN);
  1999.     int screenHeight = GetSystemMetrics(SM_CYSCREEN);
  2000.     int windowX = (screenWidth - WINDOW_WIDTH) / 2;
  2001.     int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
  2002.  
  2003.     // --- Change Window Title based on mode ---
  2004.     std::wstring windowTitle = L"Midnight Pool 4"/*"Direct2D 8-Ball Pool"*/;
  2005.     if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
  2006.     else windowTitle += L" (Human vs " + player2Info.name + L")";
  2007.  
  2008.     DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
  2009.  
  2010.     hwndMain = CreateWindowEx(
  2011.         0, L"BLISS_GameEngine"/*"Direct2D_8BallPool"*/, windowTitle.c_str(), dwStyle,
  2012.         windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
  2013.         NULL, NULL, hInstance, NULL
  2014.     );
  2015.  
  2016.     if (!hwndMain) {
  2017.         MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
  2018.         CoUninitialize();
  2019.         return -1;
  2020.     }
  2021.  
  2022.     // Initialize Direct2D Resources AFTER window creation
  2023.     if (FAILED(CreateDeviceResources())) {
  2024.         MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
  2025.         DestroyWindow(hwndMain);
  2026.         CoUninitialize();
  2027.         return -1;
  2028.     }
  2029.  
  2030.     InitGame(); // Initialize game state AFTER resources are ready & mode is set
  2031.     Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
  2032.     StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
  2033.     //PlayGameMusic(hwndMain); //midi func
  2034.  
  2035.     ShowWindow(hwndMain, nCmdShow);
  2036.     UpdateWindow(hwndMain);
  2037.  
  2038.     if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
  2039.         MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
  2040.         DestroyWindow(hwndMain);
  2041.         CoUninitialize();
  2042.         return -1;
  2043.     }
  2044.  
  2045.     MSG msg = { };
  2046.     // --- Modified Main Loop ---
  2047.     // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
  2048.     // or gets reset to it via F2. The main loop runs normally once game starts.
  2049.     while (GetMessage(&msg, NULL, 0, 0)) {
  2050.         // We might need modeless dialog handling here if F2 shows dialog
  2051.         // while window is active, but DialogBoxParam is modal.
  2052.         // Let's assume F2 hides main window, shows dialog, then restarts game loop.
  2053.         // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
  2054.         TranslateMessage(&msg);
  2055.         DispatchMessage(&msg);
  2056.     }
  2057.  
  2058.  
  2059.     KillTimer(hwndMain, ID_TIMER);
  2060.     DiscardDeviceResources();
  2061.     SaveSettings(); // Save settings on exit
  2062.     CoUninitialize();
  2063.  
  2064.     return (int)msg.wParam;
  2065. }
  2066.  
  2067. // --- WndProc ---
  2068. LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
  2069.     Ball* cueBall = nullptr;
  2070.     switch (msg) {
  2071.     case WM_CREATE:
  2072.         return 0;
  2073.     case WM_PAINT:
  2074.         OnPaint();
  2075.         ValidateRect(hwnd, NULL);
  2076.         return 0;
  2077.     case WM_SIZE: {
  2078.         UINT width = LOWORD(lParam);
  2079.         UINT height = HIWORD(lParam);
  2080.         OnResize(width, height);
  2081.         return 0;
  2082.     }
  2083.     case WM_TIMER:
  2084.         if (wParam == ID_TIMER) {
  2085.             GameUpdate();
  2086.             InvalidateRect(hwnd, NULL, FALSE);
  2087.         }
  2088.         return 0;
  2089.     case WM_KEYDOWN:
  2090.     {
  2091.         cueBall = GetCueBall();
  2092.         bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
  2093.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
  2094.         if (wParam == VK_F2) {
  2095.             HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
  2096.             ResetGame(hInstance);
  2097.             return 0;
  2098.         }
  2099.         else if (wParam == VK_F1) {
  2100.             MessageBox(hwnd,
  2101.                 L"Direct2D-based StickPool game made in C++ from scratch (4827+ lines of code)\n"
  2102.                 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
  2103.                 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
  2104.                 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions. Midnight Pool 4. 'BLISS' Game Engine.\n"
  2105.                 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
  2106.                 L"About This Game", MB_OK | MB_ICONINFORMATION);
  2107.             return 0;
  2108.         }
  2109.         if (wParam == 'M' || wParam == 'm') {
  2110.             if (isMusicPlaying) {
  2111.                 StopMidi();
  2112.                 isMusicPlaying = false;
  2113.             }
  2114.             else {
  2115.                 TCHAR midiPath[MAX_PATH];
  2116.                 GetModuleFileName(NULL, midiPath, MAX_PATH);
  2117.                 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
  2118.                 if (lastBackslash != NULL) {
  2119.                     *(lastBackslash + 1) = '\0';
  2120.                 }
  2121.                 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  2122.                 StartMidi(hwndMain, midiPath);
  2123.                 isMusicPlaying = true;
  2124.             }
  2125.         }
  2126.         if (canPlayerControl) {
  2127.             bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
  2128.             float angleStep = shiftPressed ? 0.05f : 0.01f;
  2129.             float powerStep = 0.2f;
  2130.             switch (wParam) {
  2131.             case VK_LEFT:
  2132.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2133.                     cueAngle -= angleStep;
  2134.                     if (cueAngle < 0) cueAngle += 2 * PI;
  2135.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2136.                     isAiming = false;
  2137.                     isDraggingStick = false;
  2138.                     keyboardAimingActive = true;
  2139.                 }
  2140.                 break;
  2141.             case VK_RIGHT:
  2142.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2143.                     cueAngle += angleStep;
  2144.                     if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
  2145.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2146.                     isAiming = false;
  2147.                     isDraggingStick = false;
  2148.                     keyboardAimingActive = true;
  2149.                 }
  2150.                 break;
  2151.             case VK_UP:
  2152.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2153.                     shotPower -= powerStep;
  2154.                     if (shotPower < 0.0f) shotPower = 0.0f;
  2155.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2156.                     isAiming = true;
  2157.                     isDraggingStick = false;
  2158.                     keyboardAimingActive = true;
  2159.                 }
  2160.                 break;
  2161.             case VK_DOWN:
  2162.                 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  2163.                     shotPower += powerStep;
  2164.                     if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
  2165.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
  2166.                     isAiming = true;
  2167.                     isDraggingStick = false;
  2168.                     keyboardAimingActive = true;
  2169.                 }
  2170.                 break;
  2171.             case VK_SPACE:
  2172.                 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  2173.                     && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
  2174.                 {
  2175.                     if (shotPower > 0.15f) {
  2176.                         firstHitBallIdThisShot = -1;
  2177.                         cueHitObjectBallThisShot = false;
  2178.                         railHitAfterContact = false;
  2179.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  2180.                         ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  2181.                         currentGameState = SHOT_IN_PROGRESS;
  2182.                         foulCommitted = false;
  2183.                         pocketedThisTurn.clear();
  2184.                         shotPower = 0;
  2185.                         isAiming = false; isDraggingStick = false;
  2186.                         keyboardAimingActive = false;
  2187.                     }
  2188.                 }
  2189.                 break;
  2190.             case VK_ESCAPE:
  2191.                 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
  2192.                 {
  2193.                     shotPower = 0.0f;
  2194.                     isAiming = false;
  2195.                     isDraggingStick = false;
  2196.                     keyboardAimingActive = false;
  2197.                     if (currentGameState != BREAKING) {
  2198.                         currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2199.                     }
  2200.                 }
  2201.                 break;
  2202.             case 'G':
  2203.                 cheatModeEnabled = !cheatModeEnabled;
  2204.                 if (cheatModeEnabled)
  2205.                     MessageBeep(MB_ICONEXCLAMATION);
  2206.                 else
  2207.                     MessageBeep(MB_OK);
  2208.                 break;
  2209.             default:
  2210.                 break;
  2211.             }
  2212.             return 0;
  2213.         }
  2214.     }
  2215.     return 0;
  2216.     case WM_MOUSEMOVE: {
  2217.         ptMouse.x = LOWORD(lParam);
  2218.         ptMouse.y = HIWORD(lParam);
  2219.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  2220.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  2221.             int oldHover = currentlyHoveredPocket;
  2222.             currentlyHoveredPocket = -1;
  2223.             for (int i = 0; i < 6; ++i) {
  2224.                 // FIXED: Use correct radius for hover detection
  2225.                 float hoverRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  2226.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < hoverRadius * hoverRadius * 2.25f) {
  2227.                     currentlyHoveredPocket = i;
  2228.                     break;
  2229.                 }
  2230.             }
  2231.             if (oldHover != currentlyHoveredPocket) {
  2232.                 InvalidateRect(hwnd, NULL, FALSE);
  2233.             }
  2234.         }
  2235.         cueBall = GetCueBall();
  2236.         if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
  2237.             Ball* ball = GetBallById(draggingBallId);
  2238.             if (ball) {
  2239.                 ball->x = (float)ptMouse.x;
  2240.                 ball->y = (float)ptMouse.y;
  2241.                 ball->vx = ball->vy = 0.0f;
  2242.             }
  2243.             return 0;
  2244.         }
  2245.         if (!cueBall) return 0;
  2246.         if (isDraggingCueBall &&
  2247.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  2248.                 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
  2249.                 currentGameState == PRE_BREAK_PLACEMENT))
  2250.         {
  2251.             bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2252.             cueBall->x = (float)ptMouse.x;
  2253.             cueBall->y = (float)ptMouse.y;
  2254.             cueBall->vx = cueBall->vy = 0;
  2255.         }
  2256.         else if ((isAiming || isDraggingStick) &&
  2257.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  2258.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  2259.         {
  2260.             float dx = (float)ptMouse.x - cueBall->x;
  2261.             float dy = (float)ptMouse.y - cueBall->y;
  2262.             if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  2263.             if (!keyboardAimingActive) {
  2264.                 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
  2265.                 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
  2266.             }
  2267.         }
  2268.         else if (isSettingEnglish &&
  2269.             ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
  2270.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
  2271.         {
  2272.             float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  2273.             float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  2274.             float dist = GetDistance(dx, dy, 0, 0);
  2275.             if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  2276.             cueSpinX = dx / spinIndicatorRadius;
  2277.             cueSpinY = dy / spinIndicatorRadius;
  2278.         }
  2279.         else {
  2280.         }
  2281.         return 0;
  2282.     }
  2283.     case WM_LBUTTONDOWN: {
  2284.         ptMouse.x = LOWORD(lParam);
  2285.         ptMouse.y = HIWORD(lParam);
  2286.         if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
  2287.             (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
  2288.             int clickedPocketIndex = -1;
  2289.             for (int i = 0; i < 6; ++i) {
  2290.                 // FIXED: Use correct radius for click detection
  2291.                 float clickRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  2292.                 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < clickRadius * clickRadius * 2.25f) {
  2293.                     clickedPocketIndex = i;
  2294.                     break;
  2295.                 }
  2296.             }
  2297.             if (clickedPocketIndex != -1) {
  2298.                 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
  2299.                 else calledPocketP2 = clickedPocketIndex;
  2300.                 InvalidateRect(hwnd, NULL, FALSE);
  2301.                 return 0;
  2302.             }
  2303.             Ball* cueBall = GetCueBall();
  2304.             int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  2305.             if (cueBall && calledPocket != -1 && GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y) < BALL_RADIUS * BALL_RADIUS * 25) {
  2306.                 currentGameState = AIMING;
  2307.                 pocketCallMessage = L"";
  2308.                 isAiming = true;
  2309.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2310.                 return 0;
  2311.             }
  2312.             return 0;
  2313.         }
  2314.         if (cheatModeEnabled) {
  2315.             for (Ball& ball : balls) {
  2316.                 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
  2317.                 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) {
  2318.                     isDraggingCueBall = true;
  2319.                     draggingBallId = ball.id;
  2320.                     if (ball.id == 0) {
  2321.                         if (currentPlayer == 1)
  2322.                             currentGameState = BALL_IN_HAND_P1;
  2323.                         else if (currentPlayer == 2 && !isPlayer2AI)
  2324.                             currentGameState = BALL_IN_HAND_P2;
  2325.                     }
  2326.                     return 0;
  2327.                 }
  2328.             }
  2329.         }
  2330.         Ball* cueBall = GetCueBall();
  2331.         bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
  2332.         bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  2333.             currentGameState == AIMING || currentGameState == BREAKING ||
  2334.             currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
  2335.             currentGameState == PRE_BREAK_PLACEMENT);
  2336.         if (canPlayerClickInteract && canInteractState) {
  2337.             float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
  2338.             if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
  2339.                 isSettingEnglish = true;
  2340.                 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
  2341.                 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
  2342.                 float dist = GetDistance(dx, dy, 0, 0);
  2343.                 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
  2344.                 cueSpinX = dx / spinIndicatorRadius;
  2345.                 cueSpinY = dy / spinIndicatorRadius;
  2346.                 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
  2347.                 return 0;
  2348.             }
  2349.         }
  2350.         if (!cueBall) return 0;
  2351.         bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  2352.         bool isPlayerAllowedToPlace = (isPlacingBall &&
  2353.             ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  2354.                 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  2355.                 (currentGameState == PRE_BREAK_PLACEMENT)));
  2356.         if (isPlayerAllowedToPlace) {
  2357.             float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  2358.             if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
  2359.                 isDraggingCueBall = true;
  2360.                 isAiming = false; isDraggingStick = false;
  2361.             }
  2362.             else {
  2363.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2364.                 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
  2365.                     cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
  2366.                     cueBall->vx = 0; cueBall->vy = 0;
  2367.                     isDraggingCueBall = false;
  2368.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  2369.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  2370.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  2371.                     cueAngle = 0.0f;
  2372.                 }
  2373.             }
  2374.             return 0;
  2375.         }
  2376.         bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
  2377.             (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
  2378.         if (canAim) {
  2379.             const float stickDrawLength = 150.0f * 1.4f;
  2380.             float currentStickAngle = cueAngle + PI;
  2381.             D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
  2382.             D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
  2383.             float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
  2384.             float stickClickThresholdSq = 36.0f;
  2385.             float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
  2386.             float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
  2387.             bool clickedStick = (distToStickSq < stickClickThresholdSq);
  2388.             bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
  2389.             if (clickedStick || clickedCueArea) {
  2390.                 isDraggingStick = clickedStick && !clickedCueArea;
  2391.                 isAiming = clickedCueArea;
  2392.                 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  2393.                 shotPower = 0;
  2394.                 float dx = (float)ptMouse.x - cueBall->x;
  2395.                 float dy = (float)ptMouse.y - cueBall->y;
  2396.                 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
  2397.                 if (currentGameState != BREAKING) currentGameState = AIMING;
  2398.             }
  2399.         }
  2400.         return 0;
  2401.     }
  2402.     case WM_LBUTTONUP: {
  2403.         // --- Cheat-mode pocket processing: uses the exact same IsBallInPocketBlackArea() test
  2404.         if (cheatModeEnabled && draggingBallId != -1) {
  2405.             Ball* b = GetBallById(draggingBallId);
  2406.             if (b) {
  2407.                 bool playedPocketSound = false;
  2408.                 for (int p = 0; p < 6; ++p) {
  2409.                     // Use the same precise black-area test used by physics.
  2410.                     if (!IsBallTouchingPocketMask_D2D(*b, p)) continue;
  2411.  
  2412.                     // Mark pocketed and record which pocket (especially important for the 8-ball)
  2413.                     if (b->id == 8) {
  2414.                         lastEightBallPocketIndex = p;
  2415.                     }
  2416.                     b->isPocketed = true;
  2417.                     b->vx = b->vy = 0.0f;
  2418.                     pocketedThisTurn.push_back(b->id);
  2419.                     if (!playedPocketSound) {
  2420.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  2421.                         playedPocketSound = true;
  2422.                     }
  2423.  
  2424.                     // If table is still "open" (no assignments yet) and the pocketed ball is an object ball,
  2425.                     // assign types to the shooter immediately.
  2426.                     if (player1Info.assignedType == BallType::NONE
  2427.                         && player2Info.assignedType == BallType::NONE
  2428.                         && (b->type == BallType::SOLID || b->type == BallType::STRIPE))
  2429.                     {
  2430.                         AssignPlayerBallTypes(b->type);
  2431.                         // Give the shooter one ball counted immediately (they just pocketed it)
  2432.                         if (currentPlayer == 1) player1Info.ballsPocketedCount = 1;
  2433.                         else                    player2Info.ballsPocketedCount = 1;
  2434.                     }
  2435.  
  2436.                     // Update pocket counts (don't count cue or 8-ball here)
  2437.                     if (b->id != 0 && b->id != 8) {
  2438.                         if (b->type == player1Info.assignedType) player1Info.ballsPocketedCount++;
  2439.                         else if (b->type == player2Info.assignedType) player2Info.ballsPocketedCount++;
  2440.                     }
  2441.  
  2442.                     // If this was an object ball (not the 8-ball), check if shooter now has 7 balls.
  2443.                     if (b->id != 8) {
  2444.                         PlayerInfo& shooter = (currentPlayer == 1 ? player1Info : player2Info);
  2445.                         if (shooter.ballsPocketedCount >= 7) {
  2446.                             // Prepare for called-pocket selection for the 8-ball
  2447.                             if (currentPlayer == 1) calledPocketP1 = -1;
  2448.                             else                  calledPocketP2 = -1;
  2449.                             currentGameState = (currentPlayer == 1) ? CHOOSING_POCKET_P1 : CHOOSING_POCKET_P2;
  2450.                             // finalize this cheat pocket step and return from WM_LBUTTONUP
  2451.                             draggingBallId = -1;
  2452.                             isDraggingCueBall = false;
  2453.                             return 0;
  2454.                         }
  2455.                         else {
  2456.                             // Keep the shooter's turn (cheat pocket gives them another opportunity)
  2457.                             currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2458.                             if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = true;
  2459.                         }
  2460.                     }
  2461.                     else {
  2462.                         // 8-ball pocketed during cheat: enforce the "called pocket" rule.
  2463.                         int called = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  2464.                         int actual = lastEightBallPocketIndex;
  2465.                         currentGameState = GAME_OVER;
  2466.                         if (actual == called) {
  2467.                             gameOverMessage = (currentPlayer == 1 ? player1Info.name : player2Info.name)
  2468.                                 + L" Wins! (Called pocket: " + std::to_wstring(called)
  2469.                                 + L", Actual pocket: " + std::to_wstring(actual) + L")";
  2470.                         }
  2471.                         else {
  2472.                             gameOverMessage = (currentPlayer == 1 ? player2Info.name : player1Info.name)
  2473.                                 + L" Wins! (Called: " + std::to_wstring(called)
  2474.                                 + L", Actual: " + std::to_wstring(actual) + L")";
  2475.                         }
  2476.                         // end the message processing immediately
  2477.                         draggingBallId = -1;
  2478.                         isDraggingCueBall = false;
  2479.                         return 0;
  2480.                     }
  2481.  
  2482.                     // we pocketed this ball — don't test other pockets for it
  2483.                     break;
  2484.                 } // end pocket loop
  2485.             }
  2486.         }
  2487.         ptMouse.x = LOWORD(lParam);
  2488.         ptMouse.y = HIWORD(lParam);
  2489.         Ball* cueBall = GetCueBall();
  2490.         if ((isAiming || isDraggingStick) &&
  2491.             ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
  2492.                 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
  2493.         {
  2494.             bool wasAiming = isAiming;
  2495.             bool wasDraggingStick = isDraggingStick;
  2496.             isAiming = false; isDraggingStick = false;
  2497.             if (shotPower > 0.15f) {
  2498.                 if (currentGameState != AI_THINKING) {
  2499.                     firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false;
  2500.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  2501.                     ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
  2502.                     currentGameState = SHOT_IN_PROGRESS;
  2503.                     foulCommitted = false; pocketedThisTurn.clear();
  2504.                 }
  2505.             }
  2506.             else if (currentGameState != AI_THINKING) {
  2507.                 if (currentGameState == BREAKING) {}
  2508.                 else {
  2509.                     currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  2510.                     if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
  2511.                 }
  2512.             }
  2513.             shotPower = 0;
  2514.         }
  2515.         if (isDraggingCueBall) {
  2516.             isDraggingCueBall = false;
  2517.             bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
  2518.             bool isPlayerAllowed = (isPlacingState &&
  2519.                 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
  2520.                     (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
  2521.                     (currentGameState == PRE_BREAK_PLACEMENT)));
  2522.             if (isPlayerAllowed && cueBall) {
  2523.                 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  2524.                 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
  2525.                     if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
  2526.                     else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
  2527.                     else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
  2528.                     cueAngle = 0.0f;
  2529.                     if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
  2530.                     {
  2531.                         CheckAndTransitionToPocketChoice(currentPlayer);
  2532.                     }
  2533.                 }
  2534.                 else {}
  2535.             }
  2536.         }
  2537.         if (isSettingEnglish) {
  2538.             isSettingEnglish = false;
  2539.         }
  2540.         return 0;
  2541.     }
  2542.     case WM_DESTROY:
  2543.         isMusicPlaying = false;
  2544.         if (midiDeviceID != 0) {
  2545.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  2546.             midiDeviceID = 0;
  2547.             SaveSettings();
  2548.         }
  2549.         PostQuitMessage(0);
  2550.         return 0;
  2551.     default:
  2552.         return DefWindowProc(hwnd, msg, wParam, lParam);
  2553.     }
  2554.     return 0;
  2555. }  
  2556.  
  2557. // --- Direct2D Resource Management ---
  2558.  
  2559. HRESULT CreateDeviceResources() {
  2560.     HRESULT hr = S_OK;
  2561.  
  2562.     // Create Direct2D Factory
  2563.     if (!pFactory) {
  2564.         hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
  2565.         if (FAILED(hr)) return hr;
  2566.     }
  2567.  
  2568.     // Create DirectWrite Factory
  2569.     if (!pDWriteFactory) {
  2570.         hr = DWriteCreateFactory(
  2571.             DWRITE_FACTORY_TYPE_SHARED,
  2572.             __uuidof(IDWriteFactory),
  2573.             reinterpret_cast<IUnknown**>(&pDWriteFactory)
  2574.         );
  2575.         if (FAILED(hr)) return hr;
  2576.     }
  2577.  
  2578.     // Create Text Formats
  2579.     if (!pTextFormat && pDWriteFactory) {
  2580.         hr = pDWriteFactory->CreateTextFormat(
  2581.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2582.             16.0f, L"en-us", &pTextFormat
  2583.         );
  2584.         if (FAILED(hr)) return hr;
  2585.         // Center align text
  2586.         pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2587.         pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2588.     }
  2589.     if (!pTextFormatBold && pDWriteFactory) {
  2590.         hr = pDWriteFactory->CreateTextFormat(
  2591.             L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2592.             16.0f, L"en-us", &pTextFormatBold
  2593.         );
  2594.         if (SUCCEEDED(hr)) {
  2595.             pTextFormatBold->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2596.             pTextFormatBold->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2597.         }
  2598.     }
  2599.     if (!pLargeTextFormat && pDWriteFactory) {
  2600.         hr = pDWriteFactory->CreateTextFormat(
  2601.             L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2602.             48.0f, L"en-us", &pLargeTextFormat
  2603.         );
  2604.         if (FAILED(hr)) return hr;
  2605.         pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
  2606.         pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2607.     }
  2608.  
  2609.     if (!pBallNumFormat && pDWriteFactory)
  2610.     {
  2611.         hr = pDWriteFactory->CreateTextFormat(
  2612.             L"Segoe UI", nullptr,
  2613.             DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
  2614.             10.0f,                       // << small size for ball decals
  2615.             L"en-us",
  2616.             &pBallNumFormat);
  2617.         if (SUCCEEDED(hr))
  2618.         {
  2619.             pBallNumFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  2620.             pBallNumFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  2621.         }
  2622.     }
  2623.  
  2624.  
  2625.     // Create Render Target (needs valid hwnd)
  2626.     if (!pRenderTarget && hwndMain) {
  2627.         RECT rc;
  2628.         GetClientRect(hwndMain, &rc);
  2629.         D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
  2630.  
  2631.         hr = pFactory->CreateHwndRenderTarget(
  2632.             D2D1::RenderTargetProperties(),
  2633.             D2D1::HwndRenderTargetProperties(hwndMain, size),
  2634.             &pRenderTarget
  2635.         );
  2636.         if (FAILED(hr)) {
  2637.             // If failed, release factories if they were created in this call
  2638.             SafeRelease(&pTextFormat);
  2639.             SafeRelease(&pLargeTextFormat);
  2640.             SafeRelease(&pDWriteFactory);
  2641.             SafeRelease(&pFactory);
  2642.             pRenderTarget = nullptr; // Ensure it's null on failure
  2643.             return hr;
  2644.         }
  2645.     }
  2646.  
  2647.     //CreatePocketMasks_D2D((int)TABLE_WIDTH, (int)TABLE_HEIGHT, TABLE_LEFT, TABLE_TOP, 1.0f);
  2648.         // --- FOOLPROOF FIX: Create a larger, padded canvas for the collision masks ---
  2649.     // This padding ensures that the enlarged pocket shapes are not clipped.
  2650.     const float maskPadding = MIDDLE_HOLE_VISUAL_RADIUS * 3.0f; // Generous padding
  2651.     CreatePocketMasks_D2D(
  2652.         (int)TABLE_WIDTH + 2 * (int)maskPadding,    // New, wider canvas
  2653.         (int)TABLE_HEIGHT + 2 * (int)maskPadding,   // New, taller canvas
  2654.         TABLE_LEFT - maskPadding,                   // Shift the origin to the top-left of the new canvas
  2655.         TABLE_TOP - maskPadding,
  2656.         1.0f
  2657.     );
  2658.  
  2659.     return hr;
  2660. }
  2661.  
  2662. void DiscardDeviceResources() {
  2663.     SafeRelease(&pRenderTarget);
  2664.     SafeRelease(&pTextFormat);
  2665.     SafeRelease(&pTextFormatBold);
  2666.     SafeRelease(&pLargeTextFormat);
  2667.     SafeRelease(&pBallNumFormat);            // NEW
  2668.     SafeRelease(&pDWriteFactory);
  2669.     ShutdownPocketMasks_D2D();
  2670.     // Keep pFactory until application exit? Or release here too? Let's release.
  2671.     SafeRelease(&pFactory);
  2672. }
  2673.  
  2674. void OnResize(UINT width, UINT height) {
  2675.     if (pRenderTarget) {
  2676.         D2D1_SIZE_U size = D2D1::SizeU(width, height);
  2677.         pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
  2678.     }
  2679. }
  2680.  
  2681. // --- Game Initialization ---
  2682. void InitGame() {
  2683.     srand((unsigned int)time(NULL)); // Seed random number generator
  2684.     isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
  2685.     aiPlannedShotDetails.isValid = false; // Reset AI planned shot
  2686.     aiIsDisplayingAim = false;
  2687.     aiAimDisplayFramesLeft = 0;
  2688.     // ... (rest of InitGame())
  2689.  
  2690.     // --- Ensure pocketed list is clear from the absolute start ---
  2691.     pocketedThisTurn.clear();
  2692.  
  2693.     balls.clear(); // Clear existing balls
  2694.  
  2695.     // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
  2696.     player1Info.assignedType = BallType::NONE;
  2697.     player1Info.ballsPocketedCount = 0;
  2698.     // Player 1 Name usually remains "Player 1"
  2699.     player2Info.assignedType = BallType::NONE;
  2700.     player2Info.ballsPocketedCount = 0;
  2701.     // Player 2 Name is set based on gameMode in ShowNewGameDialog
  2702.         // --- Reset any 8?Ball call state on new game ---
  2703.     lastEightBallPocketIndex = -1;
  2704.     calledPocketP1 = -1;
  2705.     calledPocketP2 = -1;
  2706.     pocketCallMessage = L"";
  2707.     aiPlannedShotDetails.isValid = false; // THIS IS THE CRITICAL FIX: Reset the AI's plan.
  2708.  
  2709.     // Create Cue Ball (ID 0)
  2710.     // Initial position will be set during PRE_BREAK_PLACEMENT state
  2711.     balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false, 0.0f, 0.0f });
  2712.  
  2713.     // --- Create Object Balls (Temporary List) ---
  2714.     std::vector<Ball> objectBalls;
  2715.     // Solids (1-7, Yellow)
  2716.     for (int i = 1; i <= 7; ++i) {
  2717.         //objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
  2718.         objectBalls.push_back({ i, BallType::SOLID, 0,0,0,0,
  2719.                     GetBallColor(i), false });
  2720.     }
  2721.     // Stripes (9-15, Red)
  2722.     for (int i = 9; i <= 15; ++i) {
  2723.         //objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
  2724.         objectBalls.push_back({ i, BallType::STRIPE, 0,0,0,0,
  2725.                     GetBallColor(i), false });
  2726.     }
  2727.     // 8-Ball (ID 8) - Add it to the list to be placed
  2728.     //objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
  2729.     objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0,0,0,0,
  2730.           GetBallColor(8), false });
  2731.  
  2732.  
  2733.     // --- Racking Logic (Improved) ---
  2734.     float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
  2735.     float spacingY = BALL_RADIUS * 2.0f * 1.0f;   // Vertical spacing
  2736.  
  2737.     // Define rack positions (0-14 indices corresponding to triangle spots)
  2738.     D2D1_POINT_2F rackPositions[15];
  2739.     int rackIndex = 0;
  2740.     for (int row = 0; row < 5; ++row) {
  2741.         for (int col = 0; col <= row; ++col) {
  2742.             if (rackIndex >= 15) break;
  2743.             float x = RACK_POS_X + row * spacingX;
  2744.             float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
  2745.             rackPositions[rackIndex++] = D2D1::Point2F(x, y);
  2746.         }
  2747.     }
  2748.  
  2749.     // Separate 8-ball
  2750.     Ball eightBall;
  2751.     std::vector<Ball> otherBalls; // Solids and Stripes
  2752.     bool eightBallFound = false;
  2753.     for (const auto& ball : objectBalls) {
  2754.         if (ball.id == 8) {
  2755.             eightBall = ball;
  2756.             eightBallFound = true;
  2757.         }
  2758.         else {
  2759.             otherBalls.push_back(ball);
  2760.         }
  2761.     }
  2762.     // Ensure 8 ball was actually created (should always be true)
  2763.     if (!eightBallFound) {
  2764.         // Handle error - perhaps recreate it? For now, proceed.
  2765.         eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
  2766.     }
  2767.  
  2768.  
  2769.     // Shuffle the other 14 balls
  2770.     // Use std::shuffle if available (C++11 and later) for better randomness
  2771.     // std::random_device rd;
  2772.     // std::mt19937 g(rd());
  2773.     // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
  2774.     std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
  2775.  
  2776.     // --- Place balls into the main 'balls' vector in rack order ---
  2777.     // Important: Add the cue ball (already created) first.
  2778.     // (Cue ball added at the start of the function now)
  2779.  
  2780.     // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
  2781.     int eightBallRackIndex = 4;
  2782.     eightBall.x = rackPositions[eightBallRackIndex].x;
  2783.     eightBall.y = rackPositions[eightBallRackIndex].y;
  2784.     eightBall.vx = 0;
  2785.     eightBall.vy = 0;
  2786.     eightBall.isPocketed = false;
  2787.     balls.push_back(eightBall); // Add 8 ball to the main vector
  2788.  
  2789.     // 2. Place the shuffled Solids and Stripes in the remaining spots
  2790.     size_t otherBallIdx = 0;
  2791.     //int otherBallIdx = 0;
  2792.     for (int i = 0; i < 15; ++i) {
  2793.         if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
  2794.  
  2795.         if (otherBallIdx < otherBalls.size()) {
  2796.             Ball& ballToPlace = otherBalls[otherBallIdx++];
  2797.             ballToPlace.x = rackPositions[i].x;
  2798.             ballToPlace.y = rackPositions[i].y;
  2799.             ballToPlace.vx = 0;
  2800.             ballToPlace.vy = 0;
  2801.             ballToPlace.isPocketed = false;
  2802.             balls.push_back(ballToPlace); // Add to the main game vector
  2803.         }
  2804.     }
  2805.     // --- End Racking Logic ---
  2806.  
  2807.  
  2808.     // --- Determine Who Breaks and Initial State ---
  2809.     if (isPlayer2AI) {
  2810.         /*// AI Mode: Randomly decide who breaks
  2811.         if ((rand() % 2) == 0) {
  2812.             // AI (Player 2) breaks
  2813.             currentPlayer = 2;
  2814.             currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
  2815.             aiTurnPending = true; // Trigger AI logic
  2816.         }
  2817.         else {
  2818.             // Player 1 (Human) breaks
  2819.             currentPlayer = 1;
  2820.             currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
  2821.             aiTurnPending = false;*/
  2822.         switch (openingBreakMode) {
  2823.         case CPU_BREAK:
  2824.             currentPlayer = 2; // AI breaks
  2825.             currentGameState = PRE_BREAK_PLACEMENT;
  2826.             aiTurnPending = true;
  2827.             break;
  2828.         case P1_BREAK:
  2829.             currentPlayer = 1; // Player 1 breaks
  2830.             currentGameState = PRE_BREAK_PLACEMENT;
  2831.             aiTurnPending = false;
  2832.             break;
  2833.         case FLIP_COIN_BREAK:
  2834.             if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
  2835.                 currentPlayer = 2; // AI breaks
  2836.                 currentGameState = PRE_BREAK_PLACEMENT;
  2837.                 aiTurnPending = true;
  2838.             }
  2839.             else {
  2840.                 currentPlayer = 1; // Player 1 breaks
  2841.                 currentGameState = PRE_BREAK_PLACEMENT;
  2842.                 aiTurnPending = false;
  2843.             }
  2844.             break;
  2845.         default: // Fallback to CPU break
  2846.             currentPlayer = 2;
  2847.             currentGameState = PRE_BREAK_PLACEMENT;
  2848.             aiTurnPending = true;
  2849.             break;
  2850.         }
  2851.     }
  2852.     else {
  2853.         // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
  2854.         currentPlayer = 1;
  2855.         currentGameState = PRE_BREAK_PLACEMENT;
  2856.         aiTurnPending = false; // No AI involved
  2857.     }
  2858.  
  2859.     // Reset other relevant game state variables
  2860.     foulCommitted = false;
  2861.     gameOverMessage = L"";
  2862.     firstBallPocketedAfterBreak = false;
  2863.     // pocketedThisTurn cleared at start
  2864.     // Reset shot parameters and input flags
  2865.     shotPower = 0.0f;
  2866.     cueSpinX = 0.0f;
  2867.     cueSpinY = 0.0f;
  2868.     isAiming = false;
  2869.     isDraggingCueBall = false;
  2870.     isSettingEnglish = false;
  2871.     cueAngle = 0.0f; // Reset aim angle
  2872. }
  2873.  
  2874.  
  2875. // --------------------------------------------------------------------------------
  2876. // Full GameUpdate(): integrates AI call?pocket ? aim ? shoot (no omissions)
  2877. // --------------------------------------------------------------------------------
  2878. void GameUpdate() {
  2879.     // --- 1) Handle an in?flight shot ---
  2880.     if (currentGameState == SHOT_IN_PROGRESS) {
  2881.         UpdatePhysics();
  2882.         // ? clear old 8?ball pocket info before any new pocket checks
  2883.         //lastEightBallPocketIndex = -1;
  2884.         CheckCollisions();
  2885.         CheckPockets(); // FIX: This line was missing. It's essential to check for pocketed balls every frame.
  2886.  
  2887.         if (AreBallsMoving()) {
  2888.             isAiming = false;
  2889.             aiIsDisplayingAim = false;
  2890.         }
  2891.  
  2892.         if (!AreBallsMoving()) {
  2893.             ProcessShotResults();
  2894.         }
  2895.         return;
  2896.     }
  2897.  
  2898.     // --- 2) CPU’s turn (table is static) ---
  2899.     if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
  2900.         // ??? If we've just auto?entered AI_THINKING for the 8?ball call, actually make the decision ???
  2901.         if (currentGameState == AI_THINKING && aiTurnPending) {
  2902.             aiTurnPending = false;        // consume the pending flag
  2903.             AIMakeDecision();             // CPU calls its pocket or plans its shot
  2904.             return;                       // done this tick
  2905.         }
  2906.  
  2907.         // ??? Automate the AI pocket?selection click ???
  2908.         if (currentGameState == CHOOSING_POCKET_P2) {
  2909.             // AI immediately confirms its call and moves to thinking/shooting
  2910.             currentGameState = AI_THINKING;
  2911.             aiTurnPending = true;
  2912.             return; // process on next tick
  2913.         }
  2914.         // 2A) If AI is displaying its aim line, count down then shoot
  2915.         if (aiIsDisplayingAim) {
  2916.             aiAimDisplayFramesLeft--;
  2917.             if (aiAimDisplayFramesLeft <= 0) {
  2918.                 aiIsDisplayingAim = false;
  2919.                 if (aiPlannedShotDetails.isValid) {
  2920.                     firstHitBallIdThisShot = -1;
  2921.                     cueHitObjectBallThisShot = false;
  2922.                     railHitAfterContact = false;
  2923.                     std::thread([](const TCHAR* soundName) {
  2924.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  2925.                         }, TEXT("cue.wav")).detach();
  2926.  
  2927.                         ApplyShot(
  2928.                             aiPlannedShotDetails.power,
  2929.                             aiPlannedShotDetails.angle,
  2930.                             aiPlannedShotDetails.spinX,
  2931.                             aiPlannedShotDetails.spinY
  2932.                         );
  2933.                         aiPlannedShotDetails.isValid = false;
  2934.                 }
  2935.                 currentGameState = SHOT_IN_PROGRESS;
  2936.                 foulCommitted = false;
  2937.                 pocketedThisTurn.clear();
  2938.             }
  2939.             return;
  2940.         }
  2941.  
  2942.         // 2B) Immediately after calling pocket, transition into AI_THINKING
  2943.         if (currentGameState == CHOOSING_POCKET_P2 && aiTurnPending) {
  2944.             // Start thinking/shooting right away—no human click required
  2945.             currentGameState = AI_THINKING;
  2946.             aiTurnPending = false;
  2947.             AIMakeDecision();
  2948.             return;
  2949.         }
  2950.  
  2951.         // 2C) If AI has pending actions (break, ball?in?hand, or normal turn)
  2952.         if (aiTurnPending) {
  2953.             if (currentGameState == BALL_IN_HAND_P2) {
  2954.                 AIPlaceCueBall();
  2955.                 currentGameState = AI_THINKING;
  2956.                 aiTurnPending = false;
  2957.                 AIMakeDecision();
  2958.             }
  2959.             else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  2960.                 AIBreakShot();
  2961.             }
  2962.             else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) {
  2963.                 currentGameState = AI_THINKING;
  2964.                 aiTurnPending = false;
  2965.                 AIMakeDecision();
  2966.             }
  2967.             return;
  2968.         }
  2969.     }
  2970. }
  2971.  
  2972.  
  2973. // --- Physics and Collision ---
  2974. void UpdatePhysics() {
  2975.     for (size_t i = 0; i < balls.size(); ++i) {
  2976.         Ball& b = balls[i];
  2977.         if (!b.isPocketed) {
  2978.  
  2979.             // --- FOOLPROOF FIX: Update rotation based on velocity ---
  2980.             float speed = sqrtf(b.vx * b.vx + b.vy * b.vy);
  2981.             if (speed > 0.01f) {
  2982.                 // The amount of rotation is proportional to the distance traveled.
  2983.                 // We can use the horizontal velocity component for a simple, effective rolling look.
  2984.                 b.rotationAngle += b.vx / (BALL_RADIUS * 10.0f); // Adjust divisor for spin speed
  2985.  
  2986.                 // Normalize the angle to keep it within the 0 to 2*PI range
  2987.                 const float TWO_PI = 2.0f * 3.1415926535f;
  2988.                 if (b.rotationAngle > TWO_PI) b.rotationAngle -= TWO_PI;
  2989.                 if (b.rotationAngle < 0) b.rotationAngle += TWO_PI;
  2990.             }
  2991.             // --- End Rotation Fix ---
  2992.  
  2993.                         // move
  2994.             b.x += b.vx;
  2995.             b.y += b.vy;
  2996.  
  2997.             // --- Update rotation from distance travelled this frame ---
  2998.             // Use the magnitude of the displacement (speed) to compute angular change:
  2999.             //   deltaAngle (radians) = distance / radius
  3000.             // This produces physically-plausible rotation regardless of direction.
  3001.             /* {
  3002.                 float speed = sqrtf(b.vx * b.vx + b.vy * b.vy); // distance units per frame
  3003.                 if (speed > 1e-6f) {
  3004.                     float deltaAngle = speed / BALL_RADIUS; // radians
  3005.                     // subtract -> clockwise feel, you can invert if you prefer
  3006.                     b.rotationAngle -= deltaAngle;
  3007.                     // keep angle bounded to avoid large drift (optional)
  3008.                     if (b.rotationAngle > 2.0f * PI || b.rotationAngle < -2.0f * PI)
  3009.                         b.rotationAngle = fmodf(b.rotationAngle, 2.0f * PI);
  3010.                 }
  3011.             }*/
  3012.  
  3013.             // Apply friction
  3014.             b.vx *= FRICTION;
  3015.             b.vy *= FRICTION;
  3016.  
  3017.             // --- ROTATION UPDATE: convert linear motion into visual rotation ---
  3018.             // Use the distance moved per frame (approx = speed since position increased by vx/vy per tick)
  3019.             // and convert to angular delta: deltaAngle = distance / radius.
  3020.             // Choose a sign so opposite directions produce opposite rotation.
  3021.             {
  3022.                 const float eps = 1e-5f;
  3023.                 float vx = b.vx;
  3024.                 float vy = b.vy;
  3025.                 float speed = sqrtf(vx * vx + vy * vy);
  3026.                 if (speed > eps) {
  3027.                     // distance moved this frame (we assume velocity units per tick)
  3028.                     float distance = speed; // velocities are per-tick; scale if you have explicit dt
  3029.                     float deltaAngle = distance / BALL_RADIUS; // radians per tick
  3030.  
  3031.                     // Heuristic sign: prefer rightwards motion to rotate positive, leftwards negative.
  3032.                     // This is a simple robust sign determination that gives visually plausible spin.
  3033.                     float sign = (vx > 0.0f) ? 1.0f : -1.0f;
  3034.  
  3035.                     // A small refinement: if horizontal velocity near zero, base sign on vertical
  3036.                     if (fabsf(vx) < 0.0001f) sign = (vy > 0.0f) ? 1.0f : -1.0f;
  3037.  
  3038.                     b.rotationAngle += deltaAngle * sign;
  3039.  
  3040.                     // Keep angle bounded to avoid large values
  3041.                     if (b.rotationAngle > 2.0f * PI) b.rotationAngle = fmodf(b.rotationAngle, 2.0f * PI);
  3042.                     if (b.rotationAngle < -2.0f * PI) b.rotationAngle = fmodf(b.rotationAngle, 2.0f * PI);
  3043.  
  3044.                     // rotation axis = direction perpendicular to travel. Used for highlight offset.
  3045.                     b.rotationAxis = atan2f(vy, vx) + (PI * 0.5f);
  3046.                 }
  3047.             }
  3048.             // --- End rotation update ---
  3049.  
  3050.             // Stop balls if velocity is very low
  3051.             if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
  3052.                 b.vx = 0;
  3053.                 b.vy = 0;
  3054.             }
  3055.  
  3056.             /* -----------------------------------------------------------------
  3057.    Additional clamp to guarantee the ball never escapes the table.
  3058.    The existing wall–collision code can momentarily disable the
  3059.    reflection test while the ball is close to a pocket mouth;
  3060.    that rare case allowed it to ‘slide’ through the cushion and
  3061.    leave the board.  We therefore enforce a final boundary check
  3062.    after the normal physics step.
  3063.    ----------------------------------------------------------------- */
  3064.             const float leftBound = TABLE_LEFT + BALL_RADIUS;
  3065.             const float rightBound = TABLE_RIGHT - BALL_RADIUS;
  3066.             const float topBound = TABLE_TOP + BALL_RADIUS;
  3067.             const float bottomBound = TABLE_BOTTOM - BALL_RADIUS;
  3068.  
  3069.             if (b.x < leftBound) { b.x = leftBound;   b.vx = fabsf(b.vx); }
  3070.             if (b.x > rightBound) { b.x = rightBound;  b.vx = -fabsf(b.vx); }
  3071.             if (b.y < topBound) { b.y = topBound;    b.vy = fabsf(b.vy); }
  3072.             if (b.y > bottomBound) { b.y = bottomBound; b.vy = -fabsf(b.vy); }
  3073.         }
  3074.     }
  3075. }
  3076.  
  3077. void CheckCollisions() {
  3078.     float left = TABLE_LEFT;
  3079.     float right = TABLE_RIGHT;
  3080.     float top = TABLE_TOP;
  3081.     float bottom = TABLE_BOTTOM;
  3082.  
  3083.     bool playedWallSoundThisFrame = false;
  3084.     bool playedCollideSoundThisFrame = false;
  3085.     for (size_t i = 0; i < balls.size(); ++i) {
  3086.         Ball& b1 = balls[i];
  3087.         if (b1.isPocketed) continue;
  3088.  
  3089.         bool nearPocket[6];
  3090.         for (int p = 0; p < 6; ++p) {
  3091.             // Use correct radius to check if a ball is near a pocket to prevent wall collisions
  3092.             float physicalPocketRadius = ((p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS) * 1.05f;
  3093.             float checkRadiusSq = (physicalPocketRadius + BALL_RADIUS) * (physicalPocketRadius + BALL_RADIUS) * 1.1f;
  3094.             nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < checkRadiusSq;
  3095.         }
  3096.  
  3097.         bool nearTopLeftPocket = nearPocket[0];
  3098.         bool nearTopMidPocket = nearPocket[1];
  3099.         bool nearTopRightPocket = nearPocket[2];
  3100.         bool nearBottomLeftPocket = nearPocket[3];
  3101.         bool nearBottomMidPocket = nearPocket[4];
  3102.         bool nearBottomRightPocket = nearPocket[5];
  3103.         bool collidedWallThisBall = false;
  3104.         if (b1.x - BALL_RADIUS < left) {
  3105.             if (!nearTopLeftPocket && !nearBottomLeftPocket) {
  3106.                 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  3107.                 if (!playedWallSoundThisFrame) {
  3108.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3109.                     playedWallSoundThisFrame = true;
  3110.                 }
  3111.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3112.             }
  3113.         }
  3114.         if (b1.x + BALL_RADIUS > right) {
  3115.             if (!nearTopRightPocket && !nearBottomRightPocket) {
  3116.                 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
  3117.                 if (!playedWallSoundThisFrame) {
  3118.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3119.                     playedWallSoundThisFrame = true;
  3120.                 }
  3121.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3122.             }
  3123.         }
  3124.         if (b1.y - BALL_RADIUS < top) {
  3125.             if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
  3126.                 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  3127.                 if (!playedWallSoundThisFrame) {
  3128.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3129.                     playedWallSoundThisFrame = true;
  3130.                 }
  3131.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3132.             }
  3133.         }
  3134.         if (b1.y + BALL_RADIUS > bottom) {
  3135.             if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
  3136.                 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
  3137.                 if (!playedWallSoundThisFrame) {
  3138.                     std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
  3139.                     playedWallSoundThisFrame = true;
  3140.                 }
  3141.                 if (cueHitObjectBallThisShot) railHitAfterContact = true;
  3142.             }
  3143.         }
  3144.         if (collidedWallThisBall) {
  3145.             if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
  3146.             if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
  3147.             cueSpinX *= 0.7f; cueSpinY *= 0.7f;
  3148.         }
  3149.         for (size_t j = i + 1; j < balls.size(); ++j) {
  3150.             Ball& b2 = balls[j];
  3151.             if (b2.isPocketed) continue;
  3152.             float dx = b2.x - b1.x; float dy = b2.y - b1.y;
  3153.             float distSq = dx * dx + dy * dy;
  3154.             float minDist = BALL_RADIUS * 2.0f;
  3155.             if (distSq > 1e-6 && distSq < minDist * minDist) {
  3156.                 float dist = sqrtf(distSq);
  3157.                 float overlap = minDist - dist;
  3158.                 float nx = dx / dist; float ny = dy / dist;
  3159.                 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
  3160.                 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
  3161.                 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
  3162.                 float velAlongNormal = rvx * nx + rvy * ny;
  3163.                 if (velAlongNormal > 0) {
  3164.                     if (!playedCollideSoundThisFrame) {
  3165.                         std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
  3166.                         playedCollideSoundThisFrame = true;
  3167.                     }
  3168.                     if (firstHitBallIdThisShot == -1) {
  3169.                         if (b1.id == 0) {
  3170.                             firstHitBallIdThisShot = b2.id;
  3171.                             cueHitObjectBallThisShot = true;
  3172.                         }
  3173.                         else if (b2.id == 0) {
  3174.                             firstHitBallIdThisShot = b1.id;
  3175.                             cueHitObjectBallThisShot = true;
  3176.                         }
  3177.                     }
  3178.                     else if (b1.id == 0 || b2.id == 0) {
  3179.                         cueHitObjectBallThisShot = true;
  3180.                     }
  3181.                     float impulse = velAlongNormal;
  3182.                     b1.vx -= impulse * nx; b1.vy -= impulse * ny;
  3183.                     b2.vx += impulse * nx; b2.vy += impulse * ny;
  3184.                     if (b1.id == 0 || b2.id == 0) {
  3185.                         float spinEffectFactor = 0.08f;
  3186.                         b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  3187.                         b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  3188.                         b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
  3189.                         b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
  3190.                         cueSpinX *= 0.85f; cueSpinY *= 0.85f;
  3191.                     }
  3192.                 }
  3193.             }
  3194.         }
  3195.     }
  3196. }
  3197.  
  3198.  
  3199. // Replace older CheckPockets() with this stricter test which uses the black-area helper.
  3200. bool CheckPockets() {
  3201.     bool anyPocketed = false;
  3202.     bool playedPocketSound = false;
  3203.  
  3204.     for (auto& b : balls) {
  3205.         if (b.isPocketed) continue;
  3206.  
  3207.         for (int p = 0; p < 6; ++p) {
  3208.             if (!IsBallTouchingPocketMask_D2D(b, p)) continue;
  3209.  
  3210.             // Mark pocketed
  3211.             if (b.id == 8) {
  3212.                 lastEightBallPocketIndex = p;
  3213.             }
  3214.             b.isPocketed = true;
  3215.             b.vx = b.vy = 0.0f;
  3216.             pocketedThisTurn.push_back(b.id);
  3217.             anyPocketed = true;
  3218.  
  3219.             if (!playedPocketSound) {
  3220.                 // Play pocket sound once per CheckPockets() pass
  3221.                 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
  3222.                 playedPocketSound = true;
  3223.             }
  3224.             break; // this ball is pocketed; continue with next ball
  3225.         }
  3226.     }
  3227.     return anyPocketed;
  3228. }
  3229.  
  3230.  
  3231. /*bool CheckPockets() {
  3232.     bool anyPocketed = false;
  3233.     bool ballPocketedThisCheck = false;
  3234.     for (auto& b : balls) {
  3235.         if (b.isPocketed) continue;
  3236.         for (int p = 0; p < 6; ++p) {
  3237.             D2D1_POINT_2F center = pocketPositions[p];
  3238.             float dx = b.x - center.x;
  3239.             float dy = b.y - center.y;
  3240.            
  3241.             // Use the correct radius for the pocket being checked
  3242.             float currentPocketRadius = (p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  3243.  
  3244.             bool isInPocket = false;
  3245.             // The pocketing conditions now use the correct radius
  3246.             if (p == 1) {
  3247.                 if (dy >= 0 && dx * dx + dy * dy <= currentPocketRadius * currentPocketRadius)
  3248.                     isInPocket = true;
  3249.             }
  3250.             else if (p == 4) {
  3251.                 if (dy <= 0 && dx * dx + dy * dy <= currentPocketRadius * currentPocketRadius)
  3252.                     isInPocket = true;
  3253.             }
  3254.             else {
  3255.                 if (dx * dx + dy * dy <= currentPocketRadius * currentPocketRadius)
  3256.                     isInPocket = true;
  3257.             }
  3258.  
  3259.             if (isInPocket) {
  3260.                 if (b.id == 8) {
  3261.                     lastEightBallPocketIndex = p;
  3262.                 }
  3263.                 b.isPocketed = true;
  3264.                 b.vx = b.vy = 0.0f;
  3265.                 pocketedThisTurn.push_back(b.id);
  3266.                 anyPocketed = true;
  3267.                 if (!ballPocketedThisCheck) {
  3268.                     std::thread([](const TCHAR* soundName) {
  3269.                         PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
  3270.                         }, TEXT("pocket.wav")).detach();
  3271.                         ballPocketedThisCheck = true;
  3272.                 }
  3273.                 break;
  3274.             }
  3275.         }
  3276.     }
  3277.     return anyPocketed;
  3278. }*/
  3279.  
  3280.  
  3281. bool AreBallsMoving() {
  3282.     for (size_t i = 0; i < balls.size(); ++i) {
  3283.         if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
  3284.             return true;
  3285.         }
  3286.     }
  3287.     return false;
  3288. }
  3289.  
  3290. void RespawnCueBall(bool behindHeadstring) {
  3291.     Ball* cueBall = GetCueBall();
  3292.     if (cueBall) {
  3293.         // Determine the initial target position
  3294.         float targetX, targetY;
  3295.         if (behindHeadstring) {
  3296.             targetX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
  3297.             targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  3298.         }
  3299.         else {
  3300.             targetX = TABLE_LEFT + TABLE_WIDTH / 2.0f;
  3301.             targetY = TABLE_TOP + TABLE_HEIGHT / 2.0f;
  3302.         }
  3303.  
  3304.         // FOOLPROOF FIX: Check if the target spot is valid. If not, nudge it until it is.
  3305.         int attempts = 0;
  3306.         while (!IsValidCueBallPosition(targetX, targetY, behindHeadstring) && attempts < 100) {
  3307.             // If the spot is occupied, try nudging the ball slightly.
  3308.             targetX += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  3309.             targetY += (static_cast<float>(rand() % 100 - 50) / 50.0f) * BALL_RADIUS;
  3310.             // Clamp to stay within reasonable bounds
  3311.             targetX = std::max(TABLE_LEFT + BALL_RADIUS, std::min(targetX, TABLE_RIGHT - BALL_RADIUS));
  3312.             targetY = std::max(TABLE_TOP + BALL_RADIUS, std::min(targetY, TABLE_BOTTOM - BALL_RADIUS));
  3313.             attempts++;
  3314.         }
  3315.  
  3316.         // Set the final, valid position.
  3317.         cueBall->x = targetX;
  3318.         cueBall->y = targetY;
  3319.         cueBall->vx = 0;
  3320.         cueBall->vy = 0;
  3321.         cueBall->isPocketed = false;
  3322.  
  3323.         // Set the correct game state for ball-in-hand.
  3324.         if (currentPlayer == 1) {
  3325.             currentGameState = BALL_IN_HAND_P1;
  3326.             aiTurnPending = false;
  3327.         }
  3328.         else {
  3329.             currentGameState = BALL_IN_HAND_P2;
  3330.             if (isPlayer2AI) {
  3331.                 aiTurnPending = true;
  3332.             }
  3333.         }
  3334.     }
  3335. }
  3336.  
  3337.  
  3338. // --- Game Logic ---
  3339.  
  3340. void ApplyShot(float power, float angle, float spinX, float spinY) {
  3341.     Ball* cueBall = GetCueBall();
  3342.     if (cueBall) {
  3343.  
  3344.         // --- Play Cue Strike Sound (Threaded) ---
  3345.         if (power > 0.1f) { // Only play if it's an audible shot
  3346.             std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
  3347.         }
  3348.         // --- End Sound ---
  3349.  
  3350.         cueBall->vx = cosf(angle) * power;
  3351.         cueBall->vy = sinf(angle) * power;
  3352.  
  3353.         // Apply English (Spin) - Simplified effect (Unchanged)
  3354.         cueBall->vx += sinf(angle) * spinY * 0.5f;
  3355.         cueBall->vy -= cosf(angle) * spinY * 0.5f;
  3356.         cueBall->vx -= cosf(angle) * spinX * 0.5f;
  3357.         cueBall->vy -= sinf(angle) * spinX * 0.5f;
  3358.  
  3359.         // Store spin (Unchanged)
  3360.         cueSpinX = spinX;
  3361.         cueSpinY = spinY;
  3362.  
  3363.         // --- Reset Foul Tracking flags for the new shot ---
  3364.         // (Also reset in LBUTTONUP, but good to ensure here too)
  3365.         firstHitBallIdThisShot = -1;      // No ball hit yet
  3366.         cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
  3367.         railHitAfterContact = false;     // No rail hit after contact yet
  3368.         // --- End Reset ---
  3369.  
  3370.                 // If this was the opening break shot, clear the flag
  3371.         if (isOpeningBreakShot) {
  3372.             isOpeningBreakShot = false; // Mark opening break as taken
  3373.         }
  3374.     }
  3375. }
  3376.  
  3377.  
  3378. // ---------------------------------------------------------------------
  3379. //  ProcessShotResults()
  3380. // ---------------------------------------------------------------------
  3381. void ProcessShotResults() {
  3382.     bool cueBallPocketed = false;
  3383.     bool eightBallPocketed = false;
  3384.     bool playerContinuesTurn = false;
  3385.  
  3386.     // --- Step 1: Update Ball Counts FIRST (THE CRITICAL FIX) ---
  3387.     // We must update the score before any other game logic runs.
  3388.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  3389.     int ownBallsPocketedThisTurn = 0;
  3390.  
  3391.     for (int id : pocketedThisTurn) {
  3392.         Ball* b = GetBallById(id);
  3393.         if (!b) continue;
  3394.  
  3395.         if (b->id == 0) {
  3396.             cueBallPocketed = true;
  3397.         }
  3398.         else if (b->id == 8) {
  3399.             eightBallPocketed = true;
  3400.         }
  3401.         else {
  3402.             // This is a numbered ball. Update the pocketed count for the correct player.
  3403.             if (b->type == player1Info.assignedType && player1Info.assignedType != BallType::NONE) {
  3404.                 player1Info.ballsPocketedCount++;
  3405.             }
  3406.             else if (b->type == player2Info.assignedType && player2Info.assignedType != BallType::NONE) {
  3407.                 player2Info.ballsPocketedCount++;
  3408.             }
  3409.  
  3410.             if (b->type == shootingPlayer.assignedType) {
  3411.                 ownBallsPocketedThisTurn++;
  3412.             }
  3413.         }
  3414.     }
  3415.  
  3416.     if (ownBallsPocketedThisTurn > 0) {
  3417.         playerContinuesTurn = true;
  3418.     }
  3419.  
  3420.     // --- Step 2: Handle Game-Ending 8-Ball Shot ---
  3421.     // Now that the score is updated, this check will have the correct information.
  3422.     if (eightBallPocketed) {
  3423.         CheckGameOverConditions(true, cueBallPocketed);
  3424.         if (currentGameState == GAME_OVER) {
  3425.             pocketedThisTurn.clear();
  3426.             return;
  3427.         }
  3428.     }
  3429.  
  3430.     // --- Step 3: Check for Fouls ---
  3431.     bool turnFoul = false;
  3432.     if (cueBallPocketed) {
  3433.         turnFoul = true;
  3434.     }
  3435.     else {
  3436.         Ball* firstHit = GetBallById(firstHitBallIdThisShot);
  3437.         if (!firstHit) { // Rule: Hitting nothing is a foul.
  3438.             turnFoul = true;
  3439.         }
  3440.         else { // Rule: Hitting the wrong ball type is a foul.
  3441.             if (player1Info.assignedType != BallType::NONE) { // Colors are assigned.
  3442.                 // We check if the player WAS on the 8-ball BEFORE this shot.
  3443.                 bool wasOnEightBall = (shootingPlayer.assignedType != BallType::NONE && (shootingPlayer.ballsPocketedCount - ownBallsPocketedThisTurn) >= 7);
  3444.                 if (wasOnEightBall) {
  3445.                     if (firstHit->id != 8) turnFoul = true;
  3446.                 }
  3447.                 else {
  3448.                     if (firstHit->type != shootingPlayer.assignedType) turnFoul = true;
  3449.                 }
  3450.             }
  3451.         }
  3452.     } //reenable below disabled for debugging
  3453.     //if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && pocketedThisTurn.empty()) {
  3454.         //turnFoul = true;
  3455.     //}
  3456.     foulCommitted = turnFoul;
  3457.  
  3458.     // --- Step 4: Final State Transition ---
  3459.     if (foulCommitted) {
  3460.         SwitchTurns();
  3461.         RespawnCueBall(false);
  3462.     }
  3463.     else if (player1Info.assignedType == BallType::NONE && !pocketedThisTurn.empty() && !cueBallPocketed) {
  3464.         // Assign types on the break.
  3465.         for (int id : pocketedThisTurn) {
  3466.             Ball* b = GetBallById(id);
  3467.             if (b && b->type != BallType::EIGHT_BALL) {
  3468.                 AssignPlayerBallTypes(b->type);
  3469.                 break;
  3470.             }
  3471.         }
  3472.         CheckAndTransitionToPocketChoice(currentPlayer);
  3473.     }
  3474.     else if (playerContinuesTurn) {
  3475.         // The player's turn continues. Now the check will work correctly.
  3476.         CheckAndTransitionToPocketChoice(currentPlayer);
  3477.     }
  3478.     else {
  3479.         SwitchTurns();
  3480.     }
  3481.  
  3482.     pocketedThisTurn.clear();
  3483. }
  3484.  
  3485. /*
  3486. // --- Step 3: Final State Transition ---
  3487. if (foulCommitted) {
  3488.     SwitchTurns();
  3489.     RespawnCueBall(false);
  3490. }
  3491. else if (playerContinuesTurn) {
  3492.     CheckAndTransitionToPocketChoice(currentPlayer);
  3493. }
  3494. else {
  3495.     SwitchTurns();
  3496. }
  3497.  
  3498. pocketedThisTurn.clear();
  3499. } */
  3500.  
  3501. //  Assign groups AND optionally give the shooter his first count.
  3502. bool AssignPlayerBallTypes(BallType firstPocketedType, bool creditShooter /*= true*/)
  3503. {
  3504.     if (firstPocketedType != SOLID && firstPocketedType != STRIPE)
  3505.         return false;                                 // safety
  3506.  
  3507.     /* ---------------------------------------------------------
  3508.        1.  Decide the groups
  3509.     --------------------------------------------------------- */
  3510.     if (currentPlayer == 1)
  3511.     {
  3512.         player1Info.assignedType = firstPocketedType;
  3513.         player2Info.assignedType =
  3514.             (firstPocketedType == SOLID) ? STRIPE : SOLID;
  3515.     }
  3516.     else
  3517.     {
  3518.         player2Info.assignedType = firstPocketedType;
  3519.         player1Info.assignedType =
  3520.             (firstPocketedType == SOLID) ? STRIPE : SOLID;
  3521.     }
  3522.  
  3523.     /* ---------------------------------------------------------
  3524.        2.  Count the very ball that made the assignment
  3525.     --------------------------------------------------------- */
  3526.     if (creditShooter)
  3527.     {
  3528.         if (currentPlayer == 1)
  3529.             ++player1Info.ballsPocketedCount;
  3530.         else
  3531.             ++player2Info.ballsPocketedCount;
  3532.     }
  3533.     return true;
  3534. }
  3535.  
  3536. /*bool AssignPlayerBallTypes(BallType firstPocketedType) {
  3537.     if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
  3538.         if (currentPlayer == 1) {
  3539.             player1Info.assignedType = firstPocketedType;
  3540.             player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  3541.         }
  3542.         else {
  3543.             player2Info.assignedType = firstPocketedType;
  3544.             player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
  3545.         }
  3546.         return true; // Assignment was successful
  3547.     }
  3548.     return false; // No assignment made (e.g., 8-ball was pocketed on break)
  3549. }*/
  3550. // If 8-ball was first (illegal on break generally), rules vary.
  3551. // Here, we might ignore assignment until a solid/stripe is pocketed legally.
  3552. // Or assign based on what *else* was pocketed, if anything.
  3553. // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
  3554.  
  3555.  
  3556. // --- Called in ProcessShotResults() after pocket detection ---
  3557. void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  3558. {
  3559.     // Only care if the 8?ball really went in:
  3560.     if (!eightBallPocketed) return;
  3561.  
  3562.     // Who’s shooting now?
  3563.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  3564.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  3565.  
  3566.     // Which pocket did we CALL?
  3567.     int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3568.     // Which pocket did it ACTUALLY fall into?
  3569.     int actual = lastEightBallPocketIndex;
  3570.  
  3571.     // Check legality: must have called a pocket ?0, must match actual,
  3572.     // must have pocketed all 7 of your balls first, and must not have scratched.
  3573.     bool legal = (called >= 0)
  3574.         && (called == actual)
  3575.         && (shooter.ballsPocketedCount >= 7)
  3576.         && (!cueBallPocketed);
  3577.  
  3578.     // Build a message that shows both values for debugging/tracing:
  3579.     if (legal) {
  3580.         gameOverMessage = shooter.name
  3581.             + L" Wins! "
  3582.             + L"(Called: " + std::to_wstring(called)
  3583.             + L", Actual: " + std::to_wstring(actual) + L")";
  3584.     }
  3585.     else {
  3586.         gameOverMessage = opponent.name
  3587.             + L" Wins! (Illegal 8-Ball) "
  3588.             + L"(Called: " + std::to_wstring(called)
  3589.             + L", Actual: " + std::to_wstring(actual) + L")";
  3590.     }
  3591.  
  3592.     currentGameState = GAME_OVER;
  3593. }
  3594.  
  3595.  
  3596.  
  3597. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  3598.     if (!eightBallPocketed) return;
  3599.  
  3600.     PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
  3601.     PlayerInfo& opponentPlayer = (currentPlayer == 1) ? player2Info : player1Info;
  3602.  
  3603.     // Handle 8-ball on break: re-spot and continue.
  3604.     if (player1Info.assignedType == BallType::NONE) {
  3605.         Ball* b = GetBallById(8);
  3606.         if (b) { b->isPocketed = false; b->x = RACK_POS_X; b->y = RACK_POS_Y; b->vx = b->vy = 0; }
  3607.         if (cueBallPocketed) foulCommitted = true;
  3608.         return;
  3609.     }
  3610.  
  3611.     // --- FOOLPROOF WIN/LOSS LOGIC ---
  3612.     bool wasOnEightBall = IsPlayerOnEightBall(currentPlayer);
  3613.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3614.     int actualPocket = -1;
  3615.  
  3616.     // Find which pocket the 8-ball actually went into.
  3617.     for (int id : pocketedThisTurn) {
  3618.         if (id == 8) {
  3619.             Ball* b = GetBallById(8); // This ball is already marked as pocketed, but we need its last coords.
  3620.             if (b) {
  3621.                 for (int p_idx = 0; p_idx < 6; ++p_idx) {
  3622.                     // Check last known position against pocket centers
  3623.                     if (GetDistanceSq(b->x, b->y, pocketPositions[p_idx].x, pocketPositions[p_idx].y) < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  3624.                         actualPocket = p_idx;
  3625.                         break;
  3626.                     }
  3627.                 }
  3628.             }
  3629.             break;
  3630.         }
  3631.     }
  3632.  
  3633.     // Evaluate win/loss based on a clear hierarchy of rules.
  3634.     if (!wasOnEightBall) {
  3635.         gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball Pocketed Early)";
  3636.     }
  3637.     else if (cueBallPocketed) {
  3638.         gameOverMessage = opponentPlayer.name + L" Wins! (Scratched on 8-Ball)";
  3639.     }
  3640.     else if (calledPocket == -1) {
  3641.         gameOverMessage = opponentPlayer.name + L" Wins! (Pocket Not Called)";
  3642.     }
  3643.     else if (actualPocket != calledPocket) {
  3644.         gameOverMessage = opponentPlayer.name + L" Wins! (8-Ball in Wrong Pocket)";
  3645.     }
  3646.     else {
  3647.         // WIN! All loss conditions failed, this must be a legal win.
  3648.         gameOverMessage = shootingPlayer.name + L" Wins!";
  3649.     }
  3650.  
  3651.     currentGameState = GAME_OVER;
  3652. }*/
  3653.  
  3654. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  3655. {
  3656.     if (!eightBallPocketed) return;
  3657.  
  3658.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  3659.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  3660.     // Which pocket did we call?
  3661.     int called = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3662.     // Which pocket did the ball really fall into?
  3663.     int actual = lastEightBallPocketIndex;
  3664.  
  3665.     // Legal victory only if:
  3666.     //  1) Shooter had already pocketed 7 of their object balls,
  3667.     //  2) They called a pocket,
  3668.     //  3) The 8?ball actually fell into that same pocket,
  3669.     //  4) They did not scratch on the 8?ball.
  3670.     bool legal =
  3671.         (shooter.ballsPocketedCount >= 7) &&
  3672.         (called >= 0) &&
  3673.         (called == actual) &&
  3674.         (!cueBallPocketed);
  3675.  
  3676.     if (legal) {
  3677.         gameOverMessage = shooter.name + L" Wins! "
  3678.             L"(called: " + std::to_wstring(called) +
  3679.             L", actual: " + std::to_wstring(actual) + L")";
  3680.     }
  3681.     else {
  3682.         gameOverMessage = opponent.name + L" Wins! (illegal 8-ball) "
  3683.         // For debugging you can append:
  3684.         + L" (called: " + std::to_wstring(called)
  3685.         + L", actual: " + std::to_wstring(actual) + L")";
  3686.     }
  3687.  
  3688.     currentGameState = GAME_OVER;
  3689. }*/
  3690.  
  3691. // ????????????????????????????????????????????????????????????????
  3692. //  CheckGameOverConditions()
  3693. //     – Called when the 8-ball has fallen.
  3694. //     – Decides who wins and builds the gameOverMessage.
  3695. // ????????????????????????????????????????????????????????????????
  3696. /*void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed)
  3697. {
  3698.     if (!eightBallPocketed) return;                     // safety
  3699.  
  3700.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  3701.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  3702.  
  3703.     int calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3704.     int actualPocket = lastEightBallPocketIndex;
  3705.  
  3706.     bool clearedSeven = (shooter.ballsPocketedCount >= 7);
  3707.     bool noScratch = !cueBallPocketed;
  3708.     bool callMade = (calledPocket >= 0);
  3709.  
  3710.     // helper ? turn “-1” into "None" for readability
  3711.     auto pocketToStr = [](int idx) -> std::wstring
  3712.     {
  3713.         return (idx >= 0) ? std::to_wstring(idx) : L"None";
  3714.     };
  3715.  
  3716.     if (clearedSeven && noScratch && callMade && actualPocket == calledPocket)
  3717.     {
  3718.         // legitimate win
  3719.         gameOverMessage =
  3720.             shooter.name +
  3721.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  3722.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  3723.     }
  3724.     else
  3725.     {
  3726.         // wrong pocket, scratch, or early 8-ball
  3727.         gameOverMessage =
  3728.             opponent.name +
  3729.             L" Wins! (Called pocket: " + pocketToStr(calledPocket) +
  3730.             L", Actual pocket: " + pocketToStr(actualPocket) + L")";
  3731.     }
  3732.  
  3733.     currentGameState = GAME_OVER;
  3734. }*/
  3735.  
  3736. /* void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
  3737.     if (!eightBallPocketed) return; // Only when 8-ball actually pocketed
  3738.  
  3739.     PlayerInfo& shooter = (currentPlayer == 1) ? player1Info : player2Info;
  3740.     PlayerInfo& opponent = (currentPlayer == 1) ? player2Info : player1Info;
  3741.     bool      onEightRoll = IsPlayerOnEightBall(currentPlayer);
  3742.     int       calledPocket = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  3743.     int       actualPocket = -1;
  3744.     Ball* bEight = GetBallById(8);
  3745.  
  3746.     // locate which hole the 8-ball went into
  3747.     if (bEight) {
  3748.         for (int i = 0; i < 6; ++i) {
  3749.             if (GetDistanceSq(bEight->x, bEight->y,
  3750.                 pocketPositions[i].x, pocketPositions[i].y)
  3751.                 < POCKET_RADIUS * POCKET_RADIUS * 1.5f) {
  3752.                 actualPocket = i; break;
  3753.             }
  3754.         }
  3755.     }
  3756.  
  3757.     // 1) On break / pre-assignment: re-spot & continue
  3758.     if (player1Info.assignedType == BallType::NONE) {
  3759.         if (bEight) {
  3760.             bEight->isPocketed = false;
  3761.             bEight->x = RACK_POS_X; bEight->y = RACK_POS_Y;
  3762.             bEight->vx = bEight->vy = 0;
  3763.         }
  3764.         if (cueBallPocketed) foulCommitted = true;
  3765.         return;
  3766.     }
  3767.  
  3768.     // 2) Loss if pocketed 8 early
  3769.     if (!onEightRoll) {
  3770.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" pocketed 8-ball early)";
  3771.     }
  3772.     // 3) Loss if scratched
  3773.     else if (cueBallPocketed) {
  3774.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" scratched on 8-ball)";
  3775.     }
  3776.     // 4) Loss if no pocket call
  3777.     else if (calledPocket < 0) {
  3778.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" did not call a pocket)";
  3779.     }
  3780.     // 5) Loss if in wrong pocket
  3781.     else if (actualPocket != calledPocket) {
  3782.         gameOverMessage = opponent.name + L" Wins! (" + shooter.name + L" 8-ball in wrong pocket)";
  3783.     }
  3784.     // 6) Otherwise, valid win
  3785.     else {
  3786.         gameOverMessage = shooter.name + L" Wins!";
  3787.     }
  3788.  
  3789.     currentGameState = GAME_OVER;
  3790. } */
  3791.  
  3792.  
  3793. // Switch the shooter, handle fouls and decide what state we go to next.
  3794. // ────────────────────────────────────────────────────────────────
  3795. //  SwitchTurns – final version (arrow–leak bug fixed)
  3796. // ────────────────────────────────────────────────────────────────
  3797. void SwitchTurns()
  3798. {
  3799.     /* --------------------------------------------------------- */
  3800.     /* 1.  Hand the table over to the other player               */
  3801.     /* --------------------------------------------------------- */
  3802.     currentPlayer = (currentPlayer == 1) ? 2 : 1;
  3803.  
  3804.     /* --------------------------------------------------------- */
  3805.     /* 2.  Generic per–turn resets                               */
  3806.     /* --------------------------------------------------------- */
  3807.     isAiming = false;
  3808.     shotPower = 0.0f;
  3809.     currentlyHoveredPocket = -1;
  3810.  
  3811.     /* --------------------------------------------------------- */
  3812.     /* 3.  Wipe every previous pocket call                       */
  3813.     /*    (the new shooter will choose again if needed)          */
  3814.     /* --------------------------------------------------------- */
  3815.     calledPocketP1 = -1;
  3816.     calledPocketP2 = -1;
  3817.     pocketCallMessage.clear();
  3818.  
  3819.     /* --------------------------------------------------------- */
  3820.     /* 4.  Handle fouls — cue-ball in hand overrides everything  */
  3821.     /* --------------------------------------------------------- */
  3822.     if (foulCommitted)
  3823.     {
  3824.         if (currentPlayer == 1)            // human
  3825.         {
  3826.             currentGameState = BALL_IN_HAND_P1;
  3827.             aiTurnPending = false;
  3828.         }
  3829.         else                               // P2
  3830.         {
  3831.             currentGameState = BALL_IN_HAND_P2;
  3832.             aiTurnPending = isPlayer2AI;   // AI will place cue-ball
  3833.         }
  3834.  
  3835.         foulCommitted = false;
  3836.         return;                            // we're done for this frame
  3837.     }
  3838.  
  3839.     /* --------------------------------------------------------- */
  3840.     /* 5.  Normal flow                                           */
  3841.     /*    Will put us in  ∘ PLAYER?_TURN                         */
  3842.     /*                    ∘ CHOOSING_POCKET_P?                   */
  3843.     /*                    ∘ AI_THINKING  (for CPU)               */
  3844.     /* --------------------------------------------------------- */
  3845.     CheckAndTransitionToPocketChoice(currentPlayer);
  3846. }
  3847.  
  3848.  
  3849. void AIBreakShot() {
  3850.     Ball* cueBall = GetCueBall();
  3851.     if (!cueBall) return;
  3852.  
  3853.     // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
  3854.     // AI will place the cue ball and then plan the shot.
  3855.     if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
  3856.         // Place cue ball in the kitchen randomly
  3857.         /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
  3858.         float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
  3859.         float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
  3860.         float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
  3861.  
  3862.         // --- AI Places Cue Ball for Break ---
  3863. // Decide if placing center or side. For simplicity, let's try placing slightly off-center
  3864. // towards one side for a more angled break, or center for direct apex hit.
  3865. // A common strategy is to hit the second ball of the rack.
  3866.  
  3867.         float placementY = RACK_POS_Y; // Align vertically with the rack center
  3868.         float placementX;
  3869.  
  3870.         // Randomly choose a side or center-ish placement for variation.
  3871.         int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
  3872.  
  3873.         if (placementChoice == 0) { // Left-ish
  3874.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
  3875.         }
  3876.         else if (placementChoice == 2) { // Right-ish
  3877.             placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
  3878.         }
  3879.         else { // Center-ish
  3880.             placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
  3881.         }
  3882.         placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
  3883.  
  3884.         bool validPos = false;
  3885.         int attempts = 0;
  3886.         while (!validPos && attempts < 100) {
  3887.             /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
  3888.             cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
  3889.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
  3890.                 validPos = true; // [cite: 1591]*/
  3891.                 // Try the chosen X, but vary Y slightly to find a clear spot
  3892.             cueBall->x = placementX;
  3893.             cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
  3894.             cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
  3895.  
  3896.             if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
  3897.                 validPos = true;
  3898.             }
  3899.             attempts++; // [cite: 1592]
  3900.         }
  3901.         if (!validPos) {
  3902.             // Fallback position
  3903.             /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
  3904.             cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
  3905.             if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
  3906.                 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
  3907.                 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
  3908.             }
  3909.         }
  3910.         cueBall->vx = 0; // [cite: 1595]
  3911.         cueBall->vy = 0; // [cite: 1596]
  3912.  
  3913.         // Plan a break shot: aim at the center of the rack (apex ball)
  3914.         float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
  3915.         float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
  3916.  
  3917.         float dx = targetX - cueBall->x; // [cite: 1599]
  3918.         float dy = targetY - cueBall->y; // [cite: 1600]
  3919.         float shotAngle = atan2f(dy, dx); // [cite: 1600]
  3920.         float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
  3921.  
  3922.             cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
  3923.             cueBall->y = RACK_POS_Y;
  3924.         }
  3925.         cueBall->vx = 0; cueBall->vy = 0;
  3926.  
  3927.         // --- AI Plans the Break Shot ---
  3928.         float targetX, targetY;
  3929.         // If cue ball is near center of kitchen width, aim for apex.
  3930.         // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
  3931.         float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
  3932.         if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
  3933.             // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
  3934.             targetX = RACK_POS_X; // Apex ball X
  3935.             targetY = RACK_POS_Y; // Apex ball Y
  3936.         }
  3937.         else {
  3938.             // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
  3939.             // This is a simplification. A more robust way is to find the actual second ball.
  3940.             // For now, aim slightly off the apex towards the side the cue ball is on.
  3941.             targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
  3942.             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
  3943.         }
  3944.  
  3945.         float dx = targetX - cueBall->x;
  3946.         float dy = targetY - cueBall->y;
  3947.         float shotAngle = atan2f(dy, dx);
  3948.         float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
  3949.  
  3950.         // Store planned shot details for the AI
  3951.         /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
  3952.         aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
  3953.         aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
  3954.         aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
  3955.         aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
  3956.  
  3957.         aiPlannedShotDetails.angle = shotAngle;
  3958.         aiPlannedShotDetails.power = shotPowerValue;
  3959.         aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
  3960.         aiPlannedShotDetails.spinY = 0.0f;
  3961.         aiPlannedShotDetails.isValid = true;
  3962.  
  3963.         // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
  3964.         /*::cueAngle = aiPlannedShotDetails.angle;      // [cite: 1109, 1603] Update global cueAngle
  3965.         ::shotPower = aiPlannedShotDetails.power;     // [cite: 1109, 1604] Update global shotPower
  3966.         ::cueSpinX = aiPlannedShotDetails.spinX;    // [cite: 1109]
  3967.         ::cueSpinY = aiPlannedShotDetails.spinY;    // [cite: 1110]*/
  3968.  
  3969.         ::cueAngle = aiPlannedShotDetails.angle;
  3970.         ::shotPower = aiPlannedShotDetails.power;
  3971.         ::cueSpinX = aiPlannedShotDetails.spinX;
  3972.         ::cueSpinY = aiPlannedShotDetails.spinY;
  3973.  
  3974.         // Set up for AI display via GameUpdate
  3975.         /*aiIsDisplayingAim = true;                   // [cite: 1104] Enable AI aiming visualization
  3976.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
  3977.  
  3978.         currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
  3979.                                         // GameUpdate will handle the aiAimDisplayFramesLeft countdown
  3980.                                         // and then execute the shot using aiPlannedShotDetails.
  3981.                                         // isOpeningBreakShot will be set to false within ApplyShot.
  3982.  
  3983.         // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
  3984.  
  3985.         aiIsDisplayingAim = true;
  3986.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  3987.         currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
  3988.         aiTurnPending = false;
  3989.  
  3990.         return; // The break shot is now planned and will be executed by GameUpdate
  3991.     }
  3992.  
  3993.     // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
  3994.     //    though current game logic only calls it for PRE_BREAK_PLACEMENT)
  3995.     //    This part can be extended if AIBreakShot needs to handle other scenarios.
  3996.     //    For now, the primary logic is above.
  3997. }
  3998.  
  3999. // --- Helper Functions ---
  4000.  
  4001. Ball* GetBallById(int id) {
  4002.     for (size_t i = 0; i < balls.size(); ++i) {
  4003.         if (balls[i].id == id) {
  4004.             return &balls[i];
  4005.         }
  4006.     }
  4007.     return nullptr;
  4008. }
  4009.  
  4010. Ball* GetCueBall() {
  4011.     return GetBallById(0);
  4012. }
  4013.  
  4014. float GetDistance(float x1, float y1, float x2, float y2) {
  4015.     return sqrtf(GetDistanceSq(x1, y1, x2, y2));
  4016. }
  4017.  
  4018. float GetDistanceSq(float x1, float y1, float x2, float y2) {
  4019.     float dx = x2 - x1;
  4020.     float dy = y2 - y1;
  4021.     return dx * dx + dy * dy;
  4022. }
  4023.  
  4024. bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
  4025.     // Basic bounds check (inside cushions)
  4026.     float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
  4027.     float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
  4028.     float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
  4029.     float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
  4030.  
  4031.     if (x < left || x > right || y < top || y > bottom) {
  4032.         return false;
  4033.     }
  4034.  
  4035.     // Check headstring restriction if needed
  4036.     if (checkHeadstring && x >= HEADSTRING_X) {
  4037.         return false;
  4038.     }
  4039.  
  4040.     // Check overlap with other balls
  4041.     for (size_t i = 0; i < balls.size(); ++i) {
  4042.         if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
  4043.             if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
  4044.                 return false; // Overlapping another ball
  4045.             }
  4046.         }
  4047.     }
  4048.  
  4049.     return true;
  4050. }
  4051.  
  4052. // --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
  4053.  
  4054. // Checks if a player has pocketed all their balls and is now on the 8-ball.
  4055. bool IsPlayerOnEightBall(int player) {
  4056.     PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
  4057.     if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
  4058.         Ball* eightBall = GetBallById(8);
  4059.         return (eightBall && !eightBall->isPocketed);
  4060.     }
  4061.     return false;
  4062. }
  4063.  
  4064. void CheckAndTransitionToPocketChoice(int playerID) {
  4065.     bool needsToCall = IsPlayerOnEightBall(playerID);
  4066.  
  4067.     if (needsToCall) {
  4068.         if (playerID == 1) { // Human Player 1
  4069.             currentGameState = CHOOSING_POCKET_P1;
  4070.             pocketCallMessage = player1Info.name + L": Choose a pocket for the 8-Ball...";
  4071.             if (calledPocketP1 == -1) calledPocketP1 = 2; // Default to bottom-right
  4072.         }
  4073.         else { // Player 2
  4074.             if (isPlayer2AI) {
  4075.                 // FOOLPROOF FIX: AI doesn't choose here. It transitions to a thinking state.
  4076.                 // AIMakeDecision will handle the choice and the pocket call.
  4077.                 currentGameState = AI_THINKING;
  4078.                 aiTurnPending = true; // Signal the main loop to run AIMakeDecision
  4079.             }
  4080.             else { // Human Player 2
  4081.                 currentGameState = CHOOSING_POCKET_P2;
  4082.                 pocketCallMessage = player2Info.name + L": Choose a pocket for the 8-Ball...";
  4083.                 if (calledPocketP2 == -1) calledPocketP2 = 2; // Default to bottom-right
  4084.             }
  4085.         }
  4086.     }
  4087.     else {
  4088.         // Player does not need to call a pocket, proceed to normal turn.
  4089.         pocketCallMessage = L"";
  4090.         currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
  4091.         if (playerID == 2 && isPlayer2AI) {
  4092.             aiTurnPending = true;
  4093.         }
  4094.     }
  4095. }
  4096.  
  4097. //template here
  4098.  
  4099.  
  4100. // --- CPU Ball?in?Hand Placement --------------------------------
  4101. // Moves the cue ball to a legal "ball in hand" position for the AI.
  4102. void AIPlaceCueBall() {
  4103.     Ball* cue = GetCueBall();
  4104.     if (!cue) return;
  4105.  
  4106.     // Simple strategy: place back behind the headstring at the standard break spot
  4107.     cue->x = TABLE_LEFT + TABLE_WIDTH * 0.15f;
  4108.     cue->y = RACK_POS_Y;
  4109.     cue->vx = cue->vy = 0.0f;
  4110. }
  4111.  
  4112. // --- Helper Function for Line Segment Intersection ---
  4113. // Finds intersection point of line segment P1->P2 and line segment P3->P4
  4114. // Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
  4115. bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
  4116. {
  4117.     float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
  4118.  
  4119.     // Check if lines are parallel or collinear
  4120.     if (fabs(denominator) < 1e-6) {
  4121.         return false;
  4122.     }
  4123.  
  4124.     float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
  4125.     float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
  4126.  
  4127.     // Check if intersection point lies on both segments
  4128.     if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
  4129.         intersection.x = p1.x + ua * (p2.x - p1.x);
  4130.         intersection.y = p1.y + ua * (p2.y - p1.y);
  4131.         return true;
  4132.     }
  4133.  
  4134.     return false;
  4135. }
  4136.  
  4137. // --- INSERT NEW HELPER FUNCTION HERE ---
  4138. // Calculates the squared distance from point P to the line segment AB.
  4139. float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
  4140.     float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
  4141.     if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
  4142.     // Consider P projecting onto the line AB infinite line
  4143.     // t = [(P-A) . (B-A)] / |B-A|^2
  4144.     float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
  4145.     t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
  4146.     // Projection falls on the segment
  4147.     D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
  4148.     return GetDistanceSq(p.x, p.y, projection.x, projection.y);
  4149. }
  4150. // --- End New Helper ---
  4151.  
  4152. // --- NEW AI Implementation Functions ---
  4153.  
  4154. // --- BEGIN: ENHANCED AI LOGIC ---
  4155.  
  4156. // Helper function to evaluate the quality of the table layout from the cue ball's perspective.
  4157. // A higher score means a better "leave" with more options for the next shot.
  4158. float EvaluateTableState(int player, Ball* cueBall) {
  4159.     if (!cueBall) return 0.0f;
  4160.     float score = 0.0f;
  4161.     const BallType targetType = (player == 1) ? player1Info.assignedType : player2Info.assignedType;
  4162.  
  4163.     for (Ball& b : balls) {
  4164.         // Only consider own balls that are on the table
  4165.         if (b.isPocketed || b.id == 0 || b.type != targetType) continue;
  4166.  
  4167.         // Check for clear shots to any pocket
  4168.         for (int p = 0; p < 6; ++p) {
  4169.             D2D1_POINT_2F ghostPos = CalculateGhostBallPos(&b, p);
  4170.             if (IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), ghostPos, cueBall->id, b.id)) {
  4171.                 // Bonus for having any open, pottable shot
  4172.                 score += 50.0f;
  4173.             }
  4174.         }
  4175.     }
  4176.     return score;
  4177. }
  4178.  
  4179. // Enhanced power calculation for more realistic and impactful shots.
  4180. float CalculateShotPower(float cueToGhostDist, float targetToPocketDist)
  4181. {
  4182.     constexpr float TABLE_DIAG = 900.0f;
  4183.  
  4184.     // Base power on a combination of cue travel and object ball travel.
  4185.     float powerRatio = std::clamp(cueToGhostDist / (TABLE_WIDTH * 0.7f), 0.0f, 1.0f);
  4186.     // Give more weight to the object ball's travel distance.
  4187.     powerRatio += std::clamp(targetToPocketDist / TABLE_DIAG, 0.0f, 1.0f) * 0.8f;
  4188.     powerRatio = std::clamp(powerRatio, 0.0f, 1.0f);
  4189.  
  4190.     // Use a more aggressive cubic power curve. This keeps power low for taps but ramps up very fast.
  4191.     powerRatio = powerRatio * powerRatio * powerRatio;
  4192.  
  4193.     // Heavily bias towards high power. The AI will start shots at 50% power and go up.
  4194.     const float MIN_POWER = MAX_SHOT_POWER * 0.50f;
  4195.     float power = MIN_POWER + powerRatio * (MAX_SHOT_POWER - MIN_POWER);
  4196.  
  4197.     // For very long shots, just use full power to ensure the ball gets there and for break-out potential.
  4198.     if (cueToGhostDist + targetToPocketDist > TABLE_DIAG * 0.85f) {
  4199.         power = MAX_SHOT_POWER;
  4200.     }
  4201.  
  4202.     return std::clamp(power, 0.2f, MAX_SHOT_POWER);
  4203. }
  4204.  
  4205. // Evaluates a potential shot, calculating its difficulty and the quality of the resulting cue ball position.
  4206. AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex, bool isBank) {
  4207.     AIShotInfo shotInfo;
  4208.     shotInfo.targetBall = targetBall;
  4209.     shotInfo.pocketIndex = pocketIndex;
  4210.     shotInfo.isBankShot = isBank;
  4211.     shotInfo.involves8Ball = (targetBall && targetBall->id == 8);
  4212.  
  4213.     Ball* cue = GetCueBall();
  4214.     if (!cue || !targetBall) return shotInfo;
  4215.  
  4216.     D2D1_POINT_2F pocketPos = pocketPositions[pocketIndex];
  4217.     D2D1_POINT_2F targetPos = D2D1::Point2F(targetBall->x, targetBall->y);
  4218.     D2D1_POINT_2F ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
  4219.  
  4220.     // The path from cue to the ghost ball position must be clear.
  4221.     if (!IsPathClear(D2D1::Point2F(cue->x, cue->y), ghostBallPos, cue->id, targetBall->id)) {
  4222.         return shotInfo; // Path is blocked, invalid shot.
  4223.     }
  4224.  
  4225.     // For direct shots, the path from the target ball to the pocket must also be clear.
  4226.     if (!isBank && !IsPathClear(targetPos, pocketPos, targetBall->id, -1)) {
  4227.         return shotInfo;
  4228.     }
  4229.  
  4230.     float dx = ghostBallPos.x - cue->x;
  4231.     float dy = ghostBallPos.y - cue->y;
  4232.     shotInfo.angle = atan2f(dy, dx);
  4233.  
  4234.     float cueToGhostDist = GetDistance(cue->x, cue->y, ghostBallPos.x, ghostBallPos.y);
  4235.     float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPos.x, pocketPos.y);
  4236.  
  4237.     shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist); // Set a base power
  4238.     shotInfo.score = 1000.0f - (cueToGhostDist + targetToPocketDist * 1.5f); // Base score on shot difficulty.
  4239.     if (isBank) shotInfo.score -= 250.0f; // Bank shots are harder, so they have a score penalty.
  4240.  
  4241.  
  4242.     // --- Positional Play & English (Spin) Evaluation ---
  4243.     float bestLeaveScore = -1.0f;
  4244.     // Try different spins: -1 (draw/backspin), 0 (stun), 1 (follow/topspin)
  4245.     for (int spin_type = -1; spin_type <= 1; ++spin_type) {
  4246.         float spinY = spin_type * 0.7f; // Apply vertical spin.
  4247.  
  4248.         // Adjust power based on spin type. Draw shots need more power.
  4249.         float powerMultiplier = 1.0f;
  4250.         if (spin_type == -1) powerMultiplier = 1.2f;  // 20% more power for draw
  4251.         else if (spin_type == 1) powerMultiplier = 1.05f; // 5% more power for follow
  4252.  
  4253.         float adjustedPower = std::clamp(shotInfo.power * powerMultiplier, 0.2f, MAX_SHOT_POWER);
  4254.  
  4255.         // Predict where the cue ball will end up after the shot.
  4256.         D2D1_POINT_2F cueEndPos;
  4257.         float cueTravelDist = targetToPocketDist * 0.5f + adjustedPower * 5.0f;
  4258.  
  4259.         if (spin_type == 1) { // Follow (topspin)
  4260.             cueEndPos.x = targetPos.x + cosf(shotInfo.angle) * cueTravelDist * 0.6f;
  4261.             cueEndPos.y = targetPos.y + sinf(shotInfo.angle) * cueTravelDist * 0.6f;
  4262.         }
  4263.         else if (spin_type == -1) { // Draw (backspin)
  4264.             cueEndPos.x = ghostBallPos.x - cosf(shotInfo.angle) * cueTravelDist * 0.4f;
  4265.             cueEndPos.y = ghostBallPos.y - sinf(shotInfo.angle) * cueTravelDist * 0.4f;
  4266.         }
  4267.         else { // Stun (no vertical spin) - cue ball deflects
  4268.             float perpAngle = shotInfo.angle + PI / 2.0f;
  4269.             cueEndPos.x = ghostBallPos.x + cosf(perpAngle) * cueTravelDist * 0.3f;
  4270.             cueEndPos.y = ghostBallPos.y + sinf(perpAngle) * cueTravelDist * 0.3f;
  4271.         }
  4272.  
  4273.         // Create a temporary cue ball at the predicted position to evaluate the leave.
  4274.         Ball tempCue = *cue;
  4275.         tempCue.x = cueEndPos.x;
  4276.         tempCue.y = cueEndPos.y;
  4277.         float leaveScore = EvaluateTableState(2, &tempCue);
  4278.  
  4279.         // Penalize scratches heavily.
  4280.         for (int p = 0; p < 6; ++p) {
  4281.             float physicalPocketRadius = ((p == 1 || p == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS) * 1.05f;
  4282.             if (GetDistanceSq(cueEndPos.x, cueEndPos.y, pocketPositions[p].x, pocketPositions[p].y) < physicalPocketRadius * physicalPocketRadius * 1.5f) {
  4283.                 leaveScore -= 5000.0f; // Massive penalty for a predicted scratch.
  4284.                 break;
  4285.             }
  4286.         }
  4287.  
  4288.         // If this spin results in a better position, store it.
  4289.         if (leaveScore > bestLeaveScore) {
  4290.             bestLeaveScore = leaveScore;
  4291.             shotInfo.spinY = spinY;
  4292.             shotInfo.spinX = 0; // Focusing on top/back spin for positional play.
  4293.             shotInfo.predictedCueEndPos = cueEndPos;
  4294.             shotInfo.power = adjustedPower; // IMPORTANT: Update the shot's power to the adjusted value for this spin
  4295.         }
  4296.     }
  4297.  
  4298.     shotInfo.score += bestLeaveScore * 0.5f; // Add positional score to the shot's total score.
  4299.     shotInfo.possible = true;
  4300.     return shotInfo;
  4301. }
  4302.  
  4303. // High-level planner that decides which shot to take.
  4304. AIShotInfo AIFindBestShot() {
  4305.     AIShotInfo bestShot;
  4306.     bestShot.possible = false;
  4307.  
  4308.     Ball* cue = GetCueBall();
  4309.     if (!cue) return bestShot;
  4310.  
  4311.     const bool on8 = IsPlayerOnEightBall(2);
  4312.     const BallType wantType = player2Info.assignedType;
  4313.     std::vector<AIShotInfo> possibleShots;
  4314.  
  4315.     // 1. Evaluate all possible direct shots on legal targets.
  4316.     for (Ball& b : balls) {
  4317.         if (b.isPocketed || b.id == 0) continue;
  4318.  
  4319.         bool isLegalTarget = on8 ? (b.id == 8) : (wantType == BallType::NONE || b.type == wantType);
  4320.         if (!isLegalTarget) continue;
  4321.  
  4322.         for (int p = 0; p < 6; ++p) {
  4323.             AIShotInfo cand = EvaluateShot(&b, p, false); // false = not a bank shot
  4324.             if (cand.possible) {
  4325.                 possibleShots.push_back(cand);
  4326.             }
  4327.         }
  4328.     }
  4329.  
  4330.     // TODO: Add evaluation for bank shots here if desired.
  4331.  
  4332.     // 2. Find the best shot from the list of possibilities.
  4333.     if (!possibleShots.empty()) {
  4334.         bestShot = possibleShots[0];
  4335.         for (size_t i = 1; i < possibleShots.size(); ++i) {
  4336.             if (possibleShots[i].score > bestShot.score) {
  4337.                 bestShot = possibleShots[i];
  4338.             }
  4339.         }
  4340.     }
  4341.     else {
  4342.         // 3. If no makeable shots are found, play a defensive "safety" shot.
  4343.         // This involves hitting a legal ball softly to a safe location.
  4344.         bestShot.possible = true;
  4345.         bestShot.angle = static_cast<float>(rand()) / RAND_MAX * 2.0f * PI;
  4346.         bestShot.power = MAX_SHOT_POWER * 0.25f; // A soft safety hit.
  4347.         bestShot.spinX = bestShot.spinY = 0.0f;
  4348.         bestShot.targetBall = nullptr;
  4349.         bestShot.score = -99999.0f; // Safety is a last resort.
  4350.         bestShot.pocketIndex = -1;
  4351.     }
  4352.  
  4353.     return bestShot;
  4354. }
  4355.  
  4356. // The top-level function that orchestrates the AI's turn.
  4357. void AIMakeDecision() {
  4358.     aiPlannedShotDetails.isValid = false;
  4359.     Ball* cueBall = GetCueBall();
  4360.     if (!cueBall || !isPlayer2AI || currentPlayer != 2) return;
  4361.  
  4362.     AIShotInfo bestShot = AIFindBestShot();
  4363.  
  4364.     if (bestShot.possible) {
  4365.         // If the best shot involves the 8-ball, the AI must "call" the pocket.
  4366.         if (bestShot.involves8Ball) {
  4367.             calledPocketP2 = bestShot.pocketIndex;
  4368.         }
  4369.         else {
  4370.             calledPocketP2 = -1;
  4371.         }
  4372.  
  4373.         // Load the chosen shot parameters into the game state.
  4374.         aiPlannedShotDetails.angle = bestShot.angle;
  4375.         aiPlannedShotDetails.power = bestShot.power;
  4376.         aiPlannedShotDetails.spinX = bestShot.spinX;
  4377.         aiPlannedShotDetails.spinY = bestShot.spinY;
  4378.         aiPlannedShotDetails.isValid = true;
  4379.     }
  4380.     else {
  4381.         // This case should be rare now, but as a fallback, switch turns.
  4382.         aiPlannedShotDetails.isValid = false;
  4383.     }
  4384.  
  4385.     if (aiPlannedShotDetails.isValid) {
  4386.         // Set the global aiming variables to visualize the AI's planned shot.
  4387.         cueAngle = aiPlannedShotDetails.angle;
  4388.         shotPower = aiPlannedShotDetails.power;
  4389.         aiIsDisplayingAim = true;
  4390.         aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
  4391.     }
  4392.     else {
  4393.         // If no valid shot could be found at all, concede the turn.
  4394.         SwitchTurns();
  4395.     }
  4396. }
  4397.  
  4398. // --- END: ENHANCED AI LOGIC ---
  4399.  
  4400.  
  4401.  
  4402. //  Estimate the power that will carry the cue-ball to the ghost position
  4403. //  *and* push the object-ball the remaining distance to the pocket.
  4404. //
  4405. //  • cueToGhostDist    – pixels from cue to ghost-ball centre
  4406. //  • targetToPocketDist– pixels from object-ball to chosen pocket
  4407. //
  4408. //  The function is fully deterministic (good for AI search) yet produces
  4409. //  human-looking power levels.
  4410. //
  4411.  
  4412.  
  4413. // ------------------------------------------------------------------
  4414. //  Return the ghost-ball centre needed for the target ball to roll
  4415. //  straight into the chosen pocket.
  4416. // ------------------------------------------------------------------
  4417. D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex)
  4418. {
  4419.     if (!targetBall) return D2D1::Point2F(0, 0);
  4420.  
  4421.     D2D1_POINT_2F P = pocketPositions[pocketIndex];
  4422.  
  4423.     float vx = P.x - targetBall->x;
  4424.     float vy = P.y - targetBall->y;
  4425.     float L = sqrtf(vx * vx + vy * vy);
  4426.     if (L < 1.0f) L = 1.0f;                // safety
  4427.  
  4428.     vx /= L;   vy /= L;
  4429.  
  4430.     return D2D1::Point2F(
  4431.         targetBall->x - vx * (BALL_RADIUS * 2.0f),
  4432.         targetBall->y - vy * (BALL_RADIUS * 2.0f));
  4433. }
  4434.  
  4435. // Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
  4436. // ────────────────────────────────────────────────────────────────
  4437. //   2.  Shot evaluation & search
  4438. // ────────────────────────────────────────────────────────────────
  4439.  
  4440. //  Calculate ghost-ball position so that cue hits target towards pocket
  4441. static inline D2D1_POINT_2F GhostPos(const Ball* tgt, int pocketIdx)
  4442. {
  4443.     D2D1_POINT_2F P = pocketPositions[pocketIdx];
  4444.     float vx = P.x - tgt->x;
  4445.     float vy = P.y - tgt->y;
  4446.     float L = sqrtf(vx * vx + vy * vy);
  4447.     vx /= L;  vy /= L;
  4448.     return D2D1::Point2F(tgt->x - vx * (BALL_RADIUS * 2.0f),
  4449.         tgt->y - vy * (BALL_RADIUS * 2.0f));
  4450. }
  4451.  
  4452. //  Heuristic: shorter + straighter + proper group = higher score
  4453. static inline float ScoreShot(float cue2Ghost,
  4454.     float tgt2Pocket,
  4455.     bool  correctGroup,
  4456.     bool  involves8)
  4457. {
  4458.     float base = 2000.0f - (cue2Ghost + tgt2Pocket);   // prefer close shots
  4459.     if (!correctGroup)  base -= 400.0f;                  // penalty
  4460.     if (involves8)      base += 150.0f;                  // a bit more desirable
  4461.     return base;
  4462. }
  4463.  
  4464. // Checks if line segment is clear of obstructing balls
  4465. // ────────────────────────────────────────────────────────────────
  4466. //   1.  Low-level helpers – IsPathClear & FindFirstHitBall
  4467. // ────────────────────────────────────────────────────────────────
  4468.  
  4469. //  Test if the capsule [ start … end ] (radius = BALL_RADIUS)
  4470. //  intersects any ball except the ids we want to ignore.
  4471. bool IsPathClear(D2D1_POINT_2F start,
  4472.     D2D1_POINT_2F end,
  4473.     int ignoredBallId1,
  4474.     int ignoredBallId2)
  4475. {
  4476.     float dx = end.x - start.x;
  4477.     float dy = end.y - start.y;
  4478.     float lenSq = dx * dx + dy * dy;
  4479.     if (lenSq < 1e-3f) return true;             // degenerate → treat as clear
  4480.  
  4481.     for (const Ball& b : balls)
  4482.     {
  4483.         if (b.isPocketed)      continue;
  4484.         if (b.id == ignoredBallId1 ||
  4485.             b.id == ignoredBallId2)             continue;
  4486.  
  4487.         // project ball centre onto the segment
  4488.         float t = ((b.x - start.x) * dx + (b.y - start.y) * dy) / lenSq;
  4489.         t = std::clamp(t, 0.0f, 1.0f);
  4490.  
  4491.         float cx = start.x + t * dx;
  4492.         float cy = start.y + t * dy;
  4493.  
  4494.         if (GetDistanceSq(b.x, b.y, cx, cy) < (BALL_RADIUS * BALL_RADIUS))
  4495.             return false;                       // blocked
  4496.     }
  4497.     return true;
  4498. }
  4499.  
  4500. //  Cast an (infinite) ray and return the first non-pocketed ball hit.
  4501. //  `hitDistSq` is distance² from the start point to the collision point.
  4502. Ball* FindFirstHitBall(D2D1_POINT_2F start,
  4503.     float        angle,
  4504.     float& hitDistSq)
  4505. {
  4506.     Ball* hitBall = nullptr;
  4507.     float  bestSq = std::numeric_limits<float>::max();
  4508.     float  cosA = cosf(angle);
  4509.     float  sinA = sinf(angle);
  4510.  
  4511.     for (Ball& b : balls)
  4512.     {
  4513.         if (b.id == 0 || b.isPocketed) continue;         // ignore cue & sunk balls
  4514.  
  4515.         float relX = b.x - start.x;
  4516.         float relY = b.y - start.y;
  4517.         float proj = relX * cosA + relY * sinA;          // distance along the ray
  4518.  
  4519.         if (proj <= 0) continue;                         // behind cue
  4520.  
  4521.         // closest approach of the ray to the sphere centre
  4522.         float closestX = start.x + proj * cosA;
  4523.         float closestY = start.y + proj * sinA;
  4524.         float dSq = GetDistanceSq(b.x, b.y, closestX, closestY);
  4525.  
  4526.         if (dSq <= BALL_RADIUS * BALL_RADIUS)            // intersection
  4527.         {
  4528.             float back = sqrtf(BALL_RADIUS * BALL_RADIUS - dSq);
  4529.             float collDist = proj - back;                // front surface
  4530.             float collSq = collDist * collDist;
  4531.             if (collSq < bestSq)
  4532.             {
  4533.                 bestSq = collSq;
  4534.                 hitBall = &b;
  4535.             }
  4536.         }
  4537.     }
  4538.     hitDistSq = bestSq;
  4539.     return hitBall;
  4540. }
  4541.  
  4542. // Basic check for reasonable AI aim angles (optional)
  4543. bool IsValidAIAimAngle(float angle) {
  4544.     // Placeholder - could check for NaN or infinity if calculations go wrong
  4545.     return isfinite(angle);
  4546. }
  4547.  
  4548. //midi func = start
  4549. void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
  4550.     while (isMusicPlaying) {
  4551.         MCI_OPEN_PARMS mciOpen = { 0 };
  4552.         mciOpen.lpstrDeviceType = TEXT("sequencer");
  4553.         mciOpen.lpstrElementName = midiPath;
  4554.  
  4555.         if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
  4556.             midiDeviceID = mciOpen.wDeviceID;
  4557.  
  4558.             MCI_PLAY_PARMS mciPlay = { 0 };
  4559.             mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
  4560.  
  4561.             // Wait for playback to complete
  4562.             MCI_STATUS_PARMS mciStatus = { 0 };
  4563.             mciStatus.dwItem = MCI_STATUS_MODE;
  4564.  
  4565.             do {
  4566.                 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
  4567.                 Sleep(100); // adjust as needed
  4568.             } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
  4569.  
  4570.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  4571.             midiDeviceID = 0;
  4572.         }
  4573.     }
  4574. }
  4575.  
  4576. void StartMidi(HWND hwnd, const TCHAR* midiPath) {
  4577.     if (isMusicPlaying) {
  4578.         StopMidi();
  4579.     }
  4580.     isMusicPlaying = true;
  4581.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  4582. }
  4583.  
  4584. void StopMidi() {
  4585.     if (isMusicPlaying) {
  4586.         isMusicPlaying = false;
  4587.         if (musicThread.joinable()) musicThread.join();
  4588.         if (midiDeviceID != 0) {
  4589.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  4590.             midiDeviceID = 0;
  4591.         }
  4592.     }
  4593. }
  4594.  
  4595. /*void PlayGameMusic(HWND hwnd) {
  4596.     // Stop any existing playback
  4597.     if (isMusicPlaying) {
  4598.         isMusicPlaying = false;
  4599.         if (musicThread.joinable()) {
  4600.             musicThread.join();
  4601.         }
  4602.         if (midiDeviceID != 0) {
  4603.             mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
  4604.             midiDeviceID = 0;
  4605.         }
  4606.     }
  4607.  
  4608.     // Get the path of the executable
  4609.     TCHAR exePath[MAX_PATH];
  4610.     GetModuleFileName(NULL, exePath, MAX_PATH);
  4611.  
  4612.     // Extract the directory path
  4613.     TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
  4614.     if (lastBackslash != NULL) {
  4615.         *(lastBackslash + 1) = '\0';
  4616.     }
  4617.  
  4618.     // Construct the full path to the MIDI file
  4619.     static TCHAR midiPath[MAX_PATH];
  4620.     _tcscpy_s(midiPath, MAX_PATH, exePath);
  4621.     _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
  4622.  
  4623.     // Start the background playback
  4624.     isMusicPlaying = true;
  4625.     musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
  4626. }*/
  4627. //midi func = end
  4628.  
  4629. // --- Drawing Functions ---
  4630.  
  4631. void OnPaint() {
  4632.     HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
  4633.  
  4634.     if (SUCCEEDED(hr)) {
  4635.         pRenderTarget->BeginDraw();
  4636.         DrawScene(pRenderTarget); // Pass render target
  4637.         hr = pRenderTarget->EndDraw();
  4638.  
  4639.         if (hr == D2DERR_RECREATE_TARGET) {
  4640.             DiscardDeviceResources();
  4641.             // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
  4642.             // But the timer loop will trigger redraw anyway.
  4643.         }
  4644.     }
  4645.     // If CreateDeviceResources failed, EndDraw might not be called.
  4646.     // Consider handling this more robustly if needed.
  4647. }
  4648.  
  4649. void DrawScene(ID2D1RenderTarget* pRT) {
  4650.     if (!pRT) return;
  4651.  
  4652.     //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
  4653.     // Set background color to #ffffcd (RGB: 255, 255, 205)
  4654.     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)
  4655.     //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)
  4656.  
  4657.     DrawTable(pRT, pFactory);
  4658.     DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
  4659.     DrawBalls(pRT);
  4660.     // Draw the cue stick right before/after drawing balls:
  4661.     DrawCueStick(pRT);
  4662.     DrawAimingAids(pRT); // Includes cue stick if aiming
  4663.     DrawUI(pRT);
  4664.     DrawPowerMeter(pRT);
  4665.     DrawSpinIndicator(pRT);
  4666.     DrawPocketedBallsIndicator(pRT);
  4667.     DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
  4668.  
  4669.      // Draw Game Over Message
  4670.     if (currentGameState == GAME_OVER && pTextFormat) {
  4671.         ID2D1SolidColorBrush* pBrush = nullptr;
  4672.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
  4673.         if (pBrush) {
  4674.             D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
  4675.             pRT->DrawText(
  4676.                 gameOverMessage.c_str(),
  4677.                 (UINT32)gameOverMessage.length(),
  4678.                 pTextFormat, // Use large format maybe?
  4679.                 &layoutRect,
  4680.                 pBrush
  4681.             );
  4682.             SafeRelease(&pBrush);
  4683.         }
  4684.     }
  4685.  
  4686. }
  4687.  
  4688. void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
  4689.     ID2D1SolidColorBrush* pBrush = nullptr;
  4690.     ID2D1SolidColorBrush* pPocketBackdropBrush = nullptr;
  4691.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pPocketBackdropBrush);
  4692.     if (pPocketBackdropBrush) {
  4693.         for (int i = 0; i < 6; ++i) {
  4694.             float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  4695.             D2D1_ELLIPSE backdrop = D2D1::Ellipse(pocketPositions[i], currentVisualRadius + 5.0f, currentVisualRadius + 5.0f);
  4696.             pRT->FillEllipse(&backdrop, pPocketBackdropBrush);
  4697.         }
  4698.         SafeRelease(&pPocketBackdropBrush);
  4699.     }
  4700.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
  4701.     if (!pBrush) return;
  4702.     D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
  4703.     pRT->FillRectangle(&tableRect, pBrush);
  4704.     SafeRelease(&pBrush);
  4705.     {
  4706.         ID2D1RadialGradientBrush* pSpot = nullptr;
  4707.         ID2D1GradientStopCollection* pStops = nullptr;
  4708.         D2D1_COLOR_F centreClr = D2D1::ColorF(
  4709.             std::min(1.f, TABLE_COLOR.r * 1.60f),
  4710.             std::min(1.f, TABLE_COLOR.g * 1.60f),
  4711.             std::min(1.f, TABLE_COLOR.b * 1.60f));
  4712.         const D2D1_GRADIENT_STOP gs[3] =
  4713.         {
  4714.             { 0.0f, D2D1::ColorF(centreClr.r, centreClr.g, centreClr.b, 0.95f) },
  4715.             { 0.6f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.55f) },
  4716.             { 1.0f, D2D1::ColorF(TABLE_COLOR.r, TABLE_COLOR.g, TABLE_COLOR.b, 0.0f) }
  4717.         };
  4718.         pRT->CreateGradientStopCollection(gs, 3, &pStops);
  4719.         if (pStops)
  4720.         {
  4721.             D2D1_RECT_F rc = tableRect;
  4722.             const float PAD = 18.0f;
  4723.             rc.left += PAD;  rc.top += PAD;
  4724.             rc.right -= PAD;  rc.bottom -= PAD;
  4725.             D2D1_POINT_2F centre = D2D1::Point2F(
  4726.                 (rc.left + rc.right) / 2.0f,
  4727.                 (rc.top + rc.bottom) / 2.0f);
  4728.             float rx = (rc.right - rc.left) * 0.55f;
  4729.             float ry = (rc.bottom - rc.top) * 0.55f;
  4730.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  4731.                 D2D1::RadialGradientBrushProperties(
  4732.                     centre,
  4733.                     D2D1::Point2F(0, 0),
  4734.                     rx, ry);
  4735.             pRT->CreateRadialGradientBrush(props, pStops, &pSpot);
  4736.             pStops->Release();
  4737.         }
  4738.         if (pSpot)
  4739.         {
  4740.             const float RADIUS = 20.0f;
  4741.             D2D1_ROUNDED_RECT spotlightRR =
  4742.                 D2D1::RoundedRect(tableRect, RADIUS, RADIUS);
  4743.             pRT->FillRoundedRectangle(&spotlightRR, pSpot);
  4744.             pSpot->Release();
  4745.         }
  4746.     }
  4747.     // --- BEGIN: Add Grainy Felt Texture ---
  4748.     // Create a fine, grainy texture programmatically to simulate felt.
  4749.     // We do this by drawing thousands of tiny, 1x1 rectangles with colors
  4750.     // slightly lighter or darker than the base table color.
  4751.     ID2D1SolidColorBrush* pGrainBrush = nullptr;
  4752.     pRT->CreateSolidColorBrush(TABLE_COLOR, &pGrainBrush); // Start with base color
  4753.     if (pGrainBrush)
  4754.     {
  4755.         // The number of grains. More grains = denser texture.
  4756.         // 20,000 is a good starting point for this table size.
  4757.         const int NUM_GRAINS = 20000;
  4758.  
  4759.         for (int i = 0; i < NUM_GRAINS; ++i)
  4760.         {
  4761.             // Get a random position on the table
  4762.             float x = TABLE_LEFT + (rand() % (int)TABLE_WIDTH);
  4763.             float y = TABLE_TOP + (rand() % (int)TABLE_HEIGHT);
  4764.  
  4765.             // Create a slightly lighter or darker shade of the table color for the grain.
  4766.             // The factor ranges from 0.85 to 1.15 (85% to 115% of original brightness).
  4767.             float colorFactor = 0.85f + (rand() % 31) / 100.0f;
  4768.  
  4769.             D2D1_COLOR_F grainColor = D2D1::ColorF(
  4770.                 std::clamp(TABLE_COLOR.r * colorFactor, 0.0f, 1.0f),
  4771.                 std::clamp(TABLE_COLOR.g * colorFactor, 0.0f, 1.0f),
  4772.                 std::clamp(TABLE_COLOR.b * colorFactor, 0.0f, 1.0f),
  4773.                 0.75f // Use a slight alpha to blend the grains smoothly
  4774.             );
  4775.  
  4776.             // Set the brush to the new grain color and draw a 1x1 pixel rectangle.
  4777.             // Re-using one brush with SetColor is much faster than creating a new brush per grain.
  4778.             pGrainBrush->SetColor(grainColor);
  4779.             pRT->FillRectangle(D2D1::RectF(x, y, x + 1.0f, y + 1.0f), pGrainBrush);
  4780.         }
  4781.         SafeRelease(&pGrainBrush);
  4782.     }
  4783.     // --- END: Add Grainy Felt Texture ---
  4784.     pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
  4785.     if (!pBrush) return;
  4786.     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);
  4787.     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);
  4788.     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);
  4789.     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);
  4790.     pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS), pBrush);
  4791.     pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + CORNER_HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - CORNER_HOLE_VISUAL_RADIUS), pBrush);
  4792.     SafeRelease(&pBrush);
  4793.     ID2D1SolidColorBrush* pPocketBrush = nullptr;
  4794.     //ID2D1SolidColorBrush* pRimBrush = nullptr;
  4795.     pRT->CreateSolidColorBrush(POCKET_COLOR, &pPocketBrush);
  4796.     //pRT->CreateSolidColorBrush(D2D1::ColorF(0.1f, 0.1f, 0.1f), &pRimBrush);
  4797.     if (pPocketBrush) {
  4798.     //if (pPocketBrush && pRimBrush) {
  4799.         for (int i = 0; i < 6; ++i) {
  4800.             ID2D1PathGeometry* pPath = nullptr;
  4801.             pFactory->CreatePathGeometry(&pPath);
  4802.             if (pPath) {
  4803.                 ID2D1GeometrySink* pSink = nullptr;
  4804.                 if (SUCCEEDED(pPath->Open(&pSink))) {
  4805.                     float currentVisualRadius = (i == 1 || i == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  4806.                     // FIX: Make the visual pockets larger to match the new collision masks. default=1.5:2.7|1.1:2.0=>1.0:1.7|1.0:1.3
  4807.                     float mouthRadius = currentVisualRadius * ((i == 1 || i == 4) ? 1.0f : 1.0f);
  4808.                     float backRadius = currentVisualRadius * ((i == 1 || i == 4) ? 1.0f : 1.0f);
  4809.                     //float mouthRadius = currentVisualRadius * 1.5f;
  4810.                     //float backRadius = currentVisualRadius * 1.1f;
  4811.                     D2D1_POINT_2F center = pocketPositions[i];
  4812.                     D2D1_POINT_2F p1, p2;
  4813.                     D2D1_SWEEP_DIRECTION sweep;
  4814.                     if (i == 0) {
  4815.                         p1 = D2D1::Point2F(center.x + mouthRadius, center.y);
  4816.                         p2 = D2D1::Point2F(center.x, center.y + mouthRadius);
  4817.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  4818.                     }
  4819.                     else if (i == 2) {
  4820.                         p1 = D2D1::Point2F(center.x, center.y + mouthRadius);
  4821.                         p2 = D2D1::Point2F(center.x - mouthRadius, center.y);
  4822.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  4823.                     }
  4824.                     else if (i == 3) {
  4825.                         p1 = D2D1::Point2F(center.x, center.y - mouthRadius);
  4826.                         p2 = D2D1::Point2F(center.x + mouthRadius, center.y);
  4827.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  4828.                     }
  4829.                     else if (i == 5) {
  4830.                         p1 = D2D1::Point2F(center.x - mouthRadius, center.y);
  4831.                         p2 = D2D1::Point2F(center.x, center.y - mouthRadius);
  4832.                         sweep = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  4833.                     }
  4834.                     else if (i == 1) {
  4835.                         p1 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  4836.                         p2 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  4837.                         sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  4838.                     }
  4839.                     else {
  4840.                         p1 = D2D1::Point2F(center.x + mouthRadius / 1.5f, center.y);
  4841.                         p2 = D2D1::Point2F(center.x - mouthRadius / 1.5f, center.y);
  4842.                         sweep = D2D1_SWEEP_DIRECTION_CLOCKWISE;
  4843.                     }
  4844.                     pSink->BeginFigure(center, D2D1_FIGURE_BEGIN_FILLED);
  4845.                     pSink->AddLine(p1);
  4846.                     pSink->AddArc(D2D1::ArcSegment(p2, D2D1::SizeF(backRadius, backRadius), 0.0f, sweep, D2D1_ARC_SIZE_SMALL));
  4847.                     pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  4848.                     pSink->Close();
  4849.                     SafeRelease(&pSink);
  4850.                     pRT->FillGeometry(pPath, pPocketBrush);
  4851.                     // Draw the inner rim for a beveled effect (Start)
  4852.                     /*D2D1::Matrix3x2F scale = D2D1::Matrix3x2F::Scale(0.8f, 0.8f, center);
  4853.                     ID2D1TransformedGeometry* pTransformedGeo = nullptr;
  4854.                     pFactory->CreateTransformedGeometry(pPath, &scale, &pTransformedGeo);
  4855.                     if (pTransformedGeo) {
  4856.                         pRT->FillGeometry(pTransformedGeo, pRimBrush);
  4857.                         SafeRelease(&pTransformedGeo);
  4858.                     }*/ //End
  4859.                 }
  4860.                 SafeRelease(&pPath);
  4861.             }
  4862.         }
  4863.     }
  4864.     SafeRelease(&pPocketBrush);
  4865.     //SafeRelease(&pRimBrush);
  4866.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush);
  4867.     if (!pBrush) return;
  4868.     pRT->DrawLine(
  4869.         D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
  4870.         D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
  4871.         pBrush,
  4872.         1.0f
  4873.     );
  4874.     SafeRelease(&pBrush);
  4875.     ID2D1PathGeometry* pGeometry = nullptr;
  4876.     HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
  4877.     if (SUCCEEDED(hr) && pGeometry)
  4878.     {
  4879.         ID2D1GeometrySink* pSink = nullptr;
  4880.         hr = pGeometry->Open(&pSink);
  4881.         if (SUCCEEDED(hr) && pSink)
  4882.         {
  4883.             float radius = 60.0f;
  4884.             D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
  4885.             D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius);
  4886.             pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
  4887.             D2D1_ARC_SEGMENT arc = {};
  4888.             arc.point = D2D1::Point2F(center.x, center.y + radius);
  4889.             arc.size = D2D1::SizeF(radius, radius);
  4890.             arc.rotationAngle = 0.0f;
  4891.             arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
  4892.             arc.arcSize = D2D1_ARC_SIZE_SMALL;
  4893.             pSink->AddArc(&arc);
  4894.             pSink->EndFigure(D2D1_FIGURE_END_OPEN);
  4895.             pSink->Close();
  4896.             SafeRelease(&pSink);
  4897.             ID2D1SolidColorBrush* pArcBrush = nullptr;
  4898.             pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
  4899.             if (pArcBrush)
  4900.             {
  4901.                 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
  4902.                 SafeRelease(&pArcBrush);
  4903.             }
  4904.         }
  4905.         SafeRelease(&pGeometry);
  4906.     }
  4907. }
  4908.  
  4909.  
  4910. // ----------------------------------------------
  4911. //  Helper : clamp to [0,1] and lighten a colour
  4912. // ----------------------------------------------
  4913. static D2D1_COLOR_F Lighten(const D2D1_COLOR_F& c, float factor = 1.25f)
  4914. {
  4915.     return D2D1::ColorF(
  4916.         std::min(1.0f, c.r * factor),
  4917.         std::min(1.0f, c.g * factor),
  4918.         std::min(1.0f, c.b * factor),
  4919.         c.a);
  4920. }
  4921.  
  4922. // ------------------------------------------------
  4923. //  NEW  DrawBalls – radial-gradient “spot-light”
  4924. // ------------------------------------------------
  4925. void DrawBalls(ID2D1RenderTarget* pRT)
  4926. {
  4927.     if (!pRT) return;
  4928.  
  4929.     ID2D1SolidColorBrush* pStripeBrush = nullptr;    // white stripe
  4930.     ID2D1SolidColorBrush* pBorderBrush = nullptr;    // black ring
  4931.     ID2D1SolidColorBrush* pNumWhite = nullptr;       // white decal circle
  4932.     ID2D1SolidColorBrush* pNumBlack = nullptr;       // digit colour
  4933.  
  4934.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  4935.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  4936.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  4937.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  4938.  
  4939.     for (const Ball& b : balls)
  4940.     {
  4941.         if (b.isPocketed) continue;
  4942.  
  4943.         // Save the original transform for restoration at the end of this ball.
  4944.         D2D1::Matrix3x2F originalTransform;
  4945.         pRT->GetTransform(&originalTransform);
  4946.  
  4947.         // Build the radial gradient for THIS ball
  4948.         ID2D1GradientStopCollection* pStops = nullptr;
  4949.         ID2D1RadialGradientBrush* pRad = nullptr;
  4950.  
  4951.         D2D1_GRADIENT_STOP gs[3];
  4952.         gs[0].position = 0.0f;  gs[0].color = D2D1::ColorF(1, 1, 1, 0.95f);   // bright spot
  4953.         gs[1].position = 0.35f; gs[1].color = Lighten(b.color);               // transitional
  4954.         gs[2].position = 1.0f;  gs[2].color = b.color;                        // base colour
  4955.  
  4956.         pRT->CreateGradientStopCollection(gs, 3, &pStops);
  4957.         if (pStops)
  4958.         {
  4959.             // Place the hot-spot slightly towards top-left to look more 3-D,
  4960.             // then nudge it along the rotationAxis so the highlight follows travel.
  4961.             // This gives the illusion of 'spinning on the side'.
  4962.             float baseHotX = b.x - BALL_RADIUS * 0.4f;
  4963.             float baseHotY = b.y - BALL_RADIUS * 0.4f;
  4964.  
  4965.             // small dynamic offset based on rotationAxis and rotationAngle magnitude
  4966.             float axis = b.rotationAxis; // radians, perpendicular to travel
  4967.             float spinInfluence = 0.14f; // tweak: how much spin moves the highlight (0..0.4 typical)
  4968.             float offsetMag = (fmodf(fabsf(b.rotationAngle), 2.0f * PI) / (2.0f * PI)) * (BALL_RADIUS * spinInfluence);
  4969.             D2D1_POINT_2F origin = D2D1::Point2F(
  4970.                 baseHotX + cosf(axis) * offsetMag,
  4971.                 baseHotY + sinf(axis) * offsetMag
  4972.             );
  4973.  
  4974.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  4975.                 D2D1::RadialGradientBrushProperties(
  4976.                     origin,
  4977.                     D2D1::Point2F(0, 0),
  4978.                     BALL_RADIUS * 1.3f,
  4979.                     BALL_RADIUS * 1.3f);
  4980.  
  4981.             /*// Place the hotspot slightly towards top-left (in world coords)
  4982.             D2D1_POINT_2F origin = D2D1::Point2F(b.x - BALL_RADIUS * 0.4f,
  4983.                 b.y - BALL_RADIUS * 0.4f);
  4984.             D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  4985.                 D2D1::RadialGradientBrushProperties(
  4986.                     origin,                        // gradientOrigin
  4987.                     D2D1::Point2F(0, 0),           // offset (unused)
  4988.                     BALL_RADIUS * 1.3f,            // radiusX
  4989.                     BALL_RADIUS * 1.3f);           // radiusY*/
  4990.  
  4991.             pRT->CreateRadialGradientBrush(props, pStops, &pRad);
  4992.             SafeRelease(&pStops); // safe to release stops after brush creation
  4993.         }
  4994.  
  4995.         // Compute rotation transform (convert radians -> degrees)
  4996.         float angleDeg = (b.rotationAngle * 180.0f) / PI;
  4997.         D2D1::Matrix3x2F rot = D2D1::Matrix3x2F::Rotation(angleDeg, D2D1::Point2F(b.x, b.y));
  4998.         // Apply rotation on top of existing transform
  4999.         pRT->SetTransform(rot * originalTransform);
  5000.  
  5001.         // Draw the ball (body)
  5002.         D2D1_ELLIPSE body = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  5003.         if (pRad) pRT->FillEllipse(&body, pRad);
  5004.  
  5005.         // Stripes overlay (if applicable)
  5006.         if (b.type == BallType::STRIPE && pStripeBrush)
  5007.         {
  5008.             D2D1_RECT_F stripe = D2D1::RectF(
  5009.                 b.x - BALL_RADIUS,
  5010.                 b.y - BALL_RADIUS * 0.40f,
  5011.                 b.x + BALL_RADIUS,
  5012.                 b.y + BALL_RADIUS * 0.40f);
  5013.             pRT->FillRectangle(&stripe, pStripeBrush);
  5014.  
  5015.             if (pRad)
  5016.             {
  5017.                 D2D1_ELLIPSE inner = D2D1::Ellipse(D2D1::Point2F(b.x, b.y),
  5018.                     BALL_RADIUS * 0.60f, BALL_RADIUS * 0.60f);
  5019.                 pRT->FillEllipse(&inner, pRad);
  5020.             }
  5021.         }
  5022.  
  5023.         // Draw number decal (skip cue ball)
  5024.         if (b.id != 0 && pBallNumFormat && pNumWhite && pNumBlack)
  5025.         {
  5026.             const float decalR = (b.type == BallType::STRIPE) ? BALL_RADIUS * 0.40f : BALL_RADIUS * 0.45f;
  5027.             D2D1_ELLIPSE decal = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), decalR, decalR);
  5028.             pRT->FillEllipse(&decal, pNumWhite);
  5029.             pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  5030.  
  5031.             // Use std::wstring to avoid _snwprintf_s/wcslen and literal issues.
  5032.             std::wstring numText = std::to_wstring(b.id);
  5033.             D2D1_RECT_F layout = D2D1::RectF(
  5034.                 b.x - decalR, b.y - decalR,
  5035.                 b.x + decalR, b.y + decalR);
  5036.  
  5037.             pRT->DrawTextW(
  5038.                 numText.c_str(),
  5039.                 static_cast<UINT32>(numText.length()),
  5040.                 pBallNumFormat,
  5041.                 &layout,
  5042.                 pNumBlack);
  5043.         }
  5044.  
  5045.         // Draw black border for the ball
  5046.         if (pBorderBrush)
  5047.             pRT->DrawEllipse(&body, pBorderBrush, 1.5f);
  5048.  
  5049.         // restore the render target transform for next objects
  5050.         pRT->SetTransform(originalTransform);
  5051.  
  5052.         // cleanup per-ball D2D resources
  5053.         SafeRelease(&pRad);
  5054.     } // end for each ball
  5055.  
  5056.     SafeRelease(&pStripeBrush);
  5057.     SafeRelease(&pBorderBrush);
  5058.     SafeRelease(&pNumWhite);
  5059.     SafeRelease(&pNumBlack);
  5060. }
  5061.  
  5062. /*void DrawBalls(ID2D1RenderTarget* pRT) {
  5063.     ID2D1SolidColorBrush* pBrush = nullptr;
  5064.     ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
  5065.  
  5066.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
  5067.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  5068.  
  5069.     if (!pBrush || !pStripeBrush) {
  5070.         SafeRelease(&pBrush);
  5071.         SafeRelease(&pStripeBrush);
  5072.         return;
  5073.     }
  5074.  
  5075.  
  5076.     for (size_t i = 0; i < balls.size(); ++i) {
  5077.         const Ball& b = balls[i];
  5078.         if (!b.isPocketed) {
  5079.             D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
  5080.  
  5081.             // Set main ball color
  5082.             pBrush->SetColor(b.color);
  5083.             pRT->FillEllipse(&ellipse, pBrush);
  5084.  
  5085.             // Draw Stripe if applicable
  5086.             if (b.type == BallType::STRIPE) {
  5087.                 // Draw a white band across the middle (simplified stripe)
  5088.                 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);
  5089.                 // Need to clip this rectangle to the ellipse bounds - complex!
  5090.                 // Alternative: Draw two colored arcs leaving a white band.
  5091.                 // Simplest: Draw a white circle inside, slightly smaller.
  5092.                 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
  5093.                 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
  5094.                 pBrush->SetColor(b.color); // Set back to stripe color
  5095.                 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
  5096.  
  5097.                 // Let's try drawing a thick white line across
  5098.                 // This doesn't look great. Just drawing solid red for stripes for now.
  5099.             }
  5100.  
  5101.             // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
  5102.             // if (b.id != 0 && pTextFormat) {
  5103.             //     std::wstring numStr = std::to_wstring(b.id);
  5104.             //     D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
  5105.             //     ID2D1SolidColorBrush* pNumBrush = nullptr;
  5106.             //     D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
  5107.             //     pRT->CreateSolidColorBrush(numCol, &pNumBrush);
  5108.             //     // Create a smaller text format...
  5109.             //     // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
  5110.             //     SafeRelease(&pNumBrush);
  5111.             // }
  5112.         }
  5113.     }
  5114.  
  5115.     SafeRelease(&pBrush);
  5116.     SafeRelease(&pStripeBrush);
  5117. }*/
  5118.  
  5119. void DrawCueStick(ID2D1RenderTarget* pRT)
  5120. {
  5121.     // --- Logic to determine if the cue stick should be visible ---
  5122.     // This part of your code is correct and is preserved.
  5123.     bool shouldDrawStick = false;
  5124.     if (aiIsDisplayingAim) {
  5125.         shouldDrawStick = true;
  5126.     }
  5127.     else if (currentPlayer == 1 || !isPlayer2AI) {
  5128.         switch (currentGameState) {
  5129.         case AIMING:
  5130.         case BREAKING:
  5131.         case PLAYER1_TURN:
  5132.         case PLAYER2_TURN:
  5133.         case CHOOSING_POCKET_P1:
  5134.         case CHOOSING_POCKET_P2:
  5135.             shouldDrawStick = true;
  5136.             break;
  5137.         }
  5138.     }
  5139.     if (!shouldDrawStick) return;
  5140.     // --- End visibility logic ---
  5141.  
  5142.     Ball* cue = GetCueBall();
  5143.     if (!cue) return;
  5144.  
  5145.     // --- FIX: Increased dimensions and added retraction logic ---
  5146.  
  5147.     // 1. Define the new, larger dimensions for the cue stick.
  5148.     const float tipLength = 30.0f;
  5149.     const float buttLength = 60.0f;      // Increased from 50.0f
  5150.     const float totalLength = 220.0f;    // Increased from 200.0f
  5151.     const float buttWidth = 9.0f;        // Increased from 8.0f
  5152.     const float shaftWidth = 5.0f;       // Increased from 4.0f
  5153.  
  5154.     // 2. Determine the correct angle and power to draw with.
  5155.     float angleToDraw = cueAngle;
  5156.     float powerToDraw = shotPower;
  5157.     if (aiIsDisplayingAim) { // If AI is showing its aim, use its planned shot.
  5158.         angleToDraw = aiPlannedShotDetails.angle;
  5159.         powerToDraw = aiPlannedShotDetails.power;
  5160.     }
  5161.  
  5162.     // 3. Calculate the "power offset" based on the current shot strength.
  5163.     // This is the logic from your old code that makes the stick pull back.
  5164.     float powerOffset = 0.0f;
  5165.     if ((isAiming || isDraggingStick) || aiIsDisplayingAim) {
  5166.         // The multiplier controls how far the stick pulls back.
  5167.         powerOffset = powerToDraw * 5.0f;
  5168.     }
  5169.  
  5170.     // 4. Calculate the start and end points of the cue stick, applying the offset.
  5171.     float theta = angleToDraw + PI;
  5172.     D2D1_POINT_2F base = D2D1::Point2F(
  5173.         cue->x + cosf(theta) * (buttLength + powerOffset),
  5174.         cue->y + sinf(theta) * (buttLength + powerOffset)
  5175.     );
  5176.     D2D1_POINT_2F tip = D2D1::Point2F(
  5177.         cue->x + cosf(theta) * (totalLength + powerOffset),
  5178.         cue->y + sinf(theta) * (totalLength + powerOffset)
  5179.     );
  5180.     // --- END OF FIX ---
  5181.  
  5182.     // --- The rest of your tapered drawing logic is preserved and will now use the new points ---
  5183.     ID2D1SolidColorBrush* pButtBrush = nullptr;
  5184.     ID2D1SolidColorBrush* pShaftBrush = nullptr;
  5185.     ID2D1SolidColorBrush* pTipBrush = nullptr;
  5186.     pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pButtBrush);
  5187.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.96f, 0.85f, 0.60f), &pShaftBrush);
  5188.     pRT->CreateSolidColorBrush(D2D1::ColorF(1, 1, 1), &pTipBrush);
  5189.  
  5190.     auto buildRect = [&](D2D1_POINT_2F p1, D2D1_POINT_2F p2, float w1, float w2) {
  5191.         D2D1_POINT_2F perp = { -sinf(theta) * 0.5f, cosf(theta) * 0.5f };
  5192.         perp.x *= w1; perp.y *= w1;
  5193.         D2D1_POINT_2F a = { p1.x + perp.x, p1.y + perp.y };
  5194.         D2D1_POINT_2F b = { p2.x + perp.x * (w2 / w1), p2.y + perp.y * (w2 / w1) };
  5195.         D2D1_POINT_2F c = { p2.x - perp.x * (w2 / w1), p2.y - perp.y * (w2 / w1) };
  5196.         D2D1_POINT_2F d = { p1.x - perp.x, p1.y - perp.y };
  5197.         ID2D1PathGeometry* geom = nullptr;
  5198.         if (SUCCEEDED(pFactory->CreatePathGeometry(&geom))) {
  5199.             ID2D1GeometrySink* sink = nullptr;
  5200.             if (SUCCEEDED(geom->Open(&sink))) {
  5201.                 sink->BeginFigure(a, D2D1_FIGURE_BEGIN_FILLED);
  5202.                 sink->AddLine(b);
  5203.                 sink->AddLine(c);
  5204.                 sink->AddLine(d);
  5205.                 sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5206.                 sink->Close();
  5207.             }
  5208.             SafeRelease(&sink);
  5209.         }
  5210.         return geom;
  5211.     };
  5212.  
  5213.     // --- FIX: These points are now also offset by the power ---
  5214.     D2D1_POINT_2F mid1 = { cue->x + cosf(theta) * (buttLength * 0.5f + powerOffset), cue->y + sinf(theta) * (buttLength * 0.5f + powerOffset) };
  5215.     D2D1_POINT_2F mid2 = { cue->x + cosf(theta) * (totalLength - tipLength + powerOffset), cue->y + sinf(theta) * (totalLength - tipLength + powerOffset) };
  5216.     // --- END OF FIX ---
  5217.  
  5218.     auto buttGeom = buildRect(base, mid1, buttWidth, shaftWidth);
  5219.     if (buttGeom) { pRT->FillGeometry(buttGeom, pButtBrush); SafeRelease(&buttGeom); }
  5220.  
  5221.     auto shaftGeom = buildRect(mid1, mid2, shaftWidth, shaftWidth);
  5222.     if (shaftGeom) { pRT->FillGeometry(shaftGeom, pShaftBrush); SafeRelease(&shaftGeom); }
  5223.  
  5224.     auto tipGeom = buildRect(mid2, tip, shaftWidth, shaftWidth);
  5225.     if (tipGeom) { pRT->FillGeometry(tipGeom, pTipBrush); SafeRelease(&tipGeom); }
  5226.  
  5227.     SafeRelease(&pButtBrush);
  5228.     SafeRelease(&pShaftBrush);
  5229.     SafeRelease(&pTipBrush);
  5230. }
  5231.  
  5232.  
  5233.  
  5234. /*void DrawAimingAids(ID2D1RenderTarget* pRT) {
  5235.     // Condition check at start (Unchanged)
  5236.     //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
  5237.         //currentGameState != BREAKING && currentGameState != AIMING)
  5238.     //{
  5239.         //return;
  5240.     //}
  5241.         // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
  5242.     // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
  5243.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  5244.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  5245.             currentGameState == BREAKING || currentGameState == AIMING);
  5246.     // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
  5247.     // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
  5248.         // NEW Condition: AI is displaying its aim
  5249.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
  5250.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  5251.  
  5252.     if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
  5253.         return;
  5254.     }
  5255.  
  5256.     Ball* cueBall = GetCueBall();
  5257.     if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
  5258.  
  5259.     ID2D1SolidColorBrush* pBrush = nullptr;
  5260.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  5261.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  5262.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  5263.     ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
  5264.  
  5265.     // Ensure render target is valid
  5266.     if (!pRT) return;
  5267.  
  5268.     // Create Brushes and Styles (check for failures)
  5269.     HRESULT hr;
  5270.     hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  5271.     if FAILED(hr) { SafeRelease(&pBrush); return; }
  5272.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  5273.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
  5274.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  5275.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
  5276.     // Create reflection brush (e.g., lighter shade or different color)
  5277.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  5278.     if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
  5279.     // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
  5280.     D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
  5281.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  5282.     hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
  5283.     if (FAILED(hr)) {
  5284.         SafeRelease(&pCyanBrush);
  5285.         // handle error if needed
  5286.     }
  5287.     // Create a Purple brush for primary and secondary lines
  5288.     D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
  5289.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  5290.     hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
  5291.     if (FAILED(hr)) {
  5292.         SafeRelease(&pPurpleBrush);
  5293.         // handle error if needed
  5294.     }
  5295.  
  5296.     if (pFactory) {
  5297.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  5298.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  5299.         hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  5300.         if FAILED(hr) { pDashedStyle = nullptr; }
  5301.     }
  5302.  
  5303.  
  5304.     // --- Cue Stick Drawing (Unchanged from previous fix) ---
  5305.     const float baseStickLength = 150.0f;
  5306.     const float baseStickThickness = 4.0f;
  5307.     float stickLength = baseStickLength * 1.4f;
  5308.     float stickThickness = baseStickThickness * 1.5f;
  5309.     float stickAngle = cueAngle + PI;
  5310.     float powerOffset = 0.0f;
  5311.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  5312.         // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
  5313.     if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
  5314.         powerOffset = shotPower * 5.0f;
  5315.     }
  5316.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  5317.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  5318.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
  5319.  
  5320.  
  5321.     // --- Projection Line Calculation ---
  5322.     float cosA = cosf(cueAngle);
  5323.     float sinA = sinf(cueAngle);
  5324.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
  5325.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  5326.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);*/
  5327.  
  5328. void DrawAimingAids(ID2D1RenderTarget* pRT) {
  5329.     // Determine if aiming aids should be drawn.
  5330.     bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
  5331.         (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
  5332.             currentGameState == BREAKING || currentGameState == AIMING ||
  5333.             currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2);
  5334.  
  5335.     // FOOLPROOF FIX: This is the new condition to show the AI's aim.
  5336.     bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 && aiIsDisplayingAim);
  5337.  
  5338.     if (!isHumanInteracting && !isAiVisualizingShot) {
  5339.         return;
  5340.     }
  5341.  
  5342.     Ball* cueBall = GetCueBall();
  5343.     if (!cueBall || cueBall->isPocketed) return;
  5344.  
  5345.     // --- Brush and Style Creation (No changes here) ---
  5346.     ID2D1SolidColorBrush* pBrush = nullptr;
  5347.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  5348.     ID2D1StrokeStyle* pDashedStyle = nullptr;
  5349.     ID2D1SolidColorBrush* pCueBrush = nullptr;
  5350.     ID2D1SolidColorBrush* pReflectBrush = nullptr;
  5351.     ID2D1SolidColorBrush* pCyanBrush = nullptr;
  5352.     ID2D1SolidColorBrush* pPurpleBrush = nullptr;
  5353.     pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
  5354.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
  5355.     pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
  5356.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
  5357.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Cyan), &pCyanBrush);
  5358.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Purple), &pPurpleBrush);
  5359.     if (pFactory) {
  5360.         D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
  5361.         strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
  5362.         pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
  5363.     }
  5364.     // --- End Brush Creation ---
  5365.  
  5366.     // --- FOOLPROOF FIX: Use the AI's planned angle and power for drawing ---
  5367.     float angleToDraw = cueAngle;
  5368.     float powerToDraw = shotPower;
  5369.  
  5370.     if (isAiVisualizingShot) {
  5371.         // When the AI is showing its aim, force the drawing to use its planned shot details.
  5372.         angleToDraw = aiPlannedShotDetails.angle;
  5373.         powerToDraw = aiPlannedShotDetails.power;
  5374.     }
  5375.     // --- End AI Aiming Fix ---
  5376.  
  5377.     // --- Cue Stick Drawing ---
  5378.     /*const float baseStickLength = 150.0f;
  5379.     const float baseStickThickness = 4.0f;
  5380.     float stickLength = baseStickLength * 1.4f;
  5381.     float stickThickness = baseStickThickness * 1.5f;
  5382.     float stickAngle = angleToDraw + PI; // Use the angle we determined
  5383.     float powerOffset = 0.0f;
  5384.     if ((isAiming || isDraggingStick) || isAiVisualizingShot) {
  5385.         powerOffset = powerToDraw * 5.0f; // Use the power we determined
  5386.     }
  5387.     D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
  5388.     D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
  5389.     pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);*/
  5390.  
  5391.     // --- Projection Line Calculation ---
  5392.     float cosA = cosf(angleToDraw); // Use the angle we determined
  5393.     float sinA = sinf(angleToDraw);
  5394.     float rayLength = TABLE_WIDTH + TABLE_HEIGHT;
  5395.     D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
  5396.     D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
  5397.  
  5398.     // Find the first ball hit by the aiming ray
  5399.     Ball* hitBall = nullptr;
  5400.     float firstHitDistSq = -1.0f;
  5401.     D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
  5402.     D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
  5403.  
  5404.     hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
  5405.     if (hitBall) {
  5406.         // Calculate the point on the target ball's circumference
  5407.         float collisionDist = sqrtf(firstHitDistSq);
  5408.         ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
  5409.         // Calculate ghost ball position for this specific hit (used for projection consistency)
  5410.         ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
  5411.     }
  5412.  
  5413.     // Find the first rail hit by the aiming ray
  5414.     D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
  5415.     float minRailDistSq = rayLength * rayLength;
  5416.     int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
  5417.  
  5418.     // Define table edge segments for intersection checks
  5419.     D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
  5420.     D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
  5421.     D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
  5422.     D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
  5423.  
  5424.     D2D1_POINT_2F currentIntersection;
  5425.  
  5426.     // Check Left Rail
  5427.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
  5428.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5429.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
  5430.     }
  5431.     // Check Right Rail
  5432.     if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
  5433.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5434.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
  5435.     }
  5436.     // Check Top Rail
  5437.     if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
  5438.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5439.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
  5440.     }
  5441.     // Check Bottom Rail
  5442.     if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
  5443.         float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
  5444.         if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
  5445.     }
  5446.  
  5447.  
  5448.     // --- Determine final aim line end point ---
  5449.     D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
  5450.     bool aimingAtRail = true;
  5451.  
  5452.     if (hitBall && firstHitDistSq < minRailDistSq) {
  5453.         // Ball collision is closer than rail collision
  5454.         finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
  5455.         aimingAtRail = false;
  5456.     }
  5457.  
  5458.     // --- Draw Primary Aiming Line ---
  5459.     pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  5460.  
  5461.     // --- Draw Target Circle/Indicator ---
  5462.     D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
  5463.     pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
  5464.  
  5465.     // --- Draw Projection/Reflection Lines ---
  5466.     if (!aimingAtRail && hitBall) {
  5467.         // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
  5468.         D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
  5469.         pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  5470.  
  5471.         // Calculate target ball projection based on impact line (cue collision point -> target center)
  5472.         float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
  5473.         // Clamp angle calculation if distance is tiny
  5474.         if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
  5475.             targetProjectionAngle = cueAngle; // Fallback if overlapping
  5476.         }
  5477.  
  5478.         D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
  5479.         D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
  5480.             hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
  5481.             hitBall->y + sinf(targetProjectionAngle) * 50.0f
  5482.         );
  5483.         // Draw solid line for target projection
  5484.         //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
  5485.  
  5486.     //new code start
  5487.  
  5488.                 // Dual trajectory with edge-aware contact simulation
  5489.         D2D1_POINT_2F dir = {
  5490.             targetProjectionEnd.x - targetStartPoint.x,
  5491.             targetProjectionEnd.y - targetStartPoint.y
  5492.         };
  5493.         float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
  5494.         dir.x /= dirLen;
  5495.         dir.y /= dirLen;
  5496.  
  5497.         D2D1_POINT_2F perp = { -dir.y, dir.x };
  5498.  
  5499.         // Approximate cue ball center by reversing from tip
  5500.         D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
  5501.             targetStartPoint.x - dir.x * BALL_RADIUS,
  5502.             targetStartPoint.y - dir.y * BALL_RADIUS
  5503.         };
  5504.  
  5505.         // REAL contact-ball center - use your physics object's center:
  5506.         // (replace 'objectBallPos' with whatever you actually call it)
  5507.         // (targetStartPoint is already hitBall->x, hitBall->y)
  5508.         D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
  5509.         //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
  5510.  
  5511.        // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
  5512.        // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
  5513.        // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
  5514.        // and 'perp' is perpendicular to 'dir'.
  5515.        // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
  5516.         /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
  5517.             (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
  5518.             /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
  5519.                 (targetStartPoint.y - cueBallCenter.y) * perp.y);
  5520.             float absOffset = fabsf(offset);
  5521.             float side = (offset >= 0 ? 1.0f : -1.0f);*/
  5522.  
  5523.             // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
  5524.         D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
  5525.  
  5526.         // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
  5527.         float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
  5528.             (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
  5529.         float absOffset = fabsf(offset);
  5530.         float side = (offset >= 0 ? 1.0f : -1.0f);
  5531.  
  5532.  
  5533.         // Actual contact point on target ball edge
  5534.         D2D1_POINT_2F contactPoint = {
  5535.         contactBallCenter.x + perp.x * BALL_RADIUS * side,
  5536.         contactBallCenter.y + perp.y * BALL_RADIUS * side
  5537.         };
  5538.  
  5539.         // Tangent (cut shot) path from contact point
  5540.             // Tangent (cut shot) path: from contact point to contact ball center
  5541.         D2D1_POINT_2F objectBallDir = {
  5542.             contactBallCenter.x - contactPoint.x,
  5543.             contactBallCenter.y - contactPoint.y
  5544.         };
  5545.         float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
  5546.         if (oLen != 0.0f) {
  5547.             objectBallDir.x /= oLen;
  5548.             objectBallDir.y /= oLen;
  5549.         }
  5550.  
  5551.         const float PRIMARY_LEN = 150.0f; //default=150.0f
  5552.         const float SECONDARY_LEN = 150.0f; //default=150.0f
  5553.         const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
  5554.  
  5555.         D2D1_POINT_2F primaryEnd = {
  5556.             targetStartPoint.x + dir.x * PRIMARY_LEN,
  5557.             targetStartPoint.y + dir.y * PRIMARY_LEN
  5558.         };
  5559.  
  5560.         // Secondary line starts from the contact ball's center
  5561.         D2D1_POINT_2F secondaryStart = contactBallCenter;
  5562.         D2D1_POINT_2F secondaryEnd = {
  5563.             secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
  5564.             secondaryStart.y + objectBallDir.y * SECONDARY_LEN
  5565.         };
  5566.  
  5567.         if (absOffset < STRAIGHT_EPSILON)  // straight shot?
  5568.         {
  5569.             // Straight: secondary behind primary
  5570.                     // secondary behind primary {pDashedStyle param at end}
  5571.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  5572.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  5573.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  5574.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  5575.         }
  5576.         else
  5577.         {
  5578.             // Cut shot: both visible
  5579.                     // both visible for cut shot
  5580.             pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
  5581.             //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
  5582.             pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
  5583.             //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
  5584.         }
  5585.         // End improved trajectory logic
  5586.  
  5587.     //new code end
  5588.  
  5589.         // -- Cue Ball Path after collision (Optional, requires physics) --
  5590.         // Very simplified: Assume cue deflects, angle depends on cut angle.
  5591.         // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
  5592.         // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
  5593.         // D2D1_POINT_2F cueProjectionEnd = ...
  5594.         // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  5595.  
  5596.         // --- Accuracy Comment ---
  5597.         // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
  5598.         // or shots with spin, is limited by the simplified physics model. Real pool physics involves
  5599.         // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
  5600.         // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
  5601.  
  5602.     }
  5603.     else if (aimingAtRail && hitRailIndex != -1) {
  5604.         // Aiming at a rail: Draw reflection line
  5605.         float reflectAngle = cueAngle;
  5606.         // Reflect angle based on which rail was hit
  5607.         if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
  5608.             reflectAngle = PI - cueAngle; // Reflect horizontal component
  5609.         }
  5610.         else { // Top or Bottom rail
  5611.             reflectAngle = -cueAngle; // Reflect vertical component
  5612.         }
  5613.         // Normalize angle if needed (atan2 usually handles this)
  5614.         while (reflectAngle > PI) reflectAngle -= 2 * PI;
  5615.         while (reflectAngle <= -PI) reflectAngle += 2 * PI;
  5616.  
  5617.  
  5618.         float reflectionLength = 60.0f; // Length of the reflection line
  5619.         D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
  5620.             finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
  5621.             finalLineEnd.y + sinf(reflectAngle) * reflectionLength
  5622.         );
  5623.  
  5624.         // Draw the reflection line (e.g., using a different color/style)
  5625.         pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
  5626.     }
  5627.  
  5628.     // Release resources
  5629.     SafeRelease(&pBrush);
  5630.     SafeRelease(&pGhostBrush);
  5631.     SafeRelease(&pCueBrush);
  5632.     SafeRelease(&pReflectBrush); // Release new brush
  5633.     SafeRelease(&pCyanBrush);
  5634.     SafeRelease(&pPurpleBrush);
  5635.     SafeRelease(&pDashedStyle);
  5636. }
  5637.  
  5638.  
  5639. void DrawUI(ID2D1RenderTarget* pRT) {
  5640.     if (!pTextFormat || !pLargeTextFormat) return;
  5641.  
  5642.     ID2D1SolidColorBrush* pBrush = nullptr;
  5643.     pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
  5644.     if (!pBrush) return;
  5645.  
  5646.     //new code
  5647.     // --- Always draw AI's 8?Ball call arrow when it's Player?2's turn and AI has called ---
  5648.     //if (isPlayer2AI && currentPlayer == 2 && calledPocketP2 >= 0) {
  5649.         // FIX: This condition correctly shows the AI's called pocket arrow.
  5650.     if (isPlayer2AI && IsPlayerOnEightBall(2) && calledPocketP2 >= 0) {
  5651.         // pocket index that AI called
  5652.         int idx = calledPocketP2;
  5653.         // draw large blue arrow
  5654.         ID2D1SolidColorBrush* pArrow = nullptr;
  5655.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  5656.         if (pArrow) {
  5657.             auto P = pocketPositions[idx];
  5658.             D2D1_POINT_2F tri[3] = {
  5659.                 { P.x - 15.0f, P.y - 40.0f },
  5660.                 { P.x + 15.0f, P.y - 40.0f },
  5661.                 { P.x       , P.y - 10.0f }
  5662.             };
  5663.             ID2D1PathGeometry* geom = nullptr;
  5664.             pFactory->CreatePathGeometry(&geom);
  5665.             ID2D1GeometrySink* sink = nullptr;
  5666.             geom->Open(&sink);
  5667.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  5668.             sink->AddLines(&tri[1], 2);
  5669.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5670.             sink->Close();
  5671.             pRT->FillGeometry(geom, pArrow);
  5672.             SafeRelease(&sink);
  5673.             SafeRelease(&geom);
  5674.             SafeRelease(&pArrow);
  5675.         }
  5676.         // draw “Choose a pocket...” prompt
  5677.         D2D1_RECT_F txt = D2D1::RectF(
  5678.             TABLE_LEFT,
  5679.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  5680.             TABLE_RIGHT,
  5681.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  5682.         );
  5683.         pRT->DrawText(
  5684.             L"AI has called this pocket",
  5685.             (UINT32)wcslen(L"AI has called this pocket"),
  5686.             pTextFormat,
  5687.             &txt,
  5688.             pBrush
  5689.         );
  5690.         // note: no return here — we still draw fouls/turn text underneath
  5691.     }
  5692.     //end new code
  5693.  
  5694.     // --- Player Info Area (Top Left/Right) --- (Unchanged)
  5695.     float uiTop = TABLE_TOP - 80;
  5696.     float uiHeight = 60;
  5697.     float p1Left = TABLE_LEFT;
  5698.     float p1Width = 150;
  5699.     float p2Left = TABLE_RIGHT - p1Width;
  5700.     D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
  5701.     D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
  5702.  
  5703.     // Player 1 Info Text (Unchanged)
  5704.     std::wostringstream oss1;
  5705.     oss1 << player1Info.name.c_str();
  5706.     if (player1Info.assignedType != BallType::NONE) {
  5707.         if (IsPlayerOnEightBall(1)) {
  5708.             oss1 << L"\nON 8-BALL";
  5709.         }
  5710.         else {
  5711.             oss1 << L"\n" << ((player1Info.assignedType == BallType::SOLID) ? L"Solids" : L"Stripes");
  5712.             oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
  5713.         }
  5714.     }
  5715.     else {
  5716.         oss1 << L"\n(Undecided)";
  5717.     }
  5718.     //pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
  5719.     // Use bold for current player, normal for the other
  5720.     IDWriteTextFormat* pFormatP1 = (currentPlayer == 1) ? pTextFormatBold : pTextFormat;
  5721.     pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pFormatP1, &p1Rect, pBrush);
  5722.  
  5723.     // Draw Player 1 Side Ball
  5724.     if (player1Info.assignedType != BallType::NONE)
  5725.     {
  5726.         D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 15.0f, p1Rect.top + uiHeight / 2.0f);
  5727.         float radius = 10.0f;
  5728.         D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  5729.  
  5730.         if (IsPlayerOnEightBall(1))
  5731.         {
  5732.             // Player is on the 8-ball, draw the 8-ball indicator.
  5733.             ID2D1SolidColorBrush* p8BallBrush = nullptr;
  5734.             pRT->CreateSolidColorBrush(EIGHT_BALL_COLOR, &p8BallBrush);
  5735.             if (p8BallBrush) pRT->FillEllipse(&ball, p8BallBrush);
  5736.             SafeRelease(&p8BallBrush);
  5737.  
  5738.             // Draw the number '8' decal
  5739.             ID2D1SolidColorBrush* pNumWhite = nullptr, * pNumBlack = nullptr;
  5740.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  5741.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  5742.             if (pBallNumFormat && pNumWhite && pNumBlack)
  5743.             {
  5744.                 const float decalR = radius * 0.7f;
  5745.                 D2D1_ELLIPSE decal = D2D1::Ellipse(ballCenter, decalR, decalR);
  5746.                 pRT->FillEllipse(&decal, pNumWhite);
  5747.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  5748.                 wchar_t numText[] = L"8";
  5749.                 D2D1_RECT_F layout = { ballCenter.x - decalR, ballCenter.y - decalR, ballCenter.x + decalR, ballCenter.y + decalR };
  5750.                 pRT->DrawText(numText, (UINT32)wcslen(numText), pBallNumFormat, &layout, pNumBlack);
  5751.             }
  5752.  
  5753.             // If stripes, draw a stripe band
  5754.             SafeRelease(&pNumWhite);
  5755.             SafeRelease(&pNumBlack);
  5756.         }
  5757.         else
  5758.         {
  5759.             // Default: Draw the player's assigned ball type (solid/stripe).
  5760.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  5761.             D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
  5762.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  5763.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  5764.             if (pBallBrush)
  5765.             {
  5766.                 pRT->FillEllipse(&ball, pBallBrush);
  5767.                 SafeRelease(&pBallBrush);
  5768.                 if (player1Info.assignedType == BallType::STRIPE)
  5769.                 {
  5770.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  5771.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  5772.                     if (pStripeBrush)
  5773.                     {
  5774.                         D2D1_RECT_F stripeRect = { ballCenter.x - radius, ballCenter.y - 3.0f, ballCenter.x + radius, ballCenter.y + 3.0f };
  5775.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  5776.                         SafeRelease(&pStripeBrush);
  5777.                     }
  5778.                 }
  5779.             }
  5780.         }
  5781.         // Draw a border around the indicator ball, regardless of type.
  5782.         ID2D1SolidColorBrush* pBorderBrush = nullptr;
  5783.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  5784.         if (pBorderBrush) pRT->DrawEllipse(&ball, pBorderBrush, 1.5f);
  5785.         SafeRelease(&pBorderBrush);
  5786.                 }
  5787.             //}
  5788.         //}
  5789.     //}
  5790.  
  5791.  
  5792.     // Player 2 Info Text (Unchanged)
  5793.     std::wostringstream oss2;
  5794.     oss2 << player2Info.name.c_str();
  5795.     if (player2Info.assignedType != BallType::NONE) {
  5796.         if (IsPlayerOnEightBall(2)) {
  5797.             oss2 << L"\nON 8-BALL";
  5798.         }
  5799.         else {
  5800.             oss2 << L"\n" << ((player2Info.assignedType == BallType::SOLID) ? L"Solids" : L"Stripes");
  5801.             oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
  5802.         }
  5803.     }
  5804.     else {
  5805.         oss2 << L"\n(Undecided)";
  5806.     }
  5807.  
  5808.     //pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
  5809.     // Use bold for current player, normal for the other
  5810.     IDWriteTextFormat* pFormatP2 = (currentPlayer == 2) ? pTextFormatBold : pTextFormat;
  5811.     pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pFormatP2, &p2Rect, pBrush);
  5812.  
  5813.     // Draw Player 2 Side Ball
  5814.     if (player2Info.assignedType != BallType::NONE)
  5815.     {
  5816.         D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.left - 15.0f, p2Rect.top + uiHeight / 2.0f);
  5817.         float radius = 10.0f;
  5818.         D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
  5819.  
  5820.         if (IsPlayerOnEightBall(2))
  5821.         {
  5822.             // Player is on the 8-ball, draw the 8-ball indicator.
  5823.             ID2D1SolidColorBrush* p8BallBrush = nullptr;
  5824.             pRT->CreateSolidColorBrush(EIGHT_BALL_COLOR, &p8BallBrush);
  5825.             if (p8BallBrush) pRT->FillEllipse(&ball, p8BallBrush);
  5826.             SafeRelease(&p8BallBrush);
  5827.  
  5828.             // Draw the number '8' decal
  5829.             ID2D1SolidColorBrush* pNumWhite = nullptr, * pNumBlack = nullptr;
  5830.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pNumWhite);
  5831.             pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNumBlack);
  5832.             if (pBallNumFormat && pNumWhite && pNumBlack)
  5833.             {
  5834.                 const float decalR = radius * 0.7f;
  5835.                 D2D1_ELLIPSE decal = D2D1::Ellipse(ballCenter, decalR, decalR);
  5836.                 pRT->FillEllipse(&decal, pNumWhite);
  5837.                 pRT->DrawEllipse(&decal, pNumBlack, 0.8f);
  5838.                 wchar_t numText[] = L"8";
  5839.                 D2D1_RECT_F layout = { ballCenter.x - decalR, ballCenter.y - decalR, ballCenter.x + decalR, ballCenter.y + decalR };
  5840.                 pRT->DrawText(numText, (UINT32)wcslen(numText), pBallNumFormat, &layout, pNumBlack);
  5841.             }
  5842.  
  5843.             // If stripes, draw a stripe band
  5844.             SafeRelease(&pNumWhite);
  5845.             SafeRelease(&pNumBlack);
  5846.         }
  5847.         else
  5848.         {
  5849.             // Default: Draw the player's assigned ball type (solid/stripe).
  5850.             ID2D1SolidColorBrush* pBallBrush = nullptr;
  5851.             D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
  5852.                 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
  5853.             pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
  5854.             if (pBallBrush)
  5855.             {
  5856.                 pRT->FillEllipse(&ball, pBallBrush);
  5857.                 SafeRelease(&pBallBrush);
  5858.                 if (player2Info.assignedType == BallType::STRIPE)
  5859.                 {
  5860.                     ID2D1SolidColorBrush* pStripeBrush = nullptr;
  5861.                     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
  5862.                     if (pStripeBrush)
  5863.                     {
  5864.                         D2D1_RECT_F stripeRect = { ballCenter.x - radius, ballCenter.y - 3.0f, ballCenter.x + radius, ballCenter.y + 3.0f };
  5865.                         pRT->FillRectangle(&stripeRect, pStripeBrush);
  5866.                         SafeRelease(&pStripeBrush);
  5867.                     }
  5868.                 }
  5869.             }
  5870.         }
  5871.     //}
  5872.  
  5873.     // Draw a border around the indicator ball, regardless of type.
  5874.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  5875.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  5876.     if (pBorderBrush) pRT->DrawEllipse(&ball, pBorderBrush, 1.5f);
  5877.     SafeRelease(&pBorderBrush);
  5878.     }
  5879.  
  5880.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  5881.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  5882.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  5883.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  5884.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  5885.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  5886.         float arrowTipX, arrowBackX;
  5887.  
  5888.         D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
  5889.         arrowBackX = playerBox.left - 57.0f; //25.0f
  5890.         arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
  5891.  
  5892.         float notchDepth = 12.0f;  // Increased from 6.0f to make the rectangle longer
  5893.         float notchWidth = 10.0f;
  5894.  
  5895.         float cx = arrowBackX;
  5896.         float cy = arrowCenterY;
  5897.  
  5898.         // Define triangle + rectangle tail shape
  5899.         D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy);                           // tip
  5900.         D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f);          // triangle top
  5901.         D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f);          // triangle bottom
  5902.  
  5903.         // Rectangle coordinates for the tail portion:
  5904.         D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f);   // rect top-left
  5905.         D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f);                 // rect top-right
  5906.         D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f);                 // rect bottom-right
  5907.         D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f);    // rect bottom-left
  5908.  
  5909.         ID2D1PathGeometry* pPath = nullptr;
  5910.         if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  5911.             ID2D1GeometrySink* pSink = nullptr;
  5912.             if (SUCCEEDED(pPath->Open(&pSink))) {
  5913.                 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  5914.                 pSink->AddLine(baseTop);
  5915.                 pSink->AddLine(r2); // transition from triangle into rectangle
  5916.                 pSink->AddLine(r1);
  5917.                 pSink->AddLine(r4);
  5918.                 pSink->AddLine(r3);
  5919.                 pSink->AddLine(baseBot);
  5920.                 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5921.                 pSink->Close();
  5922.                 SafeRelease(&pSink);
  5923.                 pRT->FillGeometry(pPath, pArrowBrush);
  5924.             }
  5925.             SafeRelease(&pPath);
  5926.         }
  5927.  
  5928.  
  5929.         SafeRelease(&pArrowBrush);
  5930.     }
  5931.  
  5932.     //original
  5933. /*
  5934.     // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
  5935.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  5936.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  5937.     if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
  5938.         float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
  5939.         float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
  5940.         float arrowTipX, arrowBackX;
  5941.  
  5942.         if (currentPlayer == 1) {
  5943. arrowBackX = p1Rect.left - 25.0f; // Position left of the box
  5944.             arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  5945.             // Define points for right-pointing arrow
  5946.             //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  5947.             //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  5948.             //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  5949.             // Enhanced arrow with base rectangle intersection
  5950.     float notchDepth = 6.0f; // Depth of square base "stem"
  5951.     float notchWidth = 4.0f; // Thickness of square part
  5952.  
  5953.     D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  5954.     D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  5955.     D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
  5956.     D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
  5957.     D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  5958.  
  5959.  
  5960.     ID2D1PathGeometry* pPath = nullptr;
  5961.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  5962.         ID2D1GeometrySink* pSink = nullptr;
  5963.         if (SUCCEEDED(pPath->Open(&pSink))) {
  5964.             pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  5965.             pSink->AddLine(pt2);
  5966.             pSink->AddLine(pt3);
  5967.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5968.             pSink->Close();
  5969.             SafeRelease(&pSink);
  5970.             pRT->FillGeometry(pPath, pArrowBrush);
  5971.         }
  5972.         SafeRelease(&pPath);
  5973.     }
  5974.         }
  5975.  
  5976.  
  5977.         //==================else player 2
  5978.         else { // Player 2
  5979.          // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
  5980.          // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  5981. // Let's keep it consistent: Arrow left of the active player's box, pointing right.
  5982. arrowBackX = p2Rect.left - 25.0f; // Position left of the box
  5983. arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
  5984. // Define points for right-pointing arrow
  5985. D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
  5986. D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
  5987. D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
  5988.  
  5989. ID2D1PathGeometry* pPath = nullptr;
  5990. if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  5991.     ID2D1GeometrySink* pSink = nullptr;
  5992.     if (SUCCEEDED(pPath->Open(&pSink))) {
  5993.         pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
  5994.         pSink->AddLine(pt2);
  5995.         pSink->AddLine(pt3);
  5996.         pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  5997.         pSink->Close();
  5998.         SafeRelease(&pSink);
  5999.         pRT->FillGeometry(pPath, pArrowBrush);
  6000.     }
  6001.     SafeRelease(&pPath);
  6002. }
  6003.         }
  6004.         */
  6005.  
  6006.  
  6007.         // --- Persistent Blue 8?Ball Call Arrow & Prompt ---
  6008.     /*if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  6009.     {
  6010.         // determine index (default top?right)
  6011.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  6012.         if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  6013.         if (idx < 0) idx = 2;
  6014.  
  6015.         // draw large blue arrow
  6016.         ID2D1SolidColorBrush* pArrow = nullptr;
  6017.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6018.         if (pArrow) {
  6019.             auto P = pocketPositions[idx];
  6020.             D2D1_POINT_2F tri[3] = {
  6021.                 {P.x - 15.0f, P.y - 40.0f},
  6022.                 {P.x + 15.0f, P.y - 40.0f},
  6023.                 {P.x       , P.y - 10.0f}
  6024.             };
  6025.             ID2D1PathGeometry* geom = nullptr;
  6026.             pFactory->CreatePathGeometry(&geom);
  6027.             ID2D1GeometrySink* sink = nullptr;
  6028.             geom->Open(&sink);
  6029.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6030.             sink->AddLines(&tri[1], 2);
  6031.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6032.             sink->Close();
  6033.             pRT->FillGeometry(geom, pArrow);
  6034.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  6035.         }
  6036.  
  6037.         // draw prompt
  6038.         D2D1_RECT_F txt = D2D1::RectF(
  6039.             TABLE_LEFT,
  6040.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6041.             TABLE_RIGHT,
  6042.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6043.         );
  6044.         pRT->DrawText(
  6045.             L"Choose a pocket...",
  6046.             (UINT32)wcslen(L"Choose a pocket..."),
  6047.             pTextFormat,
  6048.             &txt,
  6049.             pBrush
  6050.         );
  6051.     }*/
  6052.  
  6053.     // --- Persistent Blue 8?Ball Pocket Arrow & Prompt (once called) ---
  6054. /* if (calledPocketP1 >= 0 || calledPocketP2 >= 0)
  6055. {
  6056.     // 1) Determine pocket index
  6057.     int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  6058.     // If the other player had called but it's now your turn, still show that call
  6059.     if (idx < 0) idx = (currentPlayer == 1 ? calledPocketP2 : calledPocketP1);
  6060.     if (idx < 0) idx = 2; // default to top?right if somehow still unset
  6061.  
  6062.     // 2) Draw large blue arrow
  6063.     ID2D1SolidColorBrush* pArrow = nullptr;
  6064.     pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6065.     if (pArrow) {
  6066.         auto P = pocketPositions[idx];
  6067.         D2D1_POINT_2F tri[3] = {
  6068.             { P.x - 15.0f, P.y - 40.0f },
  6069.             { P.x + 15.0f, P.y - 40.0f },
  6070.             { P.x       , P.y - 10.0f }
  6071.         };
  6072.         ID2D1PathGeometry* geom = nullptr;
  6073.         pFactory->CreatePathGeometry(&geom);
  6074.         ID2D1GeometrySink* sink = nullptr;
  6075.         geom->Open(&sink);
  6076.         sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6077.         sink->AddLines(&tri[1], 2);
  6078.         sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6079.         sink->Close();
  6080.         pRT->FillGeometry(geom, pArrow);
  6081.         SafeRelease(&sink);
  6082.         SafeRelease(&geom);
  6083.         SafeRelease(&pArrow);
  6084.     }
  6085.  
  6086.     // 3) Draw persistent prompt text
  6087.     D2D1_RECT_F txt = D2D1::RectF(
  6088.         TABLE_LEFT,
  6089.         TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6090.         TABLE_RIGHT,
  6091.         TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6092.     );
  6093.     pRT->DrawText(
  6094.         L"Choose a pocket...",
  6095.         (UINT32)wcslen(L"Choose a pocket..."),
  6096.         pTextFormat,
  6097.         &txt,
  6098.         pBrush
  6099.     );
  6100.     // Note: no 'return'; allow foul/turn text to draw beneath if needed
  6101. } */
  6102.  
  6103. // new code ends here
  6104.  
  6105.     // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
  6106.     if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
  6107.         ID2D1SolidColorBrush* pFoulBrush = nullptr;
  6108.         pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
  6109.         if (pFoulBrush && pLargeTextFormat) {
  6110.             // Calculate Rect for bottom-middle area
  6111.             float foulWidth = 200.0f; // Adjust width as needed
  6112.             float foulHeight = 60.0f;
  6113.             float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
  6114.             // Position below the pocketed balls bar
  6115.             float foulTop = pocketedBallsBarRect.bottom + 10.0f;
  6116.             D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
  6117.  
  6118.             // --- Set text alignment to center for foul text ---
  6119.             pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  6120.             pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  6121.  
  6122.             pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
  6123.  
  6124.             // --- Restore default alignment for large text if needed elsewhere ---
  6125.             // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  6126.             // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  6127.  
  6128.             SafeRelease(&pFoulBrush);
  6129.         }
  6130.     }
  6131.  
  6132.     // --- Blue Arrow & Prompt for 8?Ball Call (while choosing or after called) ---
  6133.     if ((currentGameState == CHOOSING_POCKET_P1
  6134.         || currentGameState == CHOOSING_POCKET_P2)
  6135.         || (calledPocketP1 >= 0 || calledPocketP2 >= 0))
  6136.     {
  6137.         // determine index:
  6138.         //  - if a call exists, use it
  6139.         //  - if still choosing, use hover if any
  6140.         // determine index: use only the clicked call; default to top?right if unset
  6141.         int idx = (currentPlayer == 1 ? calledPocketP1 : calledPocketP2);
  6142.         if (idx < 0) idx = 2;
  6143.  
  6144.         // draw large blue arrow
  6145.         ID2D1SolidColorBrush* pArrow = nullptr;
  6146.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrow);
  6147.         if (pArrow) {
  6148.             auto P = pocketPositions[idx];
  6149.             D2D1_POINT_2F tri[3] = {
  6150.                 {P.x - 15.0f, P.y - 40.0f},
  6151.                 {P.x + 15.0f, P.y - 40.0f},
  6152.                 {P.x       , P.y - 10.0f}
  6153.             };
  6154.             ID2D1PathGeometry* geom = nullptr;
  6155.             pFactory->CreatePathGeometry(&geom);
  6156.             ID2D1GeometrySink* sink = nullptr;
  6157.             geom->Open(&sink);
  6158.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6159.             sink->AddLines(&tri[1], 2);
  6160.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6161.             sink->Close();
  6162.             pRT->FillGeometry(geom, pArrow);
  6163.             SafeRelease(&sink); SafeRelease(&geom); SafeRelease(&pArrow);
  6164.         }
  6165.  
  6166.         // draw prompt below pockets
  6167.         D2D1_RECT_F txt = D2D1::RectF(
  6168.             TABLE_LEFT,
  6169.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6170.             TABLE_RIGHT,
  6171.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6172.         );
  6173.         pRT->DrawText(
  6174.             L"Choose a pocket...",
  6175.             (UINT32)wcslen(L"Choose a pocket..."),
  6176.             pTextFormat,
  6177.             &txt,
  6178.             pBrush
  6179.         );
  6180.         // do NOT return here; allow foul/turn text to display under the arrow
  6181.     }
  6182.  
  6183.     // Removed Obsolete
  6184.     /*
  6185.     // --- 8-Ball Pocket Selection Arrow & Prompt ---
  6186.     if (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2) {
  6187.         // Determine which pocket to highlight (default to Top-Right if unset)
  6188.         int idx = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
  6189.         if (idx < 0) idx = 2;
  6190.  
  6191.         // Draw the downward arrow
  6192.         ID2D1SolidColorBrush* pArrowBrush = nullptr;
  6193.         pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
  6194.         if (pArrowBrush) {
  6195.             D2D1_POINT_2F P = pocketPositions[idx];
  6196.             D2D1_POINT_2F tri[3] = {
  6197.                 {P.x - 10.0f, P.y - 30.0f},
  6198.                 {P.x + 10.0f, P.y - 30.0f},
  6199.                 {P.x        , P.y - 10.0f}
  6200.             };
  6201.             ID2D1PathGeometry* geom = nullptr;
  6202.             pFactory->CreatePathGeometry(&geom);
  6203.             ID2D1GeometrySink* sink = nullptr;
  6204.             geom->Open(&sink);
  6205.             sink->BeginFigure(tri[0], D2D1_FIGURE_BEGIN_FILLED);
  6206.             sink->AddLines(&tri[1], 2);
  6207.             sink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6208.             sink->Close();
  6209.             pRT->FillGeometry(geom, pArrowBrush);
  6210.             SafeRelease(&sink);
  6211.             SafeRelease(&geom);
  6212.             SafeRelease(&pArrowBrush);
  6213.         }
  6214.  
  6215.         // Draw “Choose a pocket...” text under the table
  6216.         D2D1_RECT_F prompt = D2D1::RectF(
  6217.             TABLE_LEFT,
  6218.             TABLE_BOTTOM + CUSHION_THICKNESS + 5.0f,
  6219.             TABLE_RIGHT,
  6220.             TABLE_BOTTOM + CUSHION_THICKNESS + 30.0f
  6221.         );
  6222.         pRT->DrawText(
  6223.             L"Choose a pocket...",
  6224.             (UINT32)wcslen(L"Choose a pocket..."),
  6225.             pTextFormat,
  6226.             &prompt,
  6227.             pBrush
  6228.         );
  6229.  
  6230.         return; // Skip normal turn/foul text
  6231.     }
  6232.     */
  6233.  
  6234.  
  6235.     // Show AI Thinking State (Unchanged from previous step)
  6236.     if (currentGameState == AI_THINKING && pTextFormat) {
  6237.         ID2D1SolidColorBrush* pThinkingBrush = nullptr;
  6238.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
  6239.         if (pThinkingBrush) {
  6240.             D2D1_RECT_F thinkingRect = p2Rect;
  6241.             thinkingRect.top += 20; // Offset within P2 box
  6242.             // Ensure default text alignment for this
  6243.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  6244.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
  6245.             pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
  6246.             SafeRelease(&pThinkingBrush);
  6247.         }
  6248.     }
  6249.  
  6250.     SafeRelease(&pBrush);
  6251.  
  6252.     // --- Draw CHEAT MODE label if active ---
  6253.     if (cheatModeEnabled) {
  6254.         ID2D1SolidColorBrush* pCheatBrush = nullptr;
  6255.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
  6256.         if (pCheatBrush && pTextFormat) {
  6257.             D2D1_RECT_F cheatTextRect = D2D1::RectF(
  6258.                 TABLE_LEFT + 10.0f,
  6259.                 TABLE_TOP + 10.0f,
  6260.                 TABLE_LEFT + 200.0f,
  6261.                 TABLE_TOP + 40.0f
  6262.             );
  6263.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
  6264.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  6265.             pRT->DrawText(L"CHEAT MODE ON", static_cast<UINT32>(wcslen(L"CHEAT MODE ON")), pTextFormat, &cheatTextRect, pCheatBrush);
  6266.         }
  6267.         SafeRelease(&pCheatBrush);
  6268.     }
  6269. }
  6270.  
  6271. void DrawPowerMeter(ID2D1RenderTarget* pRT) {
  6272.     // Draw Border
  6273.     ID2D1SolidColorBrush* pBorderBrush = nullptr;
  6274.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
  6275.     if (!pBorderBrush) return;
  6276.     pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
  6277.     SafeRelease(&pBorderBrush);
  6278.  
  6279.     // Create Gradient Fill
  6280.     ID2D1GradientStopCollection* pGradientStops = nullptr;
  6281.     ID2D1LinearGradientBrush* pGradientBrush = nullptr;
  6282.     D2D1_GRADIENT_STOP gradientStops[4];
  6283.     gradientStops[0].position = 0.0f;
  6284.     gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
  6285.     gradientStops[1].position = 0.45f;
  6286.     gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
  6287.     gradientStops[2].position = 0.7f;
  6288.     gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
  6289.     gradientStops[3].position = 1.0f;
  6290.     gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
  6291.  
  6292.     pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
  6293.     if (pGradientStops) {
  6294.         D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
  6295.         props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
  6296.         props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
  6297.         pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
  6298.         SafeRelease(&pGradientStops);
  6299.     }
  6300.  
  6301.     // Calculate Fill Height
  6302.     float fillRatio = 0;
  6303.     //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
  6304.         // Determine if power meter should reflect shot power (human aiming or AI preparing)
  6305.     bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
  6306.     // NEW Condition: AI is displaying its aim, so show its chosen power
  6307.     bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
  6308.         currentGameState == AI_THINKING && aiIsDisplayingAim);
  6309.  
  6310.     if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
  6311.         fillRatio = shotPower / MAX_SHOT_POWER;
  6312.     }
  6313.     float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
  6314.     D2D1_RECT_F fillRect = D2D1::RectF(
  6315.         powerMeterRect.left,
  6316.         powerMeterRect.bottom - fillHeight,
  6317.         powerMeterRect.right,
  6318.         powerMeterRect.bottom
  6319.     );
  6320.  
  6321.     if (pGradientBrush) {
  6322.         pRT->FillRectangle(&fillRect, pGradientBrush);
  6323.         SafeRelease(&pGradientBrush);
  6324.     }
  6325.  
  6326.     // Draw scale notches
  6327.     ID2D1SolidColorBrush* pNotchBrush = nullptr;
  6328.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
  6329.     if (pNotchBrush) {
  6330.         for (int i = 0; i <= 8; ++i) {
  6331.             float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
  6332.             pRT->DrawLine(
  6333.                 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
  6334.                 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
  6335.                 pNotchBrush,
  6336.                 1.5f
  6337.             );
  6338.         }
  6339.         SafeRelease(&pNotchBrush);
  6340.     }
  6341.  
  6342.     // Draw "Power" Label Below Meter
  6343.     if (pTextFormat) {
  6344.         ID2D1SolidColorBrush* pTextBrush = nullptr;
  6345.         pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
  6346.         if (pTextBrush) {
  6347.             D2D1_RECT_F textRect = D2D1::RectF(
  6348.                 powerMeterRect.left - 20.0f,
  6349.                 powerMeterRect.bottom + 8.0f,
  6350.                 powerMeterRect.right + 20.0f,
  6351.                 powerMeterRect.bottom + 38.0f
  6352.             );
  6353.             pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
  6354.             pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
  6355.             pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
  6356.             SafeRelease(&pTextBrush);
  6357.         }
  6358.     }
  6359.  
  6360.     // Draw Glow Effect if fully charged or fading out
  6361.     static float glowPulse = 0.0f;
  6362.     static bool glowIncreasing = true;
  6363.     static float glowFadeOut = 0.0f; // NEW: tracks fading out
  6364.  
  6365.     if (shotPower >= MAX_SHOT_POWER * 0.99f) {
  6366.         // While fully charged, keep pulsing normally
  6367.         if (glowIncreasing) {
  6368.             glowPulse += 0.02f;
  6369.             if (glowPulse >= 1.0f) glowIncreasing = false;
  6370.         }
  6371.         else {
  6372.             glowPulse -= 0.02f;
  6373.             if (glowPulse <= 0.0f) glowIncreasing = true;
  6374.         }
  6375.         glowFadeOut = 1.0f; // Reset fade out to full
  6376.     }
  6377.     else if (glowFadeOut > 0.0f) {
  6378.         // If shot fired, gradually fade out
  6379.         glowFadeOut -= 0.02f;
  6380.         if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
  6381.     }
  6382.  
  6383.     if (glowFadeOut > 0.0f) {
  6384.         ID2D1SolidColorBrush* pGlowBrush = nullptr;
  6385.         float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
  6386.         pRT->CreateSolidColorBrush(
  6387.             D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
  6388.             &pGlowBrush
  6389.         );
  6390.         if (pGlowBrush) {
  6391.             float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
  6392.             float glowCenterY = powerMeterRect.top;
  6393.             D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
  6394.                 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
  6395.                 12.0f + 3.0f * glowPulse,
  6396.                 6.0f + 2.0f * glowPulse
  6397.             );
  6398.             pRT->FillEllipse(&glowEllipse, pGlowBrush);
  6399.             SafeRelease(&pGlowBrush);
  6400.         }
  6401.     }
  6402. }
  6403.  
  6404. void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
  6405.     ID2D1SolidColorBrush* pWhiteBrush = nullptr;
  6406.     ID2D1SolidColorBrush* pRedBrush = nullptr;
  6407.  
  6408.     pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
  6409.     pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
  6410.  
  6411.     if (!pWhiteBrush || !pRedBrush) {
  6412.         SafeRelease(&pWhiteBrush);
  6413.         SafeRelease(&pRedBrush);
  6414.         return;
  6415.     }
  6416.  
  6417.     // Draw White Ball Background
  6418.     D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
  6419.     pRT->FillEllipse(&bgEllipse, pWhiteBrush);
  6420.     pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
  6421.  
  6422.  
  6423.     // Draw Red Dot for Spin Position
  6424.     float dotRadius = 4.0f;
  6425.     float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
  6426.     float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
  6427.     D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
  6428.     pRT->FillEllipse(&dotEllipse, pRedBrush);
  6429.  
  6430.     SafeRelease(&pWhiteBrush);
  6431.     SafeRelease(&pRedBrush);
  6432. }
  6433.  
  6434.  
  6435. void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
  6436.     ID2D1SolidColorBrush* pBgBrush = nullptr;
  6437.     ID2D1SolidColorBrush* pBallBrush = nullptr;
  6438.  
  6439.     // Ensure render target is valid before proceeding
  6440.     if (!pRT) return;
  6441.  
  6442.     HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
  6443.     if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
  6444.  
  6445.     hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
  6446.     if (FAILED(hr)) {
  6447.         SafeRelease(&pBgBrush);
  6448.         SafeRelease(&pBallBrush);
  6449.         return; // Exit if brush creation fails
  6450.     }
  6451.  
  6452.     // Draw the background bar (rounded rect)
  6453.     D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
  6454.     float baseAlpha = 0.8f;
  6455.     float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
  6456.     float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
  6457.     pBgBrush->SetOpacity(finalAlpha);
  6458.     pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
  6459.     pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
  6460.  
  6461.     // --- Draw small circles for pocketed balls inside the bar ---
  6462.  
  6463.     // Calculate dimensions based on the bar's height for better scaling
  6464.     float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
  6465.     float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
  6466.     float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
  6467.     float padding = spacing * 0.75f; // Add padding from the edges
  6468.     float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
  6469.  
  6470.     // Starting X positions with padding
  6471.     float currentX_P1 = pocketedBallsBarRect.left + padding;
  6472.     float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
  6473.  
  6474.     int p1DrawnCount = 0;
  6475.     int p2DrawnCount = 0;
  6476.     const int maxBallsToShow = 7; // Max balls per player in the bar
  6477.  
  6478.     for (const auto& b : balls) {
  6479.         if (b.isPocketed) {
  6480.             // Skip cue ball and 8-ball in this indicator
  6481.             if (b.id == 0 || b.id == 8) continue;
  6482.  
  6483.             bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
  6484.             bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
  6485.  
  6486.             if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
  6487.                 pBallBrush->SetColor(b.color);
  6488.                 // Draw P1 balls from left to right
  6489.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  6490.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  6491.                 p1DrawnCount++;
  6492.             }
  6493.             else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
  6494.                 pBallBrush->SetColor(b.color);
  6495.                 // Draw P2 balls from right to left
  6496.                 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
  6497.                 pRT->FillEllipse(&ballEllipse, pBallBrush);
  6498.                 p2DrawnCount++;
  6499.             }
  6500.             // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
  6501.             // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
  6502.         }
  6503.     }
  6504.  
  6505.     SafeRelease(&pBgBrush);
  6506.     SafeRelease(&pBallBrush);
  6507. }
  6508.  
  6509. void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
  6510.     if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
  6511.         return; // Only show when placing/dragging
  6512.     }
  6513.  
  6514.     Ball* cueBall = GetCueBall();
  6515.     if (!cueBall) return;
  6516.  
  6517.     ID2D1SolidColorBrush* pGhostBrush = nullptr;
  6518.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
  6519.  
  6520.     if (pGhostBrush) {
  6521.         D2D1_POINT_2F drawPos;
  6522.         if (isDraggingCueBall) {
  6523.             drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
  6524.         }
  6525.         else {
  6526.             // If not dragging but in placement state, show at current ball pos
  6527.             drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
  6528.         }
  6529.  
  6530.         // Check if the placement is valid before drawing differently?
  6531.         bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
  6532.         bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
  6533.  
  6534.         if (!isValid) {
  6535.             // Maybe draw red outline if invalid placement?
  6536.             pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
  6537.         }
  6538.  
  6539.  
  6540.         D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
  6541.         pRT->FillEllipse(&ghostEllipse, pGhostBrush);
  6542.         pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
  6543.  
  6544.         SafeRelease(&pGhostBrush);
  6545.     }
  6546. }
  6547.  
  6548. void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
  6549.     if (!pFactory) return; // Need factory to create geometry
  6550.  
  6551.     int pocketToIndicate = -1;
  6552.     if (currentGameState == CHOOSING_POCKET_P1 || (currentPlayer == 1 && IsPlayerOnEightBall(1))) {
  6553.         pocketToIndicate = (calledPocketP1 >= 0) ? calledPocketP1 : currentlyHoveredPocket;
  6554.     }
  6555.     else if (currentGameState == CHOOSING_POCKET_P2 || (currentPlayer == 2 && IsPlayerOnEightBall(2))) {
  6556.         pocketToIndicate = (calledPocketP2 >= 0) ? calledPocketP2 : currentlyHoveredPocket;
  6557.     }
  6558.  
  6559.     if (pocketToIndicate < 0 || pocketToIndicate > 5) {
  6560.         return;
  6561.     }
  6562.  
  6563.     ID2D1SolidColorBrush* pArrowBrush = nullptr;
  6564.     pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
  6565.     if (!pArrowBrush) return;
  6566.  
  6567.     // FIXED: Get the correct radius for the indicated pocket
  6568.     float currentPocketRadius = (pocketToIndicate == 1 || pocketToIndicate == 4) ? MIDDLE_HOLE_VISUAL_RADIUS : CORNER_HOLE_VISUAL_RADIUS;
  6569.  
  6570.     D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
  6571.     // FIXED: Calculate arrow dimensions based on the correct pocket radius
  6572.     float pocketVis = GetPocketVisualRadius(pocketToIndicate);
  6573.     float arrowHeadSize = pocketVis * 0.5f;
  6574.     float arrowShaftLength = pocketVis * 0.3f;
  6575.     float arrowShaftWidth = arrowHeadSize * 0.4f;
  6576.     float verticalOffsetFromPocketCenter = pocketVis * 1.6f;
  6577.  
  6578.     D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
  6579.  
  6580.     // Determine arrow direction based on pocket position (top or bottom row)
  6581.     if (targetPocketCenter.y == TABLE_TOP) { // Top row pockets
  6582.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
  6583.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  6584.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
  6585.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
  6586.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
  6587.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  6588.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  6589.     }
  6590.     else { // Bottom row pockets
  6591.         tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
  6592.         baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  6593.         baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
  6594.         shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
  6595.         shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
  6596.         shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
  6597.         shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
  6598.     }
  6599.     ID2D1PathGeometry* pPath = nullptr;
  6600.     if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
  6601.         ID2D1GeometrySink* pSink = nullptr;
  6602.         if (SUCCEEDED(pPath->Open(&pSink))) {
  6603.             pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
  6604.             pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
  6605.             pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
  6606.             pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
  6607.             pSink->Close();
  6608.             SafeRelease(&pSink);
  6609.             pRT->FillGeometry(pPath, pArrowBrush);
  6610.         }
  6611.         SafeRelease(&pPath);
  6612.     }
  6613.     SafeRelease(&pArrowBrush);
  6614. }
  6615. ```
  6616.  
  6617. ==++ Here's the code for "Resource.h"::: ++==
  6618. ```resource.h
  6619. //{{NO_DEPENDENCIES}}
  6620. // Microsoft Visual C++ generated include file.
  6621. // Used by Yahoo-8Ball-Pool-Clone.rc
  6622. //
  6623. #define IDI_ICON1                       101
  6624. // --- NEW Resource IDs (Define these in your .rc file / resource.h) ---
  6625. #define IDD_NEWGAMEDLG 106
  6626. #define IDC_RADIO_2P   1003
  6627. #define IDC_RADIO_CPU  1005
  6628. #define IDC_GROUP_AI   1006
  6629. #define IDC_RADIO_EASY 1007
  6630. #define IDC_RADIO_MEDIUM 1008
  6631. #define IDC_RADIO_HARD 1009
  6632. // --- NEW Resource IDs for Opening Break ---
  6633. #define IDC_GROUP_BREAK_MODE 1010
  6634. #define IDC_RADIO_CPU_BREAK  1011
  6635. #define IDC_RADIO_P1_BREAK   1012
  6636. #define IDC_RADIO_FLIP_BREAK 1013
  6637. // --- NEW Resource ID for Table Color Dropdown ---
  6638. #define IDC_COMBO_TABLECOLOR 1014
  6639. // Standard IDOK is usually defined, otherwise define it (e.g., #define IDOK 1)
  6640.  
  6641. // Next default values for new objects
  6642. //
  6643. #ifdef APSTUDIO_INVOKED
  6644. #ifndef APSTUDIO_READONLY_SYMBOLS
  6645. #define _APS_NEXT_RESOURCE_VALUE        102
  6646. #define _APS_NEXT_COMMAND_VALUE         40002 // Incremented
  6647. #define _APS_NEXT_CONTROL_VALUE         1014 // Incremented
  6648. #define _APS_NEXT_SYMED_VALUE           101
  6649. #endif
  6650. #endif
  6651.  
  6652. ```
  6653.  
  6654. ==++ Here's the code for "Yahoo-8Ball-Pool-Clone.rc"::: ++==
  6655. ```Yahoo-8Ball-Pool-Clone.rc
  6656. // Microsoft Visual C++ generated resource script.
  6657. //
  6658. #include "resource.h"
  6659.  
  6660. #define APSTUDIO_READONLY_SYMBOLS
  6661. /////////////////////////////////////////////////////////////////////////////
  6662. //
  6663. // Generated from the TEXTINCLUDE 2 resource.
  6664. //
  6665. #include "winres.h"
  6666.  
  6667. /////////////////////////////////////////////////////////////////////////////
  6668. #undef APSTUDIO_READONLY_SYMBOLS
  6669.  
  6670. /////////////////////////////////////////////////////////////////////////////
  6671. // English (United States) resources
  6672.  
  6673. #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
  6674. LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
  6675. #pragma code_page(1252)
  6676.  
  6677. #ifdef APSTUDIO_INVOKED
  6678. /////////////////////////////////////////////////////////////////////////////
  6679. //
  6680. // TEXTINCLUDE
  6681. //
  6682.  
  6683. 1 TEXTINCLUDE
  6684. BEGIN
  6685. "resource.h\0"
  6686. END
  6687.  
  6688. 2 TEXTINCLUDE
  6689. BEGIN
  6690. "#include ""winres.h""\r\n"
  6691. "\0"
  6692. END
  6693.  
  6694. 3 TEXTINCLUDE
  6695. BEGIN
  6696. "\r\n"
  6697. "\0"
  6698. END
  6699.  
  6700. #endif    // APSTUDIO_INVOKED
  6701.  
  6702.  
  6703. /////////////////////////////////////////////////////////////////////////////
  6704. //
  6705. // Icon
  6706. //
  6707.  
  6708. // Icon with lowest ID value placed first to ensure application icon
  6709. // remains consistent on all systems.
  6710. IDI_ICON1               ICON                    "D:\\Download\\8Ball_Colored.ico"
  6711.  
  6712. #endif    // English (United States) resources
  6713. /////////////////////////////////////////////////////////////////////////////
  6714.  
  6715.  
  6716.  
  6717. #ifndef APSTUDIO_INVOKED
  6718. /////////////////////////////////////////////////////////////////////////////
  6719. //
  6720. // Generated from the TEXTINCLUDE 3 resource.
  6721. //
  6722.  
  6723.  
  6724. /////////////////////////////////////////////////////////////////////////////
  6725. #endif    // not APSTUDIO_INVOKED
  6726.  
  6727. #include <windows.h> // Needed for control styles like WS_GROUP, BS_AUTORADIOBUTTON etc.
  6728.  
  6729. /////////////////////////////////////////////////////////////////////////////
  6730. //
  6731. // Dialog
  6732. //
  6733.  
  6734. IDD_NEWGAMEDLG DIALOGEX 0, 0, 220, 185 // Dialog position (x, y) and size (width, height) in Dialog Units (DLUs) - Increased Height
  6735. STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
  6736. CAPTION "New 8-Ball Game"
  6737. FONT 8, "MS Shell Dlg", 400, 0, 0x1 // Standard dialog font
  6738. BEGIN
  6739. // --- Game Mode Selection ---
  6740. // Group Box for Game Mode (Optional visually, but helps structure)
  6741. GROUPBOX        "Game Mode", IDC_STATIC, 7, 7, 90, 50
  6742.  
  6743. // "2 Player" Radio Button (First in this group)
  6744. CONTROL         "&2 Player (Human vs Human)", IDC_RADIO_2P, "Button",
  6745. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 14, 20, 80, 10
  6746.  
  6747. // "Human vs CPU" Radio Button
  6748. CONTROL         "Human vs &CPU", IDC_RADIO_CPU, "Button",
  6749. BS_AUTORADIOBUTTON | WS_TABSTOP, 14, 35, 70, 10
  6750.  
  6751. // --- NEW: Table Color Selection ---
  6752. LTEXT           "Table Color:", IDC_STATIC, 7, 65, 50, 8
  6753. COMBOBOX        IDC_COMBO_TABLECOLOR, 7, 75, 90, 60,
  6754. CBS_DROPDOWNLIST | CBS_HASSTRINGS | WS_VSCROLL | WS_TABSTOP
  6755.  
  6756.  
  6757. // --- AI Difficulty Selection (Inside its own Group Box) ---
  6758. GROUPBOX        "AI Difficulty", IDC_GROUP_AI, 118, 7, 95, 70
  6759.  
  6760. // "Easy" Radio Button (First in the AI group)
  6761. CONTROL         "&Easy", IDC_RADIO_EASY, "Button",
  6762. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 20, 60, 10
  6763.  
  6764. // "Medium" Radio Button
  6765. CONTROL         "&Medium", IDC_RADIO_MEDIUM, "Button",
  6766. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 35, 60, 10
  6767.  
  6768. // "Hard" Radio Button
  6769. CONTROL         "&Hard", IDC_RADIO_HARD, "Button",
  6770. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 50, 60, 10
  6771.  
  6772. // --- Opening Break Modes (For Versus CPU Only) ---
  6773. GROUPBOX        "Opening Break Modes:", IDC_GROUP_BREAK_MODE, 118, 82, 95, 60
  6774.  
  6775. // "CPU Break" Radio Button (Default for this group)
  6776. CONTROL         "&CPU Break", IDC_RADIO_CPU_BREAK, "Button",
  6777. BS_AUTORADIOBUTTON | WS_GROUP | WS_TABSTOP, 125, 95, 70, 10
  6778.  
  6779. // "P1 Break" Radio Button
  6780. CONTROL         "&P1 Break", IDC_RADIO_P1_BREAK, "Button",
  6781. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 110, 70, 10
  6782.  
  6783. // "FlipCoin Break" Radio Button
  6784. CONTROL         "&FlipCoin Break", IDC_RADIO_FLIP_BREAK, "Button",
  6785. BS_AUTORADIOBUTTON | WS_TABSTOP, 125, 125, 70, 10
  6786.  
  6787.  
  6788. // --- Standard Buttons ---
  6789. DEFPUSHBUTTON   "Start", IDOK, 55, 160, 50, 14 // Default button (Enter key) - Adjusted Y position
  6790. PUSHBUTTON      "Cancel", IDCANCEL, 115, 160, 50, 14 // Adjusted Y position
  6791. END
  6792. ```
Advertisement
Add Comment
Please, Sign In to add comment