Fix analysis mode in non-XBoard build
[bonanza.git] / proce.c
diff --git a/proce.c b/proce.c
index bb41877..cfeabe1 100644 (file)
--- a/proce.c
+++ b/proce.c
@@ -52,7 +52,7 @@ static int cmd_thread( char **lasts );
 #endif
 
 #if defined(MPV)
-static int cmd_mpv( char **lasts );
+static int cmd_mpv( tree_t * restrict ptree, char **lasts );
 #endif
 
 static int proce_cui( tree_t * restrict ptree );
@@ -74,6 +74,9 @@ static int cmd_new( tree_t * restrict ptree, char **lasts );
 static int cmd_read( tree_t * restrict ptree, char **lasts );
 static int cmd_resign( tree_t * restrict ptree, char **lasts );
 static int cmd_time( char **lasts );
+static int cmd_undo( tree_t * restrict ptree );    // [HGM] undo
+static int cmd_analyze( tree_t * restrict ptree ); // [HGM] analyze
+static int cmd_exit( void );
 static int is_move( const char *str );
 
 
@@ -90,6 +93,128 @@ procedure( tree_t * restrict ptree )
   return proce_cui( ptree );
 }
 
+char *start_pos, start_data[512]; // [HGM] undo: for remembering start position
+int move_list[1024], move_ptr;
+char analyze_mode;
+
+#ifdef XBOARD
+#define IF(X) else if(!strcmp(command, X))
+
+int myTime, hisTime, movesPerSession, inc, plyNr;
+char xboard_mode;
+
+void
+xboard_to_CSA( tree_t * restrict ptree, char *in, char *out )
+{
+  char fromX=in[0], fromY=in[1], toX=in[2], toY=in[3], promo=in[4];
+  int piece=0;
+  if(fromY == '@') { // drop (contains all info needed to convert it)
+    if(fromX >= 'a') fromX += 'A' - 'a';
+    switch(fromX) { // encode piece
+      case 'P': piece = pawn;   break;
+      case 'L': piece = lance;  break;
+      case 'N': piece = knight; break;
+      case 'S': piece = silver; break;
+      case 'G': piece = gold;   break;
+      case 'B': piece = bishop; break;
+      case 'R': piece = rook;   break;
+    }
+    sprintf(out, "00%c%c%s", 'a'+'9'-toX, '1'+'9'-toY, astr_table_piece[piece]);
+  } else { // board move (need to figure out moved piece)
+    int from = ('9' - fromY)*9 + (fromX - 'a');
+    int flag = (promo == '+' ? FLAG_PROMO : 0);
+    piece = abs( BOARD[from] ); // this only works when not searching!
+printf("# piece from board: %d\n", piece);fflush(stdout);
+    if( game_status & ( flag_pondering | flag_puzzling | flag_thinking ) ) {
+      int i, to = ('9' - toY)*9 + (toX - 'a');
+      piece = 0; // kludge to force illegal CSA move
+      for( i = 0; i < root_nmove; i++ ) { // determine the piece from the move list
+        int move = root_move_list[i].move;
+        if( I2To(move) != to ) continue;
+        if( I2From(move) != from ) continue;
+        if( (move & FLAG_PROMO) != flag ) continue;
+        piece = I2PieceMove( move ); // we found the move; take the piece from it
+        break;
+      }
+printf("# piece corrected to %d\n", piece);fflush(stdout);
+    }
+    if( promo ) piece += promote;
+    sprintf(out, "%c%c%c%c%s", 'a'+'9'-fromX, '1'+'9'-fromY, 'a'+'9'-toX, '1'+'9'-toY, astr_table_piece[piece]);
+  }
+}
+
+static void
+SetTimes(void)
+{ // set white and black times from own and opponent time.
+  int moves;
+  if(movesPerSession <= 0) moves = 35; else {
+    moves = - plyNr/2;
+    while(moves <= 0) moves += movesPerSession;
+  }
+  time_limit = (myTime-inc-30)/(moves+2) + inc;
+  time_max_limit = 3*time_limit;
+  if(time_max_limit > myTime - 30)time_max_limit = myTime - 30; // keep 0.3 sec margin, as Bonanza reads the clock infrequently
+  time_limit *= 10; // msec
+  time_max_limit *= 10;
+Out("# moves=%d, time=%d inc=%d t=%d, max=%d\n", moves, myTime, inc, time_limit, time_max_limit);
+}
+
+static int
+proce_xboard(char *line, const char *command, tree_t * restrict ptree)
+{ // [HGM] added to make Bonanza.exe a native WinBoard engine
+  int value = -100000;
+  static char forceMode = 0;
+  sscanf(line + strlen(command) + 1, "%d", &value);
+Out("# command = '%s'\n", line);
+  if(0) ;
+  IF("protover") {
+#if defined(MPV)
+                   Out("feature option=\"MultiPV -spin 1 1 100\"\n");
+                   Out("feature option=\"centi-Pawn margin -spin 200 0 25000\"\n");
+#endif
+                   Out("feature variants=\"shogi\" usermove=1 myname=\"Bonanza " BNZ_VER
+                       "\" memory=1 smp=1 debug=1 colors=0 setboard=1 ping=1 sigint=0 done=1\n");
+                 }
+  IF("new")      { forceMode = plyNr = 0; SetTimes(); return 0; }
+  IF("easy")     { strcpy(line, "ponder off"); return 0; }
+  IF("hard")     { strcpy(line, "ponder on");  return 0; }
+  IF("post")     { ; }
+  IF("nopost")   { ; }
+  IF("time")     { sscanf(line+5, "%d", &myTime); }
+  IF("otim")     { sscanf(line+5, "%d", &hisTime); }
+  IF("force")    { forceMode = 1; }
+  IF("go")       { forceMode = 0; SetTimes(); plyNr++; strcpy(line, "move"); return 0; }
+  IF("memory")   { ; }
+  IF("cores")    { sprintf(line, "tlp num %d", value); return 0; }
+  IF("sd")       { sprintf(line, "limit depth %d", value); return 0; }
+  IF("st")       { ; }
+  IF("quit")     { return 0; }
+  IF("analyze")  { return 0; }
+  IF("exit")     { return 0; }
+  IF("variant")  { /* ignore, since it must be Shogi */; }
+  IF("setboard") { ; }
+  IF("option")   {
+                   if(sscanf(line+7, "MultiPV=%d", &value) == 1) { sprintf(line, "mpv num %d", value); return 0; }
+                   if(sscanf(line+7, "centi-Pawn margin=%d", &value) == 1) { sprintf(line, "mpv width %d", value); return 0; }
+                 }
+  IF("level")    { int min, sec; float fsec=0.;
+                   if(sscanf(line+6, "%d %d:%d %f", &movesPerSession, &min, &sec, &fsec) != 4)
+                      sscanf(line+6, "%d %d %f", &movesPerSession, &min, &fsec);
+                   min = 60*min + sec; myTime = hisTime = 100*min; inc = 100 * fsec;
+                 }
+  IF("usermove") { char buf[20];
+                   xboard_to_CSA( ptree, line+9, buf );
+                   if(forceMode || analyze_mode) strcpy(line, "move "), line += 5; else plyNr++, SetTimes();
+                   strcpy( line, buf );
+                   plyNr++;
+                   return 0;
+                 }
+  IF("undo")     { return 0; }
+  IF("remove")   { ; }
+  IF("ping")     { Out("pong %d\n", value); }
+  return 1;
+}
+#endif
 
 static int
 proce_cui( tree_t * restrict ptree )
