alien_fx_fiend

2D StickPool C++ D2D Pre-Collision-Motion-Effect-During-Movement

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