· 3 months ago · Jun 27, 2025, 04:05 PM
1#define WIN32_LEAN_AND_MEAN
2#define NOMINMAX
3#include <windows.h>
4#include <d2d1.h>
5#include <dwrite.h>
6#include <fstream> // For file I/O
7#include <iostream> // For some basic I/O, though not strictly necessary for just file ops
8#include <vector>
9#include <cmath>
10#include <string>
11#include <sstream> // Required for wostringstream
12#include <algorithm> // Required for std::max, std::min
13#include <ctime> // Required for srand, time
14#include <cstdlib> // Required for srand, rand (often included by others, but good practice)
15#include <commctrl.h> // Needed for radio buttons etc. in dialog (if using native controls)
16#include <mmsystem.h> // For PlaySound
17#include <tchar.h> //midi func
18#include <thread>
19#include <atomic>
20#include "resource.h"
21
22#pragma comment(lib, "Comctl32.lib") // Link against common controls library
23#pragma comment(lib, "d2d1.lib")
24#pragma comment(lib, "dwrite.lib")
25#pragma comment(lib, "Winmm.lib") // Link against Windows Multimedia library
26
27// --- Constants ---
28const float PI = 3.1415926535f;
29const float BALL_RADIUS = 10.0f;
30const float TABLE_LEFT = 100.0f;
31const float TABLE_TOP = 100.0f;
32const float TABLE_WIDTH = 700.0f;
33const float TABLE_HEIGHT = 350.0f;
34const float TABLE_RIGHT = TABLE_LEFT + TABLE_WIDTH;
35const float TABLE_BOTTOM = TABLE_TOP + TABLE_HEIGHT;
36const float CUSHION_THICKNESS = 20.0f;
37const float HOLE_VISUAL_RADIUS = 22.0f; // Visual size of the hole
38const float POCKET_RADIUS = HOLE_VISUAL_RADIUS * 1.05f; // Make detection radius slightly larger // Make detection radius match visual size (or slightly larger)
39const float MAX_SHOT_POWER = 15.0f;
40const float FRICTION = 0.985f; // Friction factor per frame
41const float MIN_VELOCITY_SQ = 0.01f * 0.01f; // Stop balls below this squared velocity
42const float HEADSTRING_X = TABLE_LEFT + TABLE_WIDTH * 0.30f; // 30% line
43const float RACK_POS_X = TABLE_LEFT + TABLE_WIDTH * 0.65f; // 65% line for rack apex
44const float RACK_POS_Y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
45const UINT ID_TIMER = 1;
46const int TARGET_FPS = 60; // Target frames per second for timer
47
48// --- Enums ---
49// --- MODIFIED/NEW Enums ---
50enum GameState {
51 SHOWING_DIALOG, // NEW: Game is waiting for initial dialog input
52 PRE_BREAK_PLACEMENT,// Player placing cue ball for break
53 BREAKING, // Player is aiming/shooting the break shot
54 CHOOSING_POCKET_P1, // NEW: Player 1 needs to call a pocket for the 8-ball
55 CHOOSING_POCKET_P2, // NEW: Player 2 needs to call a pocket for the 8-ball
56 AIMING, // Player is aiming
57 AI_THINKING, // NEW: AI is calculating its move
58 SHOT_IN_PROGRESS, // Balls are moving
59 ASSIGNING_BALLS, // Turn after break where ball types are assigned
60 PLAYER1_TURN,
61 PLAYER2_TURN,
62 BALL_IN_HAND_P1,
63 BALL_IN_HAND_P2,
64 GAME_OVER
65};
66
67enum BallType {
68 NONE,
69 SOLID, // Yellow (1-7)
70 STRIPE, // Red (9-15)
71 EIGHT_BALL, // Black (8)
72 CUE_BALL // White (0)
73};
74
75// NEW Enums for Game Mode and AI Difficulty
76enum GameMode {
77 HUMAN_VS_HUMAN,
78 HUMAN_VS_AI
79};
80
81enum AIDifficulty {
82 EASY,
83 MEDIUM,
84 HARD
85};
86
87enum OpeningBreakMode {
88 CPU_BREAK,
89 P1_BREAK,
90 FLIP_COIN_BREAK
91};
92
93// --- Structs ---
94struct Ball {
95 int id; // 0=Cue, 1-7=Solid, 8=Eight, 9-15=Stripe
96 BallType type;
97 float x, y;
98 float vx, vy;
99 D2D1_COLOR_F color;
100 bool isPocketed;
101};
102
103struct PlayerInfo {
104 BallType assignedType;
105 int ballsPocketedCount;
106 std::wstring name;
107};
108
109// --- Global Variables ---
110
111// Direct2D & DirectWrite
112ID2D1Factory* pFactory = nullptr;
113//ID2D1Factory* g_pD2DFactory = nullptr;
114ID2D1HwndRenderTarget* pRenderTarget = nullptr;
115IDWriteFactory* pDWriteFactory = nullptr;
116IDWriteTextFormat* pTextFormat = nullptr;
117IDWriteTextFormat* pLargeTextFormat = nullptr; // For "Foul!"
118
119// Game State
120HWND hwndMain = nullptr;
121GameState currentGameState = SHOWING_DIALOG; // Start by showing dialog
122std::vector<Ball> balls;
123int currentPlayer = 1; // 1 or 2
124PlayerInfo player1Info = { BallType::NONE, 0, L"Player 1" };
125PlayerInfo player2Info = { BallType::NONE, 0, L"CPU" }; // Default P2 name
126bool foulCommitted = false;
127std::wstring gameOverMessage = L"";
128bool firstBallPocketedAfterBreak = false;
129std::vector<int> pocketedThisTurn;
130// --- NEW: 8-Ball Pocket Call Globals ---
131int calledPocketP1 = -1; // Pocket index (0-5) called by Player 1 for the 8-ball. -1 means not called.
132int calledPocketP2 = -1; // Pocket index (0-5) called by Player 2 for the 8-ball.
133int currentlyHoveredPocket = -1; // For visual feedback on which pocket is being hovered
134std::wstring pocketCallMessage = L""; // Message like "Choose a pocket..."
135
136// --- NEW: Foul Tracking Globals ---
137int firstHitBallIdThisShot = -1; // ID of the first object ball hit by cue ball (-1 if none)
138bool cueHitObjectBallThisShot = false; // Did cue ball hit an object ball this shot?
139bool railHitAfterContact = false; // Did any ball hit a rail AFTER cue hit an object ball?
140// --- End New Foul Tracking Globals ---
141
142// NEW Game Mode/AI Globals
143GameMode gameMode = HUMAN_VS_HUMAN; // Default mode
144AIDifficulty aiDifficulty = MEDIUM; // Default difficulty
145OpeningBreakMode openingBreakMode = CPU_BREAK; // Default opening break mode
146bool isPlayer2AI = false; // Is Player 2 controlled by AI?
147bool aiTurnPending = false; // Flag: AI needs to take its turn when possible
148// bool aiIsThinking = false; // Replaced by AI_THINKING game state
149// NEW: Flag to indicate if the current shot is the opening break of the game
150bool isOpeningBreakShot = false;
151
152// NEW: For AI shot planning and visualization
153struct AIPlannedShot {
154 float angle;
155 float power;
156 float spinX;
157 float spinY;
158 bool isValid; // Is there a valid shot planned?
159};
160AIPlannedShot aiPlannedShotDetails; // Stores the AI's next shot
161bool aiIsDisplayingAim = false; // True when AI has decided a shot and is in "display aim" mode
162int aiAimDisplayFramesLeft = 0; // How many frames left to display AI aim
163const int AI_AIM_DISPLAY_DURATION_FRAMES = 45; // Approx 0.75 seconds at 60 FPS, adjust as needed
164
165// Input & Aiming
166POINT ptMouse = { 0, 0 };
167bool isAiming = false;
168bool isDraggingCueBall = false;
169// --- ENSURE THIS LINE EXISTS HERE ---
170bool isDraggingStick = false; // True specifically when drag initiated on the stick graphic
171// --- End Ensure ---
172bool isSettingEnglish = false;
173D2D1_POINT_2F aimStartPoint = { 0, 0 };
174float cueAngle = 0.0f;
175float shotPower = 0.0f;
176float cueSpinX = 0.0f; // Range -1 to 1
177float cueSpinY = 0.0f; // Range -1 to 1
178float pocketFlashTimer = 0.0f;
179bool cheatModeEnabled = false; // Cheat Mode toggle (G key)
180int draggingBallId = -1;
181bool keyboardAimingActive = false; // NEW FLAG: true when arrow keys modify aim/power
182MCIDEVICEID midiDeviceID = 0; //midi func
183std::atomic<bool> isMusicPlaying(false); //midi func
184std::thread musicThread; //midi func
185void StartMidi(HWND hwnd, const TCHAR* midiPath);
186void StopMidi();
187
188// UI Element Positions
189D2D1_RECT_F powerMeterRect = { TABLE_RIGHT + CUSHION_THICKNESS + 10, TABLE_TOP, TABLE_RIGHT + CUSHION_THICKNESS + 40, TABLE_BOTTOM };
190D2D1_RECT_F spinIndicatorRect = { TABLE_LEFT - CUSHION_THICKNESS - 60, TABLE_TOP + 20, TABLE_LEFT - CUSHION_THICKNESS - 20, TABLE_TOP + 60 }; // Circle area
191D2D1_POINT_2F spinIndicatorCenter = { spinIndicatorRect.left + (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f, spinIndicatorRect.top + (spinIndicatorRect.bottom - spinIndicatorRect.top) / 2.0f };
192float spinIndicatorRadius = (spinIndicatorRect.right - spinIndicatorRect.left) / 2.0f;
193D2D1_RECT_F pocketedBallsBarRect = { TABLE_LEFT, TABLE_BOTTOM + CUSHION_THICKNESS + 30, TABLE_RIGHT, TABLE_BOTTOM + CUSHION_THICKNESS + 70 };
194
195// Corrected Pocket Center Positions (aligned with table corners/edges)
196const D2D1_POINT_2F pocketPositions[6] = {
197 {TABLE_LEFT, TABLE_TOP}, // Top-Left
198 {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP}, // Top-Middle
199 {TABLE_RIGHT, TABLE_TOP}, // Top-Right
200 {TABLE_LEFT, TABLE_BOTTOM}, // Bottom-Left
201 {TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_BOTTOM}, // Bottom-Middle
202 {TABLE_RIGHT, TABLE_BOTTOM} // Bottom-Right
203};
204
205// Colors
206const D2D1_COLOR_F TABLE_COLOR = D2D1::ColorF(0.1608f, 0.4000f, 0.1765f); // Darker Green NEWCOLOR (0.0f, 0.5f, 0.1f) => (0.1608f, 0.4000f, 0.1765f)
207//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)
208const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF(0.3608f, 0.0275f, 0.0078f)); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
209//const D2D1_COLOR_F CUSHION_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // NEWCOLOR ::Red => (0.3608f, 0.0275f, 0.0078f)
210const D2D1_COLOR_F POCKET_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
211const D2D1_COLOR_F CUE_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::White);
212const D2D1_COLOR_F EIGHT_BALL_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
213const D2D1_COLOR_F SOLID_COLOR = D2D1::ColorF(D2D1::ColorF::Yellow); // Solids = Yellow
214const D2D1_COLOR_F STRIPE_COLOR = D2D1::ColorF(D2D1::ColorF::Red); // Stripes = Red
215const D2D1_COLOR_F AIM_LINE_COLOR = D2D1::ColorF(D2D1::ColorF::White, 0.7f); // Semi-transparent white
216const D2D1_COLOR_F FOUL_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
217const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(0.1333f, 0.7294f, 0.7490f); //NEWCOLOR 0.1333f, 0.7294f, 0.7490f => ::Blue
218//const D2D1_COLOR_F TURN_ARROW_COLOR = D2D1::ColorF(D2D1::ColorF::Blue);
219const D2D1_COLOR_F ENGLISH_DOT_COLOR = D2D1::ColorF(D2D1::ColorF::Red);
220const D2D1_COLOR_F UI_TEXT_COLOR = D2D1::ColorF(D2D1::ColorF::Black);
221
222// --- Forward Declarations ---
223HRESULT CreateDeviceResources();
224void DiscardDeviceResources();
225void OnPaint();
226void OnResize(UINT width, UINT height);
227void InitGame();
228void GameUpdate();
229void UpdatePhysics();
230void CheckCollisions();
231bool CheckPockets(); // Returns true if any ball was pocketed
232void ProcessShotResults();
233void ApplyShot(float power, float angle, float spinX, float spinY);
234void RespawnCueBall(bool behindHeadstring);
235bool AreBallsMoving();
236void SwitchTurns();
237void AssignPlayerBallTypes(BallType firstPocketedType);
238void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed);
239Ball* GetBallById(int id);
240Ball* GetCueBall();
241//void PlayGameMusic(HWND hwnd); //midi func
242void AIBreakShot();
243
244// Drawing Functions
245void DrawScene(ID2D1RenderTarget* pRT);
246void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory);
247void DrawBalls(ID2D1RenderTarget* pRT);
248void DrawCueStick(ID2D1RenderTarget* pRT);
249void DrawAimingAids(ID2D1RenderTarget* pRT);
250void DrawUI(ID2D1RenderTarget* pRT);
251void DrawPowerMeter(ID2D1RenderTarget* pRT);
252void DrawSpinIndicator(ID2D1RenderTarget* pRT);
253void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT);
254void DrawBallInHandIndicator(ID2D1RenderTarget* pRT);
255// NEW
256void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT);
257
258// Helper Functions
259float GetDistance(float x1, float y1, float x2, float y2);
260float GetDistanceSq(float x1, float y1, float x2, float y2);
261bool IsValidCueBallPosition(float x, float y, bool checkHeadstring);
262template <typename T> void SafeRelease(T** ppT);
263// --- NEW HELPER FORWARD DECLARATIONS ---
264bool IsPlayerOnEightBall(int player);
265void CheckAndTransitionToPocketChoice(int playerID);
266// --- ADD FORWARD DECLARATION FOR NEW HELPER HERE ---
267float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b);
268// --- End Forward Declaration ---
269bool 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
270
271// --- NEW Forward Declarations ---
272
273// AI Related
274struct AIShotInfo; // Define below
275void TriggerAIMove();
276void AIMakeDecision();
277void AIPlaceCueBall();
278AIShotInfo AIFindBestShot();
279AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex);
280bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2);
281Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq); // Added hitDistSq output
282float CalculateShotPower(float cueToGhostDist, float targetToPocketDist);
283D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex);
284bool IsValidAIAimAngle(float angle); // Basic check
285
286// Dialog Related
287INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam);
288void ShowNewGameDialog(HINSTANCE hInstance);
289void LoadSettings(); // For deserialization
290void SaveSettings(); // For serialization
291const std::wstring SETTINGS_FILE_NAME = L"Pool-Settings.txt";
292void ResetGame(HINSTANCE hInstance); // Function to handle F2 reset
293
294// --- Forward Declaration for Window Procedure --- <<< Add this line HERE
295LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
296
297// --- NEW Struct for AI Shot Evaluation ---
298struct AIShotInfo {
299 bool possible = false; // Is this shot considered viable?
300 Ball* targetBall = nullptr; // Which ball to hit
301 int pocketIndex = -1; // Which pocket to aim for (0-5)
302 D2D1_POINT_2F ghostBallPos = { 0,0 }; // Where cue ball needs to hit target ball
303 float angle = 0.0f; // Calculated shot angle
304 float power = 0.0f; // Calculated shot power
305 float score = -1.0f; // Score for this shot (higher is better)
306 bool involves8Ball = false; // Is the target the 8-ball?
307};
308
309/*
310table = TABLE_COLOR new: #29662d (0.1608, 0.4000, 0.1765) => old: (0.0f, 0.5f, 0.1f)
311rail CUSHION_COLOR = #5c0702 (0.3608, 0.0275, 0.0078) => ::Red
312gap = #e99d33 (0.9157, 0.6157, 0.2000) => ::Orange
313winbg = #5e8863 (0.3686, 0.5333, 0.3882) => 1.0f, 1.0f, 0.803f
314headstring = #47742f (0.2784, 0.4549, 0.1843) => ::White
315bluearrow = #08b0a5 (0.0314, 0.6902, 0.6471) *#22babf (0.1333,0.7294,0.7490) => ::Blue
316*/
317
318// --- NEW Settings Serialization Functions ---
319void SaveSettings() {
320 std::ofstream outFile(SETTINGS_FILE_NAME);
321 if (outFile.is_open()) {
322 outFile << static_cast<int>(gameMode) << std::endl;
323 outFile << static_cast<int>(aiDifficulty) << std::endl;
324 outFile << static_cast<int>(openingBreakMode) << std::endl;
325 outFile.close();
326 }
327 // else: Handle error, e.g., log or silently fail
328}
329
330void LoadSettings() {
331 std::ifstream inFile(SETTINGS_FILE_NAME);
332 if (inFile.is_open()) {
333 int gm, aid, obm;
334 if (inFile >> gm) {
335 gameMode = static_cast<GameMode>(gm);
336 }
337 if (inFile >> aid) {
338 aiDifficulty = static_cast<AIDifficulty>(aid);
339 }
340 if (inFile >> obm) {
341 openingBreakMode = static_cast<OpeningBreakMode>(obm);
342 }
343 inFile.close();
344
345 // Validate loaded settings (optional, but good practice)
346 if (gameMode < HUMAN_VS_HUMAN || gameMode > HUMAN_VS_AI) gameMode = HUMAN_VS_HUMAN; // Default
347 if (aiDifficulty < EASY || aiDifficulty > HARD) aiDifficulty = MEDIUM; // Default
348 if (openingBreakMode < CPU_BREAK || openingBreakMode > FLIP_COIN_BREAK) openingBreakMode = CPU_BREAK; // Default
349 }
350 // else: File doesn't exist or couldn't be opened, use defaults (already set in global vars)
351}
352// --- End Settings Serialization Functions ---
353
354// --- NEW Dialog Procedure ---
355INT_PTR CALLBACK NewGameDialogProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) {
356 switch (message) {
357 case WM_INITDIALOG:
358 {
359 // --- ACTION 4: Center Dialog Box ---
360// Optional: Force centering if default isn't working
361 RECT rcDlg, rcOwner, rcScreen;
362 HWND hwndOwner = GetParent(hDlg); // GetParent(hDlg) might be better if hwndMain is passed
363 if (hwndOwner == NULL) hwndOwner = GetDesktopWindow();
364
365 GetWindowRect(hwndOwner, &rcOwner);
366 GetWindowRect(hDlg, &rcDlg);
367 CopyRect(&rcScreen, &rcOwner); // Use owner rect as reference bounds
368
369 // Offset the owner rect relative to the screen if it's not the desktop
370 if (GetParent(hDlg) != NULL) { // If parented to main window (passed to DialogBoxParam)
371 OffsetRect(&rcOwner, -rcScreen.left, -rcScreen.top);
372 OffsetRect(&rcDlg, -rcScreen.left, -rcScreen.top);
373 OffsetRect(&rcScreen, -rcScreen.left, -rcScreen.top);
374 }
375
376
377 // Calculate centered position
378 int x = rcOwner.left + (rcOwner.right - rcOwner.left - (rcDlg.right - rcDlg.left)) / 2;
379 int y = rcOwner.top + (rcOwner.bottom - rcOwner.top - (rcDlg.bottom - rcDlg.top)) / 2;
380
381 // Ensure it stays within screen bounds (optional safety)
382 x = std::max(static_cast<int>(rcScreen.left), x);
383 y = std::max(static_cast<int>(rcScreen.top), y);
384 if (x + (rcDlg.right - rcDlg.left) > rcScreen.right)
385 x = rcScreen.right - (rcDlg.right - rcDlg.left);
386 if (y + (rcDlg.bottom - rcDlg.top) > rcScreen.bottom)
387 y = rcScreen.bottom - (rcDlg.bottom - rcDlg.top);
388
389
390 // Set the dialog position
391 SetWindowPos(hDlg, HWND_TOP, x, y, 0, 0, SWP_NOSIZE);
392
393 // --- End Centering Code ---
394
395 // Set initial state based on current global settings (or defaults)
396 CheckRadioButton(hDlg, IDC_RADIO_2P, IDC_RADIO_CPU, (gameMode == HUMAN_VS_HUMAN) ? IDC_RADIO_2P : IDC_RADIO_CPU);
397
398 CheckRadioButton(hDlg, IDC_RADIO_EASY, IDC_RADIO_HARD,
399 (aiDifficulty == EASY) ? IDC_RADIO_EASY : ((aiDifficulty == MEDIUM) ? IDC_RADIO_MEDIUM : IDC_RADIO_HARD));
400
401 // Enable/Disable AI group based on initial mode
402 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), gameMode == HUMAN_VS_AI);
403 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), gameMode == HUMAN_VS_AI);
404 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), gameMode == HUMAN_VS_AI);
405 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), gameMode == HUMAN_VS_AI);
406 // Set initial state for Opening Break Mode
407 CheckRadioButton(hDlg, IDC_RADIO_CPU_BREAK, IDC_RADIO_FLIP_BREAK,
408 (openingBreakMode == CPU_BREAK) ? IDC_RADIO_CPU_BREAK : ((openingBreakMode == P1_BREAK) ? IDC_RADIO_P1_BREAK : IDC_RADIO_FLIP_BREAK));
409 // Enable/Disable Opening Break group based on initial mode
410 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), gameMode == HUMAN_VS_AI);
411 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), gameMode == HUMAN_VS_AI);
412 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), gameMode == HUMAN_VS_AI);
413 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), gameMode == HUMAN_VS_AI);
414 }
415 return (INT_PTR)TRUE;
416
417 case WM_COMMAND:
418 switch (LOWORD(wParam)) {
419 case IDC_RADIO_2P:
420 case IDC_RADIO_CPU:
421 {
422 bool isCPU = IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED;
423 // Enable/Disable AI group controls based on selection
424 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_AI), isCPU);
425 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_EASY), isCPU);
426 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_MEDIUM), isCPU);
427 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_HARD), isCPU);
428 // Also enable/disable Opening Break Mode group
429 EnableWindow(GetDlgItem(hDlg, IDC_GROUP_BREAK_MODE), isCPU);
430 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_CPU_BREAK), isCPU);
431 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_P1_BREAK), isCPU);
432 EnableWindow(GetDlgItem(hDlg, IDC_RADIO_FLIP_BREAK), isCPU);
433 }
434 return (INT_PTR)TRUE;
435
436 case IDOK:
437 // Retrieve selected options and store in global variables
438 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU) == BST_CHECKED) {
439 gameMode = HUMAN_VS_AI;
440 if (IsDlgButtonChecked(hDlg, IDC_RADIO_EASY) == BST_CHECKED) aiDifficulty = EASY;
441 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_MEDIUM) == BST_CHECKED) aiDifficulty = MEDIUM;
442 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_HARD) == BST_CHECKED) aiDifficulty = HARD;
443
444 if (IsDlgButtonChecked(hDlg, IDC_RADIO_CPU_BREAK) == BST_CHECKED) openingBreakMode = CPU_BREAK;
445 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_P1_BREAK) == BST_CHECKED) openingBreakMode = P1_BREAK;
446 else if (IsDlgButtonChecked(hDlg, IDC_RADIO_FLIP_BREAK) == BST_CHECKED) openingBreakMode = FLIP_COIN_BREAK;
447 }
448 else {
449 gameMode = HUMAN_VS_HUMAN;
450 // openingBreakMode doesn't apply to HvsH, can leave as is or reset
451 }
452 SaveSettings(); // Save settings when OK is pressed
453 EndDialog(hDlg, IDOK); // Close dialog, return IDOK
454 return (INT_PTR)TRUE;
455
456 case IDCANCEL: // Handle Cancel or closing the dialog
457 // Optionally, could reload settings here if you want cancel to revert to previously saved state
458 EndDialog(hDlg, IDCANCEL);
459 return (INT_PTR)TRUE;
460 }
461 break; // End WM_COMMAND
462 }
463 return (INT_PTR)FALSE; // Default processing
464}
465
466// --- NEW Helper to Show Dialog ---
467void ShowNewGameDialog(HINSTANCE hInstance) {
468 if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), hwndMain, NewGameDialogProc, 0) == IDOK) {
469 // User clicked Start, reset game with new settings
470 isPlayer2AI = (gameMode == HUMAN_VS_AI); // Update AI flag
471 if (isPlayer2AI) {
472 switch (aiDifficulty) {
473 case EASY: player2Info.name = L"CPU (Easy)"; break;
474 case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
475 case HARD: player2Info.name = L"CPU (Hard)"; break;
476 }
477 }
478 else {
479 player2Info.name = L"Player 2";
480 }
481 // Update window title
482 std::wstring windowTitle = L"Direct2D 8-Ball Pool";
483 if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
484 else windowTitle += L" (Human vs " + player2Info.name + L")";
485 SetWindowText(hwndMain, windowTitle.c_str());
486
487 InitGame(); // Re-initialize game logic & board
488 InvalidateRect(hwndMain, NULL, TRUE); // Force redraw
489 }
490 else {
491 // User cancelled dialog - maybe just resume game? Or exit?
492 // For simplicity, we do nothing, game continues as it was.
493 // To exit on cancel from F2, would need more complex state management.
494 }
495}
496
497// --- NEW Reset Game Function ---
498void ResetGame(HINSTANCE hInstance) {
499 // Call the helper function to show the dialog and re-init if OK clicked
500 ShowNewGameDialog(hInstance);
501}
502
503// --- WinMain ---
504int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR, int nCmdShow) {
505 if (FAILED(CoInitialize(NULL))) {
506 MessageBox(NULL, L"COM Initialization Failed.", L"Error", MB_OK | MB_ICONERROR);
507 return -1;
508 }
509
510 // --- NEW: Load settings at startup ---
511 LoadSettings();
512
513 // --- NEW: Show configuration dialog FIRST ---
514 if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_NEWGAMEDLG), NULL, NewGameDialogProc, 0) != IDOK) {
515 // User cancelled the dialog
516 CoUninitialize();
517 return 0; // Exit gracefully if dialog cancelled
518 }
519 // Global gameMode and aiDifficulty are now set by the DialogProc
520
521 // Set AI flag based on game mode
522 isPlayer2AI = (gameMode == HUMAN_VS_AI);
523 if (isPlayer2AI) {
524 switch (aiDifficulty) {
525 case EASY: player2Info.name = L"CPU (Easy)"; break;
526 case MEDIUM: player2Info.name = L"CPU (Medium)"; break;
527 case HARD: player2Info.name = L"CPU (Hard)"; break;
528 }
529 }
530 else {
531 player2Info.name = L"Player 2";
532 }
533 // --- End of Dialog Logic ---
534
535
536 WNDCLASS wc = { };
537 wc.lpfnWndProc = WndProc;
538 wc.hInstance = hInstance;
539 wc.lpszClassName = L"Direct2D_8BallPool";
540 wc.hCursor = LoadCursor(NULL, IDC_ARROW);
541 wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
542 wc.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)); // Use your actual icon ID here
543
544 if (!RegisterClass(&wc)) {
545 MessageBox(NULL, L"Window Registration Failed.", L"Error", MB_OK | MB_ICONERROR);
546 CoUninitialize();
547 return -1;
548 }
549
550 // --- ACTION 4: Calculate Centered Window Position ---
551 const int WINDOW_WIDTH = 1000; // Define desired width
552 const int WINDOW_HEIGHT = 700; // Define desired height
553 int screenWidth = GetSystemMetrics(SM_CXSCREEN);
554 int screenHeight = GetSystemMetrics(SM_CYSCREEN);
555 int windowX = (screenWidth - WINDOW_WIDTH) / 2;
556 int windowY = (screenHeight - WINDOW_HEIGHT) / 2;
557
558 // --- Change Window Title based on mode ---
559 std::wstring windowTitle = L"Direct2D 8-Ball Pool";
560 if (gameMode == HUMAN_VS_HUMAN) windowTitle += L" (Human vs Human)";
561 else windowTitle += L" (Human vs " + player2Info.name + L")";
562
563 DWORD dwStyle = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; // No WS_THICKFRAME, No WS_MAXIMIZEBOX
564
565 hwndMain = CreateWindowEx(
566 0, L"Direct2D_8BallPool", windowTitle.c_str(), dwStyle,
567 windowX, windowY, WINDOW_WIDTH, WINDOW_HEIGHT,
568 NULL, NULL, hInstance, NULL
569 );
570
571 if (!hwndMain) {
572 MessageBox(NULL, L"Window Creation Failed.", L"Error", MB_OK | MB_ICONERROR);
573 CoUninitialize();
574 return -1;
575 }
576
577 // Initialize Direct2D Resources AFTER window creation
578 if (FAILED(CreateDeviceResources())) {
579 MessageBox(NULL, L"Failed to create Direct2D resources.", L"Error", MB_OK | MB_ICONERROR);
580 DestroyWindow(hwndMain);
581 CoUninitialize();
582 return -1;
583 }
584
585 InitGame(); // Initialize game state AFTER resources are ready & mode is set
586 Sleep(500); // Allow window to fully initialize before starting the countdown //midi func
587 StartMidi(hwndMain, TEXT("BSQ.MID")); // Replace with your MIDI filename
588 //PlayGameMusic(hwndMain); //midi func
589
590 ShowWindow(hwndMain, nCmdShow);
591 UpdateWindow(hwndMain);
592
593 if (!SetTimer(hwndMain, ID_TIMER, 1000 / TARGET_FPS, NULL)) {
594 MessageBox(NULL, L"Could not SetTimer().", L"Error", MB_OK | MB_ICONERROR);
595 DestroyWindow(hwndMain);
596 CoUninitialize();
597 return -1;
598 }
599
600 MSG msg = { };
601 // --- Modified Main Loop ---
602 // Handles the case where the game starts in SHOWING_DIALOG state (handled now before loop)
603 // or gets reset to it via F2. The main loop runs normally once game starts.
604 while (GetMessage(&msg, NULL, 0, 0)) {
605 // We might need modeless dialog handling here if F2 shows dialog
606 // while window is active, but DialogBoxParam is modal.
607 // Let's assume F2 hides main window, shows dialog, then restarts game loop.
608 // Simpler: F2 calls ResetGame which calls DialogBoxParam (modal) then InitGame.
609 TranslateMessage(&msg);
610 DispatchMessage(&msg);
611 }
612
613
614 KillTimer(hwndMain, ID_TIMER);
615 DiscardDeviceResources();
616 SaveSettings(); // Save settings on exit
617 CoUninitialize();
618
619 return (int)msg.wParam;
620}
621
622// --- WndProc ---
623LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
624 // Declare cueBall pointer once at the top, used in multiple cases
625 // For clarity, often better to declare within each case where needed.
626 Ball* cueBall = nullptr; // Initialize to nullptr
627 switch (msg) {
628 case WM_CREATE:
629 // Resources are now created in WinMain after CreateWindowEx
630 return 0;
631
632 case WM_PAINT:
633 OnPaint();
634 // Validate the entire window region after painting
635 ValidateRect(hwnd, NULL);
636 return 0;
637
638 case WM_SIZE: {
639 UINT width = LOWORD(lParam);
640 UINT height = HIWORD(lParam);
641 OnResize(width, height);
642 return 0;
643 }
644
645 case WM_TIMER:
646 if (wParam == ID_TIMER) {
647 GameUpdate(); // Update game logic and physics
648 InvalidateRect(hwnd, NULL, FALSE); // Request redraw
649 }
650 return 0;
651
652 // --- NEW: Handle F2 Key for Reset ---
653 // --- MODIFIED: Handle More Keys ---
654 case WM_KEYDOWN:
655 { // Add scope for variable declarations
656
657 // --- FIX: Get Cue Ball pointer for this scope ---
658 cueBall = GetCueBall();
659 // We might allow some keys even if cue ball is gone (like F1/F2), but actions need it
660 // --- End Fix ---
661
662 // Check which player can interact via keyboard (Humans only)
663 bool canPlayerControl = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P1 || currentGameState == PRE_BREAK_PLACEMENT)) ||
664 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT)));
665
666 // --- F1 / F2 Keys (Always available) ---
667 if (wParam == VK_F2) {
668 HINSTANCE hInstance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE);
669 ResetGame(hInstance); // Call reset function
670 return 0; // Indicate key was processed
671 }
672 else if (wParam == VK_F1) {
673 MessageBox(hwnd,
674 L"Direct2D-based StickPool game made in C++ from scratch (2764+ lines of code)\n" // Update line count if needed
675 L"First successful Clone in C++ (no other sites or projects were there to glean from.) Made /w AI assist\n"
676 L"(others were in JS/ non-8-Ball in C# etc.) w/o OOP and Graphics Frameworks all in a Single file.\n"
677 L"Copyright (C) 2025 Evans Thorpemorton, Entisoft Solutions.\n"
678 L"Includes AI Difficulty Modes, Aim-Trajectory For Table Rails + Hard Angles TipShots. || F2=New Game",
679 L"About This Game", MB_OK | MB_ICONINFORMATION);
680 return 0; // Indicate key was processed
681 }
682
683 // Check for 'M' key (uppercase or lowercase)
684 // Toggle music with "M"
685 if (wParam == 'M' || wParam == 'm') {
686 //static bool isMusicPlaying = false;
687 if (isMusicPlaying) {
688 // Stop the music
689 StopMidi();
690 isMusicPlaying = false;
691 }
692 else {
693 // Build the MIDI file path
694 TCHAR midiPath[MAX_PATH];
695 GetModuleFileName(NULL, midiPath, MAX_PATH);
696 // Keep only the directory part
697 TCHAR* lastBackslash = _tcsrchr(midiPath, '\\');
698 if (lastBackslash != NULL) {
699 *(lastBackslash + 1) = '\0';
700 }
701 // Append the MIDI filename
702 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID")); // Adjust filename if needed
703
704 // Start playing MIDI
705 StartMidi(hwndMain, midiPath);
706 isMusicPlaying = true;
707 }
708 }
709
710
711 // --- Player Interaction Keys (Only if allowed) ---
712 if (canPlayerControl) {
713 // --- Get Shift Key State ---
714 bool shiftPressed = (GetKeyState(VK_SHIFT) & 0x8000) != 0;
715 float angleStep = shiftPressed ? 0.05f : 0.01f; // Base step / Faster step (Adjust as needed) // Multiplier was 5x
716 float powerStep = 0.2f; // Power step (Adjust as needed)
717
718 switch (wParam) {
719 case VK_LEFT: // Rotate Cue Stick Counter-Clockwise
720 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
721 cueAngle -= angleStep;
722 // Normalize angle (keep between 0 and 2*PI)
723 if (cueAngle < 0) cueAngle += 2 * PI;
724 // Ensure state shows aiming visuals if turn just started
725 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
726 isAiming = false; // Keyboard adjust doesn't use mouse aiming state
727 isDraggingStick = false;
728 keyboardAimingActive = true;
729 }
730 break;
731
732 case VK_RIGHT: // Rotate Cue Stick Clockwise
733 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
734 cueAngle += angleStep;
735 // Normalize angle (keep between 0 and 2*PI)
736 if (cueAngle >= 2 * PI) cueAngle -= 2 * PI;
737 // Ensure state shows aiming visuals if turn just started
738 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
739 isAiming = false;
740 isDraggingStick = false;
741 keyboardAimingActive = true;
742 }
743 break;
744
745 case VK_UP: // Decrease Shot Power
746 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
747 shotPower -= powerStep;
748 if (shotPower < 0.0f) shotPower = 0.0f;
749 // Ensure state shows aiming visuals if turn just started
750 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
751 isAiming = true; // Keyboard adjust doesn't use mouse aiming state
752 isDraggingStick = false;
753 keyboardAimingActive = true;
754 }
755 break;
756
757 case VK_DOWN: // Increase Shot Power
758 if (currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
759 shotPower += powerStep;
760 if (shotPower > MAX_SHOT_POWER) shotPower = MAX_SHOT_POWER;
761 // Ensure state shows aiming visuals if turn just started
762 if (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN) currentGameState = AIMING;
763 isAiming = true;
764 isDraggingStick = false;
765 keyboardAimingActive = true;
766 }
767 break;
768
769 case VK_SPACE: // Trigger Shot
770 if ((currentGameState == AIMING || currentGameState == BREAKING || currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN)
771 && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING)
772 {
773 if (shotPower > 0.15f) { // Use same threshold as mouse
774 // Reset foul flags BEFORE applying shot
775 firstHitBallIdThisShot = -1;
776 cueHitObjectBallThisShot = false;
777 railHitAfterContact = false;
778
779 // Play sound & Apply Shot
780 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
781 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
782
783 // Update State
784 currentGameState = SHOT_IN_PROGRESS;
785 foulCommitted = false;
786 pocketedThisTurn.clear();
787 shotPower = 0; // Reset power after shooting
788 isAiming = false; isDraggingStick = false; // Reset aiming flags
789 keyboardAimingActive = false;
790 }
791 }
792 break;
793
794 case VK_ESCAPE: // Cancel Aim/Shot Setup
795 if ((currentGameState == AIMING || currentGameState == BREAKING) || shotPower > 0)
796 {
797 shotPower = 0.0f;
798 isAiming = false;
799 isDraggingStick = false;
800 keyboardAimingActive = false;
801 // Revert to basic turn state if not breaking
802 if (currentGameState != BREAKING) {
803 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
804 }
805 }
806 break;
807
808 case 'G': // Toggle Cheat Mode
809 cheatModeEnabled = !cheatModeEnabled;
810 if (cheatModeEnabled)
811 MessageBeep(MB_ICONEXCLAMATION); // Play a beep when enabling
812 else
813 MessageBeep(MB_OK); // Play a different beep when disabling
814 break;
815
816 default:
817 // Allow default processing for other keys if needed
818 // return DefWindowProc(hwnd, msg, wParam, lParam); // Usually not needed for WM_KEYDOWN
819 break;
820 } // End switch(wParam) for player controls
821 return 0; // Indicate player control key was processed
822 } // End if(canPlayerControl)
823 } // End scope for WM_KEYDOWN case
824 // If key wasn't F1/F2 and player couldn't control, maybe allow default processing?
825 // return DefWindowProc(hwnd, msg, wParam, lParam); // Or just return 0
826 return 0;
827
828 case WM_MOUSEMOVE: {
829 ptMouse.x = LOWORD(lParam);
830 ptMouse.y = HIWORD(lParam);
831
832 // --- NEW LOGIC: Handle Pocket Hover ---
833 if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
834 (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
835 int oldHover = currentlyHoveredPocket;
836 currentlyHoveredPocket = -1; // Reset
837 for (int i = 0; i < 6; ++i) {
838 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
839 currentlyHoveredPocket = i;
840 break;
841 }
842 }
843 if (oldHover != currentlyHoveredPocket) {
844 InvalidateRect(hwnd, NULL, FALSE);
845 }
846 // Do NOT return 0 here, allow normal mouse angle update to continue
847 }
848 // --- END NEW LOGIC ---
849
850
851 cueBall = GetCueBall(); // Declare and get cueBall pointer
852
853 if (isDraggingCueBall && cheatModeEnabled && draggingBallId != -1) {
854 Ball* ball = GetBallById(draggingBallId);
855 if (ball) {
856 ball->x = (float)ptMouse.x;
857 ball->y = (float)ptMouse.y;
858 ball->vx = ball->vy = 0.0f;
859 }
860 return 0;
861 }
862
863 if (!cueBall) return 0;
864
865 // Update Aiming Logic (Check player turn)
866 if (isDraggingCueBall &&
867 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
868 (!isPlayer2AI && currentPlayer == 2 && currentGameState == BALL_IN_HAND_P2) ||
869 currentGameState == PRE_BREAK_PLACEMENT))
870 {
871 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
872 // Tentative position update
873 cueBall->x = (float)ptMouse.x;
874 cueBall->y = (float)ptMouse.y;
875 cueBall->vx = cueBall->vy = 0;
876 }
877 else if ((isAiming || isDraggingStick) &&
878 ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
879 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
880 {
881 //NEW2 MOUSEBOUND CODE = START
882 /*// Clamp mouse inside table bounds during aiming
883 if (ptMouse.x < TABLE_LEFT) ptMouse.x = TABLE_LEFT;
884 if (ptMouse.x > TABLE_RIGHT) ptMouse.x = TABLE_RIGHT;
885 if (ptMouse.y < TABLE_TOP) ptMouse.y = TABLE_TOP;
886 if (ptMouse.y > TABLE_BOTTOM) ptMouse.y = TABLE_BOTTOM;*/
887 //NEW2 MOUSEBOUND CODE = END
888 // Aiming drag updates angle and power
889 float dx = (float)ptMouse.x - cueBall->x;
890 float dy = (float)ptMouse.y - cueBall->y;
891 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
892 //float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
893 //shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
894 if (!keyboardAimingActive) { // Only update shotPower if NOT keyboard aiming
895 float pullDist = GetDistance((float)ptMouse.x, (float)ptMouse.y, aimStartPoint.x, aimStartPoint.y);
896 shotPower = std::min(pullDist / 10.0f, MAX_SHOT_POWER);
897 }
898 }
899 else if (isSettingEnglish &&
900 ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == AIMING || currentGameState == BREAKING)) ||
901 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == PLAYER2_TURN || currentGameState == AIMING || currentGameState == BREAKING))))
902 {
903 // Setting English
904 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
905 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
906 float dist = GetDistance(dx, dy, 0, 0);
907 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
908 cueSpinX = dx / spinIndicatorRadius;
909 cueSpinY = dy / spinIndicatorRadius;
910 }
911 else {
912 //DISABLE PERM AIMING = START
913 /*// Update visual angle even when not aiming/dragging (Check player turn)
914 bool canUpdateVisualAngle = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BALL_IN_HAND_P1)) ||
915 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2)) ||
916 currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING || currentGameState == AIMING);
917
918 if (canUpdateVisualAngle && !isDraggingCueBall && !isAiming && !isDraggingStick && !keyboardAimingActive) // NEW: Prevent mouse override if keyboard aiming
919 {
920 // NEW MOUSEBOUND CODE = START
921 // Only update cue angle if mouse is inside the playable table area
922 if (ptMouse.x >= TABLE_LEFT && ptMouse.x <= TABLE_RIGHT &&
923 ptMouse.y >= TABLE_TOP && ptMouse.y <= TABLE_BOTTOM)
924 {
925 // NEW MOUSEBOUND CODE = END
926 Ball* cb = cueBall; // Use function-scope cueBall // Already got cueBall above
927 if (cb) {
928 float dx = (float)ptMouse.x - cb->x;
929 float dy = (float)ptMouse.y - cb->y;
930 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
931 }
932 } //NEW MOUSEBOUND CODE LINE = DISABLE
933 }*/
934 //DISABLE PERM AIMING = END
935 }
936 return 0;
937 } // End WM_MOUSEMOVE
938
939 case WM_LBUTTONDOWN: {
940 ptMouse.x = LOWORD(lParam);
941 ptMouse.y = HIWORD(lParam);
942
943 // --- NEW LOGIC: Handle Pocket Selection First ---
944 if ((currentGameState == CHOOSING_POCKET_P1 && currentPlayer == 1) ||
945 (currentGameState == CHOOSING_POCKET_P2 && currentPlayer == 2 && !isPlayer2AI)) {
946
947 int clickedPocketIndex = -1;
948 for (int i = 0; i < 6; ++i) {
949 if (GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, pocketPositions[i].x, pocketPositions[i].y) < HOLE_VISUAL_RADIUS * HOLE_VISUAL_RADIUS * 2.25f) {
950 clickedPocketIndex = i;
951 break;
952 }
953 }
954
955 if (clickedPocketIndex != -1) { // Player clicked on a pocket to select it
956 if (currentPlayer == 1) calledPocketP1 = clickedPocketIndex;
957 else calledPocketP2 = clickedPocketIndex;
958 // After selecting, transition to the normal aiming turn state
959 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
960 pocketCallMessage = L""; // Clear the message
961 InvalidateRect(hwnd, NULL, FALSE);
962 return 0; // Consume the click
963 }
964 // If they click anywhere else, do nothing and let them re-choose
965 return 0;
966 }
967 // --- END NEW LOGIC ---
968
969
970 if (cheatModeEnabled) {
971 // Allow dragging any ball freely
972 for (Ball& ball : balls) {
973 float distSq = GetDistanceSq(ball.x, ball.y, (float)ptMouse.x, (float)ptMouse.y);
974 if (distSq <= BALL_RADIUS * BALL_RADIUS * 4) { // Click near ball
975 isDraggingCueBall = true;
976 draggingBallId = ball.id;
977 if (ball.id == 0) {
978 // If dragging cue ball manually, ensure we stay in Ball-In-Hand state
979 if (currentPlayer == 1)
980 currentGameState = BALL_IN_HAND_P1;
981 else if (currentPlayer == 2 && !isPlayer2AI)
982 currentGameState = BALL_IN_HAND_P2;
983 }
984 return 0;
985 }
986 }
987 }
988
989 Ball* cueBall = GetCueBall(); // Declare and get cueBall pointer
990
991 // Check which player is allowed to interact via mouse click
992 bool canPlayerClickInteract = ((currentPlayer == 1) || (currentPlayer == 2 && !isPlayer2AI));
993 // Define states where interaction is generally allowed
994 bool canInteractState = (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
995 currentGameState == AIMING || currentGameState == BREAKING ||
996 currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 ||
997 currentGameState == PRE_BREAK_PLACEMENT);
998
999 // Check Spin Indicator first (Allow if player's turn/aim phase)
1000 if (canPlayerClickInteract && canInteractState) {
1001 float spinDistSq = GetDistanceSq((float)ptMouse.x, (float)ptMouse.y, spinIndicatorCenter.x, spinIndicatorCenter.y);
1002 if (spinDistSq < spinIndicatorRadius * spinIndicatorRadius * 1.2f) {
1003 isSettingEnglish = true;
1004 float dx = (float)ptMouse.x - spinIndicatorCenter.x;
1005 float dy = (float)ptMouse.y - spinIndicatorCenter.y;
1006 float dist = GetDistance(dx, dy, 0, 0);
1007 if (dist > spinIndicatorRadius) { dx *= spinIndicatorRadius / dist; dy *= spinIndicatorRadius / dist; }
1008 cueSpinX = dx / spinIndicatorRadius;
1009 cueSpinY = dy / spinIndicatorRadius;
1010 isAiming = false; isDraggingStick = false; isDraggingCueBall = false;
1011 return 0;
1012 }
1013 }
1014
1015 if (!cueBall) return 0;
1016
1017 // Check Ball-in-Hand placement/drag
1018 bool isPlacingBall = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
1019 bool isPlayerAllowedToPlace = (isPlacingBall &&
1020 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
1021 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
1022 (currentGameState == PRE_BREAK_PLACEMENT))); // Allow current player in break setup
1023
1024 if (isPlayerAllowedToPlace) {
1025 float distSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
1026 if (distSq < BALL_RADIUS * BALL_RADIUS * 9.0f) {
1027 isDraggingCueBall = true;
1028 isAiming = false; isDraggingStick = false;
1029 }
1030 else {
1031 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
1032 if (IsValidCueBallPosition((float)ptMouse.x, (float)ptMouse.y, behindHeadstring)) {
1033 cueBall->x = (float)ptMouse.x; cueBall->y = (float)ptMouse.y;
1034 cueBall->vx = 0; cueBall->vy = 0;
1035 isDraggingCueBall = false;
1036 // Transition state
1037 if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
1038 else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
1039 else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
1040 cueAngle = 0.0f;
1041 }
1042 }
1043 return 0;
1044 }
1045
1046 // Check for starting Aim (Cue Ball OR Stick)
1047 bool canAim = ((currentPlayer == 1 && (currentGameState == PLAYER1_TURN || currentGameState == BREAKING)) ||
1048 (currentPlayer == 2 && !isPlayer2AI && (currentGameState == PLAYER2_TURN || currentGameState == BREAKING)));
1049
1050 if (canAim) {
1051 const float stickDrawLength = 150.0f * 1.4f;
1052 float currentStickAngle = cueAngle + PI;
1053 D2D1_POINT_2F currentStickEnd = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * stickDrawLength, cueBall->y + sinf(currentStickAngle) * stickDrawLength);
1054 D2D1_POINT_2F currentStickTip = D2D1::Point2F(cueBall->x + cosf(currentStickAngle) * 5.0f, cueBall->y + sinf(currentStickAngle) * 5.0f);
1055 float distToStickSq = PointToLineSegmentDistanceSq(D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y), currentStickTip, currentStickEnd);
1056 float stickClickThresholdSq = 36.0f;
1057 float distToCueBallSq = GetDistanceSq(cueBall->x, cueBall->y, (float)ptMouse.x, (float)ptMouse.y);
1058 float cueBallClickRadiusSq = BALL_RADIUS * BALL_RADIUS * 25;
1059
1060 bool clickedStick = (distToStickSq < stickClickThresholdSq);
1061 bool clickedCueArea = (distToCueBallSq < cueBallClickRadiusSq);
1062
1063 if (clickedStick || clickedCueArea) {
1064 isDraggingStick = clickedStick && !clickedCueArea;
1065 isAiming = clickedCueArea;
1066 aimStartPoint = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
1067 shotPower = 0;
1068 float dx = (float)ptMouse.x - cueBall->x;
1069 float dy = (float)ptMouse.y - cueBall->y;
1070 if (dx != 0 || dy != 0) cueAngle = atan2f(dy, dx);
1071 if (currentGameState != BREAKING) currentGameState = AIMING;
1072 }
1073 }
1074 return 0;
1075 } // End WM_LBUTTONDOWN
1076
1077
1078 case WM_LBUTTONUP: {
1079 if (cheatModeEnabled && isDraggingCueBall) {
1080 isDraggingCueBall = false;
1081 if (draggingBallId == 0) {
1082 // After dropping CueBall, stay Ball-In-Hand mode if needed
1083 if (currentPlayer == 1)
1084 currentGameState = BALL_IN_HAND_P1;
1085 else if (currentPlayer == 2 && !isPlayer2AI)
1086 currentGameState = BALL_IN_HAND_P2;
1087 }
1088 draggingBallId = -1;
1089 return 0;
1090 }
1091
1092 ptMouse.x = LOWORD(lParam);
1093 ptMouse.y = HIWORD(lParam);
1094
1095 Ball* cueBall = GetCueBall(); // Get cueBall pointer
1096
1097 // Check for releasing aim drag (Stick OR Cue Ball)
1098 if ((isAiming || isDraggingStick) &&
1099 ((currentPlayer == 1 && (currentGameState == AIMING || currentGameState == BREAKING)) ||
1100 (!isPlayer2AI && currentPlayer == 2 && (currentGameState == AIMING || currentGameState == BREAKING))))
1101 {
1102 bool wasAiming = isAiming;
1103 bool wasDraggingStick = isDraggingStick;
1104 isAiming = false; isDraggingStick = false;
1105
1106 if (shotPower > 0.15f) { // Check power threshold
1107 if (currentGameState != AI_THINKING) {
1108 firstHitBallIdThisShot = -1; cueHitObjectBallThisShot = false; railHitAfterContact = false; // Reset foul flags
1109 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
1110 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
1111 currentGameState = SHOT_IN_PROGRESS;
1112 foulCommitted = false; pocketedThisTurn.clear();
1113 }
1114 }
1115 else if (currentGameState != AI_THINKING) { // Revert state if power too low
1116 if (currentGameState == BREAKING) { /* Still breaking */ }
1117 else {
1118 currentGameState = (currentPlayer == 1) ? PLAYER1_TURN : PLAYER2_TURN;
1119 if (currentPlayer == 2 && isPlayer2AI) aiTurnPending = false;
1120 }
1121 }
1122 shotPower = 0; // Reset power indicator regardless
1123 }
1124
1125 // Handle releasing cue ball drag (placement)
1126 if (isDraggingCueBall) {
1127 isDraggingCueBall = false;
1128 // Check player allowed to place
1129 bool isPlacingState = (currentGameState == BALL_IN_HAND_P1 || currentGameState == BALL_IN_HAND_P2 || currentGameState == PRE_BREAK_PLACEMENT);
1130 bool isPlayerAllowed = (isPlacingState &&
1131 ((currentPlayer == 1 && currentGameState == BALL_IN_HAND_P1) ||
1132 (currentPlayer == 2 && !isPlayer2AI && currentGameState == BALL_IN_HAND_P2) ||
1133 (currentGameState == PRE_BREAK_PLACEMENT)));
1134
1135 if (isPlayerAllowed && cueBall) {
1136 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
1137 if (IsValidCueBallPosition(cueBall->x, cueBall->y, behindHeadstring)) {
1138 // Finalize position already set by mouse move
1139 // Transition state
1140 if (currentGameState == PRE_BREAK_PLACEMENT) currentGameState = BREAKING;
1141 else if (currentGameState == BALL_IN_HAND_P1) currentGameState = PLAYER1_TURN;
1142 else if (currentGameState == BALL_IN_HAND_P2) currentGameState = PLAYER2_TURN;
1143 cueAngle = 0.0f;
1144 }
1145 else { /* Stay in BALL_IN_HAND state if final pos invalid */ }
1146 }
1147 }
1148
1149 // Handle releasing english setting
1150 if (isSettingEnglish) {
1151 isSettingEnglish = false;
1152 }
1153 return 0;
1154 } // End WM_LBUTTONUP
1155
1156 case WM_DESTROY:
1157 isMusicPlaying = false;
1158 if (midiDeviceID != 0) {
1159 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
1160 midiDeviceID = 0;
1161 SaveSettings(); // Save settings on exit
1162 }
1163 PostQuitMessage(0);
1164 return 0;
1165
1166 default:
1167 return DefWindowProc(hwnd, msg, wParam, lParam);
1168 }
1169 return 0;
1170}
1171
1172// --- Direct2D Resource Management ---
1173
1174HRESULT CreateDeviceResources() {
1175 HRESULT hr = S_OK;
1176
1177 // Create Direct2D Factory
1178 if (!pFactory) {
1179 hr = D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &pFactory);
1180 if (FAILED(hr)) return hr;
1181 }
1182
1183 // Create DirectWrite Factory
1184 if (!pDWriteFactory) {
1185 hr = DWriteCreateFactory(
1186 DWRITE_FACTORY_TYPE_SHARED,
1187 __uuidof(IDWriteFactory),
1188 reinterpret_cast<IUnknown**>(&pDWriteFactory)
1189 );
1190 if (FAILED(hr)) return hr;
1191 }
1192
1193 // Create Text Formats
1194 if (!pTextFormat && pDWriteFactory) {
1195 hr = pDWriteFactory->CreateTextFormat(
1196 L"Segoe UI", NULL, DWRITE_FONT_WEIGHT_NORMAL, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
1197 16.0f, L"en-us", &pTextFormat
1198 );
1199 if (FAILED(hr)) return hr;
1200 // Center align text
1201 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
1202 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
1203 }
1204 if (!pLargeTextFormat && pDWriteFactory) {
1205 hr = pDWriteFactory->CreateTextFormat(
1206 L"Impact", NULL, DWRITE_FONT_WEIGHT_BOLD, DWRITE_FONT_STYLE_NORMAL, DWRITE_FONT_STRETCH_NORMAL,
1207 48.0f, L"en-us", &pLargeTextFormat
1208 );
1209 if (FAILED(hr)) return hr;
1210 pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING); // Align left
1211 pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
1212 }
1213
1214
1215 // Create Render Target (needs valid hwnd)
1216 if (!pRenderTarget && hwndMain) {
1217 RECT rc;
1218 GetClientRect(hwndMain, &rc);
1219 D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top);
1220
1221 hr = pFactory->CreateHwndRenderTarget(
1222 D2D1::RenderTargetProperties(),
1223 D2D1::HwndRenderTargetProperties(hwndMain, size),
1224 &pRenderTarget
1225 );
1226 if (FAILED(hr)) {
1227 // If failed, release factories if they were created in this call
1228 SafeRelease(&pTextFormat);
1229 SafeRelease(&pLargeTextFormat);
1230 SafeRelease(&pDWriteFactory);
1231 SafeRelease(&pFactory);
1232 pRenderTarget = nullptr; // Ensure it's null on failure
1233 return hr;
1234 }
1235 }
1236
1237 return hr;
1238}
1239
1240void DiscardDeviceResources() {
1241 SafeRelease(&pRenderTarget);
1242 SafeRelease(&pTextFormat);
1243 SafeRelease(&pLargeTextFormat);
1244 SafeRelease(&pDWriteFactory);
1245 // Keep pFactory until application exit? Or release here too? Let's release.
1246 SafeRelease(&pFactory);
1247}
1248
1249void OnResize(UINT width, UINT height) {
1250 if (pRenderTarget) {
1251 D2D1_SIZE_U size = D2D1::SizeU(width, height);
1252 pRenderTarget->Resize(size); // Ignore HRESULT for simplicity here
1253 }
1254}
1255
1256// --- Game Initialization ---
1257void InitGame() {
1258 srand((unsigned int)time(NULL)); // Seed random number generator
1259 isOpeningBreakShot = true; // This is the start of a new game, so the next shot is an opening break.
1260 aiPlannedShotDetails.isValid = false; // Reset AI planned shot
1261 aiIsDisplayingAim = false;
1262 aiAimDisplayFramesLeft = 0;
1263 // ... (rest of InitGame())
1264
1265 // --- Ensure pocketed list is clear from the absolute start ---
1266 pocketedThisTurn.clear();
1267
1268 balls.clear(); // Clear existing balls
1269
1270 // Reset Player Info (Names should be set by Dialog/wWinMain/ResetGame)
1271 player1Info.assignedType = BallType::NONE;
1272 player1Info.ballsPocketedCount = 0;
1273 // Player 1 Name usually remains "Player 1"
1274 player2Info.assignedType = BallType::NONE;
1275 player2Info.ballsPocketedCount = 0;
1276 // Player 2 Name is set based on gameMode in ShowNewGameDialog
1277
1278 // Create Cue Ball (ID 0)
1279 // Initial position will be set during PRE_BREAK_PLACEMENT state
1280 balls.push_back({ 0, BallType::CUE_BALL, TABLE_LEFT + TABLE_WIDTH * 0.15f, RACK_POS_Y, 0, 0, CUE_BALL_COLOR, false });
1281
1282 // --- Create Object Balls (Temporary List) ---
1283 std::vector<Ball> objectBalls;
1284 // Solids (1-7, Yellow)
1285 for (int i = 1; i <= 7; ++i) {
1286 objectBalls.push_back({ i, BallType::SOLID, 0, 0, 0, 0, SOLID_COLOR, false });
1287 }
1288 // Stripes (9-15, Red)
1289 for (int i = 9; i <= 15; ++i) {
1290 objectBalls.push_back({ i, BallType::STRIPE, 0, 0, 0, 0, STRIPE_COLOR, false });
1291 }
1292 // 8-Ball (ID 8) - Add it to the list to be placed
1293 objectBalls.push_back({ 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false });
1294
1295
1296 // --- Racking Logic (Improved) ---
1297 float spacingX = BALL_RADIUS * 2.0f * 0.866f; // cos(30) for horizontal spacing
1298 float spacingY = BALL_RADIUS * 2.0f * 1.0f; // Vertical spacing
1299
1300 // Define rack positions (0-14 indices corresponding to triangle spots)
1301 D2D1_POINT_2F rackPositions[15];
1302 int rackIndex = 0;
1303 for (int row = 0; row < 5; ++row) {
1304 for (int col = 0; col <= row; ++col) {
1305 if (rackIndex >= 15) break;
1306 float x = RACK_POS_X + row * spacingX;
1307 float y = RACK_POS_Y + (col - row / 2.0f) * spacingY;
1308 rackPositions[rackIndex++] = D2D1::Point2F(x, y);
1309 }
1310 }
1311
1312 // Separate 8-ball
1313 Ball eightBall;
1314 std::vector<Ball> otherBalls; // Solids and Stripes
1315 bool eightBallFound = false;
1316 for (const auto& ball : objectBalls) {
1317 if (ball.id == 8) {
1318 eightBall = ball;
1319 eightBallFound = true;
1320 }
1321 else {
1322 otherBalls.push_back(ball);
1323 }
1324 }
1325 // Ensure 8 ball was actually created (should always be true)
1326 if (!eightBallFound) {
1327 // Handle error - perhaps recreate it? For now, proceed.
1328 eightBall = { 8, BallType::EIGHT_BALL, 0, 0, 0, 0, EIGHT_BALL_COLOR, false };
1329 }
1330
1331
1332 // Shuffle the other 14 balls
1333 // Use std::shuffle if available (C++11 and later) for better randomness
1334 // std::random_device rd;
1335 // std::mt19937 g(rd());
1336 // std::shuffle(otherBalls.begin(), otherBalls.end(), g);
1337 std::random_shuffle(otherBalls.begin(), otherBalls.end()); // Using deprecated for now
1338
1339 // --- Place balls into the main 'balls' vector in rack order ---
1340 // Important: Add the cue ball (already created) first.
1341 // (Cue ball added at the start of the function now)
1342
1343 // 1. Place the 8-ball in its fixed position (index 4 for the 3rd row center)
1344 int eightBallRackIndex = 4;
1345 eightBall.x = rackPositions[eightBallRackIndex].x;
1346 eightBall.y = rackPositions[eightBallRackIndex].y;
1347 eightBall.vx = 0;
1348 eightBall.vy = 0;
1349 eightBall.isPocketed = false;
1350 balls.push_back(eightBall); // Add 8 ball to the main vector
1351
1352 // 2. Place the shuffled Solids and Stripes in the remaining spots
1353 size_t otherBallIdx = 0;
1354 //int otherBallIdx = 0;
1355 for (int i = 0; i < 15; ++i) {
1356 if (i == eightBallRackIndex) continue; // Skip the 8-ball spot
1357
1358 if (otherBallIdx < otherBalls.size()) {
1359 Ball& ballToPlace = otherBalls[otherBallIdx++];
1360 ballToPlace.x = rackPositions[i].x;
1361 ballToPlace.y = rackPositions[i].y;
1362 ballToPlace.vx = 0;
1363 ballToPlace.vy = 0;
1364 ballToPlace.isPocketed = false;
1365 balls.push_back(ballToPlace); // Add to the main game vector
1366 }
1367 }
1368 // --- End Racking Logic ---
1369
1370
1371 // --- Determine Who Breaks and Initial State ---
1372 if (isPlayer2AI) {
1373 /*// AI Mode: Randomly decide who breaks
1374 if ((rand() % 2) == 0) {
1375 // AI (Player 2) breaks
1376 currentPlayer = 2;
1377 currentGameState = PRE_BREAK_PLACEMENT; // AI needs to place ball first
1378 aiTurnPending = true; // Trigger AI logic
1379 }
1380 else {
1381 // Player 1 (Human) breaks
1382 currentPlayer = 1;
1383 currentGameState = PRE_BREAK_PLACEMENT; // Human places cue ball
1384 aiTurnPending = false;*/
1385 switch (openingBreakMode) {
1386 case CPU_BREAK:
1387 currentPlayer = 2; // AI breaks
1388 currentGameState = PRE_BREAK_PLACEMENT;
1389 aiTurnPending = true;
1390 break;
1391 case P1_BREAK:
1392 currentPlayer = 1; // Player 1 breaks
1393 currentGameState = PRE_BREAK_PLACEMENT;
1394 aiTurnPending = false;
1395 break;
1396 case FLIP_COIN_BREAK:
1397 if ((rand() % 2) == 0) { // 0 for AI, 1 for Player 1
1398 currentPlayer = 2; // AI breaks
1399 currentGameState = PRE_BREAK_PLACEMENT;
1400 aiTurnPending = true;
1401 }
1402 else {
1403 currentPlayer = 1; // Player 1 breaks
1404 currentGameState = PRE_BREAK_PLACEMENT;
1405 aiTurnPending = false;
1406 }
1407 break;
1408 default: // Fallback to CPU break
1409 currentPlayer = 2;
1410 currentGameState = PRE_BREAK_PLACEMENT;
1411 aiTurnPending = true;
1412 break;
1413 }
1414 }
1415 else {
1416 // Human vs Human, Player 1 always breaks (or could add a flip coin for HvsH too if desired)
1417 currentPlayer = 1;
1418 currentGameState = PRE_BREAK_PLACEMENT;
1419 aiTurnPending = false; // No AI involved
1420 }
1421
1422 // Reset other relevant game state variables
1423 foulCommitted = false;
1424 gameOverMessage = L"";
1425 firstBallPocketedAfterBreak = false;
1426 // pocketedThisTurn cleared at start
1427 // Reset shot parameters and input flags
1428 shotPower = 0.0f;
1429 cueSpinX = 0.0f;
1430 cueSpinY = 0.0f;
1431 isAiming = false;
1432 isDraggingCueBall = false;
1433 isSettingEnglish = false;
1434 cueAngle = 0.0f; // Reset aim angle
1435}
1436
1437
1438// --- Game Loop ---
1439void GameUpdate() {
1440 if (currentGameState == SHOT_IN_PROGRESS) {
1441 UpdatePhysics();
1442 CheckCollisions();
1443
1444 if (AreBallsMoving()) {
1445 // When all balls stop, clear aiming flags
1446 isAiming = false;
1447 aiIsDisplayingAim = false;
1448 //ProcessShotResults();
1449 }
1450
1451 bool pocketed = CheckPockets(); // Store if any ball was pocketed
1452
1453 // --- Update pocket flash animation timer ---
1454 if (pocketFlashTimer > 0.0f) {
1455 pocketFlashTimer -= 0.02f;
1456 if (pocketFlashTimer < 0.0f) pocketFlashTimer = 0.0f;
1457 }
1458
1459 if (!AreBallsMoving()) {
1460 ProcessShotResults(); // Determine next state based on what happened
1461 }
1462 }
1463
1464 // --- Check if AI needs to act ---
1465 else if (isPlayer2AI && currentPlayer == 2 && !AreBallsMoving()) {
1466 if (aiIsDisplayingAim) { // AI has decided a shot and is displaying aim
1467 aiAimDisplayFramesLeft--;
1468 if (aiAimDisplayFramesLeft <= 0) {
1469 aiIsDisplayingAim = false; // Done displaying
1470 if (aiPlannedShotDetails.isValid) {
1471 // Execute the planned shot
1472 firstHitBallIdThisShot = -1;
1473 cueHitObjectBallThisShot = false;
1474 railHitAfterContact = false;
1475 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
1476 ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
1477 aiPlannedShotDetails.isValid = false; // Clear the planned shot
1478 }
1479 currentGameState = SHOT_IN_PROGRESS;
1480 foulCommitted = false;
1481 pocketedThisTurn.clear();
1482 }
1483 // Else, continue displaying aim
1484 }
1485 else if (aiTurnPending) { // AI needs to start its decision process
1486 // Valid states for AI to start thinking
1487 /*/if (currentGameState == PRE_BREAK_PLACEMENT && isOpeningBreakShot) {*/
1488 //newcode 1 commented out
1489 /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
1490 // Handle the break shot
1491 AIBreakShot();
1492 }*/ //new code 1 end
1493 /*else if (currentGameState == PRE_BREAK_PLACEMENT || currentGameState == BREAKING ||
1494 currentGameState == PLAYER2_TURN || currentGameState == BALL_IN_HAND_P2) {*/
1495
1496 // aiTurnPending might be consumed by AIBreakShot or remain for next cycle if needed
1497 /* } //new code 2 commented out
1498 else if (currentGameState == BALL_IN_HAND_P2 && currentPlayer == 2 && isPlayer2AI) {
1499 AIPlaceCueBall(); // AI places the ball first
1500 // After placement, AI needs to decide its shot.
1501 // Transition to a state where AIMakeDecision will be called for shot selection.
1502 currentGameState = PLAYER2_TURN; // Or a specific AI_AIMING_AFTER_PLACEMENT state
1503 // aiTurnPending remains true to trigger AIMakeDecision next.
1504 }
1505 else if (currentGameState == PLAYER2_TURN && currentPlayer == 2 && isPlayer2AI) {
1506 // This is for a normal turn (not break, not immediately after ball-in-hand placement)
1507
1508 currentGameState = AI_THINKING; // Set state to indicate AI is processing
1509 aiTurnPending = false; // Consume the pending turn flag
1510 AIMakeDecision(); // For normal shots (non-break)
1511 }
1512 else {
1513 // Not a state where AI should act
1514 aiTurnPending = false;
1515 }*/
1516 // 2b) AI is ready to think (pending flag)
1517 // **1) Ball-in-Hand** let AI place the cue ball first
1518 if (currentGameState == BALL_IN_HAND_P2) {
1519 // Step 1: AI places the cue ball.
1520 AIPlaceCueBall();
1521 // Step 2: Transition to thinking state for shot decision.
1522 currentGameState = AI_THINKING; //newcode5
1523 // Step 3: Consume the pending flag for the placement phase.
1524 // AIMakeDecision will handle shot planning now.
1525 aiTurnPending = false; //newcode5
1526 // Step 4: AI immediately decides the shot from the new position.
1527 AIMakeDecision(); //newcode5
1528 }
1529 // **2) Opening break** special break shot logic
1530 else if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
1531 AIBreakShot();
1532 }
1533 else if (currentGameState == PLAYER2_TURN || currentGameState == BREAKING) { //newcode5
1534 // General turn for AI to think (not ball-in-hand, not initial break placement)
1535 currentGameState = AI_THINKING; //newcode5
1536 aiTurnPending = false; // Consume the flag //newcode5
1537 AIMakeDecision(); //newcode5
1538 }
1539 // **3) Otherwise** normal shot planning
1540 /*else { //orig uncommented oldcode5
1541 currentGameState = AI_THINKING;
1542 aiTurnPending = false;
1543 AIMakeDecision();
1544 }*/
1545 }
1546
1547 //} //bracefix
1548 // If current state is AI_THINKING but not displaying aim, then AI decision has already been made
1549 }
1550}
1551
1552// --- Physics and Collision ---
1553void UpdatePhysics() {
1554 for (size_t i = 0; i < balls.size(); ++i) {
1555 Ball& b = balls[i];
1556 if (!b.isPocketed) {
1557 b.x += b.vx;
1558 b.y += b.vy;
1559
1560 // Apply friction
1561 b.vx *= FRICTION;
1562 b.vy *= FRICTION;
1563
1564 // Stop balls if velocity is very low
1565 if (GetDistanceSq(b.vx, b.vy, 0, 0) < MIN_VELOCITY_SQ) {
1566 b.vx = 0;
1567 b.vy = 0;
1568 }
1569 }
1570 }
1571}
1572
1573void CheckCollisions() {
1574 float left = TABLE_LEFT;
1575 float right = TABLE_RIGHT;
1576 float top = TABLE_TOP;
1577 float bottom = TABLE_BOTTOM;
1578 const float pocketMouthCheckRadiusSq = (POCKET_RADIUS + BALL_RADIUS) * (POCKET_RADIUS + BALL_RADIUS) * 1.1f;
1579
1580 // --- Reset Per-Frame Sound Flags ---
1581 bool playedWallSoundThisFrame = false;
1582 bool playedCollideSoundThisFrame = false;
1583 // ---
1584
1585 for (size_t i = 0; i < balls.size(); ++i) {
1586 Ball& b1 = balls[i];
1587 if (b1.isPocketed) continue;
1588
1589 bool nearPocket[6];
1590 for (int p = 0; p < 6; ++p) {
1591 nearPocket[p] = GetDistanceSq(b1.x, b1.y, pocketPositions[p].x, pocketPositions[p].y) < pocketMouthCheckRadiusSq;
1592 }
1593 bool nearTopLeftPocket = nearPocket[0];
1594 bool nearTopMidPocket = nearPocket[1];
1595 bool nearTopRightPocket = nearPocket[2];
1596 bool nearBottomLeftPocket = nearPocket[3];
1597 bool nearBottomMidPocket = nearPocket[4];
1598 bool nearBottomRightPocket = nearPocket[5];
1599
1600 bool collidedWallThisBall = false;
1601
1602 // --- Ball-Wall Collisions ---
1603 // (Check logic unchanged, added sound calls and railHitAfterContact update)
1604 // Left Wall
1605 if (b1.x - BALL_RADIUS < left) {
1606 if (!nearTopLeftPocket && !nearBottomLeftPocket) {
1607 b1.x = left + BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
1608 if (!playedWallSoundThisFrame) {
1609 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1610 playedWallSoundThisFrame = true;
1611 }
1612 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1613 }
1614 }
1615 // Right Wall
1616 if (b1.x + BALL_RADIUS > right) {
1617 if (!nearTopRightPocket && !nearBottomRightPocket) {
1618 b1.x = right - BALL_RADIUS; b1.vx *= -1.0f; collidedWallThisBall = true;
1619 if (!playedWallSoundThisFrame) {
1620 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1621 playedWallSoundThisFrame = true;
1622 }
1623 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1624 }
1625 }
1626 // Top Wall
1627 if (b1.y - BALL_RADIUS < top) {
1628 if (!nearTopLeftPocket && !nearTopMidPocket && !nearTopRightPocket) {
1629 b1.y = top + BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
1630 if (!playedWallSoundThisFrame) {
1631 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1632 playedWallSoundThisFrame = true;
1633 }
1634 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1635 }
1636 }
1637 // Bottom Wall
1638 if (b1.y + BALL_RADIUS > bottom) {
1639 if (!nearBottomLeftPocket && !nearBottomMidPocket && !nearBottomRightPocket) {
1640 b1.y = bottom - BALL_RADIUS; b1.vy *= -1.0f; collidedWallThisBall = true;
1641 if (!playedWallSoundThisFrame) {
1642 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("wall.wav")).detach();
1643 playedWallSoundThisFrame = true;
1644 }
1645 if (cueHitObjectBallThisShot) railHitAfterContact = true; // Track rail hit after contact
1646 }
1647 }
1648
1649 // Spin effect (Unchanged)
1650 if (collidedWallThisBall) {
1651 if (b1.x <= left + BALL_RADIUS || b1.x >= right - BALL_RADIUS) { b1.vy += cueSpinX * b1.vx * 0.05f; }
1652 if (b1.y <= top + BALL_RADIUS || b1.y >= bottom - BALL_RADIUS) { b1.vx -= cueSpinY * b1.vy * 0.05f; }
1653 cueSpinX *= 0.7f; cueSpinY *= 0.7f;
1654 }
1655
1656
1657 // --- Ball-Ball Collisions ---
1658 for (size_t j = i + 1; j < balls.size(); ++j) {
1659 Ball& b2 = balls[j];
1660 if (b2.isPocketed) continue;
1661
1662 float dx = b2.x - b1.x; float dy = b2.y - b1.y;
1663 float distSq = dx * dx + dy * dy;
1664 float minDist = BALL_RADIUS * 2.0f;
1665
1666 if (distSq > 1e-6 && distSq < minDist * minDist) {
1667 float dist = sqrtf(distSq);
1668 float overlap = minDist - dist;
1669 float nx = dx / dist; float ny = dy / dist;
1670
1671 // Separation (Unchanged)
1672 b1.x -= overlap * 0.5f * nx; b1.y -= overlap * 0.5f * ny;
1673 b2.x += overlap * 0.5f * nx; b2.y += overlap * 0.5f * ny;
1674
1675 float rvx = b1.vx - b2.vx; float rvy = b1.vy - b2.vy;
1676 float velAlongNormal = rvx * nx + rvy * ny;
1677
1678 if (velAlongNormal > 0) { // Colliding
1679 // --- Play Ball Collision Sound ---
1680 if (!playedCollideSoundThisFrame) {
1681 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("poolballhit.wav")).detach();
1682 playedCollideSoundThisFrame = true; // Set flag
1683 }
1684 // --- End Sound ---
1685
1686 // --- NEW: Track First Hit and Cue/Object Collision ---
1687 if (firstHitBallIdThisShot == -1) { // If first hit hasn't been recorded yet
1688 if (b1.id == 0) { // Cue ball hit b2 first
1689 firstHitBallIdThisShot = b2.id;
1690 cueHitObjectBallThisShot = true;
1691 }
1692 else if (b2.id == 0) { // Cue ball hit b1 first
1693 firstHitBallIdThisShot = b1.id;
1694 cueHitObjectBallThisShot = true;
1695 }
1696 // If neither is cue ball, doesn't count as first hit for foul purposes
1697 }
1698 else if (b1.id == 0 || b2.id == 0) {
1699 // Track subsequent cue ball collisions with object balls
1700 cueHitObjectBallThisShot = true;
1701 }
1702 // --- End First Hit Tracking ---
1703
1704
1705 // Impulse (Unchanged)
1706 float impulse = velAlongNormal;
1707 b1.vx -= impulse * nx; b1.vy -= impulse * ny;
1708 b2.vx += impulse * nx; b2.vy += impulse * ny;
1709
1710 // Spin Transfer (Unchanged)
1711 if (b1.id == 0 || b2.id == 0) {
1712 float spinEffectFactor = 0.08f;
1713 b1.vx += (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
1714 b1.vy += (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
1715 b2.vx -= (cueSpinY * ny - cueSpinX * nx) * spinEffectFactor;
1716 b2.vy -= (cueSpinY * nx + cueSpinX * ny) * spinEffectFactor;
1717 cueSpinX *= 0.85f; cueSpinY *= 0.85f;
1718 }
1719 }
1720 }
1721 } // End ball-ball loop
1722 } // End ball loop
1723} // End CheckCollisions
1724
1725
1726bool CheckPockets() {
1727 bool ballPocketedThisCheck = false; // Local flag for this specific check run
1728 for (size_t i = 0; i < balls.size(); ++i) {
1729 Ball& b = balls[i];
1730 if (!b.isPocketed) { // Only check balls that aren't already flagged as pocketed
1731 for (int p = 0; p < 6; ++p) {
1732 float distSq = GetDistanceSq(b.x, b.y, pocketPositions[p].x, pocketPositions[p].y);
1733 // --- Use updated POCKET_RADIUS ---
1734 if (distSq < POCKET_RADIUS * POCKET_RADIUS) {
1735 b.isPocketed = true;
1736 b.vx = b.vy = 0;
1737 pocketedThisTurn.push_back(b.id);
1738
1739 // --- Play Pocket Sound (Threaded) ---
1740 if (!ballPocketedThisCheck) {
1741 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("pocket.wav")).detach();
1742 ballPocketedThisCheck = true;
1743 }
1744 // --- End Sound ---
1745
1746 break; // Ball is pocketed
1747 }
1748 }
1749 }
1750 }
1751 return ballPocketedThisCheck;
1752}
1753
1754bool AreBallsMoving() {
1755 for (size_t i = 0; i < balls.size(); ++i) {
1756 if (!balls[i].isPocketed && (balls[i].vx != 0 || balls[i].vy != 0)) {
1757 return true;
1758 }
1759 }
1760 return false;
1761}
1762
1763void RespawnCueBall(bool behindHeadstring) { // 'behindHeadstring' only relevant for initial break placement
1764 Ball* cueBall = GetCueBall();
1765 if (cueBall) {
1766 // Reset position to a default
1767 //disabled for behind headstring (now move anywhere)
1768 /*cueBall->x = HEADSTRING_X * 0.5f;
1769 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;*/
1770 // Reset position to a default:
1771 if (behindHeadstring) {
1772 // Opening break: kitchen center
1773 cueBall->x = HEADSTRING_X * 0.5f;
1774 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
1775 }
1776 else {
1777 // Ball-in-hand (foul): center of full table
1778 cueBall->x = TABLE_LEFT + TABLE_WIDTH / 2.0f;
1779 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
1780 }
1781 cueBall->vx = 0;
1782 cueBall->vy = 0;
1783 cueBall->isPocketed = false;
1784
1785 // Set state based on who gets ball-in-hand
1786 /*// 'currentPlayer' already reflects who's turn it is NOW (switched before calling this)*/
1787 // 'currentPlayer' has already been switched to the player whose turn it will be.
1788 // The 'behindHeadstring' parameter to RespawnCueBall is mostly for historical reasons / initial setup.
1789 if (currentPlayer == 1) { // Player 2 (AI/Human) fouled, Player 1 (Human) gets ball-in-hand
1790 currentGameState = BALL_IN_HAND_P1;
1791 aiTurnPending = false; // Ensure AI flag off
1792 }
1793 else { // Player 1 (Human) fouled, Player 2 gets ball-in-hand
1794 if (isPlayer2AI) {
1795 // --- CONFIRMED FIX: Set correct state for AI Ball-in-Hand ---
1796 currentGameState = BALL_IN_HAND_P2; // AI now needs to place the ball
1797 aiTurnPending = true; // Trigger AI logic (will call AIPlaceCueBall first)
1798 }
1799 else { // Human Player 2
1800 currentGameState = BALL_IN_HAND_P2;
1801 aiTurnPending = false; // Ensure AI flag off
1802 }
1803 }
1804 // Handle initial placement state correctly if called from InitGame
1805 /*if (behindHeadstring && currentGameState != PRE_BREAK_PLACEMENT) {
1806 // This case might need review depending on exact initial setup flow,
1807 // but the foul logic above should now be correct.
1808 // Let's ensure initial state is PRE_BREAK_PLACEMENT if behindHeadstring is true.*/
1809 //currentGameState = PRE_BREAK_PLACEMENT;
1810 }
1811}
1812//}
1813
1814
1815// --- Game Logic ---
1816
1817void ApplyShot(float power, float angle, float spinX, float spinY) {
1818 Ball* cueBall = GetCueBall();
1819 if (cueBall) {
1820
1821 // --- Play Cue Strike Sound (Threaded) ---
1822 if (power > 0.1f) { // Only play if it's an audible shot
1823 std::thread([](const TCHAR* soundName) { PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT); }, TEXT("cue.wav")).detach();
1824 }
1825 // --- End Sound ---
1826
1827 cueBall->vx = cosf(angle) * power;
1828 cueBall->vy = sinf(angle) * power;
1829
1830 // Apply English (Spin) - Simplified effect (Unchanged)
1831 cueBall->vx += sinf(angle) * spinY * 0.5f;
1832 cueBall->vy -= cosf(angle) * spinY * 0.5f;
1833 cueBall->vx -= cosf(angle) * spinX * 0.5f;
1834 cueBall->vy -= sinf(angle) * spinX * 0.5f;
1835
1836 // Store spin (Unchanged)
1837 cueSpinX = spinX;
1838 cueSpinY = spinY;
1839
1840 // --- Reset Foul Tracking flags for the new shot ---
1841 // (Also reset in LBUTTONUP, but good to ensure here too)
1842 firstHitBallIdThisShot = -1; // No ball hit yet
1843 cueHitObjectBallThisShot = false; // Cue hasn't hit anything yet
1844 railHitAfterContact = false; // No rail hit after contact yet
1845 // --- End Reset ---
1846
1847 // If this was the opening break shot, clear the flag
1848 if (isOpeningBreakShot) {
1849 isOpeningBreakShot = false; // Mark opening break as taken
1850 }
1851 }
1852}
1853
1854
1855void ProcessShotResults() {
1856 bool cueBallPocketed = false;
1857 bool eightBallPocketed = false;
1858
1859 PlayerInfo& shootingPlayer = (currentPlayer == 1) ? player1Info : player2Info;
1860 int ownBallsPocketedThisTurn = 0;
1861
1862 for (int id : pocketedThisTurn) {
1863 Ball* b = GetBallById(id);
1864 if (!b) continue;
1865
1866 if (b->id == 0) cueBallPocketed = true;
1867 else if (b->id == 8) eightBallPocketed = true;
1868 else {
1869 if (b->type == player1Info.assignedType && player1Info.assignedType != BallType::NONE) player1Info.ballsPocketedCount++;
1870 else if (b->type == player2Info.assignedType && player2Info.assignedType != BallType::NONE) player2Info.ballsPocketedCount++;
1871 if (b->type == shootingPlayer.assignedType) {
1872 ownBallsPocketedThisTurn++;
1873 }
1874 }
1875 }
1876
1877 if (eightBallPocketed) {
1878 CheckGameOverConditions(true, cueBallPocketed);
1879 if (currentGameState == GAME_OVER) {
1880 pocketedThisTurn.clear();
1881 return;
1882 }
1883 }
1884
1885 bool turnFoul = false;
1886 if (cueBallPocketed) {
1887 turnFoul = true;
1888 }
1889 else {
1890 Ball* firstHit = GetBallById(firstHitBallIdThisShot);
1891 if (!firstHit) {
1892 turnFoul = true;
1893 }
1894 else {
1895 if (player1Info.assignedType != BallType::NONE) {
1896 if (IsPlayerOnEightBall(currentPlayer)) {
1897 if (firstHit->id != 8) turnFoul = true;
1898 }
1899 else {
1900 if (firstHit->type != shootingPlayer.assignedType) turnFoul = true;
1901 }
1902 }
1903 }
1904 }
1905
1906 if (!turnFoul && cueHitObjectBallThisShot && !railHitAfterContact && pocketedThisTurn.empty()) {
1907 turnFoul = true;
1908 }
1909
1910 foulCommitted = turnFoul;
1911
1912 if (foulCommitted) {
1913 SwitchTurns();
1914 RespawnCueBall(false);
1915 }
1916 else if (player1Info.assignedType == BallType::NONE && !pocketedThisTurn.empty() && !cueBallPocketed && !eightBallPocketed) {
1917 Ball* firstBall = GetBallById(pocketedThisTurn[0]);
1918 if (firstBall) AssignPlayerBallTypes(firstBall->type);
1919 CheckAndTransitionToPocketChoice(currentPlayer);
1920 }
1921 else if (ownBallsPocketedThisTurn > 0) {
1922 CheckAndTransitionToPocketChoice(currentPlayer);
1923 }
1924 else {
1925 SwitchTurns();
1926 }
1927
1928 pocketedThisTurn.clear();
1929}
1930
1931void AssignPlayerBallTypes(BallType firstPocketedType) {
1932 if (firstPocketedType == BallType::SOLID || firstPocketedType == BallType::STRIPE) {
1933 if (currentPlayer == 1) {
1934 player1Info.assignedType = firstPocketedType;
1935 player2Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
1936 }
1937 else {
1938 player2Info.assignedType = firstPocketedType;
1939 player1Info.assignedType = (firstPocketedType == BallType::SOLID) ? BallType::STRIPE : BallType::SOLID;
1940 }
1941 }
1942 // If 8-ball was first (illegal on break generally), rules vary.
1943 // Here, we might ignore assignment until a solid/stripe is pocketed legally.
1944 // Or assign based on what *else* was pocketed, if anything.
1945 // Simplification: Assignment only happens on SOLID or STRIPE first pocket.
1946}
1947
1948void CheckGameOverConditions(bool eightBallPocketed, bool cueBallPocketed) {
1949 if (!eightBallPocketed) return; // Only proceed if 8-ball was pocketed
1950
1951 PlayerInfo& currentPlayerInfo = (currentPlayer == 1) ? player1Info : player2Info;
1952 bool playerClearedBalls = (currentPlayerInfo.assignedType != BallType::NONE && currentPlayerInfo.ballsPocketedCount >= 7);
1953
1954 // Loss Conditions:
1955 // 1. Pocket 8-ball AND scratch (pocket cue ball)
1956 // 2. Pocket 8-ball before clearing own color group
1957 if (cueBallPocketed || (!playerClearedBalls && currentPlayerInfo.assignedType != BallType::NONE)) {
1958 gameOverMessage = (currentPlayer == 1) ? L"Player 2 Wins! (Player 1 fouled on 8-ball)" : L"Player 1 Wins! (Player 2 fouled on 8-ball)";
1959 currentGameState = GAME_OVER;
1960 }
1961 // Win Condition:
1962 // 1. Pocket 8-ball legally after clearing own color group
1963 else if (playerClearedBalls) {
1964 gameOverMessage = (currentPlayer == 1) ? L"Player 1 Wins!" : L"Player 2 Wins!";
1965 currentGameState = GAME_OVER;
1966 }
1967 // Special case: 8 ball pocketed on break. Usually re-spot or re-rack.
1968 // Simple: If it happens during assignment phase, treat as foul, respawn 8ball.
1969 else if (player1Info.assignedType == BallType::NONE) {
1970 Ball* eightBall = GetBallById(8);
1971 if (eightBall) {
1972 eightBall->isPocketed = false;
1973 // Place 8-ball on foot spot (approx RACK_POS_X) or center if occupied
1974 eightBall->x = RACK_POS_X;
1975 eightBall->y = RACK_POS_Y;
1976 eightBall->vx = eightBall->vy = 0;
1977 // Check overlap and nudge if necessary (simplified)
1978 }
1979 // Apply foul rules if cue ball was also pocketed
1980 if (cueBallPocketed) {
1981 foulCommitted = true;
1982 // Don't switch turns on break scratch + 8ball pocket? Rules vary.
1983 // Let's make it a foul, switch turns, ball in hand.
1984 SwitchTurns();
1985 RespawnCueBall(false); // Ball in hand for opponent
1986 }
1987 else {
1988 // Just respawned 8ball, continue turn or switch based on other balls pocketed.
1989 // Let ProcessShotResults handle turn logic based on other pocketed balls.
1990 }
1991 // Prevent immediate game over message by returning here
1992 return;
1993 }
1994
1995
1996}
1997
1998
1999void SwitchTurns() {
2000 currentPlayer = (currentPlayer == 1) ? 2 : 1;
2001 isAiming = false;
2002 shotPower = 0;
2003 CheckAndTransitionToPocketChoice(currentPlayer); // Use the new helper
2004}
2005
2006void AIBreakShot() {
2007 Ball* cueBall = GetCueBall();
2008 if (!cueBall) return;
2009
2010 // This function is called when it's AI's turn for the opening break and state is PRE_BREAK_PLACEMENT.
2011 // AI will place the cue ball and then plan the shot.
2012 if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
2013 // Place cue ball in the kitchen randomly
2014 /*float kitchenMinX = TABLE_LEFT + BALL_RADIUS; // [cite: 1071, 1072, 1587]
2015 float kitchenMaxX = HEADSTRING_X - BALL_RADIUS; // [cite: 1072, 1078, 1588]
2016 float kitchenMinY = TABLE_TOP + BALL_RADIUS; // [cite: 1071, 1072, 1588]
2017 float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS; // [cite: 1072, 1073, 1589]*/
2018
2019 // --- AI Places Cue Ball for Break ---
2020// Decide if placing center or side. For simplicity, let's try placing slightly off-center
2021// towards one side for a more angled break, or center for direct apex hit.
2022// A common strategy is to hit the second ball of the rack.
2023
2024 float placementY = RACK_POS_Y; // Align vertically with the rack center
2025 float placementX;
2026
2027 // Randomly choose a side or center-ish placement for variation.
2028 int placementChoice = rand() % 3; // 0: Left-ish, 1: Center-ish, 2: Right-ish in kitchen
2029
2030 if (placementChoice == 0) { // Left-ish
2031 placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) - (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the left within kitchen
2032 }
2033 else if (placementChoice == 2) { // Right-ish
2034 placementX = HEADSTRING_X - (TABLE_WIDTH * 0.05f) + (BALL_RADIUS * (1 + (rand() % 3))); // Place slightly to the right within kitchen
2035 }
2036 else { // Center-ish
2037 placementX = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // Roughly center of kitchen
2038 }
2039 placementX = std::max(TABLE_LEFT + BALL_RADIUS + 1.0f, std::min(placementX, HEADSTRING_X - BALL_RADIUS - 1.0f)); // Clamp within kitchen X
2040
2041 bool validPos = false;
2042 int attempts = 0;
2043 while (!validPos && attempts < 100) {
2044 /*cueBall->x = kitchenMinX + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxX - kitchenMinX)); // [cite: 1589]
2045 cueBall->y = kitchenMinY + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX) / (kitchenMaxY - kitchenMinY)); // [cite: 1590]
2046 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1591]
2047 validPos = true; // [cite: 1591]*/
2048 // Try the chosen X, but vary Y slightly to find a clear spot
2049 cueBall->x = placementX;
2050 cueBall->y = placementY + (static_cast<float>(rand() % 100 - 50) / 100.0f) * BALL_RADIUS * 2.0f; // Vary Y a bit
2051 cueBall->y = std::max(TABLE_TOP + BALL_RADIUS + 1.0f, std::min(cueBall->y, TABLE_BOTTOM - BALL_RADIUS - 1.0f)); // Clamp Y
2052
2053 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true /* behind headstring */)) {
2054 validPos = true;
2055 }
2056 attempts++; // [cite: 1592]
2057 }
2058 if (!validPos) {
2059 // Fallback position
2060 /*cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f; // [cite: 1071, 1078, 1593]
2061 cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f; // [cite: 1071, 1073, 1594]
2062 if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) { // [cite: 1594]
2063 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2; // [cite: 1072, 1078, 1594]
2064 cueBall->y = RACK_POS_Y; // [cite: 1080, 1595]
2065 }
2066 }
2067 cueBall->vx = 0; // [cite: 1595]
2068 cueBall->vy = 0; // [cite: 1596]
2069
2070 // Plan a break shot: aim at the center of the rack (apex ball)
2071 float targetX = RACK_POS_X; // [cite: 1079] Aim for the apex ball X-coordinate
2072 float targetY = RACK_POS_Y; // [cite: 1080] Aim for the apex ball Y-coordinate
2073
2074 float dx = targetX - cueBall->x; // [cite: 1599]
2075 float dy = targetY - cueBall->y; // [cite: 1600]
2076 float shotAngle = atan2f(dy, dx); // [cite: 1600]
2077 float shotPowerValue = MAX_SHOT_POWER; // [cite: 1076, 1600] Use MAX_SHOT_POWER*/
2078
2079 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.75f; // A default safe spot in kitchen
2080 cueBall->y = RACK_POS_Y;
2081 }
2082 cueBall->vx = 0; cueBall->vy = 0;
2083
2084 // --- AI Plans the Break Shot ---
2085 float targetX, targetY;
2086 // If cue ball is near center of kitchen width, aim for apex.
2087 // Otherwise, aim for the second ball on the side the cue ball is on (for a cut break).
2088 float kitchenCenterRegion = (HEADSTRING_X - TABLE_LEFT) * 0.3f; // Define a "center" region
2089 if (std::abs(cueBall->x - (TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) / 2.0f)) < kitchenCenterRegion / 2.0f) {
2090 // Center-ish placement: Aim for the apex ball (ball ID 1 or first ball in rack)
2091 targetX = RACK_POS_X; // Apex ball X
2092 targetY = RACK_POS_Y; // Apex ball Y
2093 }
2094 else {
2095 // Side placement: Aim to hit the "second" ball of the rack for a wider spread.
2096 // This is a simplification. A more robust way is to find the actual second ball.
2097 // For now, aim slightly off the apex towards the side the cue ball is on.
2098 targetX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f; // X of the second row of balls
2099 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
2100 }
2101
2102 float dx = targetX - cueBall->x;
2103 float dy = targetY - cueBall->y;
2104 float shotAngle = atan2f(dy, dx);
2105 float shotPowerValue = MAX_SHOT_POWER * (0.9f + (rand() % 11) / 100.0f); // Slightly vary max power
2106
2107 // Store planned shot details for the AI
2108 /*aiPlannedShotDetails.angle = shotAngle; // [cite: 1102, 1601]
2109 aiPlannedShotDetails.power = shotPowerValue; // [cite: 1102, 1601]
2110 aiPlannedShotDetails.spinX = 0.0f; // [cite: 1102, 1601] No spin for a standard power break
2111 aiPlannedShotDetails.spinY = 0.0f; // [cite: 1103, 1602]
2112 aiPlannedShotDetails.isValid = true; // [cite: 1103, 1602]*/
2113
2114 aiPlannedShotDetails.angle = shotAngle;
2115 aiPlannedShotDetails.power = shotPowerValue;
2116 aiPlannedShotDetails.spinX = 0.0f; // No spin for break usually
2117 aiPlannedShotDetails.spinY = 0.0f;
2118 aiPlannedShotDetails.isValid = true;
2119
2120 // Update global cue parameters for immediate visual feedback if DrawAimingAids uses them
2121 /*::cueAngle = aiPlannedShotDetails.angle; // [cite: 1109, 1603] Update global cueAngle
2122 ::shotPower = aiPlannedShotDetails.power; // [cite: 1109, 1604] Update global shotPower
2123 ::cueSpinX = aiPlannedShotDetails.spinX; // [cite: 1109]
2124 ::cueSpinY = aiPlannedShotDetails.spinY; // [cite: 1110]*/
2125
2126 ::cueAngle = aiPlannedShotDetails.angle;
2127 ::shotPower = aiPlannedShotDetails.power;
2128 ::cueSpinX = aiPlannedShotDetails.spinX;
2129 ::cueSpinY = aiPlannedShotDetails.spinY;
2130
2131 // Set up for AI display via GameUpdate
2132 /*aiIsDisplayingAim = true; // [cite: 1104] Enable AI aiming visualization
2133 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES; // [cite: 1105] Set duration for display
2134
2135 currentGameState = AI_THINKING; // [cite: 1081] Transition to AI_THINKING state.
2136 // GameUpdate will handle the aiAimDisplayFramesLeft countdown
2137 // and then execute the shot using aiPlannedShotDetails.
2138 // isOpeningBreakShot will be set to false within ApplyShot.
2139
2140 // No immediate ApplyShot or sound here; GameUpdate's AI execution logic will handle it.*/
2141
2142 aiIsDisplayingAim = true;
2143 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
2144 currentGameState = AI_THINKING; // State changes to AI_THINKING, GameUpdate will handle shot execution after display
2145
2146 return; // The break shot is now planned and will be executed by GameUpdate
2147 }
2148
2149 // 2. If not in PRE_BREAK_PLACEMENT (e.g., if this function were called at other times,
2150 // though current game logic only calls it for PRE_BREAK_PLACEMENT)
2151 // This part can be extended if AIBreakShot needs to handle other scenarios.
2152 // For now, the primary logic is above.
2153}
2154
2155// --- Helper Functions ---
2156
2157Ball* GetBallById(int id) {
2158 for (size_t i = 0; i < balls.size(); ++i) {
2159 if (balls[i].id == id) {
2160 return &balls[i];
2161 }
2162 }
2163 return nullptr;
2164}
2165
2166Ball* GetCueBall() {
2167 return GetBallById(0);
2168}
2169
2170float GetDistance(float x1, float y1, float x2, float y2) {
2171 return sqrtf(GetDistanceSq(x1, y1, x2, y2));
2172}
2173
2174float GetDistanceSq(float x1, float y1, float x2, float y2) {
2175 float dx = x2 - x1;
2176 float dy = y2 - y1;
2177 return dx * dx + dy * dy;
2178}
2179
2180bool IsValidCueBallPosition(float x, float y, bool checkHeadstring) {
2181 // Basic bounds check (inside cushions)
2182 float left = TABLE_LEFT + CUSHION_THICKNESS + BALL_RADIUS;
2183 float right = TABLE_RIGHT - CUSHION_THICKNESS - BALL_RADIUS;
2184 float top = TABLE_TOP + CUSHION_THICKNESS + BALL_RADIUS;
2185 float bottom = TABLE_BOTTOM - CUSHION_THICKNESS - BALL_RADIUS;
2186
2187 if (x < left || x > right || y < top || y > bottom) {
2188 return false;
2189 }
2190
2191 // Check headstring restriction if needed
2192 if (checkHeadstring && x >= HEADSTRING_X) {
2193 return false;
2194 }
2195
2196 // Check overlap with other balls
2197 for (size_t i = 0; i < balls.size(); ++i) {
2198 if (balls[i].id != 0 && !balls[i].isPocketed) { // Don't check against itself or pocketed balls
2199 if (GetDistanceSq(x, y, balls[i].x, balls[i].y) < (BALL_RADIUS * 2.0f) * (BALL_RADIUS * 2.0f)) {
2200 return false; // Overlapping another ball
2201 }
2202 }
2203 }
2204
2205 return true;
2206}
2207
2208// --- NEW HELPER FUNCTION IMPLEMENTATIONS ---
2209
2210// Checks if a player has pocketed all their balls and is now on the 8-ball.
2211bool IsPlayerOnEightBall(int player) {
2212 PlayerInfo& playerInfo = (player == 1) ? player1Info : player2Info;
2213 if (playerInfo.assignedType != BallType::NONE && playerInfo.assignedType != BallType::EIGHT_BALL && playerInfo.ballsPocketedCount >= 7) {
2214 Ball* eightBall = GetBallById(8);
2215 return (eightBall && !eightBall->isPocketed);
2216 }
2217 return false;
2218}
2219
2220// Centralized logic to enter the "choosing pocket" state. This fixes the indicator bugs.
2221void CheckAndTransitionToPocketChoice(int playerID) {
2222 bool needsToCall = IsPlayerOnEightBall(playerID);
2223 int* calledPocketForPlayer = (playerID == 1) ? &calledPocketP1 : &calledPocketP2;
2224
2225 if (needsToCall && *calledPocketForPlayer == -1) { // Only transition if a pocket hasn't been called yet
2226 pocketCallMessage = ((playerID == 1) ? player1Info.name : player2Info.name) + L": Choose a pocket...";
2227 if (playerID == 1) {
2228 currentGameState = CHOOSING_POCKET_P1;
2229 }
2230 else { // Player 2
2231 if (isPlayer2AI) {
2232 currentGameState = AI_THINKING;
2233 aiTurnPending = true;
2234 }
2235 else {
2236 currentGameState = CHOOSING_POCKET_P2;
2237 }
2238 }
2239 if (!(playerID == 2 && isPlayer2AI)) {
2240 *calledPocketForPlayer = 5; // Default to top-right if none chosen
2241 }
2242 }
2243 else {
2244 // Player does not need to call a pocket (or already has), proceed to normal turn.
2245 pocketCallMessage = L""; // Clear any message
2246 currentGameState = (playerID == 1) ? PLAYER1_TURN : PLAYER2_TURN;
2247 if (playerID == 2 && isPlayer2AI) {
2248 aiTurnPending = true;
2249 }
2250 }
2251}
2252
2253template <typename T>
2254void SafeRelease(T** ppT) {
2255 if (*ppT) {
2256 (*ppT)->Release();
2257 *ppT = nullptr;
2258 }
2259}
2260
2261// --- Helper Function for Line Segment Intersection ---
2262// Finds intersection point of line segment P1->P2 and line segment P3->P4
2263// Returns true if they intersect, false otherwise. Stores intersection point in 'intersection'.
2264bool LineSegmentIntersection(D2D1_POINT_2F p1, D2D1_POINT_2F p2, D2D1_POINT_2F p3, D2D1_POINT_2F p4, D2D1_POINT_2F& intersection)
2265{
2266 float denominator = (p4.y - p3.y) * (p2.x - p1.x) - (p4.x - p3.x) * (p2.y - p1.y);
2267
2268 // Check if lines are parallel or collinear
2269 if (fabs(denominator) < 1e-6) {
2270 return false;
2271 }
2272
2273 float ua = ((p4.x - p3.x) * (p1.y - p3.y) - (p4.y - p3.y) * (p1.x - p3.x)) / denominator;
2274 float ub = ((p2.x - p1.x) * (p1.y - p3.y) - (p2.y - p1.y) * (p1.x - p3.x)) / denominator;
2275
2276 // Check if intersection point lies on both segments
2277 if (ua >= 0.0f && ua <= 1.0f && ub >= 0.0f && ub <= 1.0f) {
2278 intersection.x = p1.x + ua * (p2.x - p1.x);
2279 intersection.y = p1.y + ua * (p2.y - p1.y);
2280 return true;
2281 }
2282
2283 return false;
2284}
2285
2286// --- INSERT NEW HELPER FUNCTION HERE ---
2287// Calculates the squared distance from point P to the line segment AB.
2288float PointToLineSegmentDistanceSq(D2D1_POINT_2F p, D2D1_POINT_2F a, D2D1_POINT_2F b) {
2289 float l2 = GetDistanceSq(a.x, a.y, b.x, b.y);
2290 if (l2 == 0.0f) return GetDistanceSq(p.x, p.y, a.x, a.y); // Segment is a point
2291 // Consider P projecting onto the line AB infinite line
2292 // t = [(P-A) . (B-A)] / |B-A|^2
2293 float t = ((p.x - a.x) * (b.x - a.x) + (p.y - a.y) * (b.y - a.y)) / l2;
2294 t = std::max(0.0f, std::min(1.0f, t)); // Clamp t to the segment [0, 1]
2295 // Projection falls on the segment
2296 D2D1_POINT_2F projection = D2D1::Point2F(a.x + t * (b.x - a.x), a.y + t * (b.y - a.y));
2297 return GetDistanceSq(p.x, p.y, projection.x, projection.y);
2298}
2299// --- End New Helper ---
2300
2301// --- NEW AI Implementation Functions ---
2302
2303// Main entry point for AI turn
2304void AIMakeDecision() {
2305 //AIShotInfo bestShot = { false }; // Declare here
2306 // This function is called when currentGameState is AI_THINKING (for a normal shot decision)
2307 Ball* cueBall = GetCueBall();
2308 if (!cueBall || !isPlayer2AI || currentPlayer != 2) {
2309 aiPlannedShotDetails.isValid = false; // Ensure no shot if conditions not met
2310 return;
2311 }
2312
2313 // Phase 1: Placement if needed (Ball-in-Hand or Initial Break)
2314 /*if ((isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) || currentGameState == BALL_IN_HAND_P2) {
2315 AIPlaceCueBall(); // Handles kitchen placement for break or regular ball-in-hand
2316 if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT) {
2317 currentGameState = BREAKING; // Now AI needs to decide the break shot parameters
2318 }
2319 // For regular BALL_IN_HAND_P2, after placement, it will proceed to find a shot.
2320 }*/
2321
2322 aiPlannedShotDetails.isValid = false; // Default to no valid shot found yet for this decision cycle
2323 // Note: isOpeningBreakShot is false here because AIBreakShot handles the break.
2324
2325 // Phase 2: Decide shot parameters (Break or Normal play)
2326 /*if (isOpeningBreakShot && currentGameState == BREAKING) {
2327 // Force cue ball into center of kitchen
2328 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
2329 cueBall->y = (TABLE_TOP + TABLE_BOTTOM) * 0.5f;
2330 cueBall->vx = cueBall->vy = 0.0f;
2331
2332 float rackCenterX = RACK_POS_X + BALL_RADIUS * 2.0f * 0.866f * 2.0f;
2333 float rackCenterY = RACK_POS_Y;
2334 float dx = rackCenterX - cueBall->x;
2335 float dy = rackCenterY - cueBall->y;
2336
2337 aiPlannedShotDetails.angle = atan2f(dy, dx);
2338 aiPlannedShotDetails.power = MAX_SHOT_POWER;
2339 aiPlannedShotDetails.spinX = 0.0f;
2340 aiPlannedShotDetails.spinY = 0.0f;
2341 aiPlannedShotDetails.isValid = true;
2342
2343 // Apply shot immediately
2344 cueAngle = aiPlannedShotDetails.angle;
2345 shotPower = aiPlannedShotDetails.power;
2346 cueSpinX = aiPlannedShotDetails.spinX;
2347 cueSpinY = aiPlannedShotDetails.spinY;
2348
2349 firstHitBallIdThisShot = -1;
2350 cueHitObjectBallThisShot = false;
2351 railHitAfterContact = false;
2352 isAiming = false;
2353 aiIsDisplayingAim = false;
2354 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
2355 //bool aiIsDisplayingAim = true;
2356
2357 std::thread([](const TCHAR* soundName) {
2358 PlaySound(soundName, NULL, SND_FILENAME | SND_NODEFAULT);
2359 }, TEXT("cue.wav")).detach();
2360
2361 ApplyShot(shotPower, cueAngle, cueSpinX, cueSpinY);
2362 currentGameState = SHOT_IN_PROGRESS;
2363 isOpeningBreakShot = false;
2364 aiTurnPending = false;
2365 pocketedThisTurn.clear();
2366 return;
2367 }
2368 else {*/
2369 // --- Normal AI Shot Decision (using AIFindBestShot) ---
2370 AIShotInfo bestShot = AIFindBestShot(); // bugtraq
2371 //bestShot = AIFindBestShot(); // bugtraq
2372 if (bestShot.possible) {
2373 aiPlannedShotDetails.angle = bestShot.angle;
2374 aiPlannedShotDetails.power = bestShot.power;
2375 aiPlannedShotDetails.spinX = 0.0f; // AI doesn't use spin yet
2376 aiPlannedShotDetails.spinY = 0.0f;
2377 aiPlannedShotDetails.isValid = true;
2378 }
2379 else {
2380 // Safety tap if no better shot found
2381 // Try to hit the closest 'own' ball gently or any ball if types not assigned
2382 Ball* ballToNudge = nullptr;
2383 float minDistSq = -1.0f;
2384 BallType aiTargetType = player2Info.assignedType;
2385 bool mustHit8Ball = (aiTargetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2386
2387 for (auto& b : balls) {
2388 if (b.isPocketed || b.id == 0) continue;
2389 bool canHitThis = false;
2390 if (mustHit8Ball) canHitThis = (b.id == 8);
2391 else if (aiTargetType != BallType::NONE) canHitThis = (b.type == aiTargetType);
2392 else canHitThis = (b.id != 8); // Can hit any non-8-ball if types not assigned
2393
2394 if (canHitThis) {
2395 float dSq = GetDistanceSq(cueBall->x, cueBall->y, b.x, b.y);
2396 if (ballToNudge == nullptr || dSq < minDistSq) {
2397 ballToNudge = &b;
2398 minDistSq = dSq;
2399 }
2400 }
2401 }
2402 if (ballToNudge) { // Found a ball to nudge
2403 aiPlannedShotDetails.angle = atan2f(ballToNudge->y - cueBall->y, ballToNudge->x - cueBall->x);
2404 aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.15f; // Gentle tap
2405 }
2406 else { // Absolute fallback: small tap forward
2407 aiPlannedShotDetails.angle = cueAngle; // Keep last angle or default
2408 //aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
2409 aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.1f;
2410 }
2411 aiPlannedShotDetails.spinX = 0.0f;
2412 aiPlannedShotDetails.spinY = 0.0f;
2413 aiPlannedShotDetails.isValid = true; // Safety shot is a "valid" plan
2414 }
2415 //} //bracefix
2416
2417 // Phase 3: Setup for Aim Display (if a valid shot was decided)
2418 if (aiPlannedShotDetails.isValid) {
2419 cueAngle = aiPlannedShotDetails.angle; // Update global for drawing
2420 shotPower = aiPlannedShotDetails.power; // Update global for drawing
2421 // cueSpinX and cueSpinY could also be set here if AI used them
2422 cueSpinX = aiPlannedShotDetails.spinX; // Also set these for drawing consistency
2423 cueSpinY = aiPlannedShotDetails.spinY; //
2424
2425 aiIsDisplayingAim = true;
2426 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES;
2427 // currentGameState remains AI_THINKING, GameUpdate will handle the display countdown and shot execution.
2428 // FIRE THE BREAK SHOT NOW
2429 // Immediately execute the break shot after setting parameters
2430 /*ApplyShot(aiPlannedShotDetails.power, aiPlannedShotDetails.angle, aiPlannedShotDetails.spinX, aiPlannedShotDetails.spinY);
2431 currentGameState = SHOT_IN_PROGRESS;
2432 aiTurnPending = false;
2433 isOpeningBreakShot = false;*/
2434 }
2435 else {
2436 // Should not happen if safety shot is always planned, but as a fallback:
2437 aiIsDisplayingAim = false;
2438 // If AI truly can't decide anything, maybe switch turn or log error. For now, it will do nothing this frame.
2439 // Or force a minimal safety tap without display.
2440 // To ensure game progresses, let's plan a minimal tap if nothing else.
2441 if (!aiPlannedShotDetails.isValid) { // Double check
2442 aiPlannedShotDetails.angle = 0.0f;
2443 aiPlannedShotDetails.power = MAX_SHOT_POWER * 0.05f; // Very small tap
2444 aiPlannedShotDetails.spinX = 0.0f; aiPlannedShotDetails.spinY = 0.0f;
2445 aiPlannedShotDetails.isValid = true;
2446 //cueAngle = aiPlannedShotDetails.angle; shotPower = aiPlannedShotDetails.power;
2447 cueAngle = aiPlannedShotDetails.angle;
2448 shotPower = aiPlannedShotDetails.power;
2449 cueSpinX = aiPlannedShotDetails.spinX;
2450 cueSpinY = aiPlannedShotDetails.spinY;
2451 aiIsDisplayingAim = true; // Allow display for this minimal tap too
2452 aiAimDisplayFramesLeft = AI_AIM_DISPLAY_DURATION_FRAMES / 2; // Shorter display for fallback
2453 }
2454 }
2455 // aiTurnPending was set to false by GameUpdate before calling AIMakeDecision.
2456 // AIMakeDecision's job is to populate aiPlannedShotDetails and trigger display.
2457}
2458
2459// AI logic for placing cue ball during ball-in-hand
2460void AIPlaceCueBall() {
2461 Ball* cueBall = GetCueBall();
2462 if (!cueBall) return;
2463
2464 // --- CPU AI Opening Break: Kitchen Placement ---
2465 /*if (isOpeningBreakShot && currentGameState == PRE_BREAK_PLACEMENT && currentPlayer == 2 && isPlayer2AI) {
2466 float kitchenMinX = TABLE_LEFT + BALL_RADIUS;
2467 float kitchenMaxX = HEADSTRING_X - BALL_RADIUS;
2468 float kitchenMinY = TABLE_TOP + BALL_RADIUS;
2469 float kitchenMaxY = TABLE_BOTTOM - BALL_RADIUS;
2470 bool validPositionFound = false;
2471 int attempts = 0;
2472 while (!validPositionFound && attempts < 100) {
2473 cueBall->x = kitchenMinX + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxX - kitchenMinX)));
2474 cueBall->y = kitchenMinY + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (kitchenMaxY - kitchenMinY)));
2475 if (IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
2476 validPositionFound = true;
2477 }
2478 attempts++;
2479 }
2480 if (!validPositionFound) {
2481 cueBall->x = TABLE_LEFT + (HEADSTRING_X - TABLE_LEFT) * 0.5f;
2482 cueBall->y = TABLE_TOP + TABLE_HEIGHT / 2.0f;
2483 if (!IsValidCueBallPosition(cueBall->x, cueBall->y, true)) {
2484 cueBall->x = HEADSTRING_X - BALL_RADIUS * 2.0f;
2485 cueBall->y = RACK_POS_Y;
2486 }
2487 }
2488 cueBall->vx = 0; cueBall->vy = 0;
2489 return;
2490 }*/
2491 // --- End CPU AI Opening Break Placement ---
2492
2493 // This function is now SOLELY for Ball-In-Hand placement for the AI (anywhere on the table).
2494 // Break placement is handled by AIBreakShot().
2495
2496 // Simple Strategy: Find the easiest possible shot for the AI's ball type
2497 // Place the cue ball directly behind that target ball, aiming straight at a pocket.
2498 // (More advanced: find spot offering multiple options or safety)
2499
2500 AIShotInfo bestPlacementShot = { false };
2501 D2D1_POINT_2F bestPlacePos = D2D1::Point2F(HEADSTRING_X * 0.5f, RACK_POS_Y); // Default placement
2502
2503 // A better default for ball-in-hand (anywhere) might be center table if no shot found.
2504 bestPlacePos = D2D1::Point2F(TABLE_LEFT + TABLE_WIDTH / 2.0f, TABLE_TOP + TABLE_HEIGHT / 2.0f);
2505 float bestPlacementScore = -1.0f; // Keep track of the score for the best placement found
2506
2507 BallType targetType = player2Info.assignedType;
2508 bool canTargetAnyPlacement = false; // Local scope variable for placement logic
2509 if (targetType == BallType::NONE) {
2510 canTargetAnyPlacement = true;
2511 }
2512 bool target8Ball = (!canTargetAnyPlacement && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2513 if (target8Ball) targetType = BallType::EIGHT_BALL;
2514
2515
2516 for (auto& targetBall : balls) {
2517 if (targetBall.isPocketed || targetBall.id == 0) continue;
2518
2519 // Determine if current ball is a valid target for placement consideration
2520 bool currentBallIsValidTarget = false;
2521 if (target8Ball && targetBall.id == 8) currentBallIsValidTarget = true;
2522 else if (canTargetAnyPlacement && targetBall.id != 8) currentBallIsValidTarget = true;
2523 else if (!canTargetAnyPlacement && !target8Ball && targetBall.type == targetType) currentBallIsValidTarget = true;
2524
2525 if (!currentBallIsValidTarget) continue; // Skip if not a valid target
2526
2527 for (int p = 0; p < 6; ++p) {
2528 // Calculate ideal cue ball position: straight line behind target ball aiming at pocket p
2529 float targetToPocketX = pocketPositions[p].x - targetBall.x;
2530 float targetToPocketY = pocketPositions[p].y - targetBall.y;
2531 float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
2532 if (dist < 1.0f) continue; // Avoid division by zero
2533
2534 float idealAngle = atan2f(targetToPocketY, targetToPocketX);
2535 // Place cue ball slightly behind target ball along this line
2536 float placeDist = BALL_RADIUS * 3.0f; // Place a bit behind
2537 D2D1_POINT_2F potentialPlacePos = D2D1::Point2F( // Use factory function
2538 targetBall.x - cosf(idealAngle) * placeDist,
2539 targetBall.y - sinf(idealAngle) * placeDist
2540 );
2541
2542 // Check if this placement is valid (on table, behind headstring if break, not overlapping)
2543 /*bool behindHeadstringRule = (currentGameState == PRE_BREAK_PLACEMENT);*/
2544 // For ball-in-hand (NOT break), behindHeadstringRule is false.
2545 // The currentGameState should be BALL_IN_HAND_P2 when this is called for a foul.
2546 bool behindHeadstringRule = false; // Player can place anywhere after a foul
2547 if (IsValidCueBallPosition(potentialPlacePos.x, potentialPlacePos.y, behindHeadstringRule)) {
2548 // Is path from potentialPlacePos to targetBall clear?
2549 // Use D2D1::Point2F() factory function here
2550 if (IsPathClear(potentialPlacePos, D2D1::Point2F(targetBall.x, targetBall.y), 0, targetBall.id)) {
2551 // Is path from targetBall to pocket clear?
2552 // Use D2D1::Point2F() factory function here
2553 if (IsPathClear(D2D1::Point2F(targetBall.x, targetBall.y), pocketPositions[p], targetBall.id, -1)) {
2554 // This seems like a good potential placement. Score it?
2555 // Easy AI: Just take the first valid one found.
2556 /*bestPlacePos = potentialPlacePos;
2557 goto placement_found;*/ // Use goto for simplicity in non-OOP structure
2558 // This is a possible shot. Score this placement.
2559// A simple score: distance to target ball (shorter is better for placement).
2560// More advanced: consider angle to pocket, difficulty of the shot from this placement.
2561 AIShotInfo tempShotInfo;
2562 tempShotInfo.possible = true;
2563 tempShotInfo.targetBall = &targetBall;
2564 tempShotInfo.pocketIndex = p;
2565 tempShotInfo.ghostBallPos = CalculateGhostBallPos(&targetBall, p); // Not strictly needed for placement score but good for consistency
2566 tempShotInfo.angle = idealAngle; // The angle from the placed ball to target
2567 // Use EvaluateShot's scoring mechanism if possible, or a simpler one here.
2568 float currentScore = 1000.0f / (1.0f + GetDistance(potentialPlacePos.x, potentialPlacePos.y, targetBall.x, targetBall.y)); // Inverse distance
2569
2570 if (currentScore > bestPlacementScore) {
2571 bestPlacementScore = currentScore;
2572 bestPlacePos = potentialPlacePos;
2573 }
2574 }
2575 }
2576 }
2577 }
2578 }
2579
2580placement_found:
2581 // Place the cue ball at the best found position (or default if no good spot found)
2582 cueBall->x = bestPlacePos.x;
2583 cueBall->y = bestPlacePos.y;
2584 cueBall->vx = 0;
2585 cueBall->vy = 0;
2586}
2587
2588
2589// AI finds the best shot available on the table
2590AIShotInfo AIFindBestShot() {
2591 AIShotInfo bestShotOverall = { false };
2592 Ball* cueBall = GetCueBall();
2593 if (!cueBall) return bestShotOverall;
2594 // Ensure cue ball position is up-to-date if AI just placed it
2595 // (AIPlaceCueBall should have already set cueBall->x, cueBall->y)
2596
2597 // Determine target ball type for AI (Player 2)
2598 BallType targetType = player2Info.assignedType;
2599 bool canTargetAny = false; // Can AI hit any ball (e.g., after break, before assignment)?
2600 if (targetType == BallType::NONE) {
2601 // If colors not assigned, AI aims to pocket *something* (usually lowest numbered ball legally)
2602 // Or, more simply, treat any ball as a potential target to make *a* pocket
2603 canTargetAny = true; // Simplification: allow targeting any non-8 ball.
2604 // A better rule is hit lowest numbered ball first on break follow-up.
2605 }
2606
2607 // Check if AI needs to shoot the 8-ball
2608 bool target8Ball = (!canTargetAny && targetType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2609
2610
2611 // Iterate through all potential target balls
2612 for (auto& potentialTarget : balls) {
2613 if (potentialTarget.isPocketed || potentialTarget.id == 0) continue; // Skip pocketed and cue ball
2614
2615 // Check if this ball is a valid target
2616 bool isValidTarget = false;
2617 if (target8Ball) {
2618 isValidTarget = (potentialTarget.id == 8);
2619 }
2620 else if (canTargetAny) {
2621 isValidTarget = (potentialTarget.id != 8); // Can hit any non-8 ball
2622 }
2623 else { // Colors assigned, not yet shooting 8-ball
2624 isValidTarget = (potentialTarget.type == targetType);
2625 }
2626
2627 if (!isValidTarget) continue; // Skip if not a valid target for this turn
2628
2629 // Now, check all pockets for this target ball
2630 for (int p = 0; p < 6; ++p) {
2631 AIShotInfo currentShot = EvaluateShot(&potentialTarget, p);
2632 currentShot.involves8Ball = (potentialTarget.id == 8);
2633
2634 if (currentShot.possible) {
2635 // Compare scores to find the best shot
2636 if (!bestShotOverall.possible || currentShot.score > bestShotOverall.score) {
2637 bestShotOverall = currentShot;
2638 }
2639 }
2640 }
2641 } // End loop through potential target balls
2642
2643 // If targeting 8-ball and no shot found, or targeting own balls and no shot found,
2644 // need a safety strategy. Current simple AI just takes best found or taps cue ball.
2645
2646 return bestShotOverall;
2647}
2648
2649
2650// Evaluate a potential shot at a specific target ball towards a specific pocket
2651AIShotInfo EvaluateShot(Ball* targetBall, int pocketIndex) {
2652 AIShotInfo shotInfo;
2653 shotInfo.possible = false; // Assume not possible initially
2654 shotInfo.targetBall = targetBall;
2655 shotInfo.pocketIndex = pocketIndex;
2656
2657 Ball* cueBall = GetCueBall();
2658 if (!cueBall || !targetBall) return shotInfo;
2659
2660 // --- Define local state variables needed for legality checks ---
2661 BallType aiAssignedType = player2Info.assignedType;
2662 bool canTargetAny = (aiAssignedType == BallType::NONE); // Can AI hit any ball?
2663 bool mustTarget8Ball = (!canTargetAny && aiAssignedType != BallType::NONE && player2Info.ballsPocketedCount >= 7);
2664 // ---
2665
2666 // 1. Calculate Ghost Ball position
2667 shotInfo.ghostBallPos = CalculateGhostBallPos(targetBall, pocketIndex);
2668
2669 // 2. Calculate Angle from Cue Ball to Ghost Ball
2670 float dx = shotInfo.ghostBallPos.x - cueBall->x;
2671 float dy = shotInfo.ghostBallPos.y - cueBall->y;
2672 if (fabs(dx) < 0.01f && fabs(dy) < 0.01f) return shotInfo; // Avoid aiming at same spot
2673 shotInfo.angle = atan2f(dy, dx);
2674
2675 // Basic angle validity check (optional)
2676 if (!IsValidAIAimAngle(shotInfo.angle)) {
2677 // Maybe log this or handle edge cases
2678 }
2679
2680 // 3. Check Path: Cue Ball -> Ghost Ball Position
2681 // Use D2D1::Point2F() factory function here
2682 if (!IsPathClear(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.ghostBallPos, cueBall->id, targetBall->id)) {
2683 return shotInfo; // Path blocked
2684 }
2685
2686 // 4. Check Path: Target Ball -> Pocket
2687 // Use D2D1::Point2F() factory function here
2688 if (!IsPathClear(D2D1::Point2F(targetBall->x, targetBall->y), pocketPositions[pocketIndex], targetBall->id, -1)) {
2689 return shotInfo; // Path blocked
2690 }
2691
2692 // 5. Check First Ball Hit Legality
2693 float firstHitDistSq = -1.0f;
2694 // Use D2D1::Point2F() factory function here
2695 Ball* firstHit = FindFirstHitBall(D2D1::Point2F(cueBall->x, cueBall->y), shotInfo.angle, firstHitDistSq);
2696
2697 if (!firstHit) {
2698 return shotInfo; // AI aims but doesn't hit anything? Impossible shot.
2699 }
2700
2701 // Check if the first ball hit is the intended target ball
2702 if (firstHit->id != targetBall->id) {
2703 // Allow hitting slightly off target if it's very close to ghost ball pos
2704 float ghostDistSq = GetDistanceSq(shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y, firstHit->x, firstHit->y);
2705 // Allow a tolerance roughly half the ball radius squared
2706 if (ghostDistSq > (BALL_RADIUS * 0.7f) * (BALL_RADIUS * 0.7f)) {
2707 // First hit is significantly different from the target point.
2708 // This shot path leads to hitting the wrong ball first.
2709 return shotInfo; // Foul or unintended shot
2710 }
2711 // If first hit is not target, but very close, allow it for now (might still be foul based on type).
2712 }
2713
2714 // Check legality of the *first ball actually hit* based on game rules
2715 if (!canTargetAny) { // Colors are assigned (or should be)
2716 if (mustTarget8Ball) { // Must hit 8-ball first
2717 if (firstHit->id != 8) {
2718 // return shotInfo; // FOUL - Hitting wrong ball when aiming for 8-ball
2719 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
2720 }
2721 }
2722 else { // Must hit own ball type first
2723 if (firstHit->type != aiAssignedType && firstHit->id != 8) { // Allow hitting 8-ball if own type blocked? No, standard rules usually require hitting own first.
2724 // return shotInfo; // FOUL - Hitting opponent ball or 8-ball when shouldn't
2725 // Keep shot possible for now, rely on AIFindBestShot to prioritize legal ones
2726 }
2727 else if (firstHit->id == 8) {
2728 // return shotInfo; // FOUL - Hitting 8-ball when shouldn't
2729 // Keep shot possible for now
2730 }
2731 }
2732 }
2733 // (If canTargetAny is true, hitting any ball except 8 first is legal - assuming not scratching)
2734
2735
2736 // 6. Calculate Score & Power (Difficulty affects this)
2737 shotInfo.possible = true; // If we got here, the shot is geometrically possible and likely legal enough for AI to consider
2738
2739 float cueToGhostDist = GetDistance(cueBall->x, cueBall->y, shotInfo.ghostBallPos.x, shotInfo.ghostBallPos.y);
2740 float targetToPocketDist = GetDistance(targetBall->x, targetBall->y, pocketPositions[pocketIndex].x, pocketPositions[pocketIndex].y);
2741
2742 // Simple Score: Shorter shots are better, straighter shots are slightly better.
2743 float distanceScore = 1000.0f / (1.0f + cueToGhostDist + targetToPocketDist);
2744
2745 // Angle Score: Calculate cut angle
2746 // Vector Cue -> Ghost
2747 float v1x = shotInfo.ghostBallPos.x - cueBall->x;
2748 float v1y = shotInfo.ghostBallPos.y - cueBall->y;
2749 // Vector Target -> Pocket
2750 float v2x = pocketPositions[pocketIndex].x - targetBall->x;
2751 float v2y = pocketPositions[pocketIndex].y - targetBall->y;
2752 // Normalize vectors
2753 float mag1 = sqrtf(v1x * v1x + v1y * v1y);
2754 float mag2 = sqrtf(v2x * v2x + v2y * v2y);
2755 float angleScoreFactor = 0.5f; // Default if vectors are zero len
2756 if (mag1 > 0.1f && mag2 > 0.1f) {
2757 v1x /= mag1; v1y /= mag1;
2758 v2x /= mag2; v2y /= mag2;
2759 // Dot product gives cosine of angle between cue ball path and target ball path
2760 float dotProduct = v1x * v2x + v1y * v2y;
2761 // Straighter shot (dot product closer to 1) gets higher score
2762 angleScoreFactor = (1.0f + dotProduct) / 2.0f; // Map [-1, 1] to [0, 1]
2763 }
2764 angleScoreFactor = std::max(0.1f, angleScoreFactor); // Ensure some minimum score factor
2765
2766 shotInfo.score = distanceScore * angleScoreFactor;
2767
2768 // Bonus for pocketing 8-ball legally
2769 if (mustTarget8Ball && targetBall->id == 8) {
2770 shotInfo.score *= 10.0; // Strongly prefer the winning shot
2771 }
2772
2773 // Penalty for difficult cuts? Already partially handled by angleScoreFactor.
2774
2775 // 7. Calculate Power
2776 shotInfo.power = CalculateShotPower(cueToGhostDist, targetToPocketDist);
2777
2778 // 8. Add Inaccuracy based on Difficulty (same as before)
2779 float angleError = 0.0f;
2780 float powerErrorFactor = 1.0f;
2781
2782 switch (aiDifficulty) {
2783 case EASY:
2784 angleError = (float)(rand() % 100 - 50) / 1000.0f; // +/- ~3 deg
2785 powerErrorFactor = 0.8f + (float)(rand() % 40) / 100.0f; // 80-120%
2786 shotInfo.power *= 0.8f;
2787 break;
2788 case MEDIUM:
2789 angleError = (float)(rand() % 60 - 30) / 1000.0f; // +/- ~1.7 deg
2790 powerErrorFactor = 0.9f + (float)(rand() % 20) / 100.0f; // 90-110%
2791 break;
2792 case HARD:
2793 angleError = (float)(rand() % 10 - 5) / 1000.0f; // +/- ~0.3 deg
2794 powerErrorFactor = 0.98f + (float)(rand() % 4) / 100.0f; // 98-102%
2795 break;
2796 }
2797 shotInfo.angle += angleError;
2798 shotInfo.power *= powerErrorFactor;
2799 shotInfo.power = std::max(1.0f, std::min(shotInfo.power, MAX_SHOT_POWER)); // Clamp power
2800
2801 return shotInfo;
2802}
2803
2804
2805// Calculates required power (simplified)
2806float CalculateShotPower(float cueToGhostDist, float targetToPocketDist) {
2807 // Basic model: Power needed increases with total distance the balls need to travel.
2808 // Need enough power for cue ball to reach target AND target to reach pocket.
2809 float totalDist = cueToGhostDist + targetToPocketDist;
2810
2811 // Map distance to power (needs tuning)
2812 // Let's say max power is needed for longest possible shot (e.g., corner to corner ~ 1000 units)
2813 float powerRatio = std::min(1.0f, totalDist / 800.0f); // Normalize based on estimated max distance
2814
2815 float basePower = MAX_SHOT_POWER * 0.2f; // Minimum power to move balls reliably
2816 float variablePower = (MAX_SHOT_POWER * 0.8f) * powerRatio; // Scale remaining power range
2817
2818 // Harder AI could adjust based on desired cue ball travel (more power for draw/follow)
2819 return std::min(MAX_SHOT_POWER, basePower + variablePower);
2820}
2821
2822// Calculate the position the cue ball needs to hit for the target ball to go towards the pocket
2823D2D1_POINT_2F CalculateGhostBallPos(Ball* targetBall, int pocketIndex) {
2824 float targetToPocketX = pocketPositions[pocketIndex].x - targetBall->x;
2825 float targetToPocketY = pocketPositions[pocketIndex].y - targetBall->y;
2826 float dist = sqrtf(targetToPocketX * targetToPocketX + targetToPocketY * targetToPocketY);
2827
2828 if (dist < 1.0f) { // Target is basically in the pocket
2829 // Aim slightly off-center to avoid weird physics? Or directly at center?
2830 // For simplicity, return a point slightly behind center along the reverse line.
2831 return D2D1::Point2F(targetBall->x - targetToPocketX * 0.1f, targetBall->y - targetToPocketY * 0.1f);
2832 }
2833
2834 // Normalize direction vector from target to pocket
2835 float nx = targetToPocketX / dist;
2836 float ny = targetToPocketY / dist;
2837
2838 // Ghost ball position is diameter distance *behind* the target ball along this line
2839 float ghostX = targetBall->x - nx * (BALL_RADIUS * 2.0f);
2840 float ghostY = targetBall->y - ny * (BALL_RADIUS * 2.0f);
2841
2842 return D2D1::Point2F(ghostX, ghostY);
2843}
2844
2845// Checks if line segment is clear of obstructing balls
2846bool IsPathClear(D2D1_POINT_2F start, D2D1_POINT_2F end, int ignoredBallId1, int ignoredBallId2) {
2847 float dx = end.x - start.x;
2848 float dy = end.y - start.y;
2849 float segmentLenSq = dx * dx + dy * dy;
2850
2851 if (segmentLenSq < 0.01f) return true; // Start and end are same point
2852
2853 for (const auto& ball : balls) {
2854 if (ball.isPocketed) continue;
2855 if (ball.id == ignoredBallId1) continue;
2856 if (ball.id == ignoredBallId2) continue;
2857
2858 // Check distance from ball center to the line segment
2859 float ballToStartX = ball.x - start.x;
2860 float ballToStartY = ball.y - start.y;
2861
2862 // Project ball center onto the line defined by the segment
2863 float dot = (ballToStartX * dx + ballToStartY * dy) / segmentLenSq;
2864
2865 D2D1_POINT_2F closestPointOnLine;
2866 if (dot < 0) { // Closest point is start point
2867 closestPointOnLine = start;
2868 }
2869 else if (dot > 1) { // Closest point is end point
2870 closestPointOnLine = end;
2871 }
2872 else { // Closest point is along the segment
2873 closestPointOnLine = D2D1::Point2F(start.x + dot * dx, start.y + dot * dy);
2874 }
2875
2876 // Check if the closest point is within collision distance (ball radius + path radius)
2877 if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * BALL_RADIUS)) {
2878 // Consider slightly wider path check? Maybe BALL_RADIUS * 1.1f?
2879 // if (GetDistanceSq(ball.x, ball.y, closestPointOnLine.x, closestPointOnLine.y) < (BALL_RADIUS * 1.1f)*(BALL_RADIUS*1.1f)) {
2880 return false; // Path is blocked
2881 }
2882 }
2883 return true; // No obstructions found
2884}
2885
2886// Finds the first ball hit along a path (simplified)
2887Ball* FindFirstHitBall(D2D1_POINT_2F start, float angle, float& hitDistSq) {
2888 Ball* hitBall = nullptr;
2889 hitDistSq = -1.0f; // Initialize hit distance squared
2890 float minCollisionDistSq = -1.0f;
2891
2892 float cosA = cosf(angle);
2893 float sinA = sinf(angle);
2894
2895 for (auto& ball : balls) {
2896 if (ball.isPocketed || ball.id == 0) continue; // Skip cue ball and pocketed
2897
2898 float dx = ball.x - start.x;
2899 float dy = ball.y - start.y;
2900
2901 // Project vector from start->ball onto the aim direction vector
2902 float dot = dx * cosA + dy * sinA;
2903
2904 if (dot > 0) { // Ball is generally in front
2905 // Find closest point on aim line to the ball's center
2906 float closestPointX = start.x + dot * cosA;
2907 float closestPointY = start.y + dot * sinA;
2908 float distSq = GetDistanceSq(ball.x, ball.y, closestPointX, closestPointY);
2909
2910 // Check if the aim line passes within the ball's radius
2911 if (distSq < (BALL_RADIUS * BALL_RADIUS)) {
2912 // Calculate distance from start to the collision point on the ball's circumference
2913 float backDist = sqrtf(std::max(0.f, BALL_RADIUS * BALL_RADIUS - distSq));
2914 float collisionDist = dot - backDist; // Distance along aim line to collision
2915
2916 if (collisionDist > 0) { // Ensure collision is in front
2917 float collisionDistSq = collisionDist * collisionDist;
2918 if (hitBall == nullptr || collisionDistSq < minCollisionDistSq) {
2919 minCollisionDistSq = collisionDistSq;
2920 hitBall = &ball; // Found a closer hit ball
2921 }
2922 }
2923 }
2924 }
2925 }
2926 hitDistSq = minCollisionDistSq; // Return distance squared to the first hit
2927 return hitBall;
2928}
2929
2930// Basic check for reasonable AI aim angles (optional)
2931bool IsValidAIAimAngle(float angle) {
2932 // Placeholder - could check for NaN or infinity if calculations go wrong
2933 return isfinite(angle);
2934}
2935
2936//midi func = start
2937void PlayMidiInBackground(HWND hwnd, const TCHAR* midiPath) {
2938 while (isMusicPlaying) {
2939 MCI_OPEN_PARMS mciOpen = { 0 };
2940 mciOpen.lpstrDeviceType = TEXT("sequencer");
2941 mciOpen.lpstrElementName = midiPath;
2942
2943 if (mciSendCommand(0, MCI_OPEN, MCI_OPEN_TYPE | MCI_OPEN_ELEMENT, (DWORD_PTR)&mciOpen) == 0) {
2944 midiDeviceID = mciOpen.wDeviceID;
2945
2946 MCI_PLAY_PARMS mciPlay = { 0 };
2947 mciSendCommand(midiDeviceID, MCI_PLAY, 0, (DWORD_PTR)&mciPlay);
2948
2949 // Wait for playback to complete
2950 MCI_STATUS_PARMS mciStatus = { 0 };
2951 mciStatus.dwItem = MCI_STATUS_MODE;
2952
2953 do {
2954 mciSendCommand(midiDeviceID, MCI_STATUS, MCI_STATUS_ITEM, (DWORD_PTR)&mciStatus);
2955 Sleep(100); // adjust as needed
2956 } while (mciStatus.dwReturn == MCI_MODE_PLAY && isMusicPlaying);
2957
2958 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
2959 midiDeviceID = 0;
2960 }
2961 }
2962}
2963
2964void StartMidi(HWND hwnd, const TCHAR* midiPath) {
2965 if (isMusicPlaying) {
2966 StopMidi();
2967 }
2968 isMusicPlaying = true;
2969 musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
2970}
2971
2972void StopMidi() {
2973 if (isMusicPlaying) {
2974 isMusicPlaying = false;
2975 if (musicThread.joinable()) musicThread.join();
2976 if (midiDeviceID != 0) {
2977 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
2978 midiDeviceID = 0;
2979 }
2980 }
2981}
2982
2983/*void PlayGameMusic(HWND hwnd) {
2984 // Stop any existing playback
2985 if (isMusicPlaying) {
2986 isMusicPlaying = false;
2987 if (musicThread.joinable()) {
2988 musicThread.join();
2989 }
2990 if (midiDeviceID != 0) {
2991 mciSendCommand(midiDeviceID, MCI_CLOSE, 0, NULL);
2992 midiDeviceID = 0;
2993 }
2994 }
2995
2996 // Get the path of the executable
2997 TCHAR exePath[MAX_PATH];
2998 GetModuleFileName(NULL, exePath, MAX_PATH);
2999
3000 // Extract the directory path
3001 TCHAR* lastBackslash = _tcsrchr(exePath, '\\');
3002 if (lastBackslash != NULL) {
3003 *(lastBackslash + 1) = '\0';
3004 }
3005
3006 // Construct the full path to the MIDI file
3007 static TCHAR midiPath[MAX_PATH];
3008 _tcscpy_s(midiPath, MAX_PATH, exePath);
3009 _tcscat_s(midiPath, MAX_PATH, TEXT("BSQ.MID"));
3010
3011 // Start the background playback
3012 isMusicPlaying = true;
3013 musicThread = std::thread(PlayMidiInBackground, hwnd, midiPath);
3014}*/
3015//midi func = end
3016
3017// --- Drawing Functions ---
3018
3019void OnPaint() {
3020 HRESULT hr = CreateDeviceResources(); // Ensure resources are valid
3021
3022 if (SUCCEEDED(hr)) {
3023 pRenderTarget->BeginDraw();
3024 DrawScene(pRenderTarget); // Pass render target
3025 hr = pRenderTarget->EndDraw();
3026
3027 if (hr == D2DERR_RECREATE_TARGET) {
3028 DiscardDeviceResources();
3029 // Optionally request another paint message: InvalidateRect(hwndMain, NULL, FALSE);
3030 // But the timer loop will trigger redraw anyway.
3031 }
3032 }
3033 // If CreateDeviceResources failed, EndDraw might not be called.
3034 // Consider handling this more robustly if needed.
3035}
3036
3037void DrawScene(ID2D1RenderTarget* pRT) {
3038 if (!pRT) return;
3039
3040 //pRT->Clear(D2D1::ColorF(D2D1::ColorF::LightGray)); // Background color
3041 // Set background color to #ffffcd (RGB: 255, 255, 205)
3042 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)
3043 //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)
3044
3045 DrawTable(pRT, pFactory);
3046 DrawPocketSelectionIndicator(pRT); // Draw arrow over selected/called pocket
3047 DrawBalls(pRT);
3048 DrawAimingAids(pRT); // Includes cue stick if aiming
3049 DrawUI(pRT);
3050 DrawPowerMeter(pRT);
3051 DrawSpinIndicator(pRT);
3052 DrawPocketedBallsIndicator(pRT);
3053 DrawBallInHandIndicator(pRT); // Draw cue ball ghost if placing
3054
3055 // Draw Game Over Message
3056 if (currentGameState == GAME_OVER && pTextFormat) {
3057 ID2D1SolidColorBrush* pBrush = nullptr;
3058 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pBrush);
3059 if (pBrush) {
3060 D2D1_RECT_F layoutRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP + TABLE_HEIGHT / 2 - 30, TABLE_RIGHT, TABLE_TOP + TABLE_HEIGHT / 2 + 30);
3061 pRT->DrawText(
3062 gameOverMessage.c_str(),
3063 (UINT32)gameOverMessage.length(),
3064 pTextFormat, // Use large format maybe?
3065 &layoutRect,
3066 pBrush
3067 );
3068 SafeRelease(&pBrush);
3069 }
3070 }
3071
3072}
3073
3074void DrawTable(ID2D1RenderTarget* pRT, ID2D1Factory* pFactory) {
3075 ID2D1SolidColorBrush* pBrush = nullptr;
3076
3077 // === Draw Full Orange Frame (Table Border) ===
3078 ID2D1SolidColorBrush* pFrameBrush = nullptr;
3079 pRT->CreateSolidColorBrush(D2D1::ColorF(0.9157f, 0.6157f, 0.2000f), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
3080 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pFrameBrush); //NEWCOLOR ::Orange (no brackets) => (0.9157, 0.6157, 0.2000)
3081 if (pFrameBrush) {
3082 D2D1_RECT_F outerRect = D2D1::RectF(
3083 TABLE_LEFT - CUSHION_THICKNESS,
3084 TABLE_TOP - CUSHION_THICKNESS,
3085 TABLE_RIGHT + CUSHION_THICKNESS,
3086 TABLE_BOTTOM + CUSHION_THICKNESS
3087 );
3088 pRT->FillRectangle(&outerRect, pFrameBrush);
3089 SafeRelease(&pFrameBrush);
3090 }
3091
3092 // Draw Table Bed (Green Felt)
3093 pRT->CreateSolidColorBrush(TABLE_COLOR, &pBrush);
3094 if (!pBrush) return;
3095 D2D1_RECT_F tableRect = D2D1::RectF(TABLE_LEFT, TABLE_TOP, TABLE_RIGHT, TABLE_BOTTOM);
3096 pRT->FillRectangle(&tableRect, pBrush);
3097 SafeRelease(&pBrush);
3098
3099 // Draw Cushions (Red Border)
3100 pRT->CreateSolidColorBrush(CUSHION_COLOR, &pBrush);
3101 if (!pBrush) return;
3102 // Top Cushion (split by middle pocket)
3103 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
3104 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_TOP - CUSHION_THICKNESS, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_TOP), pBrush);
3105 // Bottom Cushion (split by middle pocket)
3106 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_LEFT + TABLE_WIDTH / 2.f - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
3107 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT + TABLE_WIDTH / 2.f + HOLE_VISUAL_RADIUS, TABLE_BOTTOM, TABLE_RIGHT - HOLE_VISUAL_RADIUS, TABLE_BOTTOM + CUSHION_THICKNESS), pBrush);
3108 // Left Cushion
3109 pRT->FillRectangle(D2D1::RectF(TABLE_LEFT - CUSHION_THICKNESS, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_LEFT, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
3110 // Right Cushion
3111 pRT->FillRectangle(D2D1::RectF(TABLE_RIGHT, TABLE_TOP + HOLE_VISUAL_RADIUS, TABLE_RIGHT + CUSHION_THICKNESS, TABLE_BOTTOM - HOLE_VISUAL_RADIUS), pBrush);
3112 SafeRelease(&pBrush);
3113
3114
3115 // Draw Pockets (Black Circles)
3116 pRT->CreateSolidColorBrush(POCKET_COLOR, &pBrush);
3117 if (!pBrush) return;
3118 for (int i = 0; i < 6; ++i) {
3119 D2D1_ELLIPSE ellipse = D2D1::Ellipse(pocketPositions[i], HOLE_VISUAL_RADIUS, HOLE_VISUAL_RADIUS);
3120 pRT->FillEllipse(&ellipse, pBrush);
3121 }
3122 SafeRelease(&pBrush);
3123
3124 // Draw Headstring Line (White)
3125 pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
3126 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pBrush); // NEWCOLOR ::White => (0.2784, 0.4549, 0.1843)
3127 if (!pBrush) return;
3128 pRT->DrawLine(
3129 D2D1::Point2F(HEADSTRING_X, TABLE_TOP),
3130 D2D1::Point2F(HEADSTRING_X, TABLE_BOTTOM),
3131 pBrush,
3132 1.0f // Line thickness
3133 );
3134 SafeRelease(&pBrush);
3135
3136 // Draw Semicircle facing West (flat side East)
3137 // Draw Semicircle facing East (curved side on the East, flat side on the West)
3138 ID2D1PathGeometry* pGeometry = nullptr;
3139 HRESULT hr = pFactory->CreatePathGeometry(&pGeometry);
3140 if (SUCCEEDED(hr) && pGeometry)
3141 {
3142 ID2D1GeometrySink* pSink = nullptr;
3143 hr = pGeometry->Open(&pSink);
3144 if (SUCCEEDED(hr) && pSink)
3145 {
3146 float radius = 60.0f; // Radius for the semicircle
3147 D2D1_POINT_2F center = D2D1::Point2F(HEADSTRING_X, (TABLE_TOP + TABLE_BOTTOM) / 2.0f);
3148
3149 // For a semicircle facing East (curved side on the East), use the top and bottom points.
3150 D2D1_POINT_2F startPoint = D2D1::Point2F(center.x, center.y - radius); // Top point
3151
3152 pSink->BeginFigure(startPoint, D2D1_FIGURE_BEGIN_HOLLOW);
3153
3154 D2D1_ARC_SEGMENT arc = {};
3155 arc.point = D2D1::Point2F(center.x, center.y + radius); // Bottom point
3156 arc.size = D2D1::SizeF(radius, radius);
3157 arc.rotationAngle = 0.0f;
3158 // Use the correct identifier with the extra underscore:
3159 arc.sweepDirection = D2D1_SWEEP_DIRECTION_COUNTER_CLOCKWISE;
3160 arc.arcSize = D2D1_ARC_SIZE_SMALL;
3161
3162 pSink->AddArc(&arc);
3163 pSink->EndFigure(D2D1_FIGURE_END_OPEN);
3164 pSink->Close();
3165 SafeRelease(&pSink);
3166
3167 ID2D1SolidColorBrush* pArcBrush = nullptr;
3168 //pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.3f), &pArcBrush);
3169 pRT->CreateSolidColorBrush(D2D1::ColorF(0.4235f, 0.5647f, 0.1765f, 1.0f), &pArcBrush);
3170 if (pArcBrush)
3171 {
3172 pRT->DrawGeometry(pGeometry, pArcBrush, 1.5f);
3173 SafeRelease(&pArcBrush);
3174 }
3175 }
3176 SafeRelease(&pGeometry);
3177 }
3178
3179
3180
3181
3182}
3183
3184
3185void DrawBalls(ID2D1RenderTarget* pRT) {
3186 ID2D1SolidColorBrush* pBrush = nullptr;
3187 ID2D1SolidColorBrush* pStripeBrush = nullptr; // For stripe pattern
3188
3189 pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBrush); // Placeholder
3190 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
3191
3192 if (!pBrush || !pStripeBrush) {
3193 SafeRelease(&pBrush);
3194 SafeRelease(&pStripeBrush);
3195 return;
3196 }
3197
3198
3199 for (size_t i = 0; i < balls.size(); ++i) {
3200 const Ball& b = balls[i];
3201 if (!b.isPocketed) {
3202 D2D1_ELLIPSE ellipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS, BALL_RADIUS);
3203
3204 // Set main ball color
3205 pBrush->SetColor(b.color);
3206 pRT->FillEllipse(&ellipse, pBrush);
3207
3208 // Draw Stripe if applicable
3209 if (b.type == BallType::STRIPE) {
3210 // Draw a white band across the middle (simplified stripe)
3211 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);
3212 // Need to clip this rectangle to the ellipse bounds - complex!
3213 // Alternative: Draw two colored arcs leaving a white band.
3214 // Simplest: Draw a white circle inside, slightly smaller.
3215 D2D1_ELLIPSE innerEllipse = D2D1::Ellipse(D2D1::Point2F(b.x, b.y), BALL_RADIUS * 0.6f, BALL_RADIUS * 0.6f);
3216 pRT->FillEllipse(innerEllipse, pStripeBrush); // White center part
3217 pBrush->SetColor(b.color); // Set back to stripe color
3218 pRT->FillEllipse(innerEllipse, pBrush); // Fill again, leaving a ring - No, this isn't right.
3219
3220 // Let's try drawing a thick white line across
3221 // This doesn't look great. Just drawing solid red for stripes for now.
3222 }
3223
3224 // Draw Number (Optional - requires more complex text layout or pre-rendered textures)
3225 // if (b.id != 0 && pTextFormat) {
3226 // std::wstring numStr = std::to_wstring(b.id);
3227 // D2D1_RECT_F textRect = D2D1::RectF(b.x - BALL_RADIUS, b.y - BALL_RADIUS, b.x + BALL_RADIUS, b.y + BALL_RADIUS);
3228 // ID2D1SolidColorBrush* pNumBrush = nullptr;
3229 // D2D1_COLOR_F numCol = (b.type == BallType::SOLID || b.id == 8) ? D2D1::ColorF(D2D1::ColorF::Black) : D2D1::ColorF(D2D1::ColorF::White);
3230 // pRT->CreateSolidColorBrush(numCol, &pNumBrush);
3231 // // Create a smaller text format...
3232 // // pRT->DrawText(numStr.c_str(), numStr.length(), pSmallTextFormat, &textRect, pNumBrush);
3233 // SafeRelease(&pNumBrush);
3234 // }
3235 }
3236 }
3237
3238 SafeRelease(&pBrush);
3239 SafeRelease(&pStripeBrush);
3240}
3241
3242
3243void DrawAimingAids(ID2D1RenderTarget* pRT) {
3244 // Condition check at start (Unchanged)
3245 //if (currentGameState != PLAYER1_TURN && currentGameState != PLAYER2_TURN &&
3246 //currentGameState != BREAKING && currentGameState != AIMING)
3247 //{
3248 //return;
3249 //}
3250 // NEW Condition: Allow drawing if it's a human player's active turn/aiming/breaking,
3251 // OR if it's AI's turn and it's in AI_THINKING state (calculating) or BREAKING (aiming break).
3252 bool isHumanInteracting = (!isPlayer2AI || currentPlayer == 1) &&
3253 (currentGameState == PLAYER1_TURN || currentGameState == PLAYER2_TURN ||
3254 currentGameState == BREAKING || currentGameState == AIMING);
3255 // AI_THINKING state is when AI calculates shot. AIMakeDecision sets cueAngle/shotPower.
3256 // Also include BREAKING state if it's AI's turn and isOpeningBreakShot for break aim visualization.
3257 // NEW Condition: AI is displaying its aim
3258 bool isAiVisualizingShot = (isPlayer2AI && currentPlayer == 2 &&
3259 currentGameState == AI_THINKING && aiIsDisplayingAim);
3260
3261 if (!isHumanInteracting && !(isAiVisualizingShot || (currentGameState == AI_THINKING && aiIsDisplayingAim))) {
3262 return;
3263 }
3264
3265 Ball* cueBall = GetCueBall();
3266 if (!cueBall || cueBall->isPocketed) return; // Don't draw if cue ball is gone
3267
3268 ID2D1SolidColorBrush* pBrush = nullptr;
3269 ID2D1SolidColorBrush* pGhostBrush = nullptr;
3270 ID2D1StrokeStyle* pDashedStyle = nullptr;
3271 ID2D1SolidColorBrush* pCueBrush = nullptr;
3272 ID2D1SolidColorBrush* pReflectBrush = nullptr; // Brush for reflection line
3273
3274 // Ensure render target is valid
3275 if (!pRT) return;
3276
3277 // Create Brushes and Styles (check for failures)
3278 HRESULT hr;
3279 hr = pRT->CreateSolidColorBrush(AIM_LINE_COLOR, &pBrush);
3280 if FAILED(hr) { SafeRelease(&pBrush); return; }
3281 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.5f), &pGhostBrush);
3282 if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); return; }
3283 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0.6f, 0.4f, 0.2f), &pCueBrush);
3284 if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); return; }
3285 // Create reflection brush (e.g., lighter shade or different color)
3286 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::LightCyan, 0.6f), &pReflectBrush);
3287 if FAILED(hr) { SafeRelease(&pBrush); SafeRelease(&pGhostBrush); SafeRelease(&pCueBrush); SafeRelease(&pReflectBrush); return; }
3288 // Create a Cyan brush for primary and secondary lines //orig(75.0f / 255.0f, 0.0f, 130.0f / 255.0f);indigoColor
3289 D2D1::ColorF cyanColor(0.0, 255.0, 255.0, 255.0f);
3290 ID2D1SolidColorBrush* pCyanBrush = nullptr;
3291 hr = pRT->CreateSolidColorBrush(cyanColor, &pCyanBrush);
3292 if (FAILED(hr)) {
3293 SafeRelease(&pCyanBrush);
3294 // handle error if needed
3295 }
3296 // Create a Purple brush for primary and secondary lines
3297 D2D1::ColorF purpleColor(255.0f, 0.0f, 255.0f, 255.0f);
3298 ID2D1SolidColorBrush* pPurpleBrush = nullptr;
3299 hr = pRT->CreateSolidColorBrush(purpleColor, &pPurpleBrush);
3300 if (FAILED(hr)) {
3301 SafeRelease(&pPurpleBrush);
3302 // handle error if needed
3303 }
3304
3305 if (pFactory) {
3306 D2D1_STROKE_STYLE_PROPERTIES strokeProps = D2D1::StrokeStyleProperties();
3307 strokeProps.dashStyle = D2D1_DASH_STYLE_DASH;
3308 hr = pFactory->CreateStrokeStyle(&strokeProps, nullptr, 0, &pDashedStyle);
3309 if FAILED(hr) { pDashedStyle = nullptr; }
3310 }
3311
3312
3313 // --- Cue Stick Drawing (Unchanged from previous fix) ---
3314 const float baseStickLength = 150.0f;
3315 const float baseStickThickness = 4.0f;
3316 float stickLength = baseStickLength * 1.4f;
3317 float stickThickness = baseStickThickness * 1.5f;
3318 float stickAngle = cueAngle + PI;
3319 float powerOffset = 0.0f;
3320 //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
3321 // Show power offset if human is aiming/dragging, or if AI is preparing its shot (AI_THINKING or AI Break)
3322 if ((isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) || isAiVisualizingShot) { // Use the new condition
3323 powerOffset = shotPower * 5.0f;
3324 }
3325 D2D1_POINT_2F cueStickEnd = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (stickLength + powerOffset), cueBall->y + sinf(stickAngle) * (stickLength + powerOffset));
3326 D2D1_POINT_2F cueStickTip = D2D1::Point2F(cueBall->x + cosf(stickAngle) * (powerOffset + 5.0f), cueBall->y + sinf(stickAngle) * (powerOffset + 5.0f));
3327 pRT->DrawLine(cueStickTip, cueStickEnd, pCueBrush, stickThickness);
3328
3329
3330 // --- Projection Line Calculation ---
3331 float cosA = cosf(cueAngle);
3332 float sinA = sinf(cueAngle);
3333 float rayLength = TABLE_WIDTH + TABLE_HEIGHT; // Ensure ray is long enough
3334 D2D1_POINT_2F rayStart = D2D1::Point2F(cueBall->x, cueBall->y);
3335 D2D1_POINT_2F rayEnd = D2D1::Point2F(rayStart.x + cosA * rayLength, rayStart.y + sinA * rayLength);
3336
3337 // Find the first ball hit by the aiming ray
3338 Ball* hitBall = nullptr;
3339 float firstHitDistSq = -1.0f;
3340 D2D1_POINT_2F ballCollisionPoint = { 0, 0 }; // Point on target ball circumference
3341 D2D1_POINT_2F ghostBallPosForHit = { 0, 0 }; // Ghost ball pos for the hit ball
3342
3343 hitBall = FindFirstHitBall(rayStart, cueAngle, firstHitDistSq);
3344 if (hitBall) {
3345 // Calculate the point on the target ball's circumference
3346 float collisionDist = sqrtf(firstHitDistSq);
3347 ballCollisionPoint = D2D1::Point2F(rayStart.x + cosA * collisionDist, rayStart.y + sinA * collisionDist);
3348 // Calculate ghost ball position for this specific hit (used for projection consistency)
3349 ghostBallPosForHit = D2D1::Point2F(hitBall->x - cosA * BALL_RADIUS, hitBall->y - sinA * BALL_RADIUS); // Approx.
3350 }
3351
3352 // Find the first rail hit by the aiming ray
3353 D2D1_POINT_2F railHitPoint = rayEnd; // Default to far end if no rail hit
3354 float minRailDistSq = rayLength * rayLength;
3355 int hitRailIndex = -1; // 0:Left, 1:Right, 2:Top, 3:Bottom
3356
3357 // Define table edge segments for intersection checks
3358 D2D1_POINT_2F topLeft = D2D1::Point2F(TABLE_LEFT, TABLE_TOP);
3359 D2D1_POINT_2F topRight = D2D1::Point2F(TABLE_RIGHT, TABLE_TOP);
3360 D2D1_POINT_2F bottomLeft = D2D1::Point2F(TABLE_LEFT, TABLE_BOTTOM);
3361 D2D1_POINT_2F bottomRight = D2D1::Point2F(TABLE_RIGHT, TABLE_BOTTOM);
3362
3363 D2D1_POINT_2F currentIntersection;
3364
3365 // Check Left Rail
3366 if (LineSegmentIntersection(rayStart, rayEnd, topLeft, bottomLeft, currentIntersection)) {
3367 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3368 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 0; }
3369 }
3370 // Check Right Rail
3371 if (LineSegmentIntersection(rayStart, rayEnd, topRight, bottomRight, currentIntersection)) {
3372 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3373 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 1; }
3374 }
3375 // Check Top Rail
3376 if (LineSegmentIntersection(rayStart, rayEnd, topLeft, topRight, currentIntersection)) {
3377 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3378 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 2; }
3379 }
3380 // Check Bottom Rail
3381 if (LineSegmentIntersection(rayStart, rayEnd, bottomLeft, bottomRight, currentIntersection)) {
3382 float distSq = GetDistanceSq(rayStart.x, rayStart.y, currentIntersection.x, currentIntersection.y);
3383 if (distSq < minRailDistSq) { minRailDistSq = distSq; railHitPoint = currentIntersection; hitRailIndex = 3; }
3384 }
3385
3386
3387 // --- Determine final aim line end point ---
3388 D2D1_POINT_2F finalLineEnd = railHitPoint; // Assume rail hit first
3389 bool aimingAtRail = true;
3390
3391 if (hitBall && firstHitDistSq < minRailDistSq) {
3392 // Ball collision is closer than rail collision
3393 finalLineEnd = ballCollisionPoint; // End line at the point of contact on the ball
3394 aimingAtRail = false;
3395 }
3396
3397 // --- Draw Primary Aiming Line ---
3398 pRT->DrawLine(rayStart, finalLineEnd, pBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3399
3400 // --- Draw Target Circle/Indicator ---
3401 D2D1_ELLIPSE targetCircle = D2D1::Ellipse(finalLineEnd, BALL_RADIUS / 2.0f, BALL_RADIUS / 2.0f);
3402 pRT->DrawEllipse(&targetCircle, pBrush, 1.0f);
3403
3404 // --- Draw Projection/Reflection Lines ---
3405 if (!aimingAtRail && hitBall) {
3406 // Aiming at a ball: Draw Ghost Cue Ball and Target Ball Projection
3407 D2D1_ELLIPSE ghostCue = D2D1::Ellipse(ballCollisionPoint, BALL_RADIUS, BALL_RADIUS); // Ghost ball at contact point
3408 pRT->DrawEllipse(ghostCue, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3409
3410 // Calculate target ball projection based on impact line (cue collision point -> target center)
3411 float targetProjectionAngle = atan2f(hitBall->y - ballCollisionPoint.y, hitBall->x - ballCollisionPoint.x);
3412 // Clamp angle calculation if distance is tiny
3413 if (GetDistanceSq(hitBall->x, hitBall->y, ballCollisionPoint.x, ballCollisionPoint.y) < 1.0f) {
3414 targetProjectionAngle = cueAngle; // Fallback if overlapping
3415 }
3416
3417 D2D1_POINT_2F targetStartPoint = D2D1::Point2F(hitBall->x, hitBall->y);
3418 D2D1_POINT_2F targetProjectionEnd = D2D1::Point2F(
3419 hitBall->x + cosf(targetProjectionAngle) * 50.0f, // Projection length 50 units
3420 hitBall->y + sinf(targetProjectionAngle) * 50.0f
3421 );
3422 // Draw solid line for target projection
3423 //pRT->DrawLine(targetStartPoint, targetProjectionEnd, pBrush, 1.0f);
3424
3425 //new code start
3426
3427 // Dual trajectory with edge-aware contact simulation
3428 D2D1_POINT_2F dir = {
3429 targetProjectionEnd.x - targetStartPoint.x,
3430 targetProjectionEnd.y - targetStartPoint.y
3431 };
3432 float dirLen = sqrtf(dir.x * dir.x + dir.y * dir.y);
3433 dir.x /= dirLen;
3434 dir.y /= dirLen;
3435
3436 D2D1_POINT_2F perp = { -dir.y, dir.x };
3437
3438 // Approximate cue ball center by reversing from tip
3439 D2D1_POINT_2F cueBallCenterForGhostHit = { // Renamed for clarity if you use it elsewhere
3440 targetStartPoint.x - dir.x * BALL_RADIUS,
3441 targetStartPoint.y - dir.y * BALL_RADIUS
3442 };
3443
3444 // REAL contact-ball center - use your physics object's center:
3445 // (replace 'objectBallPos' with whatever you actually call it)
3446 // (targetStartPoint is already hitBall->x, hitBall->y)
3447 D2D1_POINT_2F contactBallCenter = targetStartPoint; // Corrected: Use the object ball's actual center
3448 //D2D1_POINT_2F contactBallCenter = D2D1::Point2F(hitBall->x, hitBall->y);
3449
3450 // The 'offset' calculation below uses 'cueBallCenterForGhostHit' (originally 'cueBallCenter').
3451 // This will result in 'offset' being 0 because 'cueBallCenterForGhostHit' is defined
3452 // such that (targetStartPoint - cueBallCenterForGhostHit) is parallel to 'dir',
3453 // and 'perp' is perpendicular to 'dir'.
3454 // Consider Change 2 if this 'offset' is not behaving as intended for the secondary line.
3455 /*float offset = ((targetStartPoint.x - cueBallCenterForGhostHit.x) * perp.x +
3456 (targetStartPoint.y - cueBallCenterForGhostHit.y) * perp.y);*/
3457 /*float offset = ((targetStartPoint.x - cueBallCenter.x) * perp.x +
3458 (targetStartPoint.y - cueBallCenter.y) * perp.y);
3459 float absOffset = fabsf(offset);
3460 float side = (offset >= 0 ? 1.0f : -1.0f);*/
3461
3462 // Use actual cue ball center for offset calculation if 'offset' is meant to quantify the cut
3463 D2D1_POINT_2F actualCueBallPhysicalCenter = D2D1::Point2F(cueBall->x, cueBall->y); // This is also rayStart
3464
3465 // Offset calculation based on actual cue ball position relative to the 'dir' line through targetStartPoint
3466 float offset = ((targetStartPoint.x - actualCueBallPhysicalCenter.x) * perp.x +
3467 (targetStartPoint.y - actualCueBallPhysicalCenter.y) * perp.y);
3468 float absOffset = fabsf(offset);
3469 float side = (offset >= 0 ? 1.0f : -1.0f);
3470
3471
3472 // Actual contact point on target ball edge
3473 D2D1_POINT_2F contactPoint = {
3474 contactBallCenter.x + perp.x * BALL_RADIUS * side,
3475 contactBallCenter.y + perp.y * BALL_RADIUS * side
3476 };
3477
3478 // Tangent (cut shot) path from contact point
3479 // Tangent (cut shot) path: from contact point to contact ball center
3480 D2D1_POINT_2F objectBallDir = {
3481 contactBallCenter.x - contactPoint.x,
3482 contactBallCenter.y - contactPoint.y
3483 };
3484 float oLen = sqrtf(objectBallDir.x * objectBallDir.x + objectBallDir.y * objectBallDir.y);
3485 if (oLen != 0.0f) {
3486 objectBallDir.x /= oLen;
3487 objectBallDir.y /= oLen;
3488 }
3489
3490 const float PRIMARY_LEN = 150.0f; //default=150.0f
3491 const float SECONDARY_LEN = 150.0f; //default=150.0f
3492 const float STRAIGHT_EPSILON = BALL_RADIUS * 0.05f;
3493
3494 D2D1_POINT_2F primaryEnd = {
3495 targetStartPoint.x + dir.x * PRIMARY_LEN,
3496 targetStartPoint.y + dir.y * PRIMARY_LEN
3497 };
3498
3499 // Secondary line starts from the contact ball's center
3500 D2D1_POINT_2F secondaryStart = contactBallCenter;
3501 D2D1_POINT_2F secondaryEnd = {
3502 secondaryStart.x + objectBallDir.x * SECONDARY_LEN,
3503 secondaryStart.y + objectBallDir.y * SECONDARY_LEN
3504 };
3505
3506 if (absOffset < STRAIGHT_EPSILON) // straight shot?
3507 {
3508 // Straight: secondary behind primary
3509 // secondary behind primary {pDashedStyle param at end}
3510 pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
3511 //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
3512 pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
3513 //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
3514 }
3515 else
3516 {
3517 // Cut shot: both visible
3518 // both visible for cut shot
3519 pRT->DrawLine(secondaryStart, secondaryEnd, pPurpleBrush, 2.0f);
3520 //pRT->DrawLine(secondaryStart, secondaryEnd, pGhostBrush, 1.0f);
3521 pRT->DrawLine(targetStartPoint, primaryEnd, pCyanBrush, 2.0f);
3522 //pRT->DrawLine(targetStartPoint, primaryEnd, pBrush, 1.0f);
3523 }
3524 // End improved trajectory logic
3525
3526 //new code end
3527
3528 // -- Cue Ball Path after collision (Optional, requires physics) --
3529 // Very simplified: Assume cue deflects, angle depends on cut angle.
3530 // float cutAngle = acosf(cosf(cueAngle - targetProjectionAngle)); // Angle between paths
3531 // float cueDeflectionAngle = ? // Depends on cutAngle, spin, etc. Hard to predict accurately.
3532 // D2D1_POINT_2F cueProjectionEnd = ...
3533 // pRT->DrawLine(ballCollisionPoint, cueProjectionEnd, pGhostBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3534
3535 // --- Accuracy Comment ---
3536 // Note: The visual accuracy of this projection, especially for cut shots (hitting the ball off-center)
3537 // or shots with spin, is limited by the simplified physics model. Real pool physics involves
3538 // collision-induced throw, spin transfer, and cue ball deflection not fully simulated here.
3539 // The ghost ball method shows the *ideal* line for a center-cue hit without spin.
3540
3541 }
3542 else if (aimingAtRail && hitRailIndex != -1) {
3543 // Aiming at a rail: Draw reflection line
3544 float reflectAngle = cueAngle;
3545 // Reflect angle based on which rail was hit
3546 if (hitRailIndex == 0 || hitRailIndex == 1) { // Left or Right rail
3547 reflectAngle = PI - cueAngle; // Reflect horizontal component
3548 }
3549 else { // Top or Bottom rail
3550 reflectAngle = -cueAngle; // Reflect vertical component
3551 }
3552 // Normalize angle if needed (atan2 usually handles this)
3553 while (reflectAngle > PI) reflectAngle -= 2 * PI;
3554 while (reflectAngle <= -PI) reflectAngle += 2 * PI;
3555
3556
3557 float reflectionLength = 60.0f; // Length of the reflection line
3558 D2D1_POINT_2F reflectionEnd = D2D1::Point2F(
3559 finalLineEnd.x + cosf(reflectAngle) * reflectionLength,
3560 finalLineEnd.y + sinf(reflectAngle) * reflectionLength
3561 );
3562
3563 // Draw the reflection line (e.g., using a different color/style)
3564 pRT->DrawLine(finalLineEnd, reflectionEnd, pReflectBrush, 1.0f, pDashedStyle ? pDashedStyle : NULL);
3565 }
3566
3567 // Release resources
3568 SafeRelease(&pBrush);
3569 SafeRelease(&pGhostBrush);
3570 SafeRelease(&pCueBrush);
3571 SafeRelease(&pReflectBrush); // Release new brush
3572 SafeRelease(&pCyanBrush);
3573 SafeRelease(&pPurpleBrush);
3574 SafeRelease(&pDashedStyle);
3575}
3576
3577
3578void DrawUI(ID2D1RenderTarget* pRT) {
3579 if (!pTextFormat || !pLargeTextFormat) return;
3580
3581 ID2D1SolidColorBrush* pBrush = nullptr;
3582 pRT->CreateSolidColorBrush(UI_TEXT_COLOR, &pBrush);
3583 if (!pBrush) return;
3584
3585 // --- Player Info Area (Top Left/Right) --- (Unchanged)
3586 float uiTop = TABLE_TOP - 80;
3587 float uiHeight = 60;
3588 float p1Left = TABLE_LEFT;
3589 float p1Width = 150;
3590 float p2Left = TABLE_RIGHT - p1Width;
3591 D2D1_RECT_F p1Rect = D2D1::RectF(p1Left, uiTop, p1Left + p1Width, uiTop + uiHeight);
3592 D2D1_RECT_F p2Rect = D2D1::RectF(p2Left, uiTop, p2Left + p1Width, uiTop + uiHeight);
3593
3594 // Player 1 Info Text (Unchanged)
3595 std::wostringstream oss1;
3596 oss1 << player1Info.name.c_str() << L"\n";
3597 if (player1Info.assignedType != BallType::NONE) {
3598 oss1 << ((player1Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
3599 oss1 << L" [" << player1Info.ballsPocketedCount << L"/7]";
3600 }
3601 else {
3602 oss1 << L"(Undecided)";
3603 }
3604 pRT->DrawText(oss1.str().c_str(), (UINT32)oss1.str().length(), pTextFormat, &p1Rect, pBrush);
3605 // Draw Player 1 Side Ball
3606 if (player1Info.assignedType != BallType::NONE)
3607 {
3608 ID2D1SolidColorBrush* pBallBrush = nullptr;
3609 D2D1_COLOR_F ballColor = (player1Info.assignedType == BallType::SOLID) ?
3610 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
3611 pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
3612 if (pBallBrush)
3613 {
3614 D2D1_POINT_2F ballCenter = D2D1::Point2F(p1Rect.right + 10.0f, p1Rect.top + 20.0f);
3615 float radius = 10.0f;
3616 D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
3617 pRT->FillEllipse(&ball, pBallBrush);
3618 SafeRelease(&pBallBrush);
3619 // Draw border around the ball
3620 ID2D1SolidColorBrush* pBorderBrush = nullptr;
3621 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
3622 if (pBorderBrush)
3623 {
3624 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
3625 SafeRelease(&pBorderBrush);
3626 }
3627
3628 // If stripes, draw a stripe band
3629 if (player1Info.assignedType == BallType::STRIPE)
3630 {
3631 ID2D1SolidColorBrush* pStripeBrush = nullptr;
3632 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
3633 if (pStripeBrush)
3634 {
3635 D2D1_RECT_F stripeRect = D2D1::RectF(
3636 ballCenter.x - radius,
3637 ballCenter.y - 3.0f,
3638 ballCenter.x + radius,
3639 ballCenter.y + 3.0f
3640 );
3641 pRT->FillRectangle(&stripeRect, pStripeBrush);
3642 SafeRelease(&pStripeBrush);
3643 }
3644 }
3645 }
3646 }
3647
3648
3649 // Player 2 Info Text (Unchanged)
3650 std::wostringstream oss2;
3651 oss2 << player2Info.name.c_str() << L"\n";
3652 if (player2Info.assignedType != BallType::NONE) {
3653 oss2 << ((player2Info.assignedType == BallType::SOLID) ? L"Solids (Yellow)" : L"Stripes (Red)");
3654 oss2 << L" [" << player2Info.ballsPocketedCount << L"/7]";
3655 }
3656 else {
3657 oss2 << L"(Undecided)";
3658 }
3659 pRT->DrawText(oss2.str().c_str(), (UINT32)oss2.str().length(), pTextFormat, &p2Rect, pBrush);
3660 // Draw Player 2 Side Ball
3661 if (player2Info.assignedType != BallType::NONE)
3662 {
3663 ID2D1SolidColorBrush* pBallBrush = nullptr;
3664 D2D1_COLOR_F ballColor = (player2Info.assignedType == BallType::SOLID) ?
3665 D2D1::ColorF(1.0f, 1.0f, 0.0f) : D2D1::ColorF(1.0f, 0.0f, 0.0f);
3666 pRT->CreateSolidColorBrush(ballColor, &pBallBrush);
3667 if (pBallBrush)
3668 {
3669 D2D1_POINT_2F ballCenter = D2D1::Point2F(p2Rect.right + 10.0f, p2Rect.top + 20.0f);
3670 float radius = 10.0f;
3671 D2D1_ELLIPSE ball = D2D1::Ellipse(ballCenter, radius, radius);
3672 pRT->FillEllipse(&ball, pBallBrush);
3673 SafeRelease(&pBallBrush);
3674 // Draw border around the ball
3675 ID2D1SolidColorBrush* pBorderBrush = nullptr;
3676 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
3677 if (pBorderBrush)
3678 {
3679 pRT->DrawEllipse(&ball, pBorderBrush, 1.5f); // thin border
3680 SafeRelease(&pBorderBrush);
3681 }
3682
3683 // If stripes, draw a stripe band
3684 if (player2Info.assignedType == BallType::STRIPE)
3685 {
3686 ID2D1SolidColorBrush* pStripeBrush = nullptr;
3687 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pStripeBrush);
3688 if (pStripeBrush)
3689 {
3690 D2D1_RECT_F stripeRect = D2D1::RectF(
3691 ballCenter.x - radius,
3692 ballCenter.y - 3.0f,
3693 ballCenter.x + radius,
3694 ballCenter.y + 3.0f
3695 );
3696 pRT->FillRectangle(&stripeRect, pStripeBrush);
3697 SafeRelease(&pStripeBrush);
3698 }
3699 }
3700 }
3701 }
3702
3703
3704 // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
3705 ID2D1SolidColorBrush* pArrowBrush = nullptr;
3706 pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
3707 if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
3708 float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
3709 float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
3710 float arrowTipX, arrowBackX;
3711
3712 D2D1_RECT_F playerBox = (currentPlayer == 1) ? p1Rect : p2Rect;
3713 arrowBackX = playerBox.left - 25.0f;
3714 arrowTipX = arrowBackX + arrowSizeBase * 0.75f;
3715
3716 float notchDepth = 12.0f; // Increased from 6.0f to make the rectangle longer
3717 float notchWidth = 10.0f;
3718
3719 float cx = arrowBackX;
3720 float cy = arrowCenterY;
3721
3722 // Define triangle + rectangle tail shape
3723 D2D1_POINT_2F tip = D2D1::Point2F(arrowTipX, cy); // tip
3724 D2D1_POINT_2F baseTop = D2D1::Point2F(cx, cy - arrowSizeBase / 2.0f); // triangle top
3725 D2D1_POINT_2F baseBot = D2D1::Point2F(cx, cy + arrowSizeBase / 2.0f); // triangle bottom
3726
3727 // Rectangle coordinates for the tail portion:
3728 D2D1_POINT_2F r1 = D2D1::Point2F(cx - notchDepth, cy - notchWidth / 2.0f); // rect top-left
3729 D2D1_POINT_2F r2 = D2D1::Point2F(cx, cy - notchWidth / 2.0f); // rect top-right
3730 D2D1_POINT_2F r3 = D2D1::Point2F(cx, cy + notchWidth / 2.0f); // rect bottom-right
3731 D2D1_POINT_2F r4 = D2D1::Point2F(cx - notchDepth, cy + notchWidth / 2.0f); // rect bottom-left
3732
3733 ID2D1PathGeometry* pPath = nullptr;
3734 if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
3735 ID2D1GeometrySink* pSink = nullptr;
3736 if (SUCCEEDED(pPath->Open(&pSink))) {
3737 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
3738 pSink->AddLine(baseTop);
3739 pSink->AddLine(r2); // transition from triangle into rectangle
3740 pSink->AddLine(r1);
3741 pSink->AddLine(r4);
3742 pSink->AddLine(r3);
3743 pSink->AddLine(baseBot);
3744 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
3745 pSink->Close();
3746 SafeRelease(&pSink);
3747 pRT->FillGeometry(pPath, pArrowBrush);
3748 }
3749 SafeRelease(&pPath);
3750 }
3751
3752
3753 SafeRelease(&pArrowBrush);
3754 }
3755
3756 //original
3757/*
3758 // --- MODIFIED: Current Turn Arrow (Blue, Bigger, Beside Name) ---
3759 ID2D1SolidColorBrush* pArrowBrush = nullptr;
3760 pRT->CreateSolidColorBrush(TURN_ARROW_COLOR, &pArrowBrush);
3761 if (pArrowBrush && currentGameState != GAME_OVER && currentGameState != SHOT_IN_PROGRESS && currentGameState != AI_THINKING) {
3762 float arrowSizeBase = 32.0f; // Base size for width/height offsets (4x original ~8)
3763 float arrowCenterY = p1Rect.top + uiHeight / 2.0f; // Center vertically with text box
3764 float arrowTipX, arrowBackX;
3765
3766 if (currentPlayer == 1) {
3767arrowBackX = p1Rect.left - 25.0f; // Position left of the box
3768 arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
3769 // Define points for right-pointing arrow
3770 //D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
3771 //D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
3772 //D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
3773 // Enhanced arrow with base rectangle intersection
3774 float notchDepth = 6.0f; // Depth of square base "stem"
3775 float notchWidth = 4.0f; // Thickness of square part
3776
3777 D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
3778 D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
3779 D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY - notchWidth / 2.0f); // Square Left-Top
3780 D2D1_POINT_2F pt4 = D2D1::Point2F(arrowBackX - notchDepth, arrowCenterY + notchWidth / 2.0f); // Square Left-Bottom
3781 D2D1_POINT_2F pt5 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
3782
3783
3784 ID2D1PathGeometry* pPath = nullptr;
3785 if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
3786 ID2D1GeometrySink* pSink = nullptr;
3787 if (SUCCEEDED(pPath->Open(&pSink))) {
3788 pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
3789 pSink->AddLine(pt2);
3790 pSink->AddLine(pt3);
3791 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
3792 pSink->Close();
3793 SafeRelease(&pSink);
3794 pRT->FillGeometry(pPath, pArrowBrush);
3795 }
3796 SafeRelease(&pPath);
3797 }
3798 }
3799
3800
3801 //==================else player 2
3802 else { // Player 2
3803 // Player 2: Arrow left of P2 box, pointing right (or right of P2 box pointing left?)
3804 // Let's keep it consistent: Arrow left of the active player's box, pointing right.
3805// Let's keep it consistent: Arrow left of the active player's box, pointing right.
3806arrowBackX = p2Rect.left - 25.0f; // Position left of the box
3807arrowTipX = arrowBackX + arrowSizeBase * 0.75f; // Pointy end extends right
3808// Define points for right-pointing arrow
3809D2D1_POINT_2F pt1 = D2D1::Point2F(arrowTipX, arrowCenterY); // Tip
3810D2D1_POINT_2F pt2 = D2D1::Point2F(arrowBackX, arrowCenterY - arrowSizeBase / 2.0f); // Top-Back
3811D2D1_POINT_2F pt3 = D2D1::Point2F(arrowBackX, arrowCenterY + arrowSizeBase / 2.0f); // Bottom-Back
3812
3813ID2D1PathGeometry* pPath = nullptr;
3814if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
3815 ID2D1GeometrySink* pSink = nullptr;
3816 if (SUCCEEDED(pPath->Open(&pSink))) {
3817 pSink->BeginFigure(pt1, D2D1_FIGURE_BEGIN_FILLED);
3818 pSink->AddLine(pt2);
3819 pSink->AddLine(pt3);
3820 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
3821 pSink->Close();
3822 SafeRelease(&pSink);
3823 pRT->FillGeometry(pPath, pArrowBrush);
3824 }
3825 SafeRelease(&pPath);
3826}
3827 }
3828 */
3829
3830 // --- MODIFIED: Foul Text (Large Red, Bottom Center) ---
3831 if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) {
3832 ID2D1SolidColorBrush* pFoulBrush = nullptr;
3833 pRT->CreateSolidColorBrush(FOUL_TEXT_COLOR, &pFoulBrush);
3834 if (pFoulBrush && pLargeTextFormat) {
3835 // Calculate Rect for bottom-middle area
3836 float foulWidth = 200.0f; // Adjust width as needed
3837 float foulHeight = 60.0f;
3838 float foulLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (foulWidth / 2.0f);
3839 // Position below the pocketed balls bar
3840 float foulTop = pocketedBallsBarRect.bottom + 10.0f;
3841 D2D1_RECT_F foulRect = D2D1::RectF(foulLeft, foulTop, foulLeft + foulWidth, foulTop + foulHeight);
3842
3843 // --- Set text alignment to center for foul text ---
3844 pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3845 pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3846
3847 pRT->DrawText(L"FOUL!", 5, pLargeTextFormat, &foulRect, pFoulBrush);
3848
3849 // --- Restore default alignment for large text if needed elsewhere ---
3850 // pLargeTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
3851 // pLargeTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3852
3853 SafeRelease(&pFoulBrush);
3854 }
3855 }
3856
3857 // --- Draw "Choose Pocket" Message ---
3858 if (!pocketCallMessage.empty() && (currentGameState == CHOOSING_POCKET_P1 || currentGameState == CHOOSING_POCKET_P2)) {
3859 ID2D1SolidColorBrush* pMsgBrush = nullptr;
3860 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White), &pMsgBrush);
3861 if (pMsgBrush && pTextFormat) {
3862 float msgWidth = 450.0f;
3863 float msgHeight = 30.0f;
3864 float msgLeft = TABLE_LEFT + (TABLE_WIDTH / 2.0f) - (msgWidth / 2.0f);
3865 float msgTop = pocketedBallsBarRect.bottom + 10.0f;
3866 if (foulCommitted && currentGameState != SHOT_IN_PROGRESS) msgTop += 30.0f;
3867
3868 D2D1_RECT_F msgRect = D2D1::RectF(msgLeft, msgTop, msgLeft + msgWidth, msgTop + msgHeight);
3869
3870 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3871 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3872 pRT->DrawText(pocketCallMessage.c_str(), (UINT32)pocketCallMessage.length(), pTextFormat, &msgRect, pMsgBrush);
3873 SafeRelease(&pMsgBrush);
3874 }
3875 }
3876
3877
3878 // Show AI Thinking State (Unchanged from previous step)
3879 if (currentGameState == AI_THINKING && pTextFormat) {
3880 ID2D1SolidColorBrush* pThinkingBrush = nullptr;
3881 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Orange), &pThinkingBrush);
3882 if (pThinkingBrush) {
3883 D2D1_RECT_F thinkingRect = p2Rect;
3884 thinkingRect.top += 20; // Offset within P2 box
3885 // Ensure default text alignment for this
3886 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3887 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_CENTER);
3888 pRT->DrawText(L"Thinking...", 11, pTextFormat, &thinkingRect, pThinkingBrush);
3889 SafeRelease(&pThinkingBrush);
3890 }
3891 }
3892
3893 SafeRelease(&pBrush);
3894
3895 // --- Draw CHEAT MODE label if active ---
3896 if (cheatModeEnabled) {
3897 ID2D1SolidColorBrush* pCheatBrush = nullptr;
3898 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Red), &pCheatBrush);
3899 if (pCheatBrush && pTextFormat) {
3900 D2D1_RECT_F cheatTextRect = D2D1::RectF(
3901 TABLE_LEFT + 10.0f,
3902 TABLE_TOP + 10.0f,
3903 TABLE_LEFT + 200.0f,
3904 TABLE_TOP + 40.0f
3905 );
3906 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_LEADING);
3907 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
3908 pRT->DrawText(L"CHEAT MODE ON", wcslen(L"CHEAT MODE ON"), pTextFormat, &cheatTextRect, pCheatBrush);
3909 }
3910 SafeRelease(&pCheatBrush);
3911 }
3912}
3913
3914void DrawPowerMeter(ID2D1RenderTarget* pRT) {
3915 // Draw Border
3916 ID2D1SolidColorBrush* pBorderBrush = nullptr;
3917 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pBorderBrush);
3918 if (!pBorderBrush) return;
3919 pRT->DrawRectangle(&powerMeterRect, pBorderBrush, 2.0f);
3920 SafeRelease(&pBorderBrush);
3921
3922 // Create Gradient Fill
3923 ID2D1GradientStopCollection* pGradientStops = nullptr;
3924 ID2D1LinearGradientBrush* pGradientBrush = nullptr;
3925 D2D1_GRADIENT_STOP gradientStops[4];
3926 gradientStops[0].position = 0.0f;
3927 gradientStops[0].color = D2D1::ColorF(D2D1::ColorF::Green);
3928 gradientStops[1].position = 0.45f;
3929 gradientStops[1].color = D2D1::ColorF(D2D1::ColorF::Yellow);
3930 gradientStops[2].position = 0.7f;
3931 gradientStops[2].color = D2D1::ColorF(D2D1::ColorF::Orange);
3932 gradientStops[3].position = 1.0f;
3933 gradientStops[3].color = D2D1::ColorF(D2D1::ColorF::Red);
3934
3935 pRT->CreateGradientStopCollection(gradientStops, 4, &pGradientStops);
3936 if (pGradientStops) {
3937 D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props = {};
3938 props.startPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.bottom);
3939 props.endPoint = D2D1::Point2F(powerMeterRect.left, powerMeterRect.top);
3940 pRT->CreateLinearGradientBrush(props, pGradientStops, &pGradientBrush);
3941 SafeRelease(&pGradientStops);
3942 }
3943
3944 // Calculate Fill Height
3945 float fillRatio = 0;
3946 //if (isAiming && (currentGameState == AIMING || currentGameState == BREAKING)) {
3947 // Determine if power meter should reflect shot power (human aiming or AI preparing)
3948 bool humanIsAimingPower = isAiming && (currentGameState == AIMING || currentGameState == BREAKING);
3949 // NEW Condition: AI is displaying its aim, so show its chosen power
3950 bool aiIsVisualizingPower = (isPlayer2AI && currentPlayer == 2 &&
3951 currentGameState == AI_THINKING && aiIsDisplayingAim);
3952
3953 if (humanIsAimingPower || aiIsVisualizingPower) { // Use the new condition
3954 fillRatio = shotPower / MAX_SHOT_POWER;
3955 }
3956 float fillHeight = (powerMeterRect.bottom - powerMeterRect.top) * fillRatio;
3957 D2D1_RECT_F fillRect = D2D1::RectF(
3958 powerMeterRect.left,
3959 powerMeterRect.bottom - fillHeight,
3960 powerMeterRect.right,
3961 powerMeterRect.bottom
3962 );
3963
3964 if (pGradientBrush) {
3965 pRT->FillRectangle(&fillRect, pGradientBrush);
3966 SafeRelease(&pGradientBrush);
3967 }
3968
3969 // Draw scale notches
3970 ID2D1SolidColorBrush* pNotchBrush = nullptr;
3971 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pNotchBrush);
3972 if (pNotchBrush) {
3973 for (int i = 0; i <= 8; ++i) {
3974 float y = powerMeterRect.top + (powerMeterRect.bottom - powerMeterRect.top) * (i / 8.0f);
3975 pRT->DrawLine(
3976 D2D1::Point2F(powerMeterRect.right + 2.0f, y),
3977 D2D1::Point2F(powerMeterRect.right + 8.0f, y),
3978 pNotchBrush,
3979 1.5f
3980 );
3981 }
3982 SafeRelease(&pNotchBrush);
3983 }
3984
3985 // Draw "Power" Label Below Meter
3986 if (pTextFormat) {
3987 ID2D1SolidColorBrush* pTextBrush = nullptr;
3988 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black), &pTextBrush);
3989 if (pTextBrush) {
3990 D2D1_RECT_F textRect = D2D1::RectF(
3991 powerMeterRect.left - 20.0f,
3992 powerMeterRect.bottom + 8.0f,
3993 powerMeterRect.right + 20.0f,
3994 powerMeterRect.bottom + 38.0f
3995 );
3996 pTextFormat->SetTextAlignment(DWRITE_TEXT_ALIGNMENT_CENTER);
3997 pTextFormat->SetParagraphAlignment(DWRITE_PARAGRAPH_ALIGNMENT_NEAR);
3998 pRT->DrawText(L"Power", 5, pTextFormat, &textRect, pTextBrush);
3999 SafeRelease(&pTextBrush);
4000 }
4001 }
4002
4003 // Draw Glow Effect if fully charged or fading out
4004 static float glowPulse = 0.0f;
4005 static bool glowIncreasing = true;
4006 static float glowFadeOut = 0.0f; // NEW: tracks fading out
4007
4008 if (shotPower >= MAX_SHOT_POWER * 0.99f) {
4009 // While fully charged, keep pulsing normally
4010 if (glowIncreasing) {
4011 glowPulse += 0.02f;
4012 if (glowPulse >= 1.0f) glowIncreasing = false;
4013 }
4014 else {
4015 glowPulse -= 0.02f;
4016 if (glowPulse <= 0.0f) glowIncreasing = true;
4017 }
4018 glowFadeOut = 1.0f; // Reset fade out to full
4019 }
4020 else if (glowFadeOut > 0.0f) {
4021 // If shot fired, gradually fade out
4022 glowFadeOut -= 0.02f;
4023 if (glowFadeOut < 0.0f) glowFadeOut = 0.0f;
4024 }
4025
4026 if (glowFadeOut > 0.0f) {
4027 ID2D1SolidColorBrush* pGlowBrush = nullptr;
4028 float effectiveOpacity = (0.3f + 0.7f * glowPulse) * glowFadeOut;
4029 pRT->CreateSolidColorBrush(
4030 D2D1::ColorF(D2D1::ColorF::Red, effectiveOpacity),
4031 &pGlowBrush
4032 );
4033 if (pGlowBrush) {
4034 float glowCenterX = (powerMeterRect.left + powerMeterRect.right) / 2.0f;
4035 float glowCenterY = powerMeterRect.top;
4036 D2D1_ELLIPSE glowEllipse = D2D1::Ellipse(
4037 D2D1::Point2F(glowCenterX, glowCenterY - 10.0f),
4038 12.0f + 3.0f * glowPulse,
4039 6.0f + 2.0f * glowPulse
4040 );
4041 pRT->FillEllipse(&glowEllipse, pGlowBrush);
4042 SafeRelease(&pGlowBrush);
4043 }
4044 }
4045}
4046
4047void DrawSpinIndicator(ID2D1RenderTarget* pRT) {
4048 ID2D1SolidColorBrush* pWhiteBrush = nullptr;
4049 ID2D1SolidColorBrush* pRedBrush = nullptr;
4050
4051 pRT->CreateSolidColorBrush(CUE_BALL_COLOR, &pWhiteBrush);
4052 pRT->CreateSolidColorBrush(ENGLISH_DOT_COLOR, &pRedBrush);
4053
4054 if (!pWhiteBrush || !pRedBrush) {
4055 SafeRelease(&pWhiteBrush);
4056 SafeRelease(&pRedBrush);
4057 return;
4058 }
4059
4060 // Draw White Ball Background
4061 D2D1_ELLIPSE bgEllipse = D2D1::Ellipse(spinIndicatorCenter, spinIndicatorRadius, spinIndicatorRadius);
4062 pRT->FillEllipse(&bgEllipse, pWhiteBrush);
4063 pRT->DrawEllipse(&bgEllipse, pRedBrush, 0.5f); // Thin red border
4064
4065
4066 // Draw Red Dot for Spin Position
4067 float dotRadius = 4.0f;
4068 float dotX = spinIndicatorCenter.x + cueSpinX * (spinIndicatorRadius - dotRadius); // Keep dot inside edge
4069 float dotY = spinIndicatorCenter.y + cueSpinY * (spinIndicatorRadius - dotRadius);
4070 D2D1_ELLIPSE dotEllipse = D2D1::Ellipse(D2D1::Point2F(dotX, dotY), dotRadius, dotRadius);
4071 pRT->FillEllipse(&dotEllipse, pRedBrush);
4072
4073 SafeRelease(&pWhiteBrush);
4074 SafeRelease(&pRedBrush);
4075}
4076
4077
4078void DrawPocketedBallsIndicator(ID2D1RenderTarget* pRT) {
4079 ID2D1SolidColorBrush* pBgBrush = nullptr;
4080 ID2D1SolidColorBrush* pBallBrush = nullptr;
4081
4082 // Ensure render target is valid before proceeding
4083 if (!pRT) return;
4084
4085 HRESULT hr = pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Black, 0.8f), &pBgBrush); // Semi-transparent black
4086 if (FAILED(hr)) { SafeRelease(&pBgBrush); return; } // Exit if brush creation fails
4087
4088 hr = pRT->CreateSolidColorBrush(D2D1::ColorF(0, 0, 0), &pBallBrush); // Placeholder, color will be set per ball
4089 if (FAILED(hr)) {
4090 SafeRelease(&pBgBrush);
4091 SafeRelease(&pBallBrush);
4092 return; // Exit if brush creation fails
4093 }
4094
4095 // Draw the background bar (rounded rect)
4096 D2D1_ROUNDED_RECT roundedRect = D2D1::RoundedRect(pocketedBallsBarRect, 10.0f, 10.0f); // Corner radius 10
4097 float baseAlpha = 0.8f;
4098 float flashBoost = pocketFlashTimer * 0.5f; // Make flash effect boost alpha slightly
4099 float finalAlpha = std::min(1.0f, baseAlpha + flashBoost);
4100 pBgBrush->SetOpacity(finalAlpha);
4101 pRT->FillRoundedRectangle(&roundedRect, pBgBrush);
4102 pBgBrush->SetOpacity(1.0f); // Reset opacity after drawing
4103
4104 // --- Draw small circles for pocketed balls inside the bar ---
4105
4106 // Calculate dimensions based on the bar's height for better scaling
4107 float barHeight = pocketedBallsBarRect.bottom - pocketedBallsBarRect.top;
4108 float ballDisplayRadius = barHeight * 0.30f; // Make balls slightly smaller relative to bar height
4109 float spacing = ballDisplayRadius * 2.2f; // Adjust spacing slightly
4110 float padding = spacing * 0.75f; // Add padding from the edges
4111 float center_Y = pocketedBallsBarRect.top + barHeight / 2.0f; // Vertical center
4112
4113 // Starting X positions with padding
4114 float currentX_P1 = pocketedBallsBarRect.left + padding;
4115 float currentX_P2 = pocketedBallsBarRect.right - padding; // Start from right edge minus padding
4116
4117 int p1DrawnCount = 0;
4118 int p2DrawnCount = 0;
4119 const int maxBallsToShow = 7; // Max balls per player in the bar
4120
4121 for (const auto& b : balls) {
4122 if (b.isPocketed) {
4123 // Skip cue ball and 8-ball in this indicator
4124 if (b.id == 0 || b.id == 8) continue;
4125
4126 bool isPlayer1Ball = (player1Info.assignedType != BallType::NONE && b.type == player1Info.assignedType);
4127 bool isPlayer2Ball = (player2Info.assignedType != BallType::NONE && b.type == player2Info.assignedType);
4128
4129 if (isPlayer1Ball && p1DrawnCount < maxBallsToShow) {
4130 pBallBrush->SetColor(b.color);
4131 // Draw P1 balls from left to right
4132 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P1 + p1DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
4133 pRT->FillEllipse(&ballEllipse, pBallBrush);
4134 p1DrawnCount++;
4135 }
4136 else if (isPlayer2Ball && p2DrawnCount < maxBallsToShow) {
4137 pBallBrush->SetColor(b.color);
4138 // Draw P2 balls from right to left
4139 D2D1_ELLIPSE ballEllipse = D2D1::Ellipse(D2D1::Point2F(currentX_P2 - p2DrawnCount * spacing, center_Y), ballDisplayRadius, ballDisplayRadius);
4140 pRT->FillEllipse(&ballEllipse, pBallBrush);
4141 p2DrawnCount++;
4142 }
4143 // Note: Balls pocketed before assignment or opponent balls are intentionally not shown here.
4144 // You could add logic here to display them differently if needed (e.g., smaller, grayed out).
4145 }
4146 }
4147
4148 SafeRelease(&pBgBrush);
4149 SafeRelease(&pBallBrush);
4150}
4151
4152void DrawBallInHandIndicator(ID2D1RenderTarget* pRT) {
4153 if (!isDraggingCueBall && (currentGameState != BALL_IN_HAND_P1 && currentGameState != BALL_IN_HAND_P2 && currentGameState != PRE_BREAK_PLACEMENT)) {
4154 return; // Only show when placing/dragging
4155 }
4156
4157 Ball* cueBall = GetCueBall();
4158 if (!cueBall) return;
4159
4160 ID2D1SolidColorBrush* pGhostBrush = nullptr;
4161 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::White, 0.6f), &pGhostBrush); // Semi-transparent white
4162
4163 if (pGhostBrush) {
4164 D2D1_POINT_2F drawPos;
4165 if (isDraggingCueBall) {
4166 drawPos = D2D1::Point2F((float)ptMouse.x, (float)ptMouse.y);
4167 }
4168 else {
4169 // If not dragging but in placement state, show at current ball pos
4170 drawPos = D2D1::Point2F(cueBall->x, cueBall->y);
4171 }
4172
4173 // Check if the placement is valid before drawing differently?
4174 bool behindHeadstring = (currentGameState == PRE_BREAK_PLACEMENT);
4175 bool isValid = IsValidCueBallPosition(drawPos.x, drawPos.y, behindHeadstring);
4176
4177 if (!isValid) {
4178 // Maybe draw red outline if invalid placement?
4179 pGhostBrush->SetColor(D2D1::ColorF(D2D1::ColorF::Red, 0.6f));
4180 }
4181
4182
4183 D2D1_ELLIPSE ghostEllipse = D2D1::Ellipse(drawPos, BALL_RADIUS, BALL_RADIUS);
4184 pRT->FillEllipse(&ghostEllipse, pGhostBrush);
4185 pRT->DrawEllipse(&ghostEllipse, pGhostBrush, 1.0f); // Outline
4186
4187 SafeRelease(&pGhostBrush);
4188 }
4189}
4190
4191void DrawPocketSelectionIndicator(ID2D1RenderTarget* pRT) {
4192 int pocketToIndicate = -1;
4193 bool isHumanChoosing = (currentGameState == CHOOSING_POCKET_P1 || (currentGameState == CHOOSING_POCKET_P2 && !isPlayer2AI));
4194
4195 if (isHumanChoosing) {
4196 // While actively choosing, the indicator follows the hover.
4197 pocketToIndicate = currentlyHoveredPocket;
4198 // If not hovering anything, show the currently selected pocket (which defaults to 5).
4199 if (pocketToIndicate == -1) {
4200 pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
4201 }
4202 }
4203 else if (IsPlayerOnEightBall(currentPlayer)) {
4204 // Once choice is made, lock the indicator on the called pocket.
4205 pocketToIndicate = (currentPlayer == 1) ? calledPocketP1 : calledPocketP2;
4206 }
4207
4208 if (pocketToIndicate < 0 || pocketToIndicate > 5) {
4209 return;
4210 }
4211
4212 ID2D1SolidColorBrush* pArrowBrush = nullptr;
4213 pRT->CreateSolidColorBrush(D2D1::ColorF(D2D1::ColorF::Yellow, 0.9f), &pArrowBrush);
4214 if (!pArrowBrush) return;
4215
4216 D2D1_POINT_2F targetPocketCenter = pocketPositions[pocketToIndicate];
4217 float arrowHeadSize = HOLE_VISUAL_RADIUS * 0.5f;
4218 float arrowShaftLength = HOLE_VISUAL_RADIUS * 0.3f;
4219 float arrowShaftWidth = arrowHeadSize * 0.4f;
4220 float verticalOffsetFromPocketCenter = HOLE_VISUAL_RADIUS * 1.6f;
4221 D2D1_POINT_2F tip, baseLeft, baseRight, shaftTopLeft, shaftTopRight, shaftBottomLeft, shaftBottomRight;
4222
4223 if (targetPocketCenter.y == TABLE_TOP) {
4224 tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y + verticalOffsetFromPocketCenter + arrowHeadSize);
4225 baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
4226 baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y + verticalOffsetFromPocketCenter);
4227 shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
4228 shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
4229 shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y - arrowShaftLength);
4230 shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y - arrowShaftLength);
4231 }
4232 else {
4233 tip = D2D1::Point2F(targetPocketCenter.x, targetPocketCenter.y - verticalOffsetFromPocketCenter - arrowHeadSize);
4234 baseLeft = D2D1::Point2F(targetPocketCenter.x - arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
4235 baseRight = D2D1::Point2F(targetPocketCenter.x + arrowHeadSize / 2.0f, targetPocketCenter.y - verticalOffsetFromPocketCenter);
4236 shaftTopLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y + arrowShaftLength);
4237 shaftTopRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y + arrowShaftLength);
4238 shaftBottomLeft = D2D1::Point2F(targetPocketCenter.x - arrowShaftWidth / 2.0f, baseLeft.y);
4239 shaftBottomRight = D2D1::Point2F(targetPocketCenter.x + arrowShaftWidth / 2.0f, baseRight.y);
4240 }
4241
4242 ID2D1PathGeometry* pPath = nullptr;
4243 if (SUCCEEDED(pFactory->CreatePathGeometry(&pPath))) {
4244 ID2D1GeometrySink* pSink = nullptr;
4245 if (SUCCEEDED(pPath->Open(&pSink))) {
4246 pSink->BeginFigure(tip, D2D1_FIGURE_BEGIN_FILLED);
4247 pSink->AddLine(baseLeft); pSink->AddLine(shaftBottomLeft); pSink->AddLine(shaftTopLeft);
4248 pSink->AddLine(shaftTopRight); pSink->AddLine(shaftBottomRight); pSink->AddLine(baseRight);
4249 pSink->EndFigure(D2D1_FIGURE_END_CLOSED);
4250 pSink->Close();
4251 SafeRelease(&pSink);
4252 pRT->FillGeometry(pPath, pArrowBrush);
4253 }
4254 SafeRelease(&pPath);
4255 }
4256 SafeRelease(&pArrowBrush);
4257}