alien_fx_fiend

2D StickPool C++ D2D V32 Final Ver (AI + Top-Right Pocket Fix !!)

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