Subversion Repositories Games.Chess Giants

Rev

Rev 75 | Rev 87 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. // main.cpp
  2.  
  3. #define DEFINE_GLOBALS
  4. #include "common.h"
  5.  
  6.  
  7. // handy macros
  8. #define GUIBUTTON_ENABLE(button) { if ((button).state == 0) (button).state = 1; }
  9. #define GUIBUTTON_DISABLE(button) { if ((button).state > 0) (button).state = 0; }
  10.  
  11.  
  12. // prototypes of locally used functions
  13. static void MainLoop_FindCurrentViewer (void);
  14. static void MainLoop_EvaluateGameState (void);
  15.  
  16.  
  17. int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, char *lpCmdLine, int nCmdShow)
  18. {
  19.    // the entry point for any Windows program
  20.  
  21.    WNDCLASSEX wc;
  22.    MENUINFO menu_info;
  23.    MSG msg;
  24.    HBITMAP hSplashBmp;
  25.    BITMAP splash_bmp;
  26.    HDC hdc;
  27.    RECT rect;
  28.    PAINTSTRUCT ps;
  29.    HBITMAP hbmTmp;
  30.    HDC hdcMem;
  31.    INPUT mousemove_input;
  32.    float previous_time;
  33.    float screensaverwatchdog_feedtime;
  34.    int frame_count;
  35.    int array_index;
  36.    char *endptr;
  37.    wchar_t app_pathname[MAX_PATH];
  38.    wchar_t font_pathname[MAX_PATH];
  39.    wchar_t temp_string[100];
  40.    struct _stat fileinfo;
  41.  
  42.    // save application instance
  43.    hAppInstance = hInstance;
  44.  
  45.    // find module and path names, and *IMPORTANT*, set the current working directory there
  46.    GetModuleFileName (NULL, app_pathname, WCHAR_SIZEOF (app_pathname));
  47.    GetDirectoryPath (app_pathname, app_path);
  48.    SetCurrentDirectoryW (app_path);
  49.  
  50.    // initialize stuff
  51.    is_registered = false;
  52.    terminate_everything = false;
  53.    hMainWnd = NULL;
  54.    hChatterChannelsWnd = NULL;
  55.    hGamesWnd = NULL;
  56.    hMOTDWnd = NULL;
  57.    hOpponentsWnd = NULL;
  58.    hSoughtWnd = NULL;
  59.    is_paused = false; // clear pause status
  60. #ifdef NDEBUG
  61.    want_framerate = false; // release mode, don't display framerate
  62. #else
  63.    want_framerate = true; // display framerate in debug mode
  64. #endif // NDEBUG
  65.    is_dialogbox_about_validated = false;
  66.    is_dialogbox_challenge_validated = false;
  67.    is_dialogbox_changeappearance_validated = false;
  68.    is_dialogbox_comment_validated = false;
  69.    is_dialogbox_endgame_validated = false;
  70.    is_dialogbox_gotomove_validated = false;
  71.    is_dialogbox_renamesides_validated = false;
  72.    is_dialogbox_load_validated = false;
  73.    is_dialogbox_message_validated = false;
  74.    is_dialogbox_newgame_validated = false;
  75.    is_dialogbox_options_validated = false;
  76.    is_dialogbox_pawnpromotion_validated = false;
  77.    is_dialogbox_playercard_validated = false;
  78.    is_dialogbox_playerinfoname_validated = false;
  79.    is_dialogbox_quit_validated = false;
  80.    is_dialogbox_resign_validated = false;
  81.    is_dialogbox_save_validated = false;
  82.    is_dialogbox_saveposition_validated = false;
  83.    is_dialogbox_sendchallenge_validated = false;
  84.    is_dialogbox_sendseek_validated = false;
  85.    is_dialogbox_takeback_validated = false;
  86.    is_window_chat_validated = false;
  87.    is_window_chatterchannels_validated = false;
  88.    is_window_games_validated = false;
  89.    is_window_motd_validated = false;
  90.    is_window_opponents_validated = false;
  91.    is_window_sought_validated = false;
  92.    save_pathname[0] = 0;
  93.    srand ((unsigned int) time (NULL)); // initialize PRNG
  94.    animation_endtime = 0.0f;
  95.    command_ignoretime = 0.0f;
  96.    sound_playtime = 0.0f;
  97.    highlight_endtime = 0.0f;
  98.    previous_time = 0.0f;
  99.    frame_count = 0;
  100.  
  101.    // load the texts and ensure we have at least one display language
  102.    LocalizedTexts_Init ();
  103.    if (language_count < 1)
  104.    {
  105.       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);
  106.       return (-1); // bomb out on error
  107.    }
  108.  
  109.    // read configuration data
  110.    Config_Load ();
  111.  
  112.    // see if the program is registered
  113.    is_registered = IsRegistrationCorrect (options.registration.user_email, options.registration.activation_code);
  114.  
  115.    // uncomment the two lines below to test the registration code
  116.    //DialogBox_Registration ();
  117.    //return (0);
  118.  
  119.    // register the window class, create the window and show it
  120.    memset (&wc, 0, sizeof (wc));
  121.    wc.cbSize = sizeof (wc);
  122.    wc.style = CS_HREDRAW | CS_VREDRAW | CS_DBLCLKS; // double-clicks support
  123.    wc.lpfnWndProc = WindowProc_Main;
  124.    wc.hInstance = hAppInstance;
  125.    wc.hIcon = LoadIcon (hAppInstance, (wchar_t *) ICON_MAIN);
  126.    wc.hCursor = LoadCursor (NULL, IDC_ARROW);
  127.    wc.lpszClassName = PROGRAM_NAME L" WndClass";
  128.    RegisterClassEx (&wc);
  129.    swprintf_s (temp_string, WCHAR_SIZEOF (temp_string), PROGRAM_NAME L"%s", (is_registered ? L"" : LOCALIZE (L"EvaluationMode"))); // build window title
  130.    if (options.want_fullscreen)
  131.       hMainWnd = CreateWindowEx (0, wc.lpszClassName, temp_string, WS_POPUPWINDOW, // temp_string holds window title
  132.                                  0, 0, GetSystemMetrics (SM_CXSCREEN), GetSystemMetrics (SM_CYSCREEN), NULL, NULL, hAppInstance, NULL);
  133.    else
  134.    {
  135.       // in windowed mode, ensure window width and height aren't greater than screen size nor lower than a safe minimum
  136.       if (options.window_width > GetSystemMetrics (SM_CXMAXTRACK))
  137.          options.window_width = GetSystemMetrics (SM_CXMAXTRACK); // check this first in case screen size is reported incorrect
  138.       if (options.window_height > GetSystemMetrics (SM_CYMAXTRACK))
  139.          options.window_height = GetSystemMetrics (SM_CYMAXTRACK);
  140.       if (options.window_width < 640)
  141.          options.window_width = 640; // check this secondly in case screen size is reported incorrect
  142.       if (options.window_height < 480)
  143.          options.window_height = 480;
  144.  
  145.       hMainWnd = CreateWindowEx (0, wc.lpszClassName, temp_string, WS_OVERLAPPEDWINDOW, // temp_string holds window title
  146.                                  GetSystemMetrics (SM_CXSCREEN) / 2 - options.window_width / 2,
  147.                                  GetSystemMetrics (SM_CYSCREEN) / 2 - options.window_height / 2,
  148.                                  options.window_width, options.window_height, NULL, NULL, hAppInstance, NULL);
  149.    }
  150.    ShowWindow (hMainWnd, nCmdShow);
  151.  
  152.    // create the main menu line, and its accelerators
  153.    hMainMenu = NULL;
  154.    hMainAccelerators = NULL;
  155.    CreateOrUpdateApplicationMenu ();
  156.  
  157.    // display the splash screen
  158.    memset ((void *) &splash_bmp, 0, sizeof (splash_bmp));
  159.    hSplashBmp = W32LoadImage (L"%s/data/splash.bmp", app_path); // load the splash bitmap
  160.    GetObject (hSplashBmp, sizeof (splash_bmp), (void *) &splash_bmp); // get a structure containing its size (among others)
  161.    hdcMem = CreateCompatibleDC (NULL); // create a device context compatible with the screen
  162.    hbmTmp = SelectBitmap (hdcMem, hSplashBmp); // select our bitmap to use in it
  163.    hdc = BeginPaint (hMainWnd, &ps); // begin painting on the main window
  164.    GetClientRect (hMainWnd, &rect);
  165.    StretchBlt (hdc, 0, 0, rect.right, rect.bottom, hdcMem, 0, 0, splash_bmp.bmWidth, splash_bmp.bmHeight, SRCCOPY); // bit blit the bitmap into it
  166.    EndPaint (hMainWnd, &ps); // end painting on the main window
  167.    SelectObject (hdcMem, hbmTmp); // restore the previous selection
  168.    DeleteDC (hdcMem); // and delete the handles to the device context
  169.    DeleteObject (hSplashBmp); // and to the bitmap that we used
  170.  
  171.    // make the menu modeless
  172.    memset (&menu_info, 0, sizeof (menu_info)); // prepare menu info structure
  173.    menu_info.cbSize = sizeof (MENUINFO);
  174.    menu_info.fMask = MIM_STYLE;
  175.    GetMenuInfo (GetMenu (hMainWnd), &menu_info); // get current style
  176.    menu_info.dwStyle |= MNS_MODELESS; // add the "modeless" flag
  177.    SetMenuInfo (GetMenu (hMainWnd), &menu_info); // and send it back
  178.  
  179.    // load status icons, bitmaps and texts
  180.    handlestatus[HANDLESTATUS_AVAILABLE].icon = W32LoadIcon (L"%s/data/icons/available.ico", app_path);
  181.    handlestatus[HANDLESTATUS_AVAILABLE].bitmap = W32LoadImage (L"%s/data/status/available.bmp", app_path);
  182.    handlestatus[HANDLESTATUS_AVAILABLE].text = LOCALIZE (L"Opponents_StatusAvailable");
  183.    handlestatus[HANDLESTATUS_INGAME].icon = W32LoadIcon (L"%s/data/icons/ingame.ico", app_path);
  184.    handlestatus[HANDLESTATUS_INGAME].bitmap = W32LoadImage (L"%s/data/status/ingame.bmp", app_path);
  185.    handlestatus[HANDLESTATUS_INGAME].text = LOCALIZE (L"Opponents_StatusInGame");
  186.    handlestatus[HANDLESTATUS_INSIMULATION].icon = W32LoadIcon (L"%s/data/icons/insimulation.ico", app_path);
  187.    handlestatus[HANDLESTATUS_INSIMULATION].bitmap = W32LoadImage (L"%s/data/status/insimulation.bmp", app_path);
  188.    handlestatus[HANDLESTATUS_INSIMULATION].text = LOCALIZE (L"Opponents_StatusInSimulation");
  189.    handlestatus[HANDLESTATUS_INTOURNAMENT].icon = W32LoadIcon (L"%s/data/icons/intournament.ico", app_path);
  190.    handlestatus[HANDLESTATUS_INTOURNAMENT].bitmap = W32LoadImage (L"%s/data/status/intournament.bmp", app_path);
  191.    handlestatus[HANDLESTATUS_INTOURNAMENT].text = LOCALIZE (L"Opponents_StatusInTournament");
  192.    handlestatus[HANDLESTATUS_EXAMININGAGAME].icon = W32LoadIcon (L"%s/data/icons/examiningagame.ico", app_path);
  193.    handlestatus[HANDLESTATUS_EXAMININGAGAME].bitmap = W32LoadImage (L"%s/data/status/examiningagame.bmp", app_path);
  194.    handlestatus[HANDLESTATUS_EXAMININGAGAME].text = LOCALIZE (L"Opponents_StatusExaminingAGame");
  195.    handlestatus[HANDLESTATUS_NOTOPENFORAMATCH].icon = W32LoadIcon (L"%s/data/icons/notopenforamatch.ico", app_path);
  196.    handlestatus[HANDLESTATUS_NOTOPENFORAMATCH].bitmap = W32LoadImage (L"%s/data/status/notopenforamatch.bmp", app_path);
  197.    handlestatus[HANDLESTATUS_NOTOPENFORAMATCH].text = LOCALIZE (L"Opponents_StatusNotOpenForAMatch");
  198.    handlestatus[HANDLESTATUS_INACTIVEORBUSY].icon = W32LoadIcon (L"%s/data/icons/inactiveorbusy.ico", app_path);
  199.    handlestatus[HANDLESTATUS_INACTIVEORBUSY].bitmap = W32LoadImage (L"%s/data/status/inactiveorbusy.bmp", app_path);
  200.    handlestatus[HANDLESTATUS_INACTIVEORBUSY].text = LOCALIZE (L"Opponents_StatusInactiveOrBusy");
  201.    handlestatus[HANDLESTATUS_OFFLINE].icon = W32LoadIcon (L"%s/data/icons/offline.ico", app_path);
  202.    handlestatus[HANDLESTATUS_OFFLINE].bitmap = W32LoadImage (L"%s/data/status/offline.bmp", app_path);
  203.    handlestatus[HANDLESTATUS_OFFLINE].text = LOCALIZE (L"Opponents_StatusOffline");
  204.  
  205.    // load the system fonts
  206.    hFontChat = CreateFont (17, 0, 0, 0, FW_DONTCARE, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS,
  207.                            CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, L"Comic Sans MS");
  208.  
  209.    // before any rendering is done, it's a good idea to know what time it is
  210.    current_time = ProcessTime ();
  211.    stoppage_time = 0;
  212.    screensaverwatchdog_feedtime = current_time + 50.0f; // feed screensaver watchdog every 50 seconds
  213.  
  214.    // initialize renderer
  215.    if (!Render_Init ())
  216.       return (-1); // bomb out on error
  217.  
  218.    // load sprites
  219.    larrow_spriteindex = Render_LoadSprite (L"%s/data/sprites/arrow-left.*", app_path);
  220.    rarrow_spriteindex = Render_LoadSprite (L"%s/data/sprites/arrow-right.*", app_path);
  221.    chatbutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/chat.*", app_path);
  222.    gamesbutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/games.*", app_path);
  223.    peoplebutton_spriteindex = Render_LoadSprite (L"%s/data/sprites/people.*", app_path);
  224.    sepia_spriteindex = Render_LoadSprite (L"%s/data/sprites/sepia.*", app_path);
  225.    for (array_index = 0; array_index < 12; array_index++)
  226.       spinner_spriteindex[array_index] = Render_LoadSprite (L"%s/data/sprites/spinner-%d.png", app_path, array_index * 30); // spinning wheel
  227.  
  228.    // add our custom fonts to the list of available fonts for the duration of the process
  229.    swprintf_s (font_pathname, WCHAR_SIZEOF (font_pathname), L"%s/data/fonts/papyrus.ttf", app_path);
  230.    AddFontResourceEx (font_pathname, FR_PRIVATE, 0);
  231.    // load rendered fonts
  232.    arrow_fontindex = Render_LoadFont (L"Papyrus", 24, false, false);
  233.    chat_fontindex = Render_LoadFont (L"Papyrus", 32, false, false);
  234.    players_fontindex = Render_LoadFont (L"Papyrus", 40, false, true);
  235.    centermsg_fontindex = Render_LoadFont (L"Papyrus", 54, false, true);
  236.  
  237.    // load themes, initialize a new human vs. human game and setup the scene
  238.    if (!Themes_Init ())
  239.       return (-1); // bomb out on error
  240.    Board_Init (&the_board, PLAYER_HUMAN, PLAYER_HUMAN, FENSTARTUP_STANDARDCHESS);
  241.    Scene_Init (&the_scene, &the_board);
  242.  
  243.    // has a filename been specifed on the command-line AND that file exists ?
  244.    if ((lpCmdLine != NULL) && (lpCmdLine[0] != 0))
  245.    {
  246.       while (*lpCmdLine == '"')
  247.          lpCmdLine++; // skip leading quotes
  248.       if ((endptr = strchr (lpCmdLine, '"')) != NULL)
  249.          *endptr = 0; // break the string at the first ending quote
  250.  
  251.       // is it a file that exists ?
  252.       if (_stat (lpCmdLine, &fileinfo) == 0)
  253.       {
  254.          ConvertToWideChar (load_pathname, WCHAR_SIZEOF (load_pathname), lpCmdLine); // save pathname string
  255.          is_dialogbox_load_validated = true; // and act as if the user just validated a load dialog box
  256.       }
  257. #ifndef NDEBUG
  258.       // else is it a registration info ? if so, parse it
  259.       else if ((strncmp (lpCmdLine, "/r=", 3) == 0) && ((endptr = strchr (&lpCmdLine[3], ',')) != NULL))
  260.       {
  261.          *endptr = 0; // break the string at the separator between user email and activation code
  262.          ConvertToWideChar (temp_string, WCHAR_SIZEOF (temp_string), &lpCmdLine[3]); // read user email
  263.          is_registered = IsRegistrationCorrect (temp_string, atoi (endptr + 1)); // and see whether we're registered or not
  264.          DialogBox_NewGame (); // still open the "new game" dialog box
  265.       }
  266. #endif // !NDEBUG
  267.       else
  268.          DialogBox_NewGame (); // if specified filename doesn't exist, fallback to the "new game" dialog box
  269.    }
  270.    else
  271.       DialogBox_NewGame (); // when no filename is specified, display the new game dialog box
  272.  
  273.    // enter the main loop
  274.    while (!terminate_everything)
  275.    {
  276.       // see what time it is
  277.       current_time = ProcessTime ();
  278.       if (is_paused)
  279.          stoppage_time += (current_time - previous_time); // if we're paused, increase stoppage time
  280.  
  281.       // is it time to feed the screensaver watchdog ? (to prevent it from starting)
  282.       if (screensaverwatchdog_feedtime < current_time)
  283.       {
  284.          mousemove_input.type = INPUT_MOUSE;
  285.          memset (&mousemove_input.mi, 0, sizeof (mousemove_input.mi)); // blank out struct = no move at all :)
  286.          mousemove_input.mi.dwFlags = MOUSEEVENTF_MOVE;
  287.          SendInput (1, &mousemove_input, sizeof (mousemove_input)); // send a fake mouse move input event
  288.  
  289.          screensaverwatchdog_feedtime = current_time + 50.0f; // feed screensaver watchdog again in 50 seconds
  290.       }
  291.  
  292.       // are we in demo mode and is it time to quit ?
  293.       if (!is_registered && (current_time > DEMO_TIMEOUT))
  294.          DestroyWindow (hMainWnd); // if so, send a quit message in order to break the loop
  295.  
  296.       // grab the current window size
  297.       GetWindowRect (hMainWnd, &rect);
  298.       options.window_width = rect.right - rect.left;
  299.       options.window_height = rect.bottom - rect.top;
  300.  
  301.       // are we in the middle of an animation or just after it ?
  302.       if (current_time < animation_endtime + 0.5f)
  303.          the_scene.update = true; // always update during animations
  304.       else
  305.          the_scene.update |= Board_Think (&the_board); // make the board (i.e, both players) think
  306.  
  307.       MainLoop_FindCurrentViewer ();  // determine current viewer
  308.  
  309.       // see if we have a message waiting for any window in the current thread and dispatch it
  310.       while (PeekMessage (&msg, NULL, 0, 0, PM_REMOVE))
  311.       {
  312.          // check for accelerator keystrokes from the main window
  313.          if ((msg.hwnd != hMainWnd) || !TranslateAccelerator (hMainWnd, hMainAccelerators, &msg))
  314.          {
  315.             TranslateMessage (&msg); // translate and dispatch all other messages
  316.             DispatchMessage (&msg);
  317.          }
  318.       }
  319.  
  320.       // handle dialog box and window return codes
  321.       if (is_dialogbox_about_validated) DialogBox_About_Validated ();
  322.       if (is_dialogbox_challenge_validated) DialogBox_Challenge_Validated ();
  323.       if (is_dialogbox_changeappearance_validated) DialogBox_ChangeAppearance_Validated ();
  324.       if (is_dialogbox_comment_validated) DialogBox_Comment_Validated ();
  325.       if (is_dialogbox_endgame_validated) DialogBox_EndGame_Validated ();
  326.       if (is_dialogbox_gotomove_validated) DialogBox_GoToMove_Validated ();
  327.       if (is_dialogbox_renamesides_validated) DialogBox_RenameSides_Validated ();
  328.       if (is_dialogbox_load_validated) DialogBox_Load_Validated ();
  329.       if (is_dialogbox_message_validated) DialogBox_Message_Validated ();
  330.       if (is_dialogbox_newgame_validated) DialogBox_NewGame_Validated ();
  331.       if (is_dialogbox_options_validated) DialogBox_Options_Validated ();
  332.       if (is_dialogbox_pawnpromotion_validated) DialogBox_PawnPromotion_Validated ();
  333.       if (is_dialogbox_playercard_validated) DialogBox_PlayerCard_Validated ();
  334.       if (is_dialogbox_playerinfoname_validated) DialogBox_PlayerInfoName_Validated ();
  335.       if (is_dialogbox_quit_validated) DialogBox_Quit_Validated ();
  336.       if (is_dialogbox_resign_validated) DialogBox_Resign_Validated ();
  337.       if (is_dialogbox_save_validated) DialogBox_Save_Validated ();
  338.       if (is_dialogbox_saveposition_validated) DialogBox_SavePosition_Validated ();
  339.       if (is_dialogbox_sendchallenge_validated) DialogBox_SendChallenge_Validated ();
  340.       if (is_dialogbox_sendseek_validated) DialogBox_SendSeek_Validated ();
  341.       if (is_dialogbox_takeback_validated) DialogBox_Takeback_Validated ();
  342.       if (is_window_chat_validated) Window_Chat_Validated ();
  343.       if (is_window_chatterchannels_validated) Window_ChatterChannels_Validated ();
  344.       if (is_window_games_validated) Window_Games_Validated ();
  345.       if (is_window_motd_validated) Window_MOTD_Validated ();
  346.       if (is_window_opponents_validated) Window_Opponents_Validated ();
  347.       if (is_window_sought_validated) Window_Sought_Validated ();
  348.  
  349.       MainLoop_EvaluateGameState (); // evaluate game state
  350.  
  351.       // is the table rotating ?
  352.       if (Player_RotateTable (&the_board.players[current_viewer], current_time - previous_time))
  353.          the_scene.update = true; // if so, update the scene
  354.  
  355.       // are we highlighting something ?
  356.       if (highlight_endtime > current_time)
  357.          the_scene.update = true; // if so, update the scene
  358.  
  359.       // else if we WERE just highlighting something, clear the hovered positions
  360.       else if (highlight_endtime + 0.1f > current_time)
  361.       {
  362.          the_board.hovered_position[0] = -1;
  363.          the_board.hovered_position[1] = -1;
  364.          the_scene.update = true; // and update the scene
  365.       }
  366.  
  367.       // if we want the game clock, update scene every second
  368.       if (options.want_clock && ((int) current_time != (int) previous_time))
  369.          the_scene.update = true;
  370.  
  371.       // if there's something in the central text buffer, update scene too
  372.       if (the_scene.gui.central_text.is_displayed)
  373.          the_scene.update = true;
  374.  
  375.       // if we have a spinning wheel, update scene too
  376.       if (the_scene.gui.want_spinwheel)
  377.          the_scene.update = true;
  378.  
  379.       // do we NOT need to update the scene ?
  380.       if (!the_scene.update)
  381.       {
  382.          // cycle through all themes and see if one of them needs to be loaded
  383.          for (array_index = 0; array_index < theme_count; array_index++)
  384.             if (!themes[array_index].is_loaded)
  385.             {
  386.                Theme_Load (&themes[array_index], false); // load a bit more of this theme
  387.                break; // and stop looping (see you next pass)
  388.             }
  389.       }
  390.  
  391.       // do we need to update the scene ?
  392.       if (the_scene.update || want_framerate)
  393.       {
  394.          Scene_Update (&the_scene, &the_board); // evaluate which parts need to be placed
  395.          Render_RenderFrame (&the_scene); // render a game frame
  396.  
  397.          the_scene.update = false; // scene no longer needs to be updated now
  398.       }
  399.  
  400.       Audio_Think (); // ensure audio is playing
  401.  
  402.       previous_time = current_time; // save previous time
  403.       if (frame_count == 100)
  404.       {
  405.          frame_count = 0; // reset frame count every 100 frames
  406.          Sleep (1); // once every 100 frames, wait a millisecond
  407.       }
  408.       else
  409.          Sleep (0); // else just allow context switching
  410.       frame_count++; // increase the frame count
  411.    }
  412.  
  413.    /////////////////////////////////////////////////////////////////////////
  414.    // at this point, we exited the main loop and we are returning to Windows
  415.  
  416.    // release scene, game, themes and shutdown Direct3D
  417.    Scene_Shutdown (&the_scene);
  418.    Board_Shutdown (&the_board);
  419.    Themes_Shutdown ();
  420.    Render_Shutdown ();
  421.  
  422.    // delete the font resources
  423.    DeleteObject (hFontChat);
  424.  
  425.    // delete the bitmap and icon ressources
  426.    for (array_index = 1; array_index < sizeof (handlestatus) / sizeof (handlestatus[0]); array_index++)
  427.    {
  428.       DeleteObject (handlestatus[array_index].bitmap);
  429.       DestroyIcon (handlestatus[array_index].icon);
  430.    }
  431.  
  432.    // unregister window class
  433.    UnregisterClass (wc.lpszClassName, hAppInstance);
  434.  
  435.    // destroy the accelerators table
  436.    if (hMainAccelerators)
  437.       DestroyAcceleratorTable (hMainAccelerators);
  438.    hMainAccelerators = NULL;
  439.  
  440.    // destroy the application menu object
  441.    if (IsMenu (hMainMenu))
  442.       DestroyMenu (hMainMenu);
  443.    hMainMenu = NULL;
  444.  
  445.    // are we not registered yet ?
  446.    if (!is_registered)
  447.       DialogBox_Registration ();
  448.  
  449.    // save configuration data
  450.    Config_Save ();
  451.  
  452.    // unload localized texts
  453.    LocalizedTexts_Shutdown ();
  454.  
  455.    return (0); // and return to Windows.
  456. }
  457.  
  458.  
  459. static void MainLoop_FindCurrentViewer (void)
  460. {
  461.    // helper function that tells who is the current viewer
  462.  
  463.    if ((the_board.players[COLOR_WHITE].type == PLAYER_HUMAN) && (the_board.players[COLOR_BLACK].type == PLAYER_HUMAN))
  464.       current_viewer = Board_ColorToMove (&the_board); // if both players are human, track them both
  465.    else if (the_board.players[COLOR_WHITE].type == PLAYER_HUMAN)
  466.       current_viewer = COLOR_WHITE; // else if only the white is human, track the white
  467.    else if (the_board.players[COLOR_BLACK].type == PLAYER_HUMAN)
  468.       current_viewer = COLOR_BLACK; // else if it's the black, track the black
  469.    else
  470.       current_viewer = COLOR_WHITE; // else no human in game, track just the white
  471.  
  472.    return; // finished, current viewer is known
  473. }
  474.  
  475.  
  476. static void MainLoop_EvaluateGameState (void)
  477. {
  478.    // function to evaluate the game state in the main loop when a part has just moved
  479.  
  480.    static wchar_t window_title[256];
  481.  
  482.    player_t *current_player;
  483.    player_t *opposite_player;
  484.    player_t *network_player;
  485.    boardmove_t *last_move;
  486.    int enabled_value;
  487.    int move_index;
  488.  
  489.    if (!the_board.reevaluate)
  490.       return; // if the board doesn't need to be reevaluated, don't do anything
  491.  
  492.    // get current and opposite players
  493.    current_player = Player_GetCurrent ();
  494.    opposite_player = Player_GetOpposite ();
  495.  
  496.    // see if we're online
  497.    network_player = Player_FindByType (PLAYER_INTERNET);
  498.  
  499.    // has the game started ?
  500.    if (the_board.move_count > 1)
  501.    {
  502.       // game has started, enable the "save" and "save as" menu options
  503.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVE, MF_ENABLED);
  504.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEAS, MF_ENABLED);
  505.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_ENABLED);
  506.  
  507.       // enable the "go to move" menu option
  508.       EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_GOTOMOVE, MF_ENABLED);
  509.  
  510.       // are we watching the last move ?
  511.       if (the_board.viewed_move == the_board.move_count - 1)
  512.       {
  513.          // get a quick acccess to the last move
  514.          last_move = &the_board.moves[the_board.move_count - 1];
  515.  
  516.          // if the current player is a human AND its opponent is a computer, allow him to ask us for a hint
  517.          if ((current_player->type == PLAYER_HUMAN) && (opposite_player->type == PLAYER_COMPUTER))
  518.             EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SUGGESTMOVE, MF_ENABLED);
  519.          else
  520.             EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SUGGESTMOVE, MF_GRAYED);
  521.  
  522.          // (if the current player is a human
  523.          //  AND (its opponent is another human AND there's at least one move played)
  524.          //       OR (its opponent is a computer AND there are at least two moves played)
  525.          //       OR (its opponent is a remote player AND we're in game AND there are at least two moves played))
  526.          // 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
  527.          if (((current_player->type == PLAYER_HUMAN)
  528.               && ((opposite_player->type == PLAYER_HUMAN)
  529.                   || ((opposite_player->type == PLAYER_COMPUTER) && (the_board.move_count > 2))
  530.                   || ((opposite_player->type == PLAYER_INTERNET) && (opposite_player->is_in_game) && (the_board.move_count > 2))))
  531.              || ((current_player->type == PLAYER_INTERNET) && (current_player->is_in_game) && (the_board.move_count > 2)))
  532.             EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_CANCELLASTMOVE, MF_ENABLED);
  533.          else
  534.             EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_CANCELLASTMOVE, MF_GRAYED);
  535.  
  536.          // is the current player in check ? (to play the right sound)
  537.          // read as: was the last move an opponent's move AND did it put us to check ?
  538.          if (last_move->is_check)
  539.          {
  540.             // is it a checkmate ? (checkmate == check + stalemate)
  541.             if (last_move->is_stalemate)
  542.             {
  543.                // display the game over dialog box
  544.                the_board.game_state = (Board_ColorToMove (&the_board) == COLOR_WHITE ? STATE_BLACKWIN_CHECKMATE : STATE_WHITEWIN_CHECKMATE);
  545.                DialogBox_EndGame ();
  546.             }
  547.          }
  548.          else
  549.          {
  550.             // is it a stalemate ?
  551.             if (last_move->is_stalemate)
  552.             {
  553.                // display the game over dialog box
  554.                the_board.game_state = STATE_DRAW_STALEMATE;
  555.                DialogBox_EndGame ();
  556.             }
  557.          }
  558.  
  559.          // have there 50 moves been played each side (i.e, 100 plies) AND is the current player human ?
  560.          if ((the_board.move_count > 100) && (current_player->type == PLAYER_HUMAN))
  561.          {
  562.             // go backwards and see when is the latest move that took an opponent's piece OR the latest pawn move
  563.             for (move_index = the_board.move_count - 1; move_index >= 0; move_index--)
  564.                if (the_board.moves[move_index].has_captured || (the_board.moves[move_index].part == PART_PAWN))
  565.                   break; // stop as soon as we find one
  566.  
  567.             // can the fifty moves draw rule be claimed AND does the current player claims it ?
  568.             if (move_index + 1 + 100 < the_board.move_count)
  569.             {
  570.                // yes. Propose it to the side that's on move
  571. // TODO: non-modal MessageBox (copy dialog_newgame.cpp and use return values)
  572.             }
  573.          }
  574.  
  575.          if (the_scene.gui.larrow.state == 0)
  576.             the_scene.gui.larrow.state = 1; // enable "back" arrow if it isn't displayed yet
  577.          if (the_scene.gui.rarrow.state != 0)
  578.             the_scene.gui.rarrow.state = 0; // disable "forward" arrow if it's already displayed
  579.  
  580.          if (the_board.game_state == STATE_PLAYING)
  581.             Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  582.                            RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (is_paused ? L"Paused" : L"Current"));
  583.          else if ((the_board.game_state == STATE_BLACKWIN_CHECKMATE) || (the_board.game_state == STATE_WHITEWIN_CHECKMATE))
  584.             Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  585.                            RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (L"EndGame_CheckMate"));
  586.          else if ((the_board.game_state == STATE_WHITEWIN_RESIGNORFORFEIT) || (the_board.game_state == STATE_BLACKWIN_RESIGNORFORFEIT))
  587.             Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  588.                            RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (L"EndGame_Resign"));
  589.          else if (the_board.game_state == STATE_DRAW_STALEMATE)
  590.             Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  591.                            RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (L"EndGame_StaleMate"));
  592.          else if (the_board.game_state == STATE_DRAW_AGREEMENT)
  593.             Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  594.                            RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (L"EndGame_Agreement"));
  595.          else if (the_board.game_state == STATE_DRAW_OTHER)
  596.             Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  597.                            RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (L"EndGame_DrawOther"));
  598.  
  599.          // enable the "comment on this move" menu option
  600.          EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_COMMENTMOVE, MF_ENABLED);
  601.       }
  602.  
  603.       // else are we watching another move, but not the beginning of the game ?
  604.       else if (the_board.viewed_move > 0)
  605.       {
  606.          if (the_scene.gui.larrow.state == 0)
  607.             the_scene.gui.larrow.state = 1; // enable "back" arrow if it isn't displayed yet
  608.          if (the_scene.gui.rarrow.state == 0)
  609.             the_scene.gui.rarrow.state = 1; // enable "forward" arrow if it isn't displayed yet
  610.          Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  611.                         RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false,
  612.                         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")));
  613.  
  614.          // enable the "save position as" and "comment on this move" menu options
  615.          EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_ENABLED);
  616.          EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_COMMENTMOVE, MF_ENABLED);
  617.       }
  618.  
  619.       // else we must be watching the beginning of the game (no move yet)
  620.       else
  621.       {
  622.          if (the_scene.gui.larrow.state != 0)
  623.             the_scene.gui.larrow.state = 0; // disable "back" arrow if it's already displayed
  624.          if (the_scene.gui.rarrow.state == 0)
  625.             the_scene.gui.rarrow.state = 1; // enable "forward" arrow if it isn't displayed yet
  626.          Scene_SetText (&the_scene.gui.arrow_text, 3.3f, 5.0f, -1, ALIGN_CENTER, ALIGN_TOP, ALIGN_CENTER, arrow_fontindex,
  627.                         RGBACOLOR_SETALPHA (options.clock_color, 0x7f), 999999.0f, false, LOCALIZE (L"Beginning"));
  628.  
  629.          // disable the "save position as" and "comment on this move" menu options
  630.          EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_GRAYED);
  631.          EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_COMMENTMOVE, MF_GRAYED);
  632.       }
  633.    }
  634.    else
  635.    {
  636.       // game has not started, disable the "save", "save as" and "save position as" menu options
  637.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVE, MF_GRAYED);
  638.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEAS, MF_GRAYED);
  639.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SAVEPOSITIONAS, MF_GRAYED);
  640.  
  641.       // if the current player is a human AND its opponent is a computer, allow him to ask us for a hint
  642.       if ((current_player->type == PLAYER_HUMAN) && (opposite_player->type == PLAYER_COMPUTER))
  643.          EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SUGGESTMOVE, MF_ENABLED);
  644.       else
  645.          EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SUGGESTMOVE, MF_GRAYED);
  646.  
  647.       // disable the "cancel last move", "comment move" and "go to move" menu options
  648.       EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_CANCELLASTMOVE, MF_GRAYED);
  649.       EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_COMMENTMOVE, MF_GRAYED);
  650.       EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_GOTOMOVE, MF_GRAYED);
  651.  
  652.       is_paused = false; // clear pause status (we can only pause a game when it's been started)
  653.  
  654.       // and disable the two arrows and the arrow text
  655.       the_scene.gui.larrow.state = 0;
  656.       the_scene.gui.rarrow.state = 0;
  657.       the_scene.gui.arrow_text.is_displayed = false;
  658.    }
  659.  
  660.    // 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
  661.    if ((current_player->type == PLAYER_HUMAN) && (opposite_player->type == PLAYER_COMPUTER))
  662.       EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SWAPSIDES, MF_ENABLED);
  663.    else
  664.       EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_SWAPSIDES, MF_GRAYED);
  665.  
  666.    // no matter whether the game started or not, enable players renaming only if we are NOT in internet mode
  667.    EnableMenuItem (GetMenu (hMainWnd), MENUID_CHESSBOARD_RENAMESIDES, (network_player == NULL ? MF_ENABLED : MF_GRAYED));
  668.  
  669.    // update window title
  670.    if ((the_board.players[COLOR_WHITE].name[0] != 0) && (the_board.players[COLOR_BLACK].name[0] != 0))
  671.    {
  672.       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")));
  673.       SetWindowText (hMainWnd, window_title); // update window title
  674.    }
  675.    else if (the_board.players[COLOR_WHITE].name[0] != 0)
  676.    {
  677.       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")));
  678.       SetWindowText (hMainWnd, window_title); // update window title
  679.    }
  680.  
  681.    // are we in internet mode AND are we logged in ?
  682.    if ((network_player != NULL) && network_player->is_logged_in)
  683.    {
  684.       // are we currently playing a game ?
  685.       if (network_player->is_in_game)
  686.       {
  687.          GUIBUTTON_ENABLE (the_scene.gui.chatbutton); // enable chat button if it's not enabled yet
  688.          GUIBUTTON_DISABLE (the_scene.gui.gamesbutton); // disable games button if it was enabled
  689.          GUIBUTTON_DISABLE (the_scene.gui.peoplebutton); // disable people button if it was enabled
  690.          EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_RESIGN, MF_ENABLED); // allow resigning
  691.       }
  692.       else
  693.       {
  694.          GUIBUTTON_DISABLE (the_scene.gui.chatbutton); // disable chat button if it was enabled
  695.          GUIBUTTON_ENABLE (the_scene.gui.gamesbutton); // enable games button if it's not enabled yet
  696.          GUIBUTTON_ENABLE (the_scene.gui.peoplebutton); // enable people button if it's not enabled yet
  697.          EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_RESIGN, MF_GRAYED); // disable ability to resign
  698.       }
  699.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_PAUSE, MF_DISABLED); // disallow pause
  700.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_STATISTICS, MF_ENABLED); // enable stats
  701.  
  702.       enabled_value = MF_ENABLED; // remember to enable the internet-related menu items
  703.    }
  704.    // else it's a local or vs. computer game
  705.    else
  706.    {
  707.       GUIBUTTON_DISABLE (the_scene.gui.chatbutton); // disable chat button if it was enabled
  708.       GUIBUTTON_DISABLE (the_scene.gui.gamesbutton); // disable games button if it was enabled
  709.       GUIBUTTON_DISABLE (the_scene.gui.peoplebutton); // disable people button if it was enabled
  710.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_PAUSE, (the_board.move_count > 1 ? MF_ENABLED : MF_GRAYED)); // allow pause if the game has started
  711.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_RESIGN, (the_board.move_count > 1 ? MF_ENABLED : MF_GRAYED)); // allow resigning if the game has started
  712.       EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_STATISTICS, MF_GRAYED); // disable stats
  713.  
  714.       enabled_value = MF_GRAYED; // remember to disable the internet-related menu items
  715.    }
  716.  
  717.    EnableMenuItem (GetMenu (hMainWnd), MENUID_GAME_SETUPPOSITION, !enabled_value); // note the inversion
  718.    EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_SHOWONLINEPLAYERS, enabled_value);
  719.    EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_SHOWSOUGHTGAMES, enabled_value);
  720.    EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_SEEKGAME, enabled_value);
  721.    if (!options.network.want_publicchat)
  722.    {
  723.       EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_CHATTERCHANNELS, MF_GRAYED); // always grayed if we don't want public chat
  724.       EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_ENTERCHATTEXT, MF_GRAYED);
  725.    }
  726.    else
  727.    {
  728.       EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_CHATTERCHANNELS, enabled_value); // else enabled only in internet mode
  729.       EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_ENTERCHATTEXT, enabled_value);
  730.    }
  731.    EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_DISPLAYPLAYERCARD, enabled_value);
  732.    EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_DISPLAYYOURCARD, enabled_value);
  733.    EnableMenuItem (GetMenu (hMainWnd), MENUID_INTERNET_MOTD, enabled_value);
  734.  
  735.    the_board.reevaluate = false; // board evaluation has been done
  736.    return; // finished, new board state is known
  737. }
  738.