Move MarkMenuItem to xoptions.c
[xboard.git] / book.c
diff --git a/book.c b/book.c
index 82d4a45..c40cd92 100644 (file)
--- a/book.c
+++ b/book.c
 
 #include <stdio.h>
 #include <string.h>
+#include <time.h>
+#include <stdlib.h>
+#include <math.h>
 
 #include "common.h"
+#include "frontend.h"
 #include "backend.h"
+#include "moves.h"
+#include "gettext.h"
+
+#ifdef ENABLE_NLS
+# define  _(s) gettext (s)
+# define N_(s) gettext_noop (s)
+#else
+# define  _(s) (s)
+# define N_(s)  s
+#endif
 
 #ifdef _MSC_VER
   typedef unsigned __int64 uint64;
@@ -40,7 +54,6 @@
   typedef unsigned long long int uint64;
 #endif
 
-
 #ifdef _MSC_VER
 #  define U64(u) (u##ui64)
 #else
@@ -55,7 +68,8 @@ typedef struct {
     uint64 key;        
     uint16 move;
     uint16 weight;
-    uint32 learn;
+    uint16 learnPoints;
+    uint16 learnCount;
 } entry_t;
 
 entry_t entry_none = {
@@ -63,8 +77,6 @@ entry_t entry_none = {
 };
 
 char *promote_pieces=" nbrqac=";
-extern char castlingRights[][BOARD_SIZE];
-extern char epStatus[];
 
 uint64 Random64[781] = {
    U64(0x9D39247E33776D41), U64(0x2AF7398005AAA5C7), U64(0x44DB015024623547), U64(0x9C15F73E62A76AE2),
@@ -271,21 +283,42 @@ uint64 *RandomEnPassant =Random64+772;
 uint64 *RandomTurn      =Random64+780;
 
 
-uint64 hash(int moveNr)
+uint64
+hash (int moveNr)
 {
-    char c;
-    int p, r, f, i, p_enc, squareNr, pieceGroup;
-    uint64 key=0, Zobrist;
+    int r, f, p_enc, squareNr, pieceGroup;
+    uint64 key=0, holdingsKey=0, Zobrist;
+    VariantClass v = gameInfo.variant;
+
+    switch(v) {
+       case VariantNormal:
+       case VariantFischeRandom: // compatible with normal
+       case VariantNoCastle:
+       case VariantXiangqi: // for historic reasons; does never collide anyway because of other King type
+           break;
+       case VariantGiveaway: // in opening same as suicide
+           key += VariantSuicide;
+           break;
+       case VariantGothic: // these are special cases of CRC, and can share book
+       case VariantCapablanca:
+           v = VariantCapaRandom;
+       default:
+           key += v; // variant type incorporated in key to allow mixed books without collisions
+    }
 
-    for(f=BOARD_LEFT; f<BOARD_RGHT; f++){
+    for(f=0; f<BOARD_WIDTH; f++){
         for(r=0; r<BOARD_HEIGHT;r++){
             ChessSquare p = boards[moveNr][r][f];
+           if(f == BOARD_LEFT-1 || f == BOARD_RGHT) continue; // between board and holdings
             if(p != EmptySquare){
                    int j = (int)p;
                    j -= (j >= (int)BlackPawn) ? (int)BlackPawn :(int)WhitePawn;
                    if(j > (int)WhiteQueen) j++;  // make space for King
                    if(j > (int) WhiteKing) j = (int)WhiteQueen + 1;
                    p_enc = 2*j + ((int)p < (int)BlackPawn);
+                   // holdings squares get nmbers immediately after board; first left, then right holdings
+                   if(f == BOARD_LEFT-2) squareNr = (BOARD_RGHT - BOARD_LEFT)*BOARD_HEIGHT + r; else
+                   if(f == BOARD_RGHT+1) squareNr = (BOARD_RGHT - BOARD_LEFT + 1)*BOARD_HEIGHT + r; else
                    squareNr = (BOARD_RGHT - BOARD_LEFT)*r + (f - BOARD_LEFT);
                    // note that in normal Chess squareNr < 64 and p_enc < 12. The following code
                    // maps other pieces and squares in this range, and then modify the corresponding
@@ -305,22 +338,24 @@ uint64 hash(int moveNr)
                                break;
                    }
                    if(squareNr >= 64) Zobrist = (Zobrist << 8) ^ (Zobrist >> 56);
+                   // holdings have separate (additive) key, to encode presence of multiple pieces on same square
+                   if(f == BOARD_LEFT-2) holdingsKey += Zobrist * boards[moveNr][r][f+1]; else
+                   if(f == BOARD_RGHT+1) holdingsKey += Zobrist * boards[moveNr][r][f-1]; else
                 key ^= Zobrist;
             }
         }
     }
-    // Holdings not implemented yet!
 
-    if(castlingRights[moveNr][2] >= 0) {
-       if(castlingRights[moveNr][0] >= 0) key^=RandomCastle[0];
-       if(castlingRights[moveNr][1] >= 0) key^=RandomCastle[1];
+    if(boards[moveNr][CASTLING][2] != NoRights) {
+       if(boards[moveNr][CASTLING][0] != NoRights) key^=RandomCastle[0];
+       if(boards[moveNr][CASTLING][1] != NoRights) key^=RandomCastle[1];
     }
-    if(castlingRights[moveNr][5] >= 0) {
-       if(castlingRights[moveNr][3] >= 0) key^=RandomCastle[2];
-       if(castlingRights[moveNr][4] >= 0) key^=RandomCastle[3];
+    if(boards[moveNr][CASTLING][5] != NoRights) {
+       if(boards[moveNr][CASTLING][3] != NoRights) key^=RandomCastle[2];
+       if(boards[moveNr][CASTLING][4] != NoRights) key^=RandomCastle[3];
     }
 
-    f = epStatus[moveNr];
+    f = boards[moveNr][EP_STATUS];
     if(f >= 0 && f < 8){
         if(!WhiteOnMove(moveNr)){
            // the test for neighboring Pawns might not be needed, 
@@ -340,12 +375,13 @@ uint64 hash(int moveNr)
     if(WhiteOnMove(moveNr)){
         key^=RandomTurn[0];
     }
-    return key;
+    return key + holdingsKey;
 }
 
 #define MOVE_BUF 100
 
-int int_from_file(FILE *f, int l, uint64 *r)
+int
+int_from_file (FILE *f, int l, uint64 *r)
 {
     int i,c;
     for(i=0;i<l;i++){
@@ -358,7 +394,8 @@ int int_from_file(FILE *f, int l, uint64 *r)
     return 0;
 }
 
-int entry_from_file(FILE *f, entry_t *entry)
+int
+entry_from_file (FILE *f, entry_t *entry)
 {
     int ret;
     uint64 r;
@@ -371,16 +408,20 @@ int entry_from_file(FILE *f, entry_t *entry)
     ret=int_from_file(f,2,&r);
     if(ret) return 1;
     entry->weight=r;
-    ret=int_from_file(f,4,&r);
+    ret=int_from_file(f,2,&r);
+    if(ret) return 1;
+    entry->learnCount=r;
+    ret=int_from_file(f,2,&r);
     if(ret) return 1;
-    entry->learn=r;
+    entry->learnPoints=r;
     return 0;
 }
 
-int find_key(FILE *f, uint64 key, entry_t *entry)
+int
+find_key (FILE *f, uint64 key, entry_t *entry)
 {
     int first, last, middle;
-    entry_t first_entry=entry_none, last_entry,middle_entry;
+    entry_t last_entry,middle_entry;
     first=-1;
     if(fseek(f,-16,SEEK_END)){
         *entry=entry_none;
@@ -402,12 +443,12 @@ int find_key(FILE *f, uint64 key, entry_t *entry)
             last_entry=middle_entry;
         }else{
             first=middle;
-            first_entry=middle_entry;
         }
     }
 }
 
-void move_to_string(char move_s[6], uint16 move)
+void
+move_to_string (char move_s[6], uint16 move)
 {
     int f,fr,ff,t,tr,tf,p;
     int width = BOARD_RGHT - BOARD_LEFT, size; // allow for alternative board formats
@@ -445,42 +486,47 @@ void move_to_string(char move_s[6], uint16 move)
     // correct FRC-style castlings in variant normal. 
     // [HGM] This is buggy code! e1h1 could very well be a normal R or Q move.
     if(!strcmp(move_s,"e1h1")){
-        strcpy(move_s,"e1g1");
+      safeStrCpy(move_s,"e1g1", 6);
     }else  if(!strcmp(move_s,"e1a1")){
-        strcpy(move_s,"e1c1");
+      safeStrCpy(move_s,"e1c1", 6);
     }else  if(!strcmp(move_s,"e8h8")){
-        strcpy(move_s,"e8g8");
+      safeStrCpy(move_s,"e8g8", 6);
     }else  if(!strcmp(move_s,"e8a8")){
-        strcpy(move_s,"e8c8");
+      safeStrCpy(move_s,"e8c8", 6);
     }
 }
 
-char *ProbeBook(int moveNr, char *book)
-{
-    FILE *f;
+int
+GetBookMoves (int moveNr, char *book, entry_t entries[])
+{   // retrieve all entries for given position from book in 'entries', return number.
+    static FILE *f = NULL;
+    static char curBook[MSG_SIZ];
     entry_t entry;
     int offset;
     uint64 key;
-    entry_t entries[MOVE_BUF];
-    int count=0;
-    int ret, i, j;
-    static char move_s[6];
-    int total_weight;
+    int count;
+    int ret;
 
-    if(book == NULL) return NULL; 
-//    if(gameInfo.variant != VariantNormal) return NULL; // Zobrist scheme only works for normal Chess, so far
-    f=fopen(book,"rb");
+    if(book == NULL || moveNr >= 2*appData.bookDepth) return -1; 
+//    if(gameInfo.variant != VariantNormal) return -1; // Zobrist scheme only works for normal Chess, so far
+    if(!f || strcmp(book, curBook)){ // keep book file open until book changed
+       strncpy(curBook, book, MSG_SIZ);
+       if(f) fclose(f);
+       f = fopen(book,"rb");
+    }
     if(!f){
-        DisplayError("Polyglot book not valid", 0);
+        DisplayError(_("Polyglot book not valid"), 0);
        appData.usePolyglotBook = FALSE;
-        return NULL;
+       return -1;
     }
 
     key = hash(moveNr);
     if(appData.debugMode) fprintf(debugFP, "book key = %08x%08x\n", (unsigned int)(key>>32), (unsigned int)key);
 
     offset=find_key(f, key, &entry);
-    if(entry.key != key) return NULL;
+    if(entry.key != key) {
+         return FALSE;
+    }
     entries[0] = entry;
     count=1;
     fseek(f, 16*(offset+1), SEEK_SET);
@@ -495,20 +541,189 @@ char *ProbeBook(int moveNr, char *book)
         if(count == MOVE_BUF) break;
         entries[count++] = entry;
     }
+    return count;
+}
+
+char *
+ProbeBook (int moveNr, char *book)
+{
+    entry_t entries[MOVE_BUF];
+    int count;
+    int i, j;
+    static char move_s[6];
+    int total_weight;
+
+    if((count = GetBookMoves(moveNr, book, entries)) <= 0) return NULL; // no book, or no hit
+
+    if(appData.bookStrength != 50) { // transform weights
+        double power = 0, maxWeight = 0.0;
+        if(appData.bookStrength) power = (100.-appData.bookStrength)/appData.bookStrength;
+        for(i=0; i<count; i++) if(entries[i].weight > maxWeight) maxWeight = entries[i].weight;
+        for(i=0; i<count; i++){
+            double weight = entries[i].weight / maxWeight;
+             if(weight > 0)
+                entries[i].weight = appData.bookStrength || weight == 1.0 ? 1e4*exp(power * log(weight)) + 0.5 : 0.0;
+        }
+    }
     total_weight = 0;
     for(i=0; i<count; i++){
         total_weight += entries[i].weight;
     }
-    srandom( time(0) );
-    j = (random() & 0x7FFF) * total_weight >> 15; // create random < total_weight
+    if(total_weight == 0) return NULL; // force book miss rather than playing moves with weight 0.
+    j = (random() & 0xFFF) * total_weight >> 12; // create random < total_weight
     total_weight = 0;
     for(i=0; i<count; i++){
         total_weight += entries[i].weight;
        if(total_weight > j) break;
     }
-    if(i >= count) DisplayFatalError("Book Fault", 0, 1); // safety catch, cannot happen
+    if(i >= count) DisplayFatalError(_("Book Fault"), 0, 1); // safety catch, cannot happen
     move_to_string(move_s, entries[i].move);
     if(appData.debugMode) fprintf(debugFP, "book move field = %d\n", entries[i].move);
 
     return move_s;
 }
+
+extern char yy_textstr[];
+entry_t lastEntries[MOVE_BUF];
+
+char *
+MovesToText (int count, entry_t *entries)
+{
+       int i, totalWeight = 0;
+       char algMove[6];
+       char *p = (char*) malloc(30*count+1);
+       for(i=0; i<count; i++) totalWeight += entries[i].weight;
+       *p = 0;
+       for(i=0; i<count; i++) {
+           char buf[MSG_SIZ];
+           move_to_string(algMove, entries[i].move);
+           buf[0] = NULLCHAR;
+           if(entries[i].learnCount || entries[i].learnPoints)
+               snprintf(buf, MSG_SIZ, " {%d/%d}", entries[i].learnPoints, entries[i].learnCount);
+           snprintf(p+strlen(p), 30, "%5.1f%% %5d %s%s\n", 100*entries[i].weight/(totalWeight+0.001),
+                                       entries[i].weight, algMove, buf);
+//lastEntries[i] = entries[i];
+       }
+       return p;
+}
+
+int
+TextToMoves (char *text, int moveNum, entry_t *entries)
+{
+       int i, w, count=0;
+      uint64 hashKey = hash(moveNum);
+       int  fromX, fromY, toX, toY, to, from;
+       ChessMove  moveType;
+       char promoChar, valid;
+       float dummy;
+       int width = BOARD_RGHT - BOARD_LEFT;
+
+       entries[0].key = hashKey; // make sure key is returned even if no moves
+       while((i=sscanf(text, "%f%%%d", &dummy, &w))==2 || (i=sscanf(text, "%d", &w))==1) {
+           if(i == 2) text = strchr(text, '%') + 1;  // skip percentage
+           if(w == 1) text = strstr(text, "1 ") + 2; // skip weight that could be recognized as move number one
+           valid = ParseOneMove(text, moveNum, &moveType, &fromX, &fromY, &toX, &toY, &promoChar);
+           text = strstr(text, yy_textstr) + strlen(yy_textstr); // skip what we parsed
+           if(!valid || moveType != NormalMove) continue;
+           if(*text == ' ' && sscanf(text+1, "{%hd/%hd}", &entries[count].learnPoints, &entries[count].learnCount) == 2) {
+               text = strchr(text+1, '}') + 1;
+           } else {
+               entries[count].learnPoints = 0;
+               entries[count].learnCount  = 0;
+           }
+           to = toX + toY * width;
+           from = fromX + fromY * width;
+           for(i=0; promote_pieces[i]; i++) if(promote_pieces[i] == promoChar) break;
+           if(!promote_pieces[i]) i = 0;
+           if(fromY == DROP_RANK) i = 8, from = ToUpper(PieceToChar(fromX)) - '@';
+           entries[count].move = to + (i * width * BOARD_HEIGHT + from) * width * BOARD_HEIGHT;
+           entries[count].key  = hashKey;
+           entries[count].weight = w;
+           count++;
+       }
+       return count;
+}
+
+Boolean bookUp;
+int currentCount;
+
+Boolean
+DisplayBook (int moveNr)
+{
+    entry_t entries[MOVE_BUF];
+    int count;
+    char *p;
+    if(!bookUp) return FALSE;
+    count = currentCount = GetBookMoves(moveNr, appData.polyglotBook, entries);
+    if(count < 0) return FALSE;
+    p = MovesToText(count, entries);
+    EditTagsPopUp(p, NULL);
+    free(p);
+    return TRUE;
+}
+
+void
+EditBookEvent ()
+{
+      bookUp = TRUE;
+       bookUp = DisplayBook(currentMove);
+}
+
+void
+int_to_file (FILE *f, int l, uint64 r)
+{
+    int i;
+    for(i=l-1;i>=0;i--) fputc(r>>8*i & 255, f);
+}
+
+void
+entry_to_file (FILE *f, entry_t *entry)
+{
+    int_to_file(f,8,entry->key);
+    int_to_file(f,2,entry->move);
+    int_to_file(f,2,entry->weight);
+    int_to_file(f,2,entry->learnCount);
+    int_to_file(f,2,entry->learnPoints);
+}
+
+char buf1[4096], buf2[4096];
+
+void
+SaveToBook (char *text)
+{
+    entry_t entries[MOVE_BUF], entry;
+    int count = TextToMoves(text, currentMove, entries);
+    int offset, i, len1=0, len2, readpos=0, writepos=0;
+    FILE *f;
+    if(!count && !currentCount) return;
+    f=fopen(appData.polyglotBook, "rb+");
+    if(!f){    DisplayError(_("Polyglot book not valid"), 0); return; }
+    offset=find_key(f, entries[0].key, &entry);
+    if(entries[0].key != entry.key && currentCount) {
+          DisplayError(_("Hash keys are different"), 0);
+         fclose(f);
+         return;
+    }
+    if(count != currentCount) {
+       readpos = 16*(offset + currentCount);
+       writepos = 16*(offset + count);
+       fseek(f, readpos, SEEK_SET);
+       readpos += len1 = fread(buf1, 1, 4096 - 16*currentCount, f); // salvage some entries immediately behind change
+    }
+    fseek(f, 16*(offset), SEEK_SET);
+    for(i=0; i<count; i++) entry_to_file(f, entries + i); // save the change
+    if(count != currentCount) {
+       do {
+           for(i=0; i<len1; i++) buf2[i] = buf1[i]; len2 = len1;
+           if(readpos > writepos) {
+               fseek(f, readpos, SEEK_SET);
+               readpos += len1 = fread(buf1, 1, 4096, f);
+           } else len1 = 0; // wrote already past old EOF
+           fseek(f, writepos, SEEK_SET);
+           fwrite(buf2, 1, len2, f);
+           writepos += len2;
+       } while(len1);
+    }
+    fclose(f);
+}
+