Subversion Repositories Games.Chess Giants

Rev

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

  1. // chessengine.cpp
  2.  
  3. #include "common.h"
  4.  
  5.  
  6. // global variables used in this module only
  7. static wchar_t chessengine_path[MAX_PATH];
  8. static wchar_t chessengine_shellcommand[MAX_PATH];
  9. static wchar_t chessengineinitfile_pathname[MAX_PATH];
  10. static int current_obstinacy;
  11. static bool is_hint_pending;
  12. FILE *fpipe;
  13.  
  14. // prototypes of local functions
  15. static void PlayerEngine_Recv (player_t *player);
  16. static void PlayerEngine_Send (player_t *player);
  17. static wchar_t *Move_BuildString (boardmove_t *move);
  18. static bool SendEngineHistoryToAuthor (void);
  19.  
  20.  
  21. bool PlayerEngine_Init (player_t *player)
  22. {
  23.    // this function starts a chess engine as a child process. This process's stdin and
  24.    // stdout are redirected to the handles we give it, so that we may read/write to it.
  25.  
  26.    engineprogram_t *program;
  27.    wchar_t current_path[MAX_PATH];
  28.    wchar_t widechar_buffer[256];
  29.    SYSTEM_INFO sysinfo;
  30.    int try_index;
  31.    FILE *fp;
  32.  
  33.    // reset stuff first
  34.    player->wants_hint = false;
  35.  
  36.    // quick access to engine program
  37.    program = &options.engine.programs[options.engine.selected_program];
  38.  
  39.    // build the chess engine module path and pathname
  40.    swprintf_s (chessengine_path, WCHAR_SIZEOF (chessengine_path), L"%s/engines/%s", app_path, program->folder);
  41.    swprintf_s (chessengine_shellcommand, WCHAR_SIZEOF (chessengine_shellcommand), L"\"%s/%s\" %s", chessengine_path, program->executable_name, program->executable_arguments);
  42.  
  43.    // start the engine behind a bidirectional I/O pipe
  44.    GetCurrentDirectory (WCHAR_SIZEOF (current_path), current_path); // save current directory
  45.    SetCurrentDirectory (chessengine_path); // temporarily set chess engine's startup directory as current directory
  46.    fpipe = pipe_open (chessengine_shellcommand, L"r+");
  47.    SetCurrentDirectory (current_path); // restore current directory
  48.    if (fpipe == NULL)
  49.    {
  50.       messagebox.hWndParent = hMainWnd;
  51.       wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
  52.       wcscpy_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"));
  53.       messagebox.flags = MB_ICONWARNING | MB_OK;
  54.       DialogBox_Message (&messagebox); // display a modeless error message box
  55.  
  56.       PlayerEngine_Shutdown (player); // on error, shutdown the engine
  57.       return (false);
  58.    }
  59.  
  60.    // wait for the engine process to display something (which will mean it's ready). Try for 5 seconds.
  61.    for (try_index = 0; try_index < 50; try_index++)
  62.    {
  63.       // read from pipe (non-blocking)
  64.       PlayerEngine_Recv (player);
  65.       if (player->recvbuffer[0] != 0)
  66.          break; // break as soon as we get something
  67.       Sleep (100); // next try in 100 milliseconds
  68.    }
  69.  
  70.    // has the engine process not spoken yet ?
  71.    if (player->recvbuffer[0] == 0)
  72.    {
  73.       messagebox.hWndParent = hMainWnd;
  74.       wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
  75.       swprintf_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"), program->folder);
  76.       messagebox.flags = MB_ICONWARNING | MB_OK;
  77.       DialogBox_Message (&messagebox); // display a modeless error message box
  78.  
  79.       PlayerEngine_Shutdown (player); // on error, shutdown the engine
  80.       return (false);
  81.    }
  82.  
  83.    // optionally initialize the debug log file
  84.    Debug_Init (L"Chess engine output.txt");
  85.    Debug_Log (L"===Using engine: %s [%s]===\n", program->friendly_name, chessengine_shellcommand);
  86.  
  87.    // build the init file full qualified path name and try to open it
  88.    swprintf_s (chessengineinitfile_pathname, WCHAR_SIZEOF (chessengineinitfile_pathname), L"%s/engines/%s/init.txt", app_path, program->folder);
  89.    _wfopen_s (&fp, chessengineinitfile_pathname, L"r");
  90.  
  91.    // could the init file be opened ?
  92.    if (fp != NULL)
  93.    {
  94.       Debug_Log (L"===Found initialization file, parsing...===\n", chessengineinitfile_pathname);
  95.  
  96.       // SMP HACK -- assume our engine is CECP compatible and set the max CPUs to use to core max - 1
  97.       // (the computer will look like hung if all CPU is taken)
  98.       GetSystemInfo (&sysinfo); // get the number of cores and build the corresponding engine initialization order
  99.       Player_SendBuffer_Add (player, 1000, L"mt %d\n", max (1, sysinfo.dwNumberOfProcessors - 1));
  100.  
  101.       // read line per line
  102.       while (fgetws (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), fp) != NULL)
  103.       {
  104.          if ((widechar_buffer[0] == L'#') || (widechar_buffer[0] == L'\n'))
  105.             continue; // skip comments and empty lines
  106.  
  107.          // new command line found, append it to the send buffer
  108.          Player_SendBuffer_Add (player, 1000, widechar_buffer);
  109.       }
  110.  
  111.       fclose (fp); // finished, close the file
  112.    }
  113.  
  114.    // everything's okay, set engine name as the player's name
  115.    wcscpy_s (player->name, WCHAR_SIZEOF (player->name), program->friendly_name);
  116.  
  117.    return (true); // finished
  118. }
  119.  
  120.  
  121. void PlayerEngine_Shutdown (player_t *player)
  122. {
  123.    // this function terminates the chess engine process and releases all handles attached to it
  124.  
  125.    int attempt_index;
  126.  
  127.    // send the engine a quit command
  128.    Player_SendBuffer_Add (player, 1000, options.engine.programs[options.engine.selected_program].command_quit);
  129.    Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  130.    PlayerEngine_Send (player);
  131.  
  132.    // check 10 times if the engine process has ended cleanly
  133.    for (attempt_index = 0; attempt_index < 10; attempt_index++)
  134.    {
  135.       if (!pipe_isalive (fpipe))
  136.          break; // break as soon as we've told the process exited cleanly
  137.  
  138.       Sleep (100); // else wait one tenth second
  139.    }
  140.  
  141.    // close the pipe (this will terminate the child process if it hasn't terminated yet)
  142.    pipe_close (fpipe);
  143.  
  144.    Debug_Log (L"===Engine closed===\n");
  145.    return; // finished
  146. }
  147.  
  148.  
  149. bool PlayerEngine_Think (player_t *player)
  150. {
  151.    // this function reads and writes any necessary data from and to the chess engine. Returns TRUE if scene needs to be updated.
  152.  
  153.    engineprogram_t *program;
  154.    wchar_t line_buffer[256];
  155.    wchar_t *line_pointer;
  156.    wchar_t *move_string;
  157.    int char_index;
  158.    int length;
  159.    boardmove_t move;
  160.    player_t *current_player;
  161.    player_t *opposite_player;
  162.    bool do_update;
  163.  
  164.    // quick access to chess engine program
  165.    program = &options.engine.programs[options.engine.selected_program];
  166.  
  167.    // don't update the scene until told otherwise
  168.    do_update = false;
  169.  
  170.    // get current and opposite players
  171.    current_player = Player_GetCurrent ();
  172.    opposite_player = Player_GetOpposite ();
  173.  
  174.    // is the game still alive AND has the engine just died ?
  175.    if ((the_board.game_state == STATE_PLAYING) && !pipe_isalive (fpipe))
  176.    {
  177.       Debug_Log (L"===Unrecoverable engine error: opponent wins!===\n");
  178.  
  179.       // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
  180.       Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
  181.  
  182.       // display a crash notification dialog box
  183.       if (MessageBox (hMainWnd, LOCALIZE (L"Error_EngineCrashed"), LOCALIZE (L"ImportantMessage"), MB_ICONWARNING | MB_YESNO) == IDYES)
  184.          if (!SendEngineHistoryToAuthor ())
  185.             MessageBox (hMainWnd, LOCALIZE (L"NoInternetConnection"), LOCALIZE (L"FatalError"), MB_ICONWARNING | MB_OK); // send the game engine history to the author and display an error message if failed
  186.  
  187.       // and display the game over dialog box
  188.       the_board.game_state = (opposite_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
  189.       DialogBox_EndGame ();
  190.  
  191.       do_update = true; // remember to update the 3D scene
  192.    }
  193.  
  194.    // read from pipe (non-blocking)
  195.    PlayerEngine_Recv (player);
  196.  
  197.    ////////////////
  198.    // START PARSING
  199.  
  200.    // read line per line...
  201.    line_pointer = player->recvbuffer; // start at the first character
  202.    while ((line_pointer = ReadACompleteLine (line_buffer, WCHAR_SIZEOF (line_buffer), line_pointer)) != NULL)
  203.    {
  204.       // is it an empty line or engine noise ?
  205.       if ((line_buffer[0] == 0) || iswspace (line_buffer[0]))
  206.          continue; // skip empty lines and engine noise
  207.  
  208.       // is the engine offering us a draw ?
  209.       if (wcsncmp (line_buffer, L"offer draw", 10) == 0)
  210.          continue; // if so, discard its offer (engine draws are unsupported) and proceed to the next line
  211.  
  212.       // else is it an *irrevocable* draw ? (at this point there's nothing we can do but accept it)
  213.       else if (wcsstr (line_buffer, L"1/2-1/2") != NULL)
  214.       {
  215.          Debug_Log (L"===Engine tells us that it's a draw: nobody wins!===\n");
  216.  
  217.          // play defeat sound (a draw is always a sort of defeat...) at the center of the board
  218.          Audio_PlaySound (SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
  219.  
  220.          // display the game over dialog box
  221.          the_board.game_state = STATE_DRAW_OTHER;
  222.          DialogBox_EndGame ();
  223.  
  224.          do_update = true; // remember to update the 3D scene
  225.          continue; // we processed that line
  226.       }
  227.  
  228.       // else is the engine *irrevocably* resigning ? (at this point there's nothing we can do but accept it)
  229.       else if (wcsncmp (line_buffer, L"resign", 6) == 0)
  230.       {
  231.          Debug_Log (L"===Engine tells us that %s resigns: %s wins!===\n", (current_player->color == COLOR_BLACK ? "black" : "white"), (current_player->color == COLOR_BLACK ? "white" : "black"));
  232.  
  233.          // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
  234.          Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
  235.  
  236.          // display the game over dialog box
  237.          the_board.game_state = (current_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
  238.          DialogBox_EndGame ();
  239.  
  240.          do_update = true; // remember to update the 3D scene
  241.          continue; // we processed that line
  242.       }
  243.  
  244.       // is engine allowed to resign ? if so, check if it's a game results
  245.       if (options.engine.obstinacy_level >= 0)
  246.       {
  247.          // is it a game result AND are we still in play ?
  248.          if ((wcsstr (line_buffer, L"1-0") != NULL) && (the_board.game_state == STATE_PLAYING))
  249.          {
  250.             // have we NOT been obstinate enough ?
  251.             if (current_obstinacy < options.engine.obstinacy_level)
  252.                current_obstinacy++; // if so, discard this resign and go on
  253.             else
  254.             {
  255.                Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
  256.  
  257.                // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
  258.                Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
  259.  
  260.                // display the game over dialog box
  261.                the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
  262.                DialogBox_EndGame ();
  263.  
  264.                do_update = true; // remember to update the 3D scene
  265.             }
  266.  
  267.             continue; // we processed that line
  268.          }
  269.          else if ((wcsstr (line_buffer, L"0-1") != NULL) && (the_board.game_state == STATE_PLAYING))
  270.          {
  271.             // have we NOT been obstinate enough ?
  272.             if (current_obstinacy < options.engine.obstinacy_level)
  273.                current_obstinacy++; // if so, discard this resign and go on
  274.             else
  275.             {
  276.                Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
  277.  
  278.                // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
  279.                Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
  280.  
  281.                // display the game over dialog box
  282.                the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
  283.                DialogBox_EndGame ();
  284.  
  285.                do_update = true; // remember to update the 3D scene
  286.             }
  287.  
  288.             continue; // we processed that line
  289.          }
  290.       }
  291.  
  292.       // has the game ended already ?
  293.       if (the_board.game_state > STATE_PLAYING)
  294.          continue; // ignore all that the engine tells us. Game is over already.
  295.  
  296.       // else is it a normal move AND not a polyglot error ?
  297.       else if (((move_string = wcsstr (line_buffer, program->replystring_move)) != NULL) && (wcsstr (line_buffer, L"illegal") == NULL))
  298.          move_string += wcslen (program->replystring_move); // go to the parsable data
  299.  
  300.       // else is it an unrecoverable engine error ?
  301.       else if (wcsstr (line_buffer, L"illegal") != NULL)
  302.       {
  303.          Debug_Log (L"===Unrecoverable engine error: opponent wins!===\n");
  304.  
  305.          // if opponent player is human, play the victory sound, else, play defeat sound at the center of the board
  306.          Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT, 0.0f, 0.0f, 0.04f);
  307.  
  308.          // display a crash notification dialog box
  309.          if (MessageBox (hMainWnd, LOCALIZE (L"Error_EngineCrashed"), LOCALIZE (L"ImportantMessage"), MB_ICONWARNING | MB_YESNO) == IDYES)
  310.             if (!SendEngineHistoryToAuthor ())
  311.                MessageBox (hMainWnd, LOCALIZE (L"NoInternetConnection"), LOCALIZE (L"FatalError"), MB_ICONWARNING | MB_OK); // send the game engine history to the author and display an error message if failed
  312.  
  313.          // and display the game over dialog box
  314.          the_board.game_state = (opposite_player->color == COLOR_BLACK ? STATE_WHITEWIN_RESIGNORFORFEIT : STATE_BLACKWIN_RESIGNORFORFEIT);
  315.          DialogBox_EndGame ();
  316.  
  317.          do_update = true; // remember to update the 3D scene
  318.       }
  319.  
  320.       // else it's any other sort of line
  321.       else
  322.          continue; // skip lines that don't contain any valid move data
  323.  
  324.       // now we are sure it's either a hint or a move (or some pondering)
  325.  
  326.       length = wcslen (move_string);
  327.       if ((length < 2) || (length > 9))
  328.          continue; // if string is too long to be a move, skip it
  329.  
  330.       // there must be valid move data on that line.
  331.  
  332.       // evaluate the engine move string
  333.       memcpy (move.slots, the_board.moves[the_board.move_count - 1].slots, sizeof (move.slots));
  334.       wcscpy_s (move.pgntext, WCHAR_SIZEOF (move.pgntext), move_string);
  335.       if (!Move_SetupFromSAN (&the_board.moves[the_board.move_count - 1], &move, Board_ColorToMove (&the_board)))
  336.       {
  337.          Debug_Log (L"===Skipping line (invalid move syntax)===\n%s", move_string);
  338.          continue; // so now, if there are NOT two digits AND it's not a kind of castle, it can't be a move so skip that line
  339.       }
  340.  
  341.       // is it NOT a hint, are blunders allowed, should we do one now AND can we do one now ?
  342.       if (!is_hint_pending && (options.engine.blunder_chances > 0) && (rand () % 100 < options.engine.blunder_chances)
  343.           && Move_FindRandomMove (&the_board.moves[the_board.move_count - 1], player->color, &move))
  344.       {
  345.          Player_SendBuffer_Add (player, 1000, program->command_force, Move_BuildString (&move)); // send the blunderous move to the engine
  346.          Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  347.          if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
  348.             Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
  349.          Debug_Log (L"===Discarding engine move, forcing a blunderous move (%s) instead===\n", Move_BuildString (&move)); // blunder
  350.       }
  351.  
  352.       // mark the engine's selected and hovered squares
  353.       Board_SetSelectedAndHovered (&the_board, move.source[0], move.source[1], move.target[0], move.target[1]);
  354.  
  355.       // was it NOT a hint ?
  356.       if (!is_hint_pending)
  357.       {
  358.          the_scene.gui.central_text.disappear_time = current_time + 1.0f; // fade the "thinking" phrase out now (FIXME: ugly)
  359.          the_scene.gui.want_spinwheel = false; // stop spinning wheel
  360.  
  361.          Board_AppendMove (&the_board, the_board.selected_position[0], the_board.selected_position[1], the_board.hovered_position[0], the_board.hovered_position[1], move.promotion_type, NULL);
  362.          the_board.has_playerchanged = true; // do the movement and switch players
  363.  
  364.          // forget the hovered and selected positions
  365.          Board_SetSelectedAndHovered (&the_board, -1, -1, -1, -1);
  366.          animation_endtime = current_time + ANIMATION_DURATION; // wait for animation time seconds
  367.       }
  368.  
  369.       // else it was a hint
  370.       else
  371.       {
  372.          the_scene.gui.central_text.disappear_time = current_time + 0.1f; // fade the "thinking" phrase out now quickly (FIXME: ugly)
  373.          the_scene.gui.want_spinwheel = false; // stop spinning wheel
  374.  
  375.          highlight_endtime = current_time + 2.0f; // just highlight this part for a little more than one second
  376.          is_hint_pending = false; // remember no hint is pending any longer
  377.  
  378.          // we must now restore the board to its last state. Just set up the board again from its current Forsyth-Edwards notation
  379.          Debug_Log (L"===Hint received, rebuilding board and telling engine to backup 1 move===\n");
  380.          Debug_Log (L"===setting up board using FEN string===\n");
  381.  
  382.          // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
  383.          // then get the current game state in FEN format and feed it to the engine
  384.          Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
  385.          Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  386.          Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
  387.          Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  388.  
  389.          if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
  390.             Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
  391.       }
  392.  
  393.       do_update = true; // remember to update the 3D scene
  394.    }
  395.  
  396.    // now clean the input buffer of all the lines we parsed
  397.    line_pointer = wcsrchr (player->recvbuffer, L'\n'); // reach the last carriage return
  398.    if (line_pointer != NULL)
  399.    {
  400.       line_pointer++; // skip the carriage return
  401.       length = wcslen (line_pointer); // get the remaining string length
  402.       for (char_index = 0; char_index < length; char_index++)
  403.          player->recvbuffer[char_index] = line_pointer[char_index]; // and recopy the remaining string at the beginning of the buffer
  404.       player->recvbuffer[char_index] = 0; // finish the string ourselves
  405.    }
  406.  
  407.    // END PARSING
  408.    //////////////
  409.  
  410.    /////////////////////////////////
  411.    // START NOTIFICATIONS PROCESSING
  412.  
  413.    // have we been notified that the board was just set up ?
  414.    if (the_board.was_setup)
  415.    {
  416.       Debug_Log (L"===Got board setup notification from interface===\n");
  417.  
  418.       // send a new game command to the chess engine
  419.       Player_SendBuffer_Add (player, 1000, program->command_new);
  420.       Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  421.  
  422.       // just set up the board from its Forsyth-Edwards notation
  423.       Debug_Log (L"===setting up board using FEN string===\n");
  424.  
  425.       // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
  426.       // then get the current game state in FEN format and feed it to the engine
  427.       Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
  428.       Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  429.       Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
  430.       Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  431.  
  432.       current_obstinacy = 0; // reset current obstinacy
  433.       is_hint_pending = false; // no hint was requested so far
  434.  
  435.       if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
  436.          Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
  437.    }
  438.  
  439.    // have we been notified that players are swapping colors ? (N.B. when this happens in human vs. computer mode, it's always that the human player is *GIVING* his turn)
  440.    if (the_board.want_playerswap)
  441.    {
  442.       Debug_Log (L"===Got player SWAP notification from interface===\n");
  443.       Player_SendBuffer_Add (player, 1000, program->command_go); // tell engine it's now the current player
  444.       Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  445.    }
  446.  
  447.    // have we been notified that the current player just changed ?
  448.    if (the_board.has_playerchanged)
  449.    {
  450.       Debug_Log (L"===Got player change notification from interface===\n");
  451.  
  452.       // is the current player our color ? (meaning is it engine's turn to play) ?
  453.       if (Board_ColorToMove (&the_board) == player->color)
  454.       {
  455.          // is it NOT a board setup AND has at least one move been played (meaning it was just the other's turn before) ?
  456.          if (!the_board.was_setup && (the_board.move_count > 1))
  457.          {
  458.             Debug_Log (L"===Player just played, sending the chosen move to engine===\n");
  459.             if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
  460.                Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
  461.  
  462.             // instruct it about its allowed search depth BEFORE each move (this ensures engine will be "ready" to handle the command)
  463.             // then build the move string, and send the move string to the engine
  464.             Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
  465.             Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  466.             Player_SendBuffer_Add (player, 1000, program->command_move, Move_BuildString (&the_board.moves[the_board.move_count - 1]));
  467.             Player_SendBuffer_Add (player, 1000, L"\n"); // end the send buffer with a carriage return
  468.          }
  469.  
  470.          // else game has not started yet, but it's our turn
  471.          else
  472.          {
  473.             Player_SendBuffer_Add (player, 1000, program->command_go); // so let's start the game
  474.             Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  475.          }
  476.       }
  477.    }
  478.  
  479.    // END NOTIFICATIONS PROCESSING
  480.    ///////////////////////////////
  481.  
  482.    // is it NOT our turn ?
  483.    if (current_player != player)
  484.    {
  485.       // does our opponent want a hint ?
  486.       if (current_player->wants_hint)
  487.       {
  488.          current_player->wants_hint = false; // don't ask twice
  489.          Debug_Log (L"===Hint requested, asking engine for it===\n");
  490.          Player_SendBuffer_Add (player, 1000, program->command_go); // tell the computer to analyze this position
  491.          Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  492.          is_hint_pending = true; // remember a hint is pending
  493.  
  494.          // FIXME: move to scene.cpp
  495.          Scene_UpdateText (&the_scene.gui.central_text, RGBA_TO_RGBACOLOR (255, 255, 255, 191), DURATION_INFINITE, true, LOCALIZE (L"Thinking")); // display the "thinking" phrase in the middle of the screen
  496.          the_scene.gui.want_spinwheel = true; // start spinning wheel
  497.          do_update = true; // remember to update the 3D scene
  498.       }
  499.  
  500.       // does our opponent want to cancel a move ?
  501.       if (current_player->wants_cancel)
  502.       {
  503.          current_player->wants_cancel = false; // don't ask twice (remember now before we switch players)
  504.          Debug_Log (L"===Move cancellation requested, rebuilding board and telling engine to backup 2 moves===\n");
  505.  
  506.          // rewind game 2 moves back
  507.          the_board.moves = (boardmove_t *) SAFE_realloc (the_board.moves, the_board.move_count, max (1, the_board.move_count - 2), sizeof (boardmove_t), false);
  508.          the_board.move_count = max (1, the_board.move_count - 2); // figure out how many moves we have now
  509.          the_board.viewed_move = the_board.move_count - 1; // take us back to the last move
  510.          the_board.game_state = STATE_PLAYING; // remember the game is now playing (in case we wanted to cancel the closing move of a finished game, this opens the game again)
  511.  
  512.          // just set up the board from its Forsyth-Edwards notation
  513.          Debug_Log (L"===setting up board using FEN string===\n");
  514.  
  515.          // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
  516.          // then get the current game state in FEN format and feed it to the engine
  517.          Player_SendBuffer_Add (player, 1000, program->command_sd, options.engine.depth);
  518.          Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  519.          Player_SendBuffer_Add (player, 1000, program->command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
  520.          Player_SendBuffer_Add (player, 1000, L"\n"); // since the format string was read from the options, don't forget to end it with a carriage return
  521.  
  522.          if (_wcsnicmp (program->friendly_name, L"Crafty", 6) == 0)
  523.             Player_SendBuffer_Add (player, 1000, L"disp\n"); // FIXME: we no longer need this Crafty-specific hack, do we?
  524.  
  525.          do_update = true; // remember to update the 3D scene
  526.       }
  527.    }
  528.  
  529.    // write to pipe (when we're allowed to)
  530.    if (!player->sendbuffer_locked && (animation_endtime + 1.0f < current_time))
  531.       PlayerEngine_Send (player);
  532.  
  533.    return (do_update); // finished, return whether we should update the scene or not
  534. }
  535.  
  536.  
  537. static void PlayerEngine_Recv (player_t *player)
  538. {
  539.    // helper function to read data from the pipe communicating with the game engine process
  540.  
  541.    //unsigned long amount_to_read;
  542.    unsigned long read_count;
  543.    int length;
  544.    unsigned int initial_pos;
  545.  
  546.    // get reception buffer's initial end position
  547.    initial_pos = wcslen (player->recvbuffer);
  548.    length = initial_pos;
  549.  
  550.    // as long as the pipe reports us there is data to read, read one byte at a time
  551.    while (pipe_hasdata (fpipe))
  552.    {
  553.       read_count = pipe_read (fpipe, player->ascii_recvbuffer, 1);
  554.       if (read_count == 0)
  555.          break; // read the pipe; if it fails, stop trying
  556.       if ((player->ascii_recvbuffer[0] == '\r') || (player->ascii_recvbuffer[0] == '%'))
  557.          continue; // ignore carriage returns and percent signs
  558.  
  559.       // convert the received character to wide char and append it to recvbuffer
  560.       player->ascii_recvbuffer[1] = 0; // terminate the received string ourselves
  561.       ConvertToWideChar (&player->recvbuffer[length], player->recvbuffer_size - length, player->ascii_recvbuffer);
  562.       length++; // there's one more character in the player's recv buffer
  563.    }
  564.  
  565.    // write what we received (if we received anything)
  566.    if (wcslen (player->recvbuffer) > initial_pos)
  567.       Debug_Log (L"===================================RECEIVED:===================================\n%s\n", &player->recvbuffer[initial_pos]);
  568.  
  569.    return; // finished
  570. }
  571.  
  572.  
  573. static void PlayerEngine_Send (player_t *player)
  574. {
  575.    // helper function to send data through the pipe communicating with the game engine process
  576.  
  577.    wchar_t widechar_buffer[256];
  578.    wchar_t *line_pointer;
  579.    char ascii_buffer[256];
  580.    unsigned long amount_written;
  581.  
  582.    player->sendbuffer_locked = true; // lock the buffer
  583.  
  584.    // write what we're sending (if we're sending anything)
  585.    if (player->sendbuffer[0] != 0)
  586.       Debug_Log (L"====================================SENDING:===================================\n%s\n", player->sendbuffer);
  587.  
  588.    // now read line per line...
  589.    line_pointer = player->sendbuffer; // start at the first character
  590.    while ((line_pointer = wcsgets (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), line_pointer)) != NULL)
  591.    {
  592.       wcscat_s (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), L"\n"); // put the carriage return back
  593.       ConvertTo7BitASCII (ascii_buffer, sizeof (ascii_buffer), widechar_buffer); // convert to ASCII
  594.       amount_written = pipe_write (fpipe, ascii_buffer, strlen (ascii_buffer)); // send data
  595.    }
  596.  
  597.    player->sendbuffer[0] = 0; // what we had to send has been sent, reset the send buffer
  598.    player->sendbuffer_locked = false; // and unlock it
  599.  
  600.    return; // finished
  601. }
  602.  
  603.  
  604. static wchar_t *Move_BuildString (boardmove_t *move)
  605. {
  606.    // helper function to build a move string to send to the engine from a particular board move. NOT THREAD SAFE.
  607.  
  608.    static wchar_t output_string[8];
  609.  
  610.    // construct the four first characters
  611.    swprintf_s (output_string, WCHAR_SIZEOF (output_string), L"%c%c%c%c",
  612.                L'a' + move->source[1], L'1' + move->source[0],
  613.                L'a' + move->target[1], L'1' + move->target[0]);
  614.  
  615.    // append any eventual promotion
  616.    if (move->promotion_type == PART_ROOK)
  617.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"r");
  618.    else if (move->promotion_type == PART_KNIGHT)
  619.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"n");
  620.    else if (move->promotion_type == PART_BISHOP)
  621.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"b");
  622.    else if (move->promotion_type == PART_QUEEN)
  623.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"q");
  624.  
  625.    return (output_string); // finished, return the move string
  626. }
  627.  
  628.  
  629. static bool SendEngineHistoryToAuthor (void)
  630. {
  631.    // this function upload the engine history to the remote server for debug purposes.
  632.  
  633.    static char history_buffer[512 * 1024];
  634.    static char base64_buffer[1024 * 1024];
  635.    static char http_buffer[1024 * 1024]; // used both for request and reply
  636.  
  637.    struct sockaddr_in service;
  638.    struct hostent *hostinfo;
  639.    int write_index;
  640.    int read_index;
  641.    int length;
  642.    SOCKET s;
  643.    FILE *fp;
  644.  
  645.    // get a hand on the log file and read its contents
  646.    _wfopen_s (&fp, logfile_pathname, L"rb");
  647.    if (fp == NULL)
  648.       return (false); // couldn't open game history log file, return an error condition
  649.    fseek (fp, 0, SEEK_END);
  650.    length = ftell (fp); // get file size
  651.    fseek (fp, 0, SEEK_SET);
  652.    if (length > sizeof (base64_buffer) - 1)
  653.       return (false); // history file too big, return an error condition
  654.    fread (base64_buffer, 1, length, fp);
  655.    base64_buffer[length] = 0; // terminate buffer ourselves
  656.    fclose (fp);
  657.    ConvertTo7BitASCII (history_buffer, sizeof (history_buffer), (wchar_t *) base64_buffer);
  658.  
  659.    // initialize the network subsystem if required
  660.    if (!Network_Init ())
  661.       return (false); // couldn't initialize WinSock, return an error condition
  662.  
  663.    // get our distribution server's IP address from the host name
  664.    hostinfo = gethostbyname ("pmbaty.com");
  665.    if (hostinfo == NULL)
  666.       return (false); // couldn't resolve hostname, return an error condition
  667.  
  668.    // fill in the sockaddr server structure with the server hostinfo data
  669.    service.sin_family = AF_INET;
  670.    service.sin_addr.s_addr = inet_addr (inet_ntoa (*(struct in_addr *) hostinfo->h_addr_list[0]));
  671.    service.sin_port = htons (80); // connect to webserver there (port 80)
  672.  
  673.    // create our socket
  674.    if ((s = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET)
  675.       return (false); // couldn't resolve hostname, return an error condition
  676.  
  677.    // connect to the distributor's webserver using that socket
  678.    if (connect (s, (struct sockaddr *) &service, sizeof (service)) == -1)
  679.    {
  680.       closesocket (s); // finished communicating, close TCP socket
  681.       return (false); // couldn't resolve hostname, return an error condition
  682.    }
  683.  
  684.    // build the HTTP POST query and send it
  685.    length = strlen ("data=") + base64_encode (base64_buffer, history_buffer, strlen (history_buffer));
  686.    sprintf_s (http_buffer, sizeof (http_buffer),
  687.       "POST /chess/sendcrash.php HTTP/1.1\r\n"
  688.       "Host: pmbaty.com\r\n"
  689.       "Content-Type: application/x-www-form-urlencoded\r\n"
  690.       "Content-Length: %d\r\n"
  691.       "Connection: close\r\n"
  692.       "\r\n"
  693.       "data=", length);
  694.    strcat_s (http_buffer, sizeof (http_buffer), base64_buffer);
  695.    length = strlen (http_buffer);
  696.    write_index = send (s, http_buffer, length, 0); // send the HTTP query
  697.    if (write_index != length)
  698.    {
  699.       closesocket (s); // finished communicating, close TCP socket
  700.       return (false); // couldn't resolve hostname, return an error condition
  701.    }
  702.  
  703.    // read the reply (10 seconds timeout)
  704.    http_buffer[0] = 0;
  705.    read_index = RecvWithTimeout (s, 10.0f, http_buffer, sizeof (http_buffer), 0);
  706.    if (read_index < 1)
  707.    {
  708.       closesocket (s); // finished communicating, close TCP socket
  709.       return (false); // couldn't resolve hostname, return an error condition
  710.    }
  711.  
  712.    closesocket (s); // finished communicating, close TCP socket
  713.  
  714.    // terminate recv buffer ourselves
  715.    http_buffer[read_index] = 0;
  716.  
  717.    //MessageBoxA (NULL, http_buffer, "HTTP response", MB_OK);
  718.    return (strstr (http_buffer, "Success") != NULL); // and return whether the server accepted our post
  719. }
  720.