Subversion Repositories Games.Chess Giants

Rev

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