Subversion Repositories Games.Chess Giants

Rev

Rev 77 | Rev 116 | 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 chessenginemodule_path[MAX_PATH];
  8. static wchar_t chessenginemodule_pathname[MAX_PATH];
  9. static wchar_t chessengineinitfile_pathname[MAX_PATH];
  10. static PROCESS_INFORMATION PlayerEngine_pi;
  11. static HANDLE hChessEngineStdinRd;
  12. static HANDLE hChessEngineStdinWr;
  13. static HANDLE hChessEngineStdoutRd;
  14. static HANDLE hChessEngineStdoutWr;
  15. static int current_obstinacy;
  16. static bool is_hint_pending;
  17.  
  18. // prototypes of local functions
  19. static void PlayerEngine_Recv (player_t *player);
  20. static void PlayerEngine_Send (player_t *player);
  21. static wchar_t *Move_BuildString (boardmove_t *move);
  22.  
  23.  
  24. bool PlayerEngine_Init (player_t *player)
  25. {
  26.    // this function starts a chess engine as a child process. This process's stdin and
  27.    // stdout are redirected to the handles we give it, so that we may read/write to it.
  28.  
  29.    wchar_t widechar_buffer[256];
  30.    SYSTEM_INFO sysinfo;
  31.    SECURITY_ATTRIBUTES saAttr;
  32.    STARTUPINFO si;
  33.    int try_index;
  34.    FILE *fp;
  35.  
  36.    // reset stuff first
  37.    hChessEngineStdinRd = NULL;
  38.    hChessEngineStdinWr = NULL;
  39.    hChessEngineStdoutRd = NULL;
  40.    hChessEngineStdoutWr = NULL;
  41.    player->wants_hint = false;
  42.  
  43.    // load the selected engine parameters
  44.    Config_LoadEngine (options.engine.program);
  45.  
  46.    // build the chess engine module path and pathname
  47.    swprintf_s (chessenginemodule_path, WCHAR_SIZEOF (chessenginemodule_path), L"%s/engines/%s", app_path, options.engine.program);
  48.    swprintf_s (chessenginemodule_pathname, WCHAR_SIZEOF (chessenginemodule_pathname), L"%s/engines/%s/%s", app_path, options.engine.program, options.engine.program_options.cmdline);
  49.  
  50.    // prepare the pipes' security attributes
  51.    memset (&saAttr, 0, sizeof (saAttr));
  52.    saAttr.nLength = sizeof (SECURITY_ATTRIBUTES);
  53.    saAttr.bInheritHandle = true; // set the bInheritHandle flag so pipe handles are inherited
  54.  
  55.    // create a pipe for the child process's stdout
  56.    CreatePipe (&hChessEngineStdoutRd, &hChessEngineStdoutWr, &saAttr, 0);
  57.    SetHandleInformation (hChessEngineStdoutRd, HANDLE_FLAG_INHERIT, 0); // ensure the read handle to the pipe for STDOUT is not inherited
  58.  
  59.    // create a pipe for the child process's stdin
  60.    CreatePipe (&hChessEngineStdinRd, &hChessEngineStdinWr, &saAttr, 0);
  61.    SetHandleInformation (hChessEngineStdinWr, HANDLE_FLAG_INHERIT, 0); // ensure the write handle to the pipe for STDIN is not inherited.
  62.  
  63.    // spawn the chess engine process with redirected input and output
  64.    memset (&si, 0, sizeof (si));
  65.    si.cb = sizeof (STARTUPINFOA);
  66.    si.dwFlags = STARTF_USESTDHANDLES;
  67.    si.hStdInput = hChessEngineStdinRd;
  68.    si.hStdOutput = hChessEngineStdoutWr;
  69.    si.hStdError = hChessEngineStdoutWr;
  70.    if (!CreateProcess (chessenginemodule_pathname, // module pathname
  71.                        options.engine.program_options.cmdline, // command line
  72.                        NULL, NULL,
  73.                        true, // handles are inherited
  74.                        CREATE_NO_WINDOW | DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
  75.                        NULL,
  76.                        chessenginemodule_path, // process path
  77.                        &si, // STARTUPINFO pointer
  78.                        &PlayerEngine_pi)) // receives PROCESS_INFORMATION
  79.    {
  80.       messagebox.hWndParent = hMainWnd;
  81.       wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
  82.       wcscpy_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"));
  83.       messagebox.flags = MB_ICONWARNING | MB_OK;
  84.       DialogBox_Message (&messagebox); // display a modeless error message box
  85.  
  86.       PlayerEngine_Shutdown (player); // on error, shutdown the engine
  87.       return (false);
  88.    }
  89.  
  90.    // wait for the engine process to display something (which will mean it's ready). Try for 5 seconds.
  91.    for (try_index = 0; try_index < 50; try_index++)
  92.    {
  93.       // read from pipe (non-blocking)
  94.       PlayerEngine_Recv (player);
  95.       if (player->recvbuffer[0] != 0)
  96.          break; // break as soon as we get something
  97.       Sleep (100); // next try in 100 milliseconds
  98.    }
  99.  
  100.    // has the engine process not spoken yet ?
  101.    if (player->recvbuffer[0] == 0)
  102.    {
  103.       messagebox.hWndParent = hMainWnd;
  104.       wcscpy_s (messagebox.title, WCHAR_SIZEOF (messagebox.title), LOCALIZE (L"ImportantMessage"));
  105.       wcscpy_s (messagebox.text, WCHAR_SIZEOF (messagebox.text), LOCALIZE (L"Error_ChessEngineInitializationFailed"));
  106.       messagebox.flags = MB_ICONWARNING | MB_OK;
  107.       DialogBox_Message (&messagebox); // display a modeless error message box
  108.  
  109.       PlayerEngine_Shutdown (player); // on error, shutdown the engine
  110.       return (false);
  111.    }
  112.  
  113.    // eventually initialize the debug log file
  114.    Debug_Init (L"Chess engine output.txt");
  115.  
  116.    // build the init file full qualified path name and try to open it
  117.    swprintf_s (chessengineinitfile_pathname, WCHAR_SIZEOF (chessengineinitfile_pathname), L"%s/engines/%s/init.txt", app_path, options.engine.program);
  118.    _wfopen_s (&fp, chessengineinitfile_pathname, L"r");
  119.  
  120.    // could the init file be opened ?
  121.    if (fp != NULL)
  122.    {
  123.       Debug_Log (L"===Found initialization file, parsing...===\n");
  124.  
  125.       // SMP HACK -- assume our engine is CECP compatible and set the max CPUs to use to core max - 1
  126.       // (the computer will look like hung if all CPU is taken)
  127.       GetSystemInfo (&sysinfo); // get the number of cores and build the corresponding engine initialization order
  128.       Player_SendBuffer_Add (player, 1000, L"mt %d\n", max (1, sysinfo.dwNumberOfProcessors - 1));
  129.  
  130.       // read line per line
  131.       while (fgetws (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), fp) != NULL)
  132.       {
  133.          if ((widechar_buffer[0] == L'#') || (widechar_buffer[0] == L'\n'))
  134.             continue; // skip comments and empty lines
  135.  
  136.          // new command line found, append it to the send buffer
  137.          Player_SendBuffer_Add (player, 1000, widechar_buffer);
  138.       }
  139.  
  140.       fclose (fp); // finished, close the file
  141.    }
  142.  
  143.    // everything's okay, set engine name as the player's name
  144.    wcscpy_s (player->name, WCHAR_SIZEOF (player->name), options.engine.program_options.name);
  145.  
  146.    return (true); // finished
  147. }
  148.  
  149.  
  150. void PlayerEngine_Shutdown (player_t *player)
  151. {
  152.    // this function terminates the chess engine process and releases all handles attached to it
  153.  
  154.    unsigned long exit_code;
  155.    unsigned long handle_flags;
  156.    int attempt_index;
  157.  
  158.    // send the engine a quit command
  159.    Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_quit);
  160.    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
  161.    PlayerEngine_Send (player);
  162.  
  163.    // close the pipe handles
  164.    if (hChessEngineStdinRd)
  165.       CloseHandle (hChessEngineStdinRd);
  166.    hChessEngineStdinRd = NULL;
  167.    if (hChessEngineStdinWr)
  168.       CloseHandle (hChessEngineStdinWr);
  169.    hChessEngineStdinWr = NULL;
  170.    if (hChessEngineStdoutRd)
  171.       CloseHandle (hChessEngineStdoutRd);
  172.    hChessEngineStdoutRd = NULL;
  173.    if (hChessEngineStdoutWr)
  174.       CloseHandle (hChessEngineStdoutWr);
  175.    hChessEngineStdoutWr = NULL;
  176.  
  177.    // check 10 times if the engine process has ended cleanly
  178.    for (attempt_index = 0; attempt_index < 10; attempt_index++)
  179.    {
  180.       if (GetExitCodeProcess (PlayerEngine_pi.hProcess, &exit_code) && (exit_code != STILL_ACTIVE))
  181.          break; // break as soon as we've told the process exited cleanly
  182.  
  183.       Sleep (100); // else wait one tenth second
  184.    }
  185.  
  186.    // has the engine NOT closen by itself yet ?
  187.    if ((attempt_index == 10) && GetExitCodeProcess (PlayerEngine_pi.hProcess, &exit_code) && (exit_code == STILL_ACTIVE))
  188.    {
  189.       Debug_Log (L"===Engine not closen, terminating process manually===\n");
  190.  
  191.       // terminate the chess engine process using our smart technique ^^
  192.       if (!SafeTerminateProcess (PlayerEngine_pi.hProcess, 0))
  193.          TerminateProcess (PlayerEngine_pi.hProcess, 0); // if process doesn't want to shutdown, kill it
  194.    }
  195.    else
  196.       Debug_Log (L"===Engine closed cleanly===\n");
  197.  
  198.    if (PlayerEngine_pi.hProcess)
  199.       CloseHandle (PlayerEngine_pi.hProcess);
  200.    PlayerEngine_pi.hProcess = NULL;
  201.    if (GetHandleInformation (PlayerEngine_pi.hThread, &handle_flags))
  202.       CloseHandle (PlayerEngine_pi.hThread);
  203.    PlayerEngine_pi.hThread = NULL;
  204.  
  205.    // and finally reset the process information structure
  206.    memset (&PlayerEngine_pi, 0, sizeof (PlayerEngine_pi));
  207.  
  208.    return; // finished
  209. }
  210.  
  211.  
  212. bool PlayerEngine_Think (player_t *player)
  213. {
  214.    // this function reads and writes any necessary data from and to the chess engine. Returns TRUE if scene needs to be updated.
  215.  
  216.    wchar_t line_buffer[256];
  217.    wchar_t *line_pointer;
  218.    wchar_t *move_string;
  219.    int char_index;
  220.    int length;
  221.    boardmove_t move;
  222.    player_t *current_player;
  223.    player_t *opposite_player;
  224.    bool do_update;
  225.  
  226.    // don't update the scene until told otherwise
  227.    do_update = false;
  228.  
  229.    // get current and opposite players
  230.    current_player = Player_GetCurrent ();
  231.    opposite_player = Player_GetOpposite ();
  232.  
  233.    // read from pipe (non-blocking)
  234.    PlayerEngine_Recv (player);
  235.  
  236.    ////////////////
  237.    // START PARSING
  238.  
  239.    // read line per line...
  240.    line_pointer = player->recvbuffer; // start at the first character
  241.    while ((line_pointer = ReadACompleteLine (line_buffer, WCHAR_SIZEOF (line_buffer), line_pointer)) != NULL)
  242.    {
  243.       // is it an empty line or engine noise ?
  244.       if ((line_buffer[0] == 0) || iswspace (line_buffer[0]))
  245.          continue; // skip empty lines and engine noise
  246.  
  247.       // is the engine *irrevocably* resigning ? (at this point there's nothing we can do but accept it)
  248.       if (wcsncmp (line_buffer, L"resign", 6) == 0)
  249.       {
  250.          if (current_player->color == COLOR_BLACK)
  251.             Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
  252.          else
  253.             Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
  254.  
  255.          // if opponent player is human, play the victory sound, else, play defeat sound
  256.          Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
  257.  
  258.          // display the game over dialog box
  259.          if (current_player->color == COLOR_BLACK)
  260.             the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
  261.          else
  262.             the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
  263.          DialogBox_EndGame ();
  264.  
  265.          do_update = true; // remember to update the 3D scene
  266.  
  267.          continue; // we processed that line
  268.       }
  269.  
  270.       // else is the engine offering us a draw ?
  271.       if (wcsncmp (line_buffer, L"offer draw", 6) == 0)
  272.          continue; // if so, discard its offer (engine draws are unsupported) and proceed to the next line
  273.  
  274.       // is engine allowed to resign ? if so, check if it's a game results
  275.       if (options.engine.obstinacy_level >= 0)
  276.       {
  277.          // is it a game result AND are we still in play ?
  278.          if ((wcsstr (line_buffer, L"1-0") != NULL) && (the_board.game_state == STATE_PLAYING))
  279.          {
  280.             // have we NOT been obstinate enough ?
  281.             if (current_obstinacy < options.engine.obstinacy_level)
  282.                current_obstinacy++; // if so, discard this resign and go on
  283.             else
  284.             {
  285.                Debug_Log (L"===Engine tells us that black resigns: white wins!===\n");
  286.  
  287.                // if opponent player is human, play the victory sound, else, play defeat sound
  288.                Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
  289.  
  290.                // display the game over dialog box
  291.                the_board.game_state = STATE_WHITEWIN_RESIGNORFORFEIT;
  292.                DialogBox_EndGame ();
  293.  
  294.                do_update = true; // remember to update the 3D scene
  295.             }
  296.  
  297.             continue; // we processed that line
  298.          }
  299.          else if ((wcsstr (line_buffer, L"0-1") != NULL) && (the_board.game_state == STATE_PLAYING))
  300.          {
  301.             // have we NOT been obstinate enough ?
  302.             if (current_obstinacy < options.engine.obstinacy_level)
  303.                current_obstinacy++; // if so, discard this resign and go on
  304.             else
  305.             {
  306.                Debug_Log (L"===Engine tells us that white resigns: black wins!===\n");
  307.  
  308.                // if opponent player is human, play the victory sound, else, play defeat sound
  309.                Audio_PlaySound (opposite_player->type == PLAYER_HUMAN ? SOUNDTYPE_VICTORY : SOUNDTYPE_DEFEAT);
  310.  
  311.                // display the game over dialog box
  312.                the_board.game_state = STATE_BLACKWIN_RESIGNORFORFEIT;
  313.                DialogBox_EndGame ();
  314.  
  315.                do_update = true; // remember to update the 3D scene
  316.             }
  317.  
  318.             continue; // we processed that line
  319.          }
  320.       }
  321.  
  322.       // has the game ended already ?
  323.       if (the_board.game_state > STATE_PLAYING)
  324.          continue; // ignore all that the engine tells us. Game is over already.
  325.  
  326.       // else is it a normal move ?
  327.       else if ((move_string = wcsstr (line_buffer, options.engine.program_options.replystring_move)) != NULL)
  328.          move_string += wcslen (options.engine.program_options.replystring_move); // go to the parsable data
  329.  
  330.       // else it's any other sort of line
  331.       else
  332.          continue; // skip lines that don't contain any valid move data
  333.  
  334.       // now we are sure it's either a hint or a move (or some pondering)
  335.  
  336.       length = wcslen (move_string);
  337.       if ((length < 2) || (length > 9))
  338.          continue; // if string is too long to be a move, skip it
  339.  
  340.       // there must be valid move data on that line.
  341.  
  342.       // evaluate the engine move string
  343.       memcpy (move.slots, the_board.moves[the_board.move_count - 1].slots, sizeof (move.slots));
  344.       wcscpy_s (move.pgntext, WCHAR_SIZEOF (move.pgntext), move_string);
  345.       if (!Move_SetupFromSAN (&the_board.moves[the_board.move_count - 1], &move, Board_ColorToMove (&the_board)))
  346.       {
  347.          Debug_Log (L"===Skipping line (invalid move syntax)===\n%s", move_string);
  348.          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
  349.       }
  350.  
  351.       // is it NOT a hint, are blunders allowed, should we do one now AND can we do one now ?
  352.       if (!is_hint_pending && (options.engine.blunder_chances > 0) && (rand () % 100 < options.engine.blunder_chances)
  353.           && Move_FindRandomMove (&the_board.moves[the_board.move_count - 1], player->color, &move))
  354.       {
  355.          Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_force, Move_BuildString (&move)); // send the blunderous move to the engine
  356.          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
  357.          if (wcscmp (options.engine.program, L"Crafty") == 0)
  358.             Player_SendBuffer_Add (player, 1000, L"disp\n");
  359.          Debug_Log (L"===Discarding engine move, forcing a blunderous move (%s) instead===\n", Move_BuildString (&move)); // blunder
  360.       }
  361.  
  362.       // mark the engine's selected and hovered squares
  363.       Board_SetSelectedAndHovered (&the_board, move.source[0], move.source[1], move.target[0], move.target[1]);
  364.  
  365.       // was it NOT a hint ?
  366.       if (!is_hint_pending)
  367.       {
  368.          the_scene.gui.central_text.disappear_time = current_time + 1.0f; // fade the "thinking" phrase out now (FIXME: ugly)
  369.          the_scene.gui.want_spinwheel = false; // stop spinning wheel
  370.  
  371.          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);
  372.          the_board.has_playerchanged = true; // do the movement and switch players
  373.  
  374.          // forget the hovered and selected positions
  375.          Board_SetSelectedAndHovered (&the_board, -1, -1, -1, -1);
  376.          animation_endtime = current_time + ANIMATION_DURATION; // wait for animation time seconds
  377.          sound_playtime = current_time + ANIMATION_DURATION - 0.1f; // play sound near the end of animation
  378.       }
  379.  
  380.       // else it was a hint
  381.       else
  382.       {
  383.          the_scene.gui.central_text.disappear_time = current_time + 0.1f; // fade the "thinking" phrase out now quickly (FIXME: ugly)
  384.          the_scene.gui.want_spinwheel = false; // stop spinning wheel
  385.  
  386.          highlight_endtime = current_time + 2.0f; // just highlight this part for a little more than one second
  387.          is_hint_pending = false; // remember no hint is pending any longer
  388.  
  389.          // we must now restore the board to its last state. Just set up the board again from its current Forsyth-Edwards notation
  390.          Debug_Log (L"===Hint received, rebuilding board and telling engine to backup 1 move===\n");
  391.          Debug_Log (L"===setting up board using FEN string===\n");
  392.  
  393.          // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
  394.          // then get the current game state in FEN format and feed it to the engine
  395.          Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
  396.          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
  397.          Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
  398.          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
  399.  
  400.          if (wcscmp (options.engine.program, L"Crafty") == 0)
  401.             Player_SendBuffer_Add (player, 1000, L"disp\n");
  402.       }
  403.  
  404.       do_update = true; // remember to update the 3D scene
  405.    }
  406.  
  407.    // now clean the input buffer of all the lines we parsed
  408.    line_pointer = wcsrchr (player->recvbuffer, L'\n'); // reach the last carriage return
  409.    if (line_pointer != NULL)
  410.    {
  411.       line_pointer++; // skip the carriage return
  412.       length = wcslen (line_pointer); // get the remaining string length
  413.       for (char_index = 0; char_index < length; char_index++)
  414.          player->recvbuffer[char_index] = line_pointer[char_index]; // and recopy the remaining string at the beginning of the buffer
  415.       player->recvbuffer[char_index] = 0; // finish the string ourselves
  416.    }
  417.  
  418.    // END PARSING
  419.    //////////////
  420.  
  421.    /////////////////////////////////
  422.    // START NOTIFICATIONS PROCESSING
  423.  
  424.    // have we been notified that the board was just set up ?
  425.    if (the_board.was_setup)
  426.    {
  427.       Debug_Log (L"===Got board setup notification from interface===\n");
  428.  
  429.       // send a new game command to the chess engine
  430.       Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_new);
  431.       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
  432.  
  433.       // just set up the board from its Forsyth-Edwards notation
  434.       Debug_Log (L"===setting up board using FEN string===\n");
  435.  
  436.       // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
  437.       // then get the current game state in FEN format and feed it to the engine
  438.       Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
  439.       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
  440.       Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
  441.       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
  442.  
  443.       current_obstinacy = 0; // reset current obstinacy
  444.       is_hint_pending = false; // no hint was requested so far
  445.  
  446.       if (wcscmp (options.engine.program, L"Crafty") == 0)
  447.          Player_SendBuffer_Add (player, 1000, L"disp\n");
  448.    }
  449.  
  450.    // 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)
  451.    if (the_board.want_playerswap)
  452.    {
  453.       Debug_Log (L"===Got player SWAP notification from interface===\n");
  454.       Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_go); // tell engine it's now the current player
  455.       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
  456.    }
  457.  
  458.    // have we been notified that the current player just changed ?
  459.    if (the_board.has_playerchanged)
  460.    {
  461.       Debug_Log (L"===Got player change notification from interface===\n");
  462.  
  463.       // is the current player our color ? (meaning is it engine's turn to play) ?
  464.       if (Board_ColorToMove (&the_board) == player->color)
  465.       {
  466.          // is it NOT a board setup AND has at least one move been played (meaning it was just the other's turn before) ?
  467.          if (!the_board.was_setup && (the_board.move_count > 1))
  468.          {
  469.             Debug_Log (L"===Player just played, sending the chosen move to engine===\n");
  470.             if (wcscmp (options.engine.program, L"Crafty") == 0)
  471.                Player_SendBuffer_Add (player, 1000, L"disp\n");
  472.  
  473.             // instruct it about its allowed search depth BEFORE each move (this ensures engine will be "ready" to handle the command)
  474.             // then build the move string, and send the move string to the engine
  475.             Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
  476.             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
  477.             Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_move, Move_BuildString (&the_board.moves[the_board.move_count - 1]));
  478.             Player_SendBuffer_Add (player, 1000, L"\n"); // end the send buffer with a carriage return
  479.          }
  480.  
  481.          // else game has not started yet, but it's our turn
  482.          else
  483.          {
  484.             Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_go); // so let's start the game
  485.             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
  486.          }
  487.       }
  488.    }
  489.  
  490.    // END NOTIFICATIONS PROCESSING
  491.    ///////////////////////////////
  492.  
  493.    // is it NOT our turn ?
  494.    if (current_player != player)
  495.    {
  496.       // does our opponent want a hint ?
  497.       if (current_player->wants_hint)
  498.       {
  499.          current_player->wants_hint = false; // don't ask twice
  500.          Debug_Log (L"===Hint requested, asking engine for it===\n");
  501.          Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_go); // tell the computer to analyze this position
  502.          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
  503.          is_hint_pending = true; // remember a hint is pending
  504.  
  505.          // FIXME: move to scene.cpp
  506.          Scene_SetText (&the_scene.gui.central_text, 50.0f, 40.0f, -1, ALIGN_CENTER, ALIGN_CENTER, ALIGN_CENTER, centermsg_fontindex, RGBA_TO_RGBACOLOR (255, 255, 255, 191),
  507.                         999999.0f, true, LOCALIZE (L"Thinking")); // display the "thinking" phrase in the middle of the screen
  508.          the_scene.gui.want_spinwheel = true; // start spinning wheel
  509.          do_update = true; // remember to update the 3D scene
  510.       }
  511.  
  512.       // does our opponent want to cancel a move ?
  513.       if (current_player->wants_cancel)
  514.       {
  515.          current_player->wants_cancel = false; // don't ask twice (remember now before we switch players)
  516.          Debug_Log (L"===Move cancellation requested, rebuilding board and telling engine to backup 2 moves===\n");
  517.  
  518.          // rewind game 2 moves back
  519.          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);
  520.          the_board.move_count = max (1, the_board.move_count - 2); // figure out how many moves we have now
  521.          the_board.viewed_move = the_board.move_count - 1; // take us back to the last move
  522.  
  523.          // just set up the board from its Forsyth-Edwards notation
  524.          Debug_Log (L"===setting up board using FEN string===\n");
  525.  
  526.          // instruct it about its allowed search depth BEFORE each table set (this ensures engine will be "ready" to handle the command)
  527.          // then get the current game state in FEN format and feed it to the engine
  528.          Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_sd, options.engine.depth);
  529.          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
  530.          Player_SendBuffer_Add (player, 1000, options.engine.program_options.command_setboard, the_board.moves[the_board.move_count - 1].fen_string);
  531.          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
  532.  
  533.          if (wcscmp (options.engine.program, L"Crafty") == 0)
  534.             Player_SendBuffer_Add (player, 1000, L"disp\n");
  535.  
  536.          do_update = true; // remember to update the 3D scene
  537.       }
  538.    }
  539.  
  540.    // write to pipe (when we're allowed to)
  541.    if (!player->sendbuffer_locked && (animation_endtime + 1.0f < current_time))
  542.       PlayerEngine_Send (player);
  543.  
  544.    return (do_update); // finished, return whether we should update the scene or not
  545. }
  546.  
  547.  
  548. static void PlayerEngine_Recv (player_t *player)
  549. {
  550.    // helper function to read data from the pipe communicating with the game engine process
  551.  
  552.    unsigned long amount_to_read;
  553.    unsigned long read_count;
  554.    int byte_index;
  555.    int rewrite_index;
  556.    int length;
  557.    unsigned int initial_pos;
  558.  
  559.    // get reception buffer's initial end position
  560.    initial_pos = wcslen (player->recvbuffer);
  561.  
  562.    // as long as the pipe reports us there is data to read...
  563.    while (PeekNamedPipe (hChessEngineStdoutRd, NULL, 0, NULL, &amount_to_read, NULL) && (amount_to_read > 0))
  564.    {
  565.       if (!ReadFile (hChessEngineStdoutRd, player->ascii_recvbuffer, min (amount_to_read, (unsigned long) player->recvbuffer_size - 1), &read_count, NULL))
  566.          break; // read the pipe; if it fails, stop trying
  567.  
  568.       // parse all received data and eradicate all carriage returns and percent signs
  569.       rewrite_index = 0;
  570.       for (byte_index = 0; byte_index < (int) read_count; byte_index++)
  571.          if ((player->ascii_recvbuffer[byte_index] != '\r') && (player->ascii_recvbuffer[byte_index] != '%'))
  572.          {
  573.             player->ascii_recvbuffer[rewrite_index] = player->ascii_recvbuffer[byte_index];
  574.             rewrite_index++;
  575.          }
  576.       player->ascii_recvbuffer[rewrite_index] = 0; // terminate the buffer ourselves
  577.  
  578.       // convert to wide char and append it to recvbuffer
  579.       length = wcslen (player->recvbuffer);
  580.       ConvertToWideChar (&player->recvbuffer[length], player->recvbuffer_size - length, player->ascii_recvbuffer);
  581.    }
  582.  
  583.    // write what we received (if we received anything)
  584.    if (wcslen (player->recvbuffer) > initial_pos)
  585.       Debug_Log (L"===================================RECEIVED:===================================\n%s\n", &player->recvbuffer[initial_pos]);
  586.  
  587.    return; // finished
  588. }
  589.  
  590.  
  591. static void PlayerEngine_Send (player_t *player)
  592. {
  593.    // helper function to send data through the pipe communicating with the game engine process
  594.  
  595.    wchar_t widechar_buffer[256];
  596.    wchar_t *line_pointer;
  597.    char ascii_buffer[256];
  598.    unsigned long amount_written;
  599.  
  600.    player->sendbuffer_locked = true; // lock the buffer
  601.  
  602.    // write what we're sending (if we're sending anything)
  603.    if (player->sendbuffer[0] != 0)
  604.       Debug_Log (L"====================================SENDING:===================================\n%s\n", player->sendbuffer);
  605.  
  606.    // now read line per line...
  607.    line_pointer = player->sendbuffer; // start at the first character
  608.    while ((line_pointer = wcsgets (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), line_pointer)) != NULL)
  609.    {
  610.       wcscat_s (widechar_buffer, WCHAR_SIZEOF (widechar_buffer), L"\n"); // put the carriage return back
  611.       ConvertTo7BitASCII (ascii_buffer, sizeof (ascii_buffer), widechar_buffer); // convert to ASCII
  612.       WriteFile (hChessEngineStdinWr, ascii_buffer, strlen (ascii_buffer), &amount_written, NULL); // send data
  613.    }
  614.  
  615.    player->sendbuffer[0] = 0; // what we had to send has been sent, reset the send buffer
  616.    player->sendbuffer_locked = false; // and unlock it
  617.  
  618.    return; // finished
  619. }
  620.  
  621.  
  622. static wchar_t *Move_BuildString (boardmove_t *move)
  623. {
  624.    // helper function to build a move string to send to the engine from a particular board move. NOT THREAD SAFE.
  625.  
  626.    static wchar_t output_string[8];
  627.  
  628.    // construct the four first characters
  629.    swprintf_s (output_string, WCHAR_SIZEOF (output_string), L"%c%c%c%c",
  630.                L'a' + move->source[1], L'1' + move->source[0],
  631.                L'a' + move->target[1], L'1' + move->target[0]);
  632.  
  633.    // append any eventual promotion
  634.    if (move->promotion_type == PART_ROOK)
  635.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"r");
  636.    else if (move->promotion_type == PART_KNIGHT)
  637.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"n");
  638.    else if (move->promotion_type == PART_BISHOP)
  639.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"b");
  640.    else if (move->promotion_type == PART_QUEEN)
  641.       wcscat_s  (output_string, WCHAR_SIZEOF (output_string), L"q");
  642.  
  643.    return (output_string); // finished, return the move string
  644. }
  645.