// main.cpp
#define DEFINE_GLOBALS
#include "common.h"
// prototypes of locally used functions
static void MainLoop_FindCurrentViewer (void);
static void MainLoop_EvaluateGameState (void);
int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, char *lpCmdLine, int nCmdShow)
{
// the entry point for any Windows program
WNDCLASSEX wc;
MENUINFO menu_info;
MSG msg;
HBITMAP hSplashBmp;
BITMAP splash_bmp;
HDC hdc;
RECT rect;
PAINTSTRUCT ps;
HBITMAP hbmTmp;
HDC hdcMem;
HKEY hRegistryKey;
INPUT mousemove_input;
float previous_time;
float screensaverwatchdog_feedtime;
int frame_count;
int array_index;
char *endptr;
wchar_t app_pathname[MAX_PATH];
wchar_t font_pathname[MAX_PATH];
wchar_t temp_string[MAX_PATH];
DWORD ascii_buffersize;
// does an InstallerPath registry key exist? if so, it means we've just been installed
ascii_buffersize = sizeof (temp_string);
if ((RegOpenKeyEx (HKEY_CURRENT_USER, L"SOFTWARE\\Chess Giants", 0, KEY_READ | KEY_SET_VALUE, &hRegistryKey) == 0)
&& (RegQueryValueEx (hRegistryKey, L"InstallerPath", 0, NULL, (BYTE *) temp_string, &ascii_buffersize) == 0))
{
temp_string[ascii_buffersize / sizeof (wchar_t)] = 0; // terminate the string ourselves (strings in the registry MAY have no null terminator)
// delete the installer
DeleteFile (temp_string);
// delete the registry value and close the registry key
RegDeleteValue (hRegistryKey, L"InstallerPath");
RegCloseKey (hRegistryKey);
}
// save application instance
hAppInstance = hInstance;
// find module and path names, and *IMPORTANT*, set the current working directory there
GetModuleFileName (NULL, app_pathname, WCHAR_SIZEOF (app_pathname));
GetDirectoryPath (app_pathname, app_path);
SetCurrentDirectoryW (app_path);
// initialize stuff
terminate_everything = false;
hMainWnd = NULL;
hChatterChannelsWnd = NULL;
hGamesWnd = NULL;
hMOTDWnd = NULL;
hOpponentsWnd = NULL;
hSoughtWnd = NULL;
is_paused = false; // clear pause status
#ifdef NO_REGISTRATION
is_registered = true;
want_framerate = true; // display framerate in debug mode
#else // !NO_REGISTRATION
is_registered = false;
dont_nag = false;
want_framerate = false; // release mode, don't display framerate
#endif // NO_REGISTRATION
is_dialogbox_displayed = false;
is_dialogbox_about_validated = false;
is_dialogbox_challenge_validated = false;
is_dialogbox_changeappearance_validated = false;
is_dialogbox_comment_validated = false;
is_dialogbox_endgame_validated = false;
is_dialogbox_gotomove_validated = false;
is_dialogbox_renamesides_validated = false;
is_dialogbox_load_validated = false;
is_dialogbox_message_validated = false;
is_dialogbox_newgame_validated = false;
is_dialogbox_options_validated = false;
is_dialogbox_pawnpromotion_validated = false;
is_dialogbox_playercard_validated = false;
is_dialogbox_playerinfoname_validated = false;
is_dialogbox_quit_validated = false;
is_dialogbox_resign_validated = false;
is_dialogbox_save_validated = false;
is_dialogbox_saveposition_validated = false;
is_dialogbox_sendchallenge_validated = false;
is_dialogbox_sendseek_validated = false;
is_dialogbox_takeback_validated = false;
is_window_chat_validated = false;
is_window_chatterchannels_validated = false;
is_window_games_validated = false;
is_window_motd_validated = false;
is_window_opponents_validated = false;
is_window_sought_validated = false;
save_pathname[0] = 0;
srand ((unsigned int) time (NULL)); // initialize PRNG
animation_endtime = 0.0f;
command_ignoretime = 0.0f;
highlight_endtime = 0.0f;
previous_time = 0.0f;
frame_count = 0;
// load the texts and ensure we have at least one display language
LocalizedTexts_Init ();
if (language_count < 1)
{
MessageBox (NULL, L"Chess Giants was unable to load its data files.\nThe game cannot start.\n\nPlease reinstall this program to fix the problem.", L"Chess Giants", MB_ICONERROR | MB_OK);
return (-1); // bomb out on error
}
// read configuration data
Config_Load ();
// see if the program is registered
#ifndef NO_REGISTRATION
is_registered = IsRegistrationCorrect (options.registration.user_email, options.registration.activation_code);
// is it not ? if so, try to read alternate registration data from the registry
if (!is_registered && (RegOpenKeyEx (HKEY_CURRENT_USER, L"SOFTWARE\\Chess Giants", 0, KEY_READ, &hRegistryKey) == 0))
{
ascii_buffersize = sizeof (options.registration.user_email); // in bytes
if (RegQueryValueEx (hRegistryKey, L"UserEmail", 0, NULL, (BYTE *) options.registration.user_email, &ascii_buffersize) == 0)
options.registration.user_email[ascii_buffersize / sizeof (wchar_t)] = 0; // terminate the string ourselves (strings in the registry MAY have no null terminator)
ascii_buffersize = sizeof (options.registration.activation_code); // in bytes
if (RegQueryValueEx (hRegistryKey, L"ActivationCode", 0, NULL, (BYTE *) &options.registration.activation_code, &ascii_buffersize) != 0)
options.registration.activation_code = 0; // if we can't read the activation code DWORD properly, reset it
RegCloseKey (hRegistryKey); // once we've read the data we were interested in, close the registry key
// now check again if we're registered
is_registered = IsRegistrationCorrect (options.registration.user_email, options.registration.activation_code);
}
#endif // !NO_REGISTRATION
// if we're not registered, display a dialog box to invite the user to enter his donor email to unlock the program
//if (!is_registered)
//{
// DialogBox_Registration ();
//}
//DialogBox_Registration ();
//return (0);
// register the window class, create the window and show it
memset (&wc, 0, sizeof (wc));
wc.cbSize = sizeof (wc);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; // double-clicks support
wc.lpfnWndProc = WindowProc_Main;
wc.hInstance = hAppInstance;
wc.hIcon = LoadIcon (hAppInstance, (wchar_t *) ICON_MAIN);
wc.hCursor = LoadCursor (NULL, IDC_ARROW);
wc.lpszClassName = PROGRAM_NAME L" WndClass";
RegisterClassEx (&wc);
swprintf_s (temp_string, WCHAR_SIZEOF (temp_string), PROGRAM_NAME L"%s", (is_registered ? L"" : LOCALIZE (L"EvaluationMode"))); // build window title
if (options.want_fullscreen)
hMainWnd = CreateWindowEx (0, wc.lpszClassName, temp_string, WS_POPUPWINDOW, // temp_string holds window title
0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), NULL, NULL, hAppInstance, NULL);
else
{
// in windowed mode, ensure window width and height aren't greater than screen size nor lower than a safe minimum
if (options.window_width > GetSystemMetrics (SM_CXMAXTRACK))
options.window_width = GetSystemMetrics (SM_CXMAXTRACK); // check this first in case screen size is reported incorrect
if (options.window_height > GetSystemMetrics (SM_CYMAXTRACK))
options.window_height = GetSystemMetrics (SM_CYMAXTRACK);
if (options.window_width < 640)
options.window_width = 640; // check this secondly in case screen size is reported incorrect
if (options.window_height < 480)
options.window_height = 480;
hMainWnd = CreateWindowEx (0, wc.lpszClassName, temp_string, WS_OVERLAPPEDWINDOW, // temp_string holds window title
GetSystemMetrics (SM_CXSCREEN) / 2 - options.window_width / 2,
GetSystemMetrics (SM_CYSCREEN) / 2 - options.window_height / 2,
options.window_width, options.window_height, NULL, NULL, hAppInstance, NULL);
}
ShowWindow (hMainWnd, (options.want_maximized ? SW_SHOWMAXIMIZED : nCmdShow)); // show it maximized if it was closed so
// create the main menu line, and its accelerators
hMainMenu = NULL;
hMainAccelerators = NULL;
CreateOrUpdateApplicationMenu ();
// display the splash screen (uglily first, using GDI functions)
memset ((void *) &splash_bmp, 0, sizeof (splash_bmp));
hSplashBmp = W32LoadImage (L"%s/data/splash.bmp", app_path); // load the splash bitmap
GetObject (hSplashBmp, sizeof (splash_bmp), (void *) &splash_bmp); // get a structure containing its size (among others)
hdcMem = CreateCompatibleDC (NULL); // create a device context compatible with the screen
hbmTmp = SelectBitmap (hdcMem, hSplashBmp); // select our bitmap to use in it
hdc = BeginPaint (hMainWnd, &ps); // begin painting on the main window
GetClientRect (hMainWnd, &rect);
StretchBlt (hdc, 0, 0, rect.right, rect.bottom, hdcMem, 0, 0, splash_bmp.bmWidth, splash_bmp.bmHeight, SRCCOPY); // bit blit the bitmap into it
EndPaint (hMainWnd, &ps); // end painting on the main window
SelectObject (hdcMem, hbmTmp); // restore the previous selection
DeleteDC (hdcMem); // and delete the handles to the device context
DeleteObject (hSplashBmp); // and to the bitmap that we used
// make the menu modeless
memset (&menu_info, 0, sizeof (menu_info)); // prepare menu info structure
menu_info.cbSize = sizeof (MENUINFO);
menu_info.fMask = MIM_STYLE;
GetMenuInfo (GetMenu (hMainWnd), &menu_info); // get current style
menu_info.dwStyle |= MNS_MODELESS; // add the "modeless" flag
SetMenuInfo (GetMenu (hMainWnd), &menu_info); // and send it back
// load status icons, bitmaps and texts
handlestatus[HANDLESTATUS_AVAILABLE].icon = W32LoadIcon (L"%s/data/icons/available.ico", app_path);
handlestatus[HANDLESTATUS_AVAILABLE].bitmap = W32LoadImage (L"%s/data/status/available.bmp", app_path);
handlestatus[HANDLESTATUS_AVAILABLE].text = LOCALIZE (L"Opponents_StatusAvailable");
handlestatus[HANDLESTATUS_INGAME].icon = W32LoadIcon (L"%s/data/icons/ingame.ico", app_path);
handlestatus[HANDLESTATUS_INGAME].bitmap = W32LoadImage (L"%s/data/status/ingame.bmp", app_path);
handlestatus[HANDLESTATUS_INGAME].text = LOCALIZE (L"Opponents_StatusInGame");
handlestatus[HANDLESTATUS_INSIMULATION].icon = W32LoadIcon (L"%s/data/icons/insimulation.ico", app_path);
handlestatus[HANDLESTATUS_INSIMULATION].bitmap = W32LoadImage (L"%s/data/status/insimulation.bmp", app_path);
handlestatus[HANDLESTATUS_INSIMULATION].text = LOCALIZE (L"Opponents_StatusInSimulation");
handlestatus[HANDLESTATUS_INTOURNAMENT].icon = W32LoadIcon (L"%s/data/icons/intournament.ico", app_path);
handlestatus[HANDLESTATUS_INTOURNAMENT].bitmap = W32LoadImage (L"%s/data/status/intournament.bmp", app_path);
handlestatus[HANDLESTATUS_INTOURNAMENT].text = LOCALIZE (L"Opponents_StatusInTournament");
handlestatus[HANDLESTATUS_EXAMININGAGAME].icon = W32LoadIcon (L"%s/data/icons/examiningagame.ico", app_path);
handlestatus[HANDLESTATUS_EXAMININGAGAME].bitmap = W32LoadImage (L"%s/data/status/examiningagame.bmp", app_path);
handlestatus[HANDLESTATUS_EXAMININGAGAME].text = LOCALIZE (L"Opponents_StatusExaminingAGame");
handlestatus[HANDLESTATUS_NOTOPENFORAMATCH].icon = W32LoadIcon (L"%s/data/icons/notopenforamatch.ico", app_path);
handlestatus[HANDLESTATUS_NOTOPENFORAMATCH].bitmap = W32LoadImage (L"%s/data/status/notopenforamatch.bmp", app_path);
handlestatus[HANDLESTATUS_NOTOPENFORAMATCH].text = LOCALIZE (L"Opponents_StatusNotOpenForAMatch");
handlestatus[HANDLESTATUS_INACTIVEORBUSY].icon = W32LoadIcon (L"%s/data/icons/inactiveorbusy.ico", app_path);
handlestatus[HANDLESTATUS_INACTIVEORBUSY].bitmap = W32LoadImage (L"%s/data/status/inactiveorbusy.bmp", app_path);
handlestatus[HANDLESTATUS_INACTIVEORBUSY].text = LOCALIZE (L"Opponents_StatusInactiveOrBusy");
handlestatus[HANDLESTATUS_OFFLINE].icon = W32LoadIcon (L"%s/data/icons/offline.ico", app_path);
handlestatus[HANDLESTATUS_OFFLINE].bitmap = W32LoadImage (L"%s/data/status/offline.bmp", app_path);
handlestatus[HANDLESTATUS_OFFLINE].text = LOCALIZE (L"Opponents_StatusOffline");
// load the system fonts
hFontChat = CreateFont (17, 0, 0, 0, FW_DONTCARE, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Comic Sans MS");
// before any rendering is done, it's a good idea to know what time it is
current_time = ProcessTime ();
stoppage_time = 0;
screensaverwatchdog_feedtime = current_time + 50.0f; // feed screensaver watchdog every 50 seconds
// initialize audio and renderer, and display a cleaner version of the splash screen this time :)
if (!Audio_Init () || !Render_Init (L"%s/data/splash.bmp", app_path))
return (-1); // bomb out on error
// load sprites
llarrow_spriteindex = Render_LoadSprite (L"%s/data/sprites/arrow-leftmost.png", app_path);
larrow_spriteindex = Render_LoadSprite (L"%s/data/sprites/arrow-left.png", app_path);
rarrow_spriteindex = Render_LoadSprite (L"%s/data/sprites/arrow-right.png", app_path);
rrarrow_spriteindex = Render_LoadSprite (L"%s/data/sprites/arrow-rightmost.png", app_path);
newgamebutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/newgame.png", app_path);
opengamebutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/opengame.png", app_path);
chatbutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/chat.png", app_path);
gamesbutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/games.png", app_path);
peoplebutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/people.png", app_path);
sepia_spriteindex = Render_LoadSprite (L"%s/data/sprites/sepia.png", app_path);
for (array_index = 0; array_index < 12; array_index++)
spinner_spriteindex[array_index] = Render_LoadSprite (L"%s/data/sprites/spinner-%d.png", app_path, array_index * 30); // spinning wheel
// add our custom fonts to the list of available fonts for the duration of the process
swprintf_s (font_pathname, WCHAR_SIZEOF (font_pathname), L"%s/data/fonts/papyrus.ttf", app_path);
AddFontResourceEx (font_pathname, FR_PRIVATE, 0);
// load rendered fonts
arrow_fontindex = Render_LoadFont (L"Papyrus", 24, false, false);
chat_fontindex = Render_LoadFont (L"Papyrus", 32, false, false);
players_fontindex = Render_LoadFont (L"Papyrus", 40, false, true);
centermsg_fontindex = Render_LoadFont (L"Papyrus", 54, false, true);
// load themes, initialize a new human vs. human game and setup the scene
if (!Themes_Init ())
return (-1); // bomb out on error
Board_Init (&the_board, PLAYER_HUMAN, PLAYER_HUMAN, L"standard", FENSTARTUP_STANDARDCHESS);
Scene_Init (&the_scene, &the_board);
// has a filename been specifed on the command-line AND that file exists ?
if ((lpCmdLine != NULL) && (lpCmdLine[0] != 0))
{
while (*lpCmdLine == '"')
lpCmdLine++; // skip leading quotes
if ((endptr = strchr (lpCmdLine, '"')) != NULL)
*endptr = 0; // break the string at the first ending quote
// is it a file that exists ? (don't use stat() which is broken on WinXP)
if (_access (lpCmdLine, 0) == 0)
{
ConvertToWideChar (load_pathname, WCHAR_SIZEOF (load_pathname), lpCmdLine); // save pathname string
is_dialogbox_load_validated = true; // and act as if the user just validated a load dialog box
}
#ifndef NO_REGISTRATION
// else is it a registration info ? if so, parse it
else if ((strncmp (lpCmdLine, "/r=", 3) == 0) && ((endptr = strchr (&lpCmdLine[3], ',')) != NULL))
{
*endptr = 0; // break the string at the separator between user email and activation code
ConvertToWideChar (temp_string, WCHAR_SIZEOF (temp_string), &lpCmdLine[3]); // read user email
is_registered = IsRegistrationCorrect (temp_string, atoi (endptr + 1)); // and see whether we're registered or not
}
#endif // !NO_REGISTRATION
}
// TODO: this + offline statistics
// enter the main loop
while (!terminate_everything)
{
// see what time it is
current_time = ProcessTime ();
if (is_paused)
stoppage_time += (current_time - previous_time); // if we're paused, increase stoppage time
// is it time to feed the screensaver watchdog ? (to prevent it from starting)
if (screensaverwatchdog_feedtime < current_time)
{
mousemove_input.type = INPUT_MOUSE;
memset (&mousemove_input.mi, 0, sizeof (mousemove_input.mi)); // blank out struct = no move at all :)
mousemove_input.mi.dwFlags = MOUSEEVENTF_MOVE;
SendInput (1, &mousemove_input, sizeof (mousemove_input)); // send a fake mouse move input event
screensaverwatchdog_feedtime = current_time + 50.0f; // feed screensaver watchdog again in 50 seconds
}
// are we in demo mode and is it time to quit ?
if (!is_registered && (current_time > DEMO_TIMEOUT))
DestroyWindow (hMainWnd); // if so, send a quit message in order to break the loop
// are we in the middle of an animation or just after it ?
if (current_time < animation_endtime + 0.5f)
the_scene.update = true; // always update during animations
else
the_scene.update |= Board_Think (&the_board); // make the board (i.e, both players) think
MainLoop_FindCurrentViewer (); // determine current viewer
// see if we have a message waiting for any window in the current thread and dispatch it
while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
{
// check for accelerator keystrokes from the main window
if ((msg.hwnd != hMainWnd) || !TranslateAccelerator (hMainWnd, hMainAccelerators, &msg))
{
TranslateMessage (&msg); // translate and dispatch all other messages
DispatchMessage (&msg);
}
}
// handle dialog box and window return codes
if (is_dialogbox_about_validated) DialogBox_About_Validated ();
if (is_dialogbox_challenge_validated) DialogBox_Challenge_Validated ();
if (is_dialogbox_changeappearance_validated) DialogBox_ChangeAppearance_Validated ();
if (is_dialogbox_comment_validated) DialogBox_Comment_Validated ();
if (is_dialogbox_endgame_validated) DialogBox_EndGame_Validated ();
if (is_dialogbox_gotomove_validated) DialogBox_GoToMove_Validated ();
if (is_dialogbox_renamesides_validated) DialogBox_RenameSides_Validated ();
if (is_dialogbox_load_validated) DialogBox_Load_Validated ();
if (is_dialogbox_message_validated) DialogBox_Message_Validated ();
if (is_dialogbox_newgame_validated) DialogBox_NewGame_Validated ();
if (is_dialogbox_options_validated) DialogBox_Options_Validated ();
if (is_dialogbox_pawnpromotion_validated) DialogBox_PawnPromotion_Validated ();
if (is_dialogbox_playercard_validated) DialogBox_PlayerCard_Validated ();
if (is_dialogbox_playerinfoname_validated) DialogBox_PlayerInfoName_Validated ();
if (is_dialogbox_quit_validated) DialogBox_Quit_Validated ();
if (is_dialogbox_resign_validated) DialogBox_Resign_Validated ();
if (is_dialogbox_save_validated) DialogBox_Save_Validated ();
if (is_dialogbox_saveposition_validated) DialogBox_SavePosition_Validated ();
if (is_dialogbox_sendchallenge_validated) DialogBox_SendChallenge_Validated ();
if (is_dialogbox_sendseek_validated) DialogBox_SendSeek_Validated ();
if (is_dialogbox_takeback_validated) DialogBox_Takeback_Validated ();
if (is_window_chat_validated) Window_Chat_Validated ();
if (is_window_chatterchannels_validated) Window_ChatterChannels_Validated ();
if (is_window_games_validated) Window_Games_Validated ();
if (is_window_motd_validated) Window_MOTD_Validated ();
if (is_window_opponents_validated) Window_Opponents_Validated ();
if (is_window_sought_validated) Window_Sought_Validated ();
MainLoop_EvaluateGameState (); // evaluate game state
// is the table rotating ?
if (Player_RotateTable (&the_board.players[current_viewer], current_time - previous_time))
the_scene.update = true; // if so, update the scene
// are we highlighting something ?
if (highlight_endtime > current_time)
the_scene.update = true; // if so, update the scene
// else if we WERE just highlighting something, clear the hovered positions
else if (highlight_endtime + 0.1f > current_time)
{
the_board.hovered_position[0] = -1;
the_board.hovered_position[1] = -1;
the_scene.update = true; // and update the scene
}
// if we want the game clock, update scene every second
if (options.want_clock && ((int) current_time != (int) previous_time))
the_scene.update = true;
// if there's something in the central text buffer, update scene too
if (the_scene.gui.central_text.is_displayed)
the_scene.update = true;
// if we have a spinning wheel, update scene too
if (the_scene.gui.want_spinwheel)
the_scene.update = true;
// is our theme not loaded yet ?
if (!theme->is_loaded)
Theme_LoadABitMore (theme); // load a bit more of it
// else do we NOT need to update the scene ?
else if (!the_scene.update)
{
// cycle through all themes and see if one of them needs to be loaded
for (array_index = 0; array_index < theme_count; array_index++)
if (!themes[array_index].is_loaded)
{
Theme_LoadABitMore (&themes[array_index]); // load a bit more of this theme
break; // and stop looping (see you next pass)
}
}
// either we need to update the scene, or we want to do it continuously
else
{
Scene_Update (&the_scene, &the_board); // evaluate which parts need to be placed
Render_RenderFrame (&the_scene); // render a game frame
the_scene.update = false; // scene no longer needs to be updated now
}
Audio_Think (); // ensure audio is playing
previous_time = current_time; // save previous time
if (frame_count == 100)
{
frame_count = 0; // reset frame count every 100 frames
Sleep (1); // once every 100 frames, wait a millisecond
}
else
Sleep (0); // else just allow context switching
frame_count++; // increase the frame count
}
/////////////////////////////////////////////////////////////////////////
// at this point, we exited the main loop and we are returning to Windows
// release scene, game, themes and shutdown renderer and audio
Scene_Shutdown (&the_scene);
Board_Shutdown (&the_board);
Themes_Shutdown ();
Render_Shutdown ();
Audio_Shutdown ();
// delete the font resources
DeleteObject (hFontChat);
// delete the bitmap and icon ressources
for (array_index = 1; array_index < sizeof (handlestatus) / sizeof (handlestatus[0]); array_index++)
{
DeleteObject (handlestatus[array_index].bitmap);
DestroyIcon (handlestatus[array_index].icon);
}
// unregister window class
UnregisterClass (wc.lpszClassName, hAppInstance);
// destroy the accelerators table
if (hMainAccelerators)
DestroyAcceleratorTable (hMainAccelerators);
hMainAccelerators = NULL;
// destroy the application menu object
if (IsMenu (hMainMenu))
DestroyMenu (hMainMenu);
hMainMenu = NULL;
// are we not registered yet AND have we NOT been told to don't nag?
#ifndef NO_REGISTRATION
if (!is_registered && !dont_nag)
DialogBox_Registration ();
#endif // !NO_REGISTRATION
// save configuration data
Config_Save ();
// unload localized texts
LocalizedTexts_Shutdown ();
ExitProcess (0); // it looks like this is needed to terminate reluctant Chess Giants instances...
return (0); // and return to Windows.
}
static void MainLoop_FindCurrentViewer (void)
{
// helper function that tells who is the current viewer
if ((the_board.players[COLOR_WHITE].type == PLAYER_HUMAN) && (the_board.players[COLOR_BLACK].type == PLAYER_HUMAN))
current_viewer = Board_ColorToMove (&the_board); // if both players are human, track them both
else if (the_board.players[COLOR_WHITE].type == PLAYER_HUMAN)
current_viewer = COLOR_WHITE; // else if only the white is human, track the white
else if (the_board.players[COLOR_BLACK].type == PLAYER_HUMAN)
current_viewer = COLOR_BLACK; // else if it's the black, track the black
else
current_viewer = COLOR_WHITE; // else no human in game, track just the white
return; // finished, current viewer is known
}
static void MainLoop_EvaluateGameState (void)
{
// function to evaluate the game state in the main loop when a part has just moved
static wchar_t window_title[256];
player_t *current_player;
player_t *opposite_player;
player_t *network_player;
boardmove_t *last_move;
int enabled_value;
int move_index;
// get current and opposite players, and see if we're online
current_player = Player_GetCurrent ();
opposite_player = Player_GetOpposite ();
network_player = Player_FindByType (PLAYER_INTERNET);
// if no dialog box is in focus AND the view distance and pitch is lower than the minimum, enable the "new game" and "open game" buttons
if (!is_dialogbox_displayed && (network_player == NULL) && (current_distance == CLOSEUP_VIEW_DISTANCE) && (current_pitch == CLOSEUP_VIEW_PITCH))
{
GUIBUTTON_ENABLE (the_scene.gui.newgamebutton);
GUIBUTTON_ENABLE (the_scene.gui.opengamebutton);
}
else
{
GUIBUTTON_DISABLE (the_scene.gui.newgamebutton);
GUIBUTTON_DISABLE (the_scene.gui.opengamebutton);
}
if (!the_board.reevaluate)
return; // if the board doesn't need to be reevaluated, don't do anything
// has the game started ?
if (the_board.move_count > 1)
{
// game has started, enable the "save" and "save as" menu options
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVE, MF_ENABLED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEAS, MF_ENABLED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_ENABLED);
// disable the start position setup mode
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SETUPPOSITION, MF_GRAYED);
// enable the "go to move" menu option
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_GOTOMOVE, MF_ENABLED);
// are we watching the last move ?
if (the_board.viewed_move == the_board.move_count - 1)
{
// get a quick acccess to the last move
last_move = &the_board.moves[the_board.move_count - 1];
// if the current player is a human AND its opponent is a computer, allow him to ask us for a hint
if ((current_player->type == PLAYER_HUMAN) && (opposite_player->type == PLAYER_COMPUTER))
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_SUGGESTMOVE, MF_ENABLED);
else
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_SUGGESTMOVE, MF_GRAYED);
// (if the current player is a human
// AND (its opponent is another human AND there's at least one move played)
// OR (its opponent is a computer AND there are at least two moves played)
// OR (its opponent is a remote player AND we're in game AND there are at least two moves played))
// OR the current player is a remote player AND we're in game AND there are at least two moves played), allow him to cancel move
if (((current_player->type == PLAYER_HUMAN)
&& ((opposite_player->type == PLAYER_HUMAN)
|| ((opposite_player->type == PLAYER_COMPUTER) && (the_board.move_count > 2))
|| ((opposite_player->type == PLAYER_INTERNET) && (opposite_player->is_in_game) && (the_board.move_count > 2))))
|| ((current_player->type == PLAYER_INTERNET) && (current_player->is_in_game) && (the_board.move_count > 2)))
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_CANCELLASTMOVE, MF_ENABLED);
else
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_CANCELLASTMOVE, MF_GRAYED);
// is the current player in check ? (to play the right sound)
// read as: was the last move an opponent's move AND did it put us to check ?
if (last_move->is_check)
{
// is it a checkmate ? (checkmate == check + stalemate)
if (last_move->is_stalemate)
{
// display the game over dialog box
the_board.game_state = (Board_ColorToMove (&the_board) == COLOR_WHITE ? STATE_BLACKWIN_CHECKMATE : STATE_WHITEWIN_CHECKMATE);
DialogBox_EndGame ();
}
}
else
{
// is it a stalemate ?
if (last_move->is_stalemate)
{
// display the game over dialog box
the_board.game_state = STATE_DRAW_STALEMATE;
DialogBox_EndGame ();
}
}
// have there 50 moves been played each side (i.e, 100 plies) AND is the current player human ?
if ((the_board.move_count > 100) && (current_player->type == PLAYER_HUMAN))
{
// go backwards and see when is the latest move that took an opponent's piece OR the latest pawn move
for (move_index = the_board.move_count - 1; move_index >= 0; move_index--)
if (the_board.moves[move_index].has_captured || (the_board.moves[move_index].part == PART_PAWN))
break; // stop as soon as we find one
// can the fifty moves draw rule be claimed AND does the current player claims it ?
if (move_index + 1 + 100 < the_board.move_count)
{
// yes. Propose it to the side that's on move
// TODO: non-modal MessageBox (copy dialog_newgame.cpp and use return values)
}
}
GUIBUTTON_ENABLE (the_scene.gui.llarrow); // enable "jump to beginning" arrow if it isn't displayed yet
GUIBUTTON_ENABLE (the_scene.gui.larrow); // enable "back" arrow if it isn't displayed yet
GUIBUTTON_DISABLE (the_scene.gui.rarrow); // disable "forward" arrow if it's already displayed
GUIBUTTON_DISABLE (the_scene.gui.rrarrow); // disable "jump to end" arrow if it's already displayed
if (the_board.game_state == STATE_PLAYING)
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, LOCALIZE (is_paused ? L"Paused" : L"Current"));
else if ((the_board.game_state == STATE_BLACKWIN_CHECKMATE) || (the_board.game_state == STATE_WHITEWIN_CHECKMATE))
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, L"%s\n%s", LOCALIZE (L"EndGame_CheckMate"), LOCALIZE (L"EndGame_Title"));
else if ((the_board.game_state == STATE_WHITEWIN_RESIGNORFORFEIT) || (the_board.game_state == STATE_BLACKWIN_RESIGNORFORFEIT))
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, L"%s\n%s", LOCALIZE (L"EndGame_Resign"), LOCALIZE (L"EndGame_Title"));
else if (the_board.game_state == STATE_DRAW_STALEMATE)
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, L"%s\n%s", LOCALIZE (L"EndGame_StaleMate"), LOCALIZE (L"EndGame_Title"));
else if (the_board.game_state == STATE_DRAW_AGREEMENT)
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, L"%s\n%s", LOCALIZE (L"EndGame_Agreement"), LOCALIZE (L"EndGame_Title"));
else if (the_board.game_state == STATE_DRAW_OTHER)
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, L"%s\n%s", LOCALIZE (L"EndGame_DrawOther"), LOCALIZE (L"EndGame_Title"));
// enable the "comment on this move" menu option
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_COMMENTMOVE, MF_ENABLED);
}
// else are we watching another move, but not the beginning of the game ?
else if (the_board.viewed_move > 0)
{
GUIBUTTON_ENABLE (the_scene.gui.llarrow); // enable "jump to beginning" arrow if it isn't displayed yet
GUIBUTTON_ENABLE (the_scene.gui.larrow); // enable "back" arrow if it isn't displayed yet
GUIBUTTON_ENABLE (the_scene.gui.rarrow); // enable "forward" arrow if it isn't displayed yet
GUIBUTTON_ENABLE (the_scene.gui.rrarrow); // enable "jump to end" arrow if it isn't displayed yet
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, L"%s %d\n%s", LOCALIZE (L"Move"), (the_board.viewed_move + 1) / 2, (the_board.viewed_move % 2 ? LOCALIZE (L"Games_White"): LOCALIZE (L"Games_Black")));
// hints are not usable when watching the game history
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_SUGGESTMOVE, MF_GRAYED);
// enable the "save position as" and "comment on this move" menu options
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_ENABLED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_COMMENTMOVE, MF_ENABLED);
}
// else we must be watching the beginning of the game (no move yet)
else
{
GUIBUTTON_DISABLE (the_scene.gui.llarrow); // disable "jump to beginning" arrow if it's already displayed
GUIBUTTON_DISABLE (the_scene.gui.larrow); // disable "back" arrow if it's already displayed
GUIBUTTON_ENABLE (the_scene.gui.rarrow); // enable "forward" arrow if it isn't displayed yet
GUIBUTTON_ENABLE (the_scene.gui.rrarrow); // enable "jump to end" arrow if it isn't displayed yet
Scene_UpdateText (&the_scene.gui.arrow_text, RGBACOLOR_SETALPHA (options.clock_color, 0x7f), DURATION_INFINITE, false, LOCALIZE (L"Beginning"));
// hints are not usable when watching the game history
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_SUGGESTMOVE, MF_GRAYED);
// disable the "save position as" and "comment on this move" menu options
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_GRAYED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_COMMENTMOVE, MF_GRAYED);
}
}
else
{
// game has not started, disable the "save", "save as" and "save position as" menu options
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVE, MF_GRAYED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEAS, MF_GRAYED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_GRAYED);
// if we are NOT on Internet play AND no longer in closeup mode, enable the start position setup mode
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SETUPPOSITION, ((network_player == NULL) && (current_distance != CLOSEUP_VIEW_DISTANCE) && (current_pitch != CLOSEUP_VIEW_PITCH) ? MF_ENABLED : MF_GRAYED));
// if the current player is a human AND its opponent is a computer, allow him to ask us for a hint
if ((current_player->type == PLAYER_HUMAN) && (opposite_player->type == PLAYER_COMPUTER))
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_SUGGESTMOVE, MF_ENABLED);
else
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_SUGGESTMOVE, MF_GRAYED);
// disable the "cancel last move", "comment move" and "go to move" menu options
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_CANCELLASTMOVE, MF_GRAYED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_COMMENTMOVE, MF_GRAYED);
EnableMenuItem (GetMenu (hMainWnd), MENUID_MOVE_GOTOMOVE, MF_GRAYED);
is_paused = false; // clear pause status (we can only pause a game when it's been started)
// and disable the navigation arrows and the arrow text
GUIBUTTON_DISABLE (the_scene.gui.llarrow);
GUIBUTTON_DISABLE (the_scene.gui.larrow);
GUIBUTTON_DISABLE (the_scene.gui.rarrow);
GUIBUTTON_DISABLE (the_scene.gui.rrarrow);
the_scene.gui.arrow_text.is_displayed = false;
}
// no matter whether the game started or not, if the current player is a human AND its opponent is a computer, allow him to swap sides
if ((current_player->type == PLAYER_HUMAN) && (opposite_player->type == PLAYER_COMPUTER))
EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SWAPSIDES, MF_ENABLED);
else
EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SWAPSIDES, MF_GRAYED);
// no matter whether the game started or not, enable players renaming only if we are NOT in internet mode
EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_RENAMESIDES, (network_player == NULL ? MF_ENABLED : MF_GRAYED));
// update window title
if ((the_board.players[COLOR_WHITE].name[0] != 0) && (the_board.players[COLOR_BLACK].name[0] != 0))
{
swprintf_s (window_title, WCHAR_SIZEOF (window_title), L"%s %s %s - " PROGRAM_NAME L"%s", the_board.players[COLOR_WHITE].name, LOCALIZE (L"Versus"), the_board.players[COLOR_BLACK].name, (is_registered ? L"" : LOCALIZE (L"EvaluationMode")));
SetWindowText (hMainWnd, window_title); // update window title
}
else if (the_board.players[COLOR_WHITE].name[0] != 0)
{
swprintf_s (window_title, WCHAR_SIZEOF (window_title), L"%s - " PROGRAM_NAME L"%s", the_board.players[COLOR_WHITE].name, (is_registered ? L"" : LOCALIZE (L"EvaluationMode")));
SetWindowText (hMainWnd, window_title); // update window title
}
// are we in internet mode AND are we logged in ?
if ((network_player != NULL) && network_player->is_logged_in)
{
// are we currently playing a game ?
if (network_player->is_in_game)
{
GUIBUTTON_ENABLE (the_scene.gui.chatbutton); // enable chat button if it's not enabled yet
GUIBUTTON_DISABLE (the_scene.gui.gamesbutton); // disable games button if it was enabled
GUIBUTTON_DISABLE (the_scene.gui.peoplebutton); // disable people button if it was enabled
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_RESIGN, ((the_board.game_state == STATE_PLAYING) && (the_board.move_count > 1) ? MF_ENABLED : MF_GRAYED)); // allow resigning if the game has started AND it's not terminated)
}
else
{
GUIBUTTON_DISABLE (the_scene.gui.chatbutton); // disable chat button if it was enabled
GUIBUTTON_ENABLE (the_scene.gui.gamesbutton); // enable games button if it's not enabled yet
GUIBUTTON_ENABLE (the_scene.gui.peoplebutton); // enable people button if it's not enabled yet
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_RESIGN, MF_GRAYED); // disable ability to resign
}
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_PAUSE, MF_DISABLED); // disallow pause
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_STATISTICS, MF_ENABLED); // enable stats
enabled_value = MF_ENABLED; // remember to enable the internet-related menu items
}
// else it's a local or vs. computer game
else
{
GUIBUTTON_DISABLE (the_scene.gui.chatbutton); // disable chat button if it was enabled
GUIBUTTON_DISABLE (the_scene.gui.gamesbutton); // disable games button if it was enabled
GUIBUTTON_DISABLE (the_scene.gui.peoplebutton); // disable people button if it was enabled
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_PAUSE, ((the_board.game_state == STATE_PLAYING) && (the_board.move_count > 1) ? MF_ENABLED : MF_GRAYED)); // allow pause if the game has started
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_RESIGN, ((the_board.game_state == STATE_PLAYING) && (the_board.move_count > 1) ? MF_ENABLED : MF_GRAYED)); // allow resigning if the game has started AND it's not terminated)
EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_STATISTICS, MF_GRAYED); // disable stats
enabled_value = MF_GRAYED; // remember to disable the internet-related menu items
}
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_SHOWONLINEPLAYERS, enabled_value);
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_SHOWSOUGHTGAMES, enabled_value);
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_SEEKGAME, enabled_value);
if (!options.network.want_publicchat)
{
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_CHATTERCHANNELS, MF_GRAYED); // always grayed if we don't want public chat
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_ENTERCHATTEXT, MF_GRAYED);
}
else
{
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_CHATTERCHANNELS, enabled_value); // else enabled only in internet mode
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_ENTERCHATTEXT, enabled_value);
}
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_DISPLAYPLAYERCARD, enabled_value);
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_DISPLAYYOURCARD, enabled_value);
EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_MOTD, enabled_value);
the_board.reevaluate = false; // board evaluation has been done
return; // finished, new board state is known
}