Subversion Repositories Games.Chess Giants

Rev

Rev 39 | Rev 44 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

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