alien_fx_fiend

2D StickPool C++ D2D Post Balls Spinning Clockwise Motion Not Axis (Linear+Direction Aware Collisio)

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