Subversion Repositories Games.Chess Giants

Rev

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