Subversion Repositories Games.Chess Giants

Rev

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