@@ -100,6 +225,24 @@ proce_cui( tree_t * restrict ptree )
   token = strtok_r( str_cmdline, str_delimiters, &last );
 
   if ( token == NULL || *token == '#' ) { return 1; }
+#ifdef XBOARD
+  { 
+    if(xboard_mode) {
+      if( proce_xboard(str_cmdline, token, ptree) )  return 1; // command already processed
+      Out("# translated command '%s'\n", str_cmdline);         // command translated for processing by Bonanza
+      token = strtok_r( str_cmdline, str_delimiters, &last );  // redo parsing
+    } else
+    if ( ! strcmp( token, "xboard" ) )  { xboard_mode = 1; game_status |= flag_noprompt; return 1; }
+  }
+#endif
+  if ( ! strcmp( token, "analyze" ) )   { return cmd_analyze( ptree ); } // [HGM] analyze
+  if ( ! strcmp( token, "exit" ) )      { return cmd_exit(); }           // [HGM] analyze
+  if ( ! strcmp( token, "move" ) )      { return cmd_move( ptree, &last ); }
+  if ( ! strcmp( token, "undo" ) )      { return cmd_undo( ptree ); }    // [HGM] undo
+#if defined(MPV)
+  if ( ! strcmp( token, "mpv" ) )       { return cmd_mpv( ptree, &last ); }
+#endif
+  analyze_mode = 0; // [HGM] analyze: all other commands terminate analysis
   if ( is_move( token ) ) { return cmd_usrmove( ptree, token, &last ); }
   if ( ! strcmp( token, "s" ) )         { return cmd_move_now(); }
   if ( ! strcmp( token, "beep" ) )      { return cmd_beep( &last); }
@@ -107,7 +250,6 @@ proce_cui( tree_t * restrict ptree )
   if ( ! strcmp( token, "display" ) )   { return cmd_display( ptree, &last ); }
   if ( ! strcmp( token, "hash" ) )      { return cmd_hash( &last ); }
   if ( ! strcmp( token, "limit" ) )     { return cmd_limit( &last ); }
-  if ( ! strcmp( token, "move" ) )      { return cmd_move( ptree, &last ); }
   if ( ! strcmp( token, "new" ) )       { return cmd_new( ptree, &last ); }
   if ( ! strcmp( token, "peek" ) )      { return cmd_peek( &last ); }
   if ( ! strcmp( token, "ping" ) )      { return cmd_ping(); }
@@ -127,9 +269,6 @@ proce_cui( tree_t * restrict ptree )
 #if defined(DEKUNOBOU)
   if ( ! strcmp( token, "dekunobou" ) ) { return cmd_dek( &last ); }
 #endif
-#if defined(MPV)
-  if ( ! strcmp( token, "mpv" ) )       { return cmd_mpv( &last ); }
-#endif
 #if defined(TLP)
   if ( ! strcmp( token, "tlp" ) )       { return cmd_thread( &last ); }
 #endif
@@ -289,6 +428,71 @@ cmd_mnjmove( tree_t * restrict ptree, char **lasts, int is_alter )
 
 
 static int
+do_analyze( tree_t * restrict ptree )
+{ // [HGM] analyze: do a ponder search on the current position
+  int iret;
+  if ( get_elapsed( &time_start ) < 0 ) { return -1; }
+  time_limit = time_max_limit = 1e9; // kludge: use huge time to mimic infinity
+#ifdef XBOARD
+  Out("1 0 0 0 New Search\n"); // make sure lower depth is emitted, so XBoard undestand new search started
+#endif
+  game_status |= flag_pondering;
+  iret         = iterate( ptree, 0 );
+  game_status &= ~flag_pondering;
+  return iret;
+}
+
+
+static int
+cmd_undo( tree_t * restrict ptree )
+{ // [HGM] undo: restart the game, and feed all moves except the last
+  int i, last = move_ptr;
+  char *p = start_data;
+  if( move_ptr <= 0 ) {
+    str_error = "undo past start of game ignored";
+    return -2;
+  }
+
+  AbortDifficultCommand;
+
+  last--;
+  cmd_new( ptree, &p );
+  for(i=0; i<last; i++) {
+    make_move_root( ptree, move_list[i], 0);
+  }
+
+  if ( analyze_mode ) return do_analyze ( ptree ); // [HGM] analyze: analysis should continue after undo
+
+  return 1;
+}
+
+
+static int
+cmd_analyze( tree_t * restrict ptree )
+{ // [HGM] analyze: switch on analyze mode, and start analyzing
+  AbortDifficultCommand;
+
+  analyze_mode = 1;
+  return do_analyze( ptree );
+}
+
+
+static int
+cmd_exit( void )
+{ // [HGM] analyze: switch off analysis mode
+  if ( !analyze_mode ) {
+    str_error = "was not analyzing";
+    return -2;
+  }
+
+  if ( game_status & flag_pondering ) { game_status |= flag_quit_ponder; return 2; }
+  analyze_mode = 0;
+
+  return 1;
+}
+
+
+static int
 is_move( const char *str )
 {
   if ( isdigit( (int)str[0] ) && isdigit( (int)str[1] )
@@ -402,6 +606,9 @@ cmd_usrmove( tree_t * restrict ptree, const char *str_move, char **lasts )
        game_status      &= ~flag_pondering;
        game_status      |= flag_thinking;
        n_nobook_move    += 1;
+#ifdef XBOARD
+      if(!xboard_mode)
+#endif
        set_search_limit_time( root_turn );
 
        OutCsaShogi( "info ponder end\n" );
@@ -1000,6 +1207,12 @@ cmd_move( tree_t * restrict ptree, char **lasts )
 
   if ( str == NULL )
     {
+      if ( analyze_mode ) // [HGM] analyze: in analysis mode we cannot set the engine thinking (but perhaps play PV move?)
+         {
+           str_error = str_bad_cmdline;
+           return -2;
+         }
+
       iret = get_elapsed( &time_turn_start );
       if ( iret < 0 ) { return iret; }
       
@@ -1008,6 +1221,12 @@ cmd_move( tree_t * restrict ptree, char **lasts )
     }
   else if ( ! strcmp( str, "restraint" ) )
     {
+      if ( analyze_mode ) // [HGM] analyze: in analysis mode we cannot set the engine thinking
+         {
+           str_error = str_bad_cmdline;
+           return -2;
+         }
+
       iret = get_elapsed( &time_turn_start );
       if ( iret < 0 ) { return iret; }
       
@@ -1043,6 +1262,8 @@ cmd_move( tree_t * restrict ptree, char **lasts )
                                          | flag_detect_hang
                                          | flag_rejections ) );
     if ( iret < 0 ) { return iret; }
+
+    if ( analyze_mode ) return do_analyze ( ptree ); // [HGM] analyze: analysis should continue after feeding moves
   }
   
   return 1;
@@ -1060,8 +1281,11 @@ cmd_new( tree_t * restrict ptree, char **lasts )
 
   AbortDifficultCommand;
 
+  start_pos = *lasts; move_ptr = 0; // [HGM] undo: remember start position
+
   if ( str1 != NULL )
     {
+      strncpy(start_data, str1, 511); // [HGM] undo: remember start position
       memset( &min_posi.asquare, empty, nsquare );
       min_posi.hand_black = min_posi.hand_white = 0;
       iret = read_board_rep1( str1, &min_posi );
@@ -1344,7 +1568,7 @@ cmd_learn( tree_t * restrict ptree, char **lasts )
 
 #if defined(MPV)
 static int
-cmd_mpv( char **lasts )
+cmd_mpv( tree_t * restrict ptree, char **lasts )
 {
   const char *str = strtok_r( NULL, str_delimiters, lasts );
   char *ptr;
@@ -1374,6 +1598,8 @@ cmd_mpv( char **lasts )
 
       mpv_num = (int)l;
 
+      if ( analyze_mode ) return do_analyze ( ptree ); // [HGM] analyze: analysis should continue changing num
+
       return 1;
     }
   else if ( ! strcmp( str, "width" ) )
@@ -1395,6 +1621,8 @@ cmd_mpv( char **lasts )
 
       mpv_width = (int)l;
 
+      if ( analyze_mode ) return do_analyze ( ptree ); // [HGM] analyze: analysis should continue after changing width
+
       return 1;
     }