Rev 176 | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed
| Rev 176 | Rev 185 | ||
|---|---|---|---|
| Line 18... | Line 18... | ||
| 18 | */ | 18 | */ | 
| 19 | 19 | ||
| 20 | #include <algorithm> | 20 | #include <algorithm> | 
| 21 | #include <atomic> | 21 | #include <atomic> | 
| 22 | #include <cstdint> | 22 | #include <cstdint> | 
| 23 | #include <cstring>   // For std::memset | 23 | #include <cstring>   // For std::memset and std::memcpy | 
| 24 | #include <deque> | 24 | #include <deque> | 
| 25 | #include <fstream> | 25 | #include <fstream> | 
| 26 | #include <iostream> | 26 | #include <iostream> | 
| 27 | #include <list> | 27 | #include <list> | 
| 28 | #include <sstream> | 28 | #include <sstream> | 
| Line 32... | Line 32... | ||
| 32 | #include "../movegen.h" | 32 | #include "../movegen.h" | 
| 33 | #include "../position.h" | 33 | #include "../position.h" | 
| 34 | #include "../search.h" | 34 | #include "../search.h" | 
| 35 | #include "../thread_win32.h" | 35 | #include "../thread_win32.h" | 
| 36 | #include "../types.h" | 36 | #include "../types.h" | 
| - | 37 | #include "../uci.h" | |
| 37 | 38 | ||
| 38 | #include "tbprobe.h" | 39 | #include "tbprobe.h" | 
| 39 | 40 | ||
| 40 | #ifndef _WIN32 | 41 | #ifndef _WIN32 | 
| 41 | #include <fcntl.h> | 42 | #include <fcntl.h> | 
| Line 51... | Line 52... | ||
| 51 | using namespace Tablebases; | 52 | using namespace Tablebases; | 
| 52 | 53 | ||
| 53 | int Tablebases::MaxCardinality; | 54 | int Tablebases::MaxCardinality; | 
| 54 | 55 | ||
| 55 | namespace { | 56 | namespace { | 
| - | 57 | ||
| - | 58 | constexpr int TBPIECES = 7; // Max number of supported pieces | |
| - | 59 | ||
| - | 60 | enum { BigEndian, LittleEndian }; | |
| - | 61 | enum TBType { KEY, WDL, DTZ }; // Used as template parameter | |
| 56 | 62 | ||
| 57 | // Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables | 63 | // Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables | 
| 58 | enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, SingleValue = 128 }; | 64 | enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, Wide = 16, SingleValue = 128 }; | 
| 59 | 65 | ||
| 60 | inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); } | 66 | inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); } | 
| 61 | inline Square operator^=(Square& s, int i) { return s = Square(int(s) ^ i); } | 67 | inline Square operator^=(Square& s, int i) { return s = Square(int(s) ^ i); } | 
| 62 | inline Square operator^(Square s, int i) { return Square(int(s) ^ i); } | 68 | inline Square operator^(Square s, int i) { return Square(int(s) ^ i); } | 
| 63 | 69 | ||
| 64 | // DTZ tables don't store valid scores for moves that reset the rule50 counter | - | |
| 65 | // like captures and pawn moves but we can easily recover the correct dtz of the | - | |
| 66 | // previous move if we know the position's WDL score. | - | |
| 67 | int dtz_before_zeroing(WDLScore wdl) { | - | |
| 68 | return wdl == WDLWin ? 1 : | - | |
| 69 | wdl == WDLCursedWin ? 101 : | - | |
| 70 | wdl == WDLBlessedLoss ? -101 : | - | |
| 71 | wdl == WDLLoss ? -1 : 0; | - | |
| 72 | } | - | |
| 73 | - | ||
| 74 | // Return the sign of a number (-1, 0, 1) | - | |
| 75 | template <typename T> int sign_of(T val) { | - | |
| 76 | return (T(0) < val) - (val < T(0)); | - | |
| 77 | } | - | |
| 78 | - | ||
| 79 | // Numbers in little endian used by sparseIndex[] to point into blockLength[] | - | |
| 80 | struct SparseEntry { | - | |
| 81 | char block[4]; // Number of block | - | |
| 82 | char offset[2]; // Offset within the block | - | |
| 83 | }; | - | |
| 84 | - | ||
| 85 | static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes"); | - | |
| 86 | - | ||
| 87 | typedef uint16_t Sym; // Huffman symbol | - | |
| 88 | - | ||
| 89 | struct LR { | - | |
| 90 | enum Side { Left, Right, Value }; | - | |
| 91 | - | ||
| 92 | uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12 | - | |
| 93 |                    // bits is the right-hand symbol. If symbol has length 1, | - | |
| 94 |                    // then the first byte is the stored value. | - | |
| 95 | template<Side S> | - | |
| 96 | Sym get() { | - | |
| 97 | return S == Left ? ((lr[1] & 0xF) << 8) | lr[0] : | - | |
| 98 | S == Right ? (lr[2] << 4) | (lr[1] >> 4) : | - | |
| 99 | S == Value ? lr[0] : (assert(false), Sym(-1)); | - | |
| 100 |     } | - | |
| 101 | }; | - | |
| 102 | - | ||
| 103 | static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes"); | - | |
| 104 | - | ||
| 105 | const int TBPIECES = 6; | - | |
| 106 | - | ||
| 107 | struct PairsData { | - | |
| 108 | int flags; | - | |
| 109 | size_t sizeofBlock; // Block size in bytes | - | |
| 110 | size_t span; // About every span values there is a SparseIndex[] entry | - | |
| 111 | int blocksNum; // Number of blocks in the TB file | - | |
| 112 | int maxSymLen; // Maximum length in bits of the Huffman symbols | - | |
| 113 | int minSymLen; // Minimum length in bits of the Huffman symbols | - | |
| 114 | Sym* lowestSym; // lowestSym[l] is the symbol of length l with the lowest value | - | |
| 115 | LR* btree; // btree[sym] stores the left and right symbols that expand sym | - | |
| 116 | uint16_t* blockLength; // Number of stored positions (minus one) for each block: 1..65536 | - | |
| 117 | int blockLengthSize; // Size of blockLength[] table: padded so it's bigger than blocksNum | - | |
| 118 | SparseEntry* sparseIndex; // Partial indices into blockLength[] | - | |
| 119 | size_t sparseIndexSize; // Size of SparseIndex[] table | - | |
| 120 | uint8_t* data; // Start of Huffman compressed data | - | |
| 121 | std::vector<uint64_t> base64; // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l | - | |
| 122 | std::vector<uint8_t> symlen; // Number of values (-1) represented by a given Huffman symbol: 1..256 | - | |
| 123 | Piece pieces[TBPIECES]; // Position pieces: the order of pieces defines the groups | - | |
| 124 | uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces | - | |
| 125 | int groupLen[TBPIECES+1]; // Number of pieces in a given group: KRKN -> (3, 1) | - | |
| 126 | }; | - | |
| 127 | - | ||
| 128 | // Helper struct to avoid manually defining entry copy constructor as we | - | |
| 129 | // should because the default one is not compatible with std::atomic_bool. | - | |
| 130 | struct Atomic { | - | |
| 131 | Atomic() = default; | - | |
| 132 | Atomic(const Atomic& e) { ready = e.ready.load(); } // MSVC 2013 wants assignment within body | - | |
| 133 | std::atomic_bool ready; | - | |
| 134 | }; | - | |
| 135 | - | ||
| 136 | // We define types for the different parts of the WDLEntry and DTZEntry with | - | |
| 137 | // corresponding specializations for pieces or pawns. | - | |
| 138 | - | ||
| 139 | struct WDLEntryPiece { | - | |
| 140 | PairsData* precomp; | - | |
| 141 | }; | - | |
| 142 | - | ||
| 143 | struct WDLEntryPawn { | - | |
| 144 | uint8_t pawnCount[2]; // [Lead color / other color] | - | |
| 145 | WDLEntryPiece file[2][4]; // [wtm / btm][FILE_A..FILE_D] | - | |
| 146 | }; | - | |
| 147 | - | ||
| 148 | struct DTZEntryPiece { | - | |
| 149 | PairsData* precomp; | - | |
| 150 | uint16_t map_idx[4]; // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss | - | |
| 151 | uint8_t* map; | - | |
| 152 | }; | - | |
| 153 | - | ||
| 154 | struct DTZEntryPawn { | - | |
| 155 | uint8_t pawnCount[2]; | - | |
| 156 | DTZEntryPiece file[4]; | - | |
| 157 | uint8_t* map; | - | |
| 158 | }; | - | |
| 159 | - | ||
| 160 | struct TBEntry : public Atomic { | - | |
| 161 | void* baseAddress; | - | |
| 162 | uint64_t mapping; | - | |
| 163 |     Key key; | - | |
| 164 |     Key key2; | - | |
| 165 | int pieceCount; | - | |
| 166 | bool hasPawns; | - | |
| 167 | bool hasUniquePieces; | - | |
| 168 | }; | - | |
| 169 | - | ||
| 170 | // Now the main types: WDLEntry and DTZEntry | - | |
| 171 | struct WDLEntry : public TBEntry { | - | |
| 172 | WDLEntry(const std::string& code); | - | |
| 173 | ~WDLEntry(); | - | |
| 174 | union { | - | |
| 175 | 
 | 70 | const std::string PieceToChar = " PNBRQK pnbrqk"; | 
| 176 |         WDLEntryPawn  pawnTable; | - | |
| 177 | }; | - | |
| 178 | }; | - | |
| 179 | - | ||
| 180 | struct DTZEntry : public TBEntry { | - | |
| 181 | DTZEntry(const WDLEntry& wdl); | - | |
| 182 | ~DTZEntry(); | - | |
| 183 | union { | - | |
| 184 |         DTZEntryPiece pieceTable; | - | |
| 185 |         DTZEntryPawn  pawnTable; | - | |
| 186 | }; | - | |
| 187 | }; | - | |
| 188 | - | ||
| 189 | typedef decltype(WDLEntry::pieceTable) WDLPieceTable; | - | |
| 190 | typedef decltype(DTZEntry::pieceTable) DTZPieceTable; | - | |
| 191 | typedef decltype(WDLEntry::pawnTable ) WDLPawnTable; | - | |
| 192 | typedef decltype(DTZEntry::pawnTable ) DTZPawnTable; | - | |
| 193 | - | ||
| 194 | auto item(WDLPieceTable& e, int stm, int ) -> decltype(e[stm])& { return e[stm]; } | - | |
| 195 | auto item(DTZPieceTable& e, int , int ) -> decltype(e)& { return e; } | - | |
| 196 | auto item(WDLPawnTable& e, int stm, int f) -> decltype(e.file[stm][f])& { return e.file[stm][f]; } | - | |
| 197 | auto item(DTZPawnTable& e, int , int f) -> decltype(e.file[f])& { return e.file[f]; } | - | |
| 198 | - | ||
| 199 | template<typename E> struct Ret { typedef int type; }; | - | |
| 200 | template<> struct Ret<WDLEntry> { typedef WDLScore type; }; | - | |
| 201 | 71 | ||
| 202 | int MapPawns[SQUARE_NB]; | 72 | int MapPawns[SQUARE_NB]; | 
| 203 | int MapB1H1H7[SQUARE_NB]; | 73 | int MapB1H1H7[SQUARE_NB]; | 
| 204 | int MapA1D1D4[SQUARE_NB]; | 74 | int MapA1D1D4[SQUARE_NB]; | 
| 205 | int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB] | 75 | int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB] | 
| - | 76 | ||
| - | 77 | int Binomial[6][SQUARE_NB]; // [k][n] k elements from a set of n elements | |
| - | 78 | int LeadPawnIdx[6][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB] | |
| - | 79 | int LeadPawnsSize[6][4]; // [leadPawnsCnt][FILE_A..FILE_D] | |
| 206 | 80 | ||
| 207 | // Comparison function to sort leading pawns in ascending MapPawns[] order | 81 | // Comparison function to sort leading pawns in ascending MapPawns[] order | 
| 208 | bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; } | 82 | bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; } | 
| 209 | int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); } | 83 | int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); } | 
| 210 | 84 | ||
| 211 | 
 | 85 | constexpr Value WDL_to_value[] = { | 
| 212 | -VALUE_MATE + MAX_PLY + 1, | 86 | -VALUE_MATE + MAX_PLY + 1, | 
| 213 | VALUE_DRAW - 2, | 87 | VALUE_DRAW - 2, | 
| 214 | VALUE_DRAW, | 88 | VALUE_DRAW, | 
| 215 | VALUE_DRAW + 2, | 89 | VALUE_DRAW + 2, | 
| 216 | VALUE_MATE - MAX_PLY - 1 | 90 | VALUE_MATE - MAX_PLY - 1 | 
| 217 | }; | 91 | }; | 
| 218 | - | ||
| 219 | const std::string PieceToChar = " PNBRQK pnbrqk"; | - | |
| 220 | - | ||
| 221 | int Binomial[6][SQUARE_NB]; // [k][n] k elements from a set of n elements | - | |
| 222 | int LeadPawnIdx[5][SQUARE_NB]; // [leadPawnsCnt][SQUARE_NB] | - | |
| 223 | int LeadPawnsSize[5][4]; // [leadPawnsCnt][FILE_A..FILE_D] | - | |
| 224 | - | ||
| 225 | enum { BigEndian, LittleEndian }; | - | |
| 226 | 92 | ||
| 227 | template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1> | 93 | template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1> | 
| 228 | inline void | 94 | inline void swap_endian(T& x) | 
| 229 | { | 95 | { | 
| - | 96 | static_assert(std::is_unsigned<T>::value, "Argument of swap_endian not unsigned"); | |
| - | 97 | ||
| 230 | 
 | 98 | uint8_t tmp, *c = (uint8_t*)&x; | 
| 231 | for (int i = 0; i < Half; ++i) | 99 | for (int i = 0; i < Half; ++i) | 
| 232 | tmp = c[i], c[i] = c[End - i], c[End - i] = tmp; | 100 | tmp = c[i], c[i] = c[End - i], c[End - i] = tmp; | 
| 233 | } | 101 | } | 
| 234 | template<> inline void | 102 | template<> inline void swap_endian<uint8_t>(uint8_t&) {} | 
| 235 | 103 | ||
| 236 | template<typename T, int LE> T number(void* addr) | 104 | template<typename T, int LE> T number(void* addr) | 
| 237 | { | 105 | { | 
| 238 | const union { uint32_t i; char c[4]; } Le = { 0x01020304 }; | 106 | static const union { uint32_t i; char c[4]; } Le = { 0x01020304 }; | 
| 239 | const bool IsLittleEndian = (Le.c[0] == 4); | 107 | static const bool IsLittleEndian = (Le.c[0] == 4); | 
| 240 | 108 | ||
| 241 |     T v; | 109 |     T v; | 
| 242 | 110 | ||
| 243 | if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare) | 111 | if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare) | 
| 244 | std::memcpy(&v, addr, sizeof(T)); | 112 | std::memcpy(&v, addr, sizeof(T)); | 
| 245 |     else | 113 |     else | 
| 246 | v = *((T*)addr); | 114 | v = *((T*)addr); | 
| 247 | 115 | ||
| 248 | if (LE != IsLittleEndian) | 116 | if (LE != IsLittleEndian) | 
| 249 | 
 | 117 | swap_endian(v); | 
| 250 | return v; | 118 | return v; | 
| 251 | } | 119 | } | 
| 252 | 120 | ||
| - | 121 | // DTZ tables don't store valid scores for moves that reset the rule50 counter | |
| - | 122 | // like captures and pawn moves but we can easily recover the correct dtz of the | |
| - | 123 | // previous move if we know the position's WDL score. | |
| - | 124 | int dtz_before_zeroing(WDLScore wdl) { | |
| - | 125 | return wdl == WDLWin ? 1 : | |
| - | 126 | wdl == WDLCursedWin ? 101 : | |
| 253 | 
 | 127 | wdl == WDLBlessedLoss ? -101 : | 
| - | 128 | wdl == WDLLoss ? -1 : 0; | |
| - | 129 | } | |
| 254 | 130 | ||
| - | 131 | // Return the sign of a number (-1, 0, 1) | |
| 255 | 
 | 132 | template <typename T> int sign_of(T val) { | 
| 256 | 
 | 133 | return (T(0) < val) - (val < T(0)); | 
| - | 134 | } | |
| 257 | 135 | ||
| - | 136 | // Numbers in little endian used by sparseIndex[] to point into blockLength[] | |
| - | 137 | struct SparseEntry { | |
| 258 | 
 | 138 | char block[4]; // Number of block | 
| 259 | 
 | 139 | char offset[2]; // Offset within the block | 
| - | 140 | }; | |
| 260 | 141 | ||
| 261 | 
 | 142 | static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes"); | 
| 262 | 143 | ||
| 263 | std::deque<WDLEntry> wdlTable; | - | |
| 264 | 
 | 144 | typedef uint16_t Sym; // Huffman symbol | 
| 265 | 145 | ||
| 266 | 
 | 146 | struct LR { | 
| 267 | 
 | 147 | enum Side { Left, Right }; | 
| 268 | 148 | ||
| 269 | 
 | 149 | uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12 | 
| 270 | 
 | 150 |                    // bits is the right-hand symbol. If symbol has length 1, | 
| 271 | 
 | 151 |                    // then the left-hand symbol is the stored value. | 
| 272 | 
 | 152 | template<Side S> | 
| 273 | 
 | 153 | Sym get() { | 
| 274 | - | ||
| 275 | 
 | 154 | return S == Left ? ((lr[1] & 0xF) << 8) | lr[0] : | 
| 276 | 
 | 155 | S == Right ? (lr[2] << 4) | (lr[1] >> 4) : (assert(false), Sym(-1)); | 
| 277 |     } | 156 |     } | 
| - | 157 | }; | |
| 278 | 158 | ||
| 279 | public: | - | |
| 280 | 
 | 159 | static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes"); | 
| 281 | E* get(Key key) { | - | |
| 282 | Entry* entry = hashTable[key >> (64 - TBHASHBITS)]; | - | |
| 283 | 160 | ||
| 284 | for (int i = 0; i < HSHMAX; ++i, ++entry) | - | |
| 285 | if (entry->first == key) | - | |
| 286 | 
 | 161 | // Tablebases data layout is structured as following: | 
| 287 | 162 | // | |
| 288 | return nullptr; | - | |
| 289 |   } | - | |
| 290 | - | ||
| 291 | void clear() { | - | |
| 292 | 
 | 163 | //  TBFile:   memory maps/unmaps the physical .rtbw and .rtbz files | 
| 293 | wdlTable.clear(); | - | |
| 294 | dtzTable.clear(); | - | |
| 295 |   } | - | |
| 296 | 
 | 164 | //  TBTable:  one object for each file with corresponding indexing information | 
| 297 | 
 | 165 | //  TBTables: has ownership of TBTable objects, keeping a list and a hash | 
| 298 | }; | - | |
| 299 | - | ||
| 300 | HashTable EntryTable; | - | |
| 301 | 166 | ||
| - | 167 | // class TBFile memory maps/unmaps the single .rtbw and .rtbz files. Files are | |
| - | 168 | // memory mapped for best performance. Files are mapped at first access: at init | |
| - | 169 | // time only existence of the file is checked. | |
| 302 | class TBFile : public std::ifstream { | 170 | class TBFile : public std::ifstream { | 
| 303 | 171 | ||
| 304 | std::string fname; | 172 | std::string fname; | 
| 305 | 173 | ||
| 306 | public: | 174 | public: | 
| Line 313... | Line 181... | ||
| 313 | static std::string Paths; | 181 | static std::string Paths; | 
| 314 | 182 | ||
| 315 | TBFile(const std::string& f) { | 183 | TBFile(const std::string& f) { | 
| 316 | 184 | ||
| 317 | #ifndef _WIN32 | 185 | #ifndef _WIN32 | 
| 318 | 
 | 186 | constexpr char SepChar = ':'; | 
| 319 | #else | 187 | #else | 
| 320 | 
 | 188 | constexpr char SepChar = ';'; | 
| 321 | #endif | 189 | #endif | 
| 322 | std::stringstream ss(Paths); | 190 | std::stringstream ss(Paths); | 
| 323 | std::string path; | 191 | std::string path; | 
| 324 | 192 | ||
| 325 | while (std::getline(ss, path, SepChar)) { | 193 | while (std::getline(ss, path, SepChar)) { | 
| Line 330... | Line 198... | ||
| 330 |         } | 198 |         } | 
| 331 |     } | 199 |     } | 
| 332 | 200 | ||
| 333 |     // Memory map the file and check it. File should be already open and will be | 201 |     // Memory map the file and check it. File should be already open and will be | 
| 334 |     // closed after mapping. | 202 |     // closed after mapping. | 
| 335 | uint8_t* map(void** baseAddress, uint64_t* mapping, | 203 | uint8_t* map(void** baseAddress, uint64_t* mapping, TBType type) { | 
| 336 | 204 | ||
| 337 | assert(is_open()); | 205 | assert(is_open()); | 
| 338 | 206 | ||
| 339 | close(); // Need to re-open to get native file descriptor | 207 | close(); // Need to re-open to get native file descriptor | 
| 340 | 208 | ||
| Line 346... | Line 214... | ||
| 346 | return *baseAddress = nullptr, nullptr; | 214 | return *baseAddress = nullptr, nullptr; | 
| 347 | 215 | ||
| 348 | fstat(fd, &statbuf); | 216 | fstat(fd, &statbuf); | 
| 349 | *mapping = statbuf.st_size; | 217 | *mapping = statbuf.st_size; | 
| 350 | *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0); | 218 | *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0); | 
| - | 219 | madvise(*baseAddress, statbuf.st_size, MADV_RANDOM); | |
| 351 | ::close(fd); | 220 | ::close(fd); | 
| 352 | 221 | ||
| 353 | if (*baseAddress == MAP_FAILED) { | 222 | if (*baseAddress == MAP_FAILED) { | 
| 354 | std::cerr << "Could not mmap() " << fname << std::endl; | 223 | std::cerr << "Could not mmap() " << fname << std::endl; | 
| 355 | exit(1); | 224 | exit(1); | 
| Line 380... | Line 249... | ||
| 380 | exit(1); | 249 | exit(1); | 
| 381 |         } | 250 |         } | 
| 382 | #endif | 251 | #endif | 
| 383 | uint8_t* data = (uint8_t*)*baseAddress; | 252 | uint8_t* data = (uint8_t*)*baseAddress; | 
| 384 | 253 | ||
| 385 | 
 | 254 | constexpr uint8_t Magics[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 }, | 
| 386 | 
 | 255 | { 0x71, 0xE8, 0x23, 0x5D } }; | 
| 387 | || *data++ != *TB_MAGIC++ | - | |
| - | 256 | ||
| 388 | 
 | 257 | if (memcmp(data, Magics[type == WDL], 4)) { | 
| 389 | std::cerr << "Corrupted table in file " << fname << std::endl; | 258 | std::cerr << "Corrupted table in file " << fname << std::endl; | 
| 390 | unmap(*baseAddress, *mapping); | 259 | unmap(*baseAddress, *mapping); | 
| 391 | return *baseAddress = nullptr, nullptr; | 260 | return *baseAddress = nullptr, nullptr; | 
| 392 |         } | 261 |         } | 
| 393 | 262 | ||
| 394 | return data; | 263 | return data + 4; // Skip Magics's header | 
| 395 |     } | 264 |     } | 
| 396 | 265 | ||
| 397 | static void unmap(void* baseAddress, uint64_t mapping) { | 266 | static void unmap(void* baseAddress, uint64_t mapping) { | 
| 398 | 267 | ||
| 399 | #ifndef _WIN32 | 268 | #ifndef _WIN32 | 
| Line 405... | Line 274... | ||
| 405 |     } | 274 |     } | 
| 406 | }; | 275 | }; | 
| 407 | 276 | ||
| 408 | std::string TBFile::Paths; | 277 | std::string TBFile::Paths; | 
| 409 | 278 | ||
| - | 279 | // struct PairsData contains low level indexing information to access TB data. | |
| - | 280 | // There are 8, 4 or 2 PairsData records for each TBTable, according to type of | |
| - | 281 | // table and if positions have pawns or not. It is populated at first access. | |
| - | 282 | struct PairsData { | |
| - | 283 | uint8_t flags; // Table flags, see enum TBFlag | |
| - | 284 | uint8_t maxSymLen; // Maximum length in bits of the Huffman symbols | |
| - | 285 | uint8_t minSymLen; // Minimum length in bits of the Huffman symbols | |
| - | 286 | uint32_t blocksNum; // Number of blocks in the TB file | |
| - | 287 | size_t sizeofBlock; // Block size in bytes | |
| - | 288 | size_t span; // About every span values there is a SparseIndex[] entry | |
| - | 289 | Sym* lowestSym; // lowestSym[l] is the symbol of length l with the lowest value | |
| - | 290 | LR* btree; // btree[sym] stores the left and right symbols that expand sym | |
| - | 291 | uint16_t* blockLength; // Number of stored positions (minus one) for each block: 1..65536 | |
| - | 292 | uint32_t blockLengthSize; // Size of blockLength[] table: padded so it's bigger than blocksNum | |
| - | 293 | SparseEntry* sparseIndex; // Partial indices into blockLength[] | |
| - | 294 | size_t sparseIndexSize; // Size of SparseIndex[] table | |
| - | 295 | uint8_t* data; // Start of Huffman compressed data | |
| - | 296 | std::vector<uint64_t> base64; // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l | |
| - | 297 | std::vector<uint8_t> symlen; // Number of values (-1) represented by a given Huffman symbol: 1..256 | |
| - | 298 | Piece pieces[TBPIECES]; // Position pieces: the order of pieces defines the groups | |
| - | 299 | uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces | |
| - | 300 | int groupLen[TBPIECES+1]; // Number of pieces in a given group: KRKN -> (3, 1) | |
| - | 301 | uint16_t map_idx[4]; // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss (used in DTZ) | |
| - | 302 | }; | |
| - | 303 | ||
| - | 304 | // struct TBTable contains indexing information to access the corresponding TBFile. | |
| - | 305 | // There are 2 types of TBTable, corresponding to a WDL or a DTZ file. TBTable | |
| - | 306 | // is populated at init time but the nested PairsData records are populated at | |
| - | 307 | // first access, when the corresponding file is memory mapped. | |
| - | 308 | template<TBType Type> | |
| - | 309 | struct TBTable { | |
| - | 310 | typedef typename std::conditional<Type == WDL, WDLScore, int>::type Ret; | |
| - | 311 | ||
| - | 312 | static constexpr int Sides = Type == WDL ? 2 : 1; | |
| - | 313 | ||
| - | 314 | std::atomic_bool ready; | |
| - | 315 | void* baseAddress; | |
| - | 316 | uint8_t* map; | |
| - | 317 | uint64_t mapping; | |
| - | 318 |     Key key; | |
| - | 319 |     Key key2; | |
| - | 320 | int pieceCount; | |
| - | 321 | bool hasPawns; | |
| - | 322 | bool hasUniquePieces; | |
| - | 323 | uint8_t pawnCount[2]; // [Lead color / other color] | |
| - | 324 | PairsData items[Sides][4]; // [wtm / btm][FILE_A..FILE_D or 0] | |
| - | 325 | ||
| - | 326 | PairsData* get(int stm, int f) { | |
| - | 327 | return &items[stm % Sides][hasPawns ? f : 0]; | |
| - | 328 |     } | |
| - | 329 | ||
| - | 330 | TBTable() : ready(false), baseAddress(nullptr) {} | |
| 410 | 
 | 331 | explicit TBTable(const std::string& code); | 
| - | 332 | explicit TBTable(const TBTable<WDL>& wdl); | |
| - | 333 | ||
| - | 334 | ~TBTable() { | |
| - | 335 | if (baseAddress) | |
| - | 336 | TBFile::unmap(baseAddress, mapping); | |
| - | 337 |     } | |
| - | 338 | }; | |
| - | 339 | ||
| - | 340 | template<> | |
| - | 341 | TBTable<WDL>::TBTable(const std::string& code) : TBTable() { | |
| 411 | 342 | ||
| 412 |     StateInfo st; | 343 |     StateInfo st; | 
| 413 |     Position pos; | 344 |     Position pos; | 
| 414 | 345 | ||
| 415 | memset(this, 0, sizeof(WDLEntry)); | - | |
| 416 | - | ||
| 417 | ready = false; | - | |
| 418 | key = pos.set(code, WHITE, &st).material_key(); | 346 | key = pos.set(code, WHITE, &st).material_key(); | 
| 419 | pieceCount = | 347 | pieceCount = pos.count<ALL_PIECES>(); | 
| 420 | hasPawns = pos.pieces(PAWN); | 348 | hasPawns = pos.pieces(PAWN); | 
| 421 | 349 | ||
| - | 350 | hasUniquePieces = false; | |
| 422 | for (Color c = WHITE; c <= BLACK; ++c) | 351 | for (Color c = WHITE; c <= BLACK; ++c) | 
| 423 | for (PieceType pt = PAWN; pt < KING; ++pt) | 352 | for (PieceType pt = PAWN; pt < KING; ++pt) | 
| 424 | if (popcount(pos.pieces(c, pt)) == 1) | 353 | if (popcount(pos.pieces(c, pt)) == 1) | 
| 425 | hasUniquePieces = true; | 354 | hasUniquePieces = true; | 
| 426 | 355 | ||
| 427 | if (hasPawns) { | - | |
| 428 | 
 | 356 |     // Set the leading color. In case both sides have pawns the leading color | 
| 429 | 
 | 357 |     // is the side with less pawns because this leads to better compression. | 
| 430 | 
 | 358 | bool c = !pos.count<PAWN>(BLACK) | 
| 431 | 
 | 359 | || ( pos.count<PAWN>(WHITE) | 
| 432 | 
 | 360 | && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE)); | 
| 433 | 361 | ||
| 434 | 
 | 362 | pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK); | 
| 435 | 
 | 363 | pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE); | 
| 436 |     } | - | |
| 437 | 364 | ||
| 438 | key2 = pos.set(code, BLACK, &st).material_key(); | 365 | key2 = pos.set(code, BLACK, &st).material_key(); | 
| 439 | } | 366 | } | 
| 440 | 367 | ||
| 441 | 
 | 368 | template<> | 
| - | 369 | TBTable<DTZ>::TBTable(const TBTable<WDL>& wdl) : TBTable() { | |
| 442 | 370 | ||
| 443 | if (baseAddress) | - | |
| 444 | TBFile::unmap(baseAddress, mapping); | - | |
| 445 | - | ||
| 446 | for (int i = 0; i < 2; ++i) | - | |
| 447 | if (hasPawns) | - | |
| 448 | for (File f = FILE_A; f <= FILE_D; ++f) | - | |
| 449 | 
 | 371 |     // Use the corresponding WDL table to avoid recalculating all from scratch | 
| 450 |         else | - | |
| 451 | delete pieceTable[i].precomp; | - | |
| 452 | } | - | |
| 453 | - | ||
| 454 | DTZEntry::DTZEntry(const WDLEntry& wdl) { | - | |
| 455 | - | ||
| 456 | memset(this, 0, sizeof(DTZEntry)); | - | |
| 457 | - | ||
| 458 | ready = false; | - | |
| 459 | key = wdl.key; | 372 | key = wdl.key; | 
| 460 | key2 = wdl.key2; | 373 | key2 = wdl.key2; | 
| 461 | pieceCount = wdl.pieceCount; | 374 | pieceCount = wdl.pieceCount; | 
| 462 | hasPawns = wdl.hasPawns; | 375 | hasPawns = wdl.hasPawns; | 
| 463 | hasUniquePieces = wdl.hasUniquePieces; | 376 | hasUniquePieces = wdl.hasUniquePieces; | 
| - | 377 | pawnCount[0] = wdl.pawnCount[0]; | |
| - | 378 | pawnCount[1] = wdl.pawnCount[1]; | |
| - | 379 | } | |
| 464 | 380 | ||
| - | 381 | // class TBTables creates and keeps ownership of the TBTable objects, one for | |
| - | 382 | // each TB file found. It supports a fast, hash based, table lookup. Populated | |
| - | 383 | // at init time, accessed at probe time. | |
| 465 | 
 | 384 | class TBTables { | 
| - | 385 | ||
| - | 386 | typedef std::tuple<Key, TBTable<WDL>*, TBTable<DTZ>*> Entry; | |
| - | 387 | ||
| - | 388 | static constexpr int Size = 1 << 12; // 4K table, indexed by key's 12 lsb | |
| - | 389 | static constexpr int Overflow = 1; // Number of elements allowed to map to the last bucket | |
| - | 390 | ||
| - | 391 | Entry hashTable[Size + Overflow]; | |
| - | 392 | ||
| - | 393 | std::deque<TBTable<WDL>> wdlTable; | |
| - | 394 | std::deque<TBTable<DTZ>> dtzTable; | |
| - | 395 | ||
| - | 396 | void insert(Key key, TBTable<WDL>* wdl, TBTable<DTZ>* dtz) { | |
| - | 397 | uint32_t homeBucket = (uint32_t)key & (Size - 1); | |
| 466 | 
 | 398 | Entry entry = std::make_tuple(key, wdl, dtz); | 
| - | 399 | ||
| - | 400 |         // Ensure last element is empty to avoid overflow when looking up | |
| - | 401 | for (uint32_t bucket = homeBucket; bucket < Size + Overflow - 1; ++bucket) { | |
| - | 402 | Key otherKey = std::get<KEY>(hashTable[bucket]); | |
| - | 403 | if (otherKey == key || !std::get<WDL>(hashTable[bucket])) { | |
| - | 404 | hashTable[bucket] = entry; | |
| - | 405 | return; | |
| - | 406 |             } | |
| - | 407 | ||
| - | 408 |             // Robin Hood hashing: If we've probed for longer than this element, | |
| - | 409 |             // insert here and search for a new spot for the other element instead. | |
| - | 410 | uint32_t otherHomeBucket = (uint32_t)otherKey & (Size - 1); | |
| - | 411 | if (otherHomeBucket > homeBucket) { | |
| 467 | 
 | 412 | swap(entry, hashTable[bucket]); | 
| - | 413 | key = otherKey; | |
| - | 414 | homeBucket = otherHomeBucket; | |
| - | 415 |             } | |
| - | 416 |         } | |
| - | 417 | std::cerr << "TB hash table size too low!" << std::endl; | |
| - | 418 | exit(1); | |
| 468 |     } | 419 |     } | 
| 469 | } | - | |
| 470 | 420 | ||
| - | 421 | public: | |
| - | 422 | template<TBType Type> | |
| 471 | 
 | 423 | TBTable<Type>* get(Key key) { | 
| - | 424 | for (const Entry* entry = &hashTable[(uint32_t)key & (Size - 1)]; ; ++entry) { | |
| - | 425 | if (std::get<KEY>(*entry) == key || !std::get<Type>(*entry)) | |
| - | 426 | return std::get<Type>(*entry); | |
| - | 427 |         } | |
| - | 428 |     } | |
| 472 | 429 | ||
| 473 | 
 | 430 | void clear() { | 
| 474 | 
 | 431 | memset(hashTable, 0, sizeof(hashTable)); | 
| - | 432 | wdlTable.clear(); | |
| - | 433 | dtzTable.clear(); | |
| - | 434 |     } | |
| - | 435 | size_t size() const { return wdlTable.size(); } | |
| - | 436 | void add(const std::vector<PieceType>& pieces); | |
| - | 437 | }; | |
| 475 | 438 | ||
| 476 | 
 | 439 | TBTables TBTables; | 
| 477 | for (File f = FILE_A; f <= FILE_D; ++f) | - | |
| 478 | delete pawnTable.file[f].precomp; | - | |
| 479 |     else | - | |
| 480 | delete pieceTable.precomp; | - | |
| 481 | } | - | |
| 482 | 440 | ||
| - | 441 | // If the corresponding file exists two new objects TBTable<WDL> and TBTable<DTZ> | |
| - | 442 | // are created and added to the lists and hash table. Called at init time. | |
| 483 | void | 443 | void TBTables::add(const std::vector<PieceType>& pieces) { | 
| 484 | 444 | ||
| 485 | std::string code; | 445 | std::string code; | 
| 486 | 446 | ||
| 487 | for (PieceType pt : pieces) | 447 | for (PieceType pt : pieces) | 
| 488 | code += PieceToChar[pt]; | 448 | code += PieceToChar[pt]; | 
| Line 497... | Line 457... | ||
| 497 | MaxCardinality = std::max((int)pieces.size(), MaxCardinality); | 457 | MaxCardinality = std::max((int)pieces.size(), MaxCardinality); | 
| 498 | 458 | ||
| 499 | wdlTable.emplace_back(code); | 459 | wdlTable.emplace_back(code); | 
| 500 | dtzTable.emplace_back(wdlTable.back()); | 460 | dtzTable.emplace_back(wdlTable.back()); | 
| 501 | 461 | ||
| - | 462 |     // Insert into the hash keys for both colors: KRvK with KR white and black | |
| 502 | insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back()); | 463 | insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back()); | 
| 503 | insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back()); | 464 | insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back()); | 
| 504 | } | 465 | } | 
| 505 | 466 | ||
| 506 | // TB tables are compressed with canonical Huffman code. The compressed data is divided into | 467 | // TB tables are compressed with canonical Huffman code. The compressed data is divided into | 
| Line 537... | Line 498... | ||
| 537 |     // with index I(k), where: | 498 |     // with index I(k), where: | 
| 538 |     // | 499 |     // | 
| 539 |     //       I(k) = k * d->span + d->span / 2      (1) | 500 |     //       I(k) = k * d->span + d->span / 2      (1) | 
| 540 | 501 | ||
| 541 |     // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1) | 502 |     // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1) | 
| 542 | uint32_t k = | 503 | uint32_t k = idx / d->span; | 
| 543 | 504 | ||
| 544 |     // Then we read the corresponding SparseIndex[] entry | 505 |     // Then we read the corresponding SparseIndex[] entry | 
| 545 | uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block); | 506 | uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block); | 
| 546 | int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset); | 507 | int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset); | 
| 547 | 508 | ||
| Line 562... | Line 523... | ||
| 562 | 523 | ||
| 563 | while (offset > d->blockLength[block]) | 524 | while (offset > d->blockLength[block]) | 
| 564 | offset -= d->blockLength[block++] + 1; | 525 | offset -= d->blockLength[block++] + 1; | 
| 565 | 526 | ||
| 566 |     // Finally, we find the start address of our block of canonical Huffman symbols | 527 |     // Finally, we find the start address of our block of canonical Huffman symbols | 
| 567 | uint32_t* ptr = (uint32_t*)(d->data + block * d->sizeofBlock); | 528 | uint32_t* ptr = (uint32_t*)(d->data + ((uint64_t)block * d->sizeofBlock)); | 
| 568 | 529 | ||
| 569 |     // Read the first 64 bits in our block, this is a (truncated) sequence of | 530 |     // Read the first 64 bits in our block, this is a (truncated) sequence of | 
| 570 |     // unknown number of symbols of unknown length but we know the first one | 531 |     // unknown number of symbols of unknown length but we know the first one | 
| 571 |     // is at the beginning of this 64 bits sequence. | 532 |     // is at the beginning of this 64 bits sequence. | 
| 572 | uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2; | 533 | uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2; | 
| Line 583... | Line 544... | ||
| 583 | ++len; | 544 | ++len; | 
| 584 | 545 | ||
| 585 |         // All the symbols of a given length are consecutive integers (numerical | 546 |         // All the symbols of a given length are consecutive integers (numerical | 
| 586 |         // sequence property), so we can compute the offset of our symbol of | 547 |         // sequence property), so we can compute the offset of our symbol of | 
| 587 |         // length len, stored at the beginning of buf64. | 548 |         // length len, stored at the beginning of buf64. | 
| 588 | sym = | 549 | sym = (buf64 - d->base64[len]) >> (64 - len - d->minSymLen); | 
| 589 | 550 | ||
| 590 |         // Now add the value of the lowest symbol of length len to get our symbol | 551 |         // Now add the value of the lowest symbol of length len to get our symbol | 
| 591 | sym += number<Sym, LittleEndian>(&d->lowestSym[len]); | 552 | sym += number<Sym, LittleEndian>(&d->lowestSym[len]); | 
| 592 | 553 | ||
| 593 |         // If our offset is within the number of values represented by symbol sym | 554 |         // If our offset is within the number of values represented by symbol sym | 
| Line 625... | Line 586... | ||
| 625 | offset -= d->symlen[left] + 1; | 586 | offset -= d->symlen[left] + 1; | 
| 626 | sym = d->btree[sym].get<LR::Right>(); | 587 | sym = d->btree[sym].get<LR::Right>(); | 
| 627 |         } | 588 |         } | 
| 628 |     } | 589 |     } | 
| 629 | 590 | ||
| 630 | return d->btree[sym].get<LR:: | 591 | return d->btree[sym].get<LR::Left>(); | 
| 631 | } | 592 | } | 
| 632 | 593 | ||
| 633 | bool check_dtz_stm( | 594 | bool check_dtz_stm(TBTable<WDL>*, int, File) { return true; } | 
| 634 | 595 | ||
| 635 | bool check_dtz_stm( | 596 | bool check_dtz_stm(TBTable<DTZ>* entry, int stm, File f) { | 
| 636 | - | ||
| 637 | int flags = entry->hasPawns ? entry->pawnTable.file[f].precomp->flags | - | |
| 638 | : entry->pieceTable.precomp->flags; | - | |
| 639 | 597 | ||
| - | 598 | auto flags = entry->get(stm, f)->flags; | |
| 640 | return (flags & TBFlag::STM) == stm | 599 | return (flags & TBFlag::STM) == stm | 
| 641 | || ((entry->key == entry->key2) && !entry->hasPawns); | 600 | || ((entry->key == entry->key2) && !entry->hasPawns); | 
| 642 | } | 601 | } | 
| 643 | 602 | ||
| 644 | // DTZ scores are sorted by frequency of occurrence and then assigned the | 603 | // DTZ scores are sorted by frequency of occurrence and then assigned the | 
| 645 | // values 0, 1, 2, ... in order of decreasing frequency. This is done for each | 604 | // values 0, 1, 2, ... in order of decreasing frequency. This is done for each | 
| 646 | // of the four WDLScore values. The mapping information necessary to reconstruct | 605 | // of the four WDLScore values. The mapping information necessary to reconstruct | 
| 647 | // the original values is stored in the TB file and read during map[] init. | 606 | // the original values is stored in the TB file and read during map[] init. | 
| 648 | WDLScore map_score( | 607 | WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); } | 
| 649 | 608 | ||
| 650 | int map_score( | 609 | int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) { | 
| 651 | 610 | ||
| 652 | 
 | 611 | constexpr int WDLMap[] = { 1, 3, 0, 2, 0 }; | 
| 653 | 612 | ||
| 654 | 
 | 613 | auto flags = entry->get(0, f)->flags; | 
| 655 | : entry->pieceTable.precomp->flags; | - | |
| 656 | 614 | ||
| 657 | uint8_t* map = entry-> | 615 | uint8_t* map = entry->map; | 
| 658 | : entry->pieceTable.map; | - | |
| 659 | - | ||
| 660 | uint16_t* idx = entry-> | 616 | uint16_t* idx = entry->get(0, f)->map_idx; | 
| 661 | 
 | 617 | if (flags & TBFlag::Mapped) { | 
| 662 | if (flags & TBFlag:: | 618 | if (flags & TBFlag::Wide) | 
| - | 619 | value = ((uint16_t *)map)[idx[WDLMap[wdl + 2]] + value]; | |
| - | 620 |         else | |
| 663 | value = map[idx[WDLMap[wdl + 2]] + value]; | 621 | value = map[idx[WDLMap[wdl + 2]] + value]; | 
| - | 622 |     } | |
| 664 | 623 | ||
| 665 |     // DTZ tables store distance to zero in number of moves or plies. We | 624 |     // DTZ tables store distance to zero in number of moves or plies. We | 
| 666 |     // want to return plies, so we have convert to plies when needed. | 625 |     // want to return plies, so we have convert to plies when needed. | 
| 667 | if ( (wdl == WDLWin && !(flags & TBFlag::WinPlies)) | 626 | if ( (wdl == WDLWin && !(flags & TBFlag::WinPlies)) | 
| 668 | || (wdl == WDLLoss && !(flags & TBFlag::LossPlies)) | 627 | || (wdl == WDLLoss && !(flags & TBFlag::LossPlies)) | 
| Line 677... | Line 636... | ||
| 677 | // encode k pieces of same type and color, first sort the pieces by square in | 636 | // encode k pieces of same type and color, first sort the pieces by square in | 
| 678 | // ascending order s1 <= s2 <= ... <= sk then compute the unique index as: | 637 | // ascending order s1 <= s2 <= ... <= sk then compute the unique index as: | 
| 679 | // | 638 | // | 
| 680 | //      idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk] | 639 | //      idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk] | 
| 681 | // | 640 | // | 
| 682 | template<typename | 641 | template<typename T, typename Ret = typename T::Ret> | 
| 683 | 
 | 642 | Ret do_probe_table(const Position& pos, T* entry, WDLScore wdl, ProbeState* result) { | 
| 684 | - | ||
| 685 | const bool IsWDL = std::is_same<Entry, WDLEntry>::value; | - | |
| 686 | 643 | ||
| 687 | Square squares[TBPIECES]; | 644 | Square squares[TBPIECES]; | 
| 688 | Piece pieces[TBPIECES]; | 645 | Piece pieces[TBPIECES]; | 
| 689 | uint64_t idx; | 646 | uint64_t idx; | 
| 690 | int next = 0, size = 0, leadPawnsCnt = 0; | 647 | int next = 0, size = 0, leadPawnsCnt = 0; | 
| Line 713... | Line 670... | ||
| 713 |     // MapPawns[] value, that is the one most toward the edges and with lowest rank. | 670 |     // MapPawns[] value, that is the one most toward the edges and with lowest rank. | 
| 714 | if (entry->hasPawns) { | 671 | if (entry->hasPawns) { | 
| 715 | 672 | ||
| 716 |         // In all the 4 tables, pawns are at the beginning of the piece sequence and | 673 |         // In all the 4 tables, pawns are at the beginning of the piece sequence and | 
| 717 |         // their color is the reference one. So we just pick the first one. | 674 |         // their color is the reference one. So we just pick the first one. | 
| 718 | Piece pc = Piece | 675 | Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor); | 
| 719 | 676 | ||
| 720 | assert(type_of(pc) == PAWN); | 677 | assert(type_of(pc) == PAWN); | 
| 721 | 678 | ||
| 722 | leadPawns = b = pos.pieces(color_of(pc), PAWN); | 679 | leadPawns = b = pos.pieces(color_of(pc), PAWN); | 
| 723 |         do | 680 |         do | 
| Line 729... | Line 686... | ||
| 729 | std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp)); | 686 | std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp)); | 
| 730 | 687 | ||
| 731 | tbFile = file_of(squares[0]); | 688 | tbFile = file_of(squares[0]); | 
| 732 | if (tbFile > FILE_D) | 689 | if (tbFile > FILE_D) | 
| 733 | tbFile = file_of(squares[0] ^ 7); // Horizontal flip: SQ_H1 -> SQ_A1 | 690 | tbFile = file_of(squares[0] ^ 7); // Horizontal flip: SQ_H1 -> SQ_A1 | 
| 734 | - | ||
| 735 | d = item(entry->pawnTable , stm, tbFile).precomp; | - | |
| 736 | } | 691 |     } | 
| 737 | d = item(entry->pieceTable, stm, tbFile).precomp; | - | |
| 738 | 692 | ||
| 739 |     // DTZ tables are one-sided, i.e. they store positions only for white to | 693 |     // DTZ tables are one-sided, i.e. they store positions only for white to | 
| 740 |     // move or only for black to move, so check for side to move to be stm, | 694 |     // move or only for black to move, so check for side to move to be stm, | 
| 741 |     // early exit otherwise. | 695 |     // early exit otherwise. | 
| 742 | if ( | 696 | if (!check_dtz_stm(entry, stm, tbFile)) | 
| 743 | return *result = CHANGE_STM, | 697 | return *result = CHANGE_STM, Ret(); | 
| 744 | 698 | ||
| 745 |     // Now we are ready to get all the position pieces (but the lead pawns) and | 699 |     // Now we are ready to get all the position pieces (but the lead pawns) and | 
| 746 |     // directly map them to the correct color and square. | 700 |     // directly map them to the correct color and square. | 
| 747 | b = pos.pieces() ^ leadPawns; | 701 | b = pos.pieces() ^ leadPawns; | 
| 748 | do { | 702 | do { | 
| Line 750... | Line 704... | ||
| 750 | squares[size] = s ^ flipSquares; | 704 | squares[size] = s ^ flipSquares; | 
| 751 | pieces[size++] = Piece(pos.piece_on(s) ^ flipColor); | 705 | pieces[size++] = Piece(pos.piece_on(s) ^ flipColor); | 
| 752 | } while (b); | 706 | } while (b); | 
| 753 | 707 | ||
| 754 | assert(size >= 2); | 708 | assert(size >= 2); | 
| - | 709 | ||
| - | 710 | d = entry->get(stm, tbFile); | |
| 755 | 711 | ||
| 756 |     // Then we reorder the pieces to have the same sequence as the one stored | 712 |     // Then we reorder the pieces to have the same sequence as the one stored | 
| 757 |     // in  | 713 |     // in pieces[i]: the sequence that ensures the best compression. | 
| 758 | for (int i = leadPawnsCnt; i < size; ++i) | 714 | for (int i = leadPawnsCnt; i < size; ++i) | 
| 759 | for (int j = i; j < size; ++j) | 715 | for (int j = i; j < size; ++j) | 
| 760 | if (d->pieces[i] == pieces[j]) | 716 | if (d->pieces[i] == pieces[j]) | 
| 761 |             { | 717 |             { | 
| 762 | std::swap(pieces[i], pieces[j]); | 718 | std::swap(pieces[i], pieces[j]); | 
| Line 870... | Line 826... | ||
| 870 | encode_remaining: | 826 | encode_remaining: | 
| 871 | idx *= d->groupIdx[0]; | 827 | idx *= d->groupIdx[0]; | 
| 872 | Square* groupSq = squares + d->groupLen[0]; | 828 | Square* groupSq = squares + d->groupLen[0]; | 
| 873 | 829 | ||
| 874 |     // Encode remainig pawns then pieces according to square, in ascending order | 830 |     // Encode remainig pawns then pieces according to square, in ascending order | 
| 875 | bool remainingPawns = entry->hasPawns && entry-> | 831 | bool remainingPawns = entry->hasPawns && entry->pawnCount[1]; | 
| 876 | 832 | ||
| 877 | while (d->groupLen[++next]) | 833 | while (d->groupLen[++next]) | 
| 878 |     { | 834 |     { | 
| 879 | std::sort(groupSq, groupSq + d->groupLen[next]); | 835 | std::sort(groupSq, groupSq + d->groupLen[next]); | 
| 880 | uint64_t n = 0; | 836 | uint64_t n = 0; | 
| Line 932... | Line 888... | ||
| 932 |     // This ensures unique encoding for the whole position. The order of the | 888 |     // This ensures unique encoding for the whole position. The order of the | 
| 933 |     // groups is a per-table parameter and could not follow the canonical leading | 889 |     // groups is a per-table parameter and could not follow the canonical leading | 
| 934 |     // pawns/pieces -> remainig pawns -> remaining pieces. In particular the | 890 |     // pawns/pieces -> remainig pawns -> remaining pieces. In particular the | 
| 935 |     // first group is at order[0] position and the remaining pawns, when present, | 891 |     // first group is at order[0] position and the remaining pawns, when present, | 
| 936 |     // are at order[1] position. | 892 |     // are at order[1] position. | 
| 937 | bool pp = e.hasPawns && e | 893 | bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides | 
| 938 | int next = pp ? 2 : 1; | 894 | int next = pp ? 2 : 1; | 
| 939 | int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0); | 895 | int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0); | 
| 940 | uint64_t idx = 1; | 896 | uint64_t idx = 1; | 
| 941 | 897 | ||
| 942 | for (int k = 0; next < n || k == order[0] || k == order[1]; ++k) | 898 | for (int k = 0; next < n || k == order[0] || k == order[1]; ++k) | 
| Line 998... | Line 954... | ||
| 998 |     // element stores the biggest index that is the tb size. | 954 |     // element stores the biggest index that is the tb size. | 
| 999 | uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen]; | 955 | uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen]; | 
| 1000 | 956 | ||
| 1001 | d->sizeofBlock = 1ULL << *data++; | 957 | d->sizeofBlock = 1ULL << *data++; | 
| 1002 | d->span = 1ULL << *data++; | 958 | d->span = 1ULL << *data++; | 
| 1003 | d->sparseIndexSize = | 959 | d->sparseIndexSize = (tbSize + d->span - 1) / d->span; // Round up | 
| 1004 | 
 | 960 | auto padding = number<uint8_t, LittleEndian>(data++); | 
| 1005 | d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t); | 961 | d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t); | 
| 1006 | d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[] | 962 | d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[] | 
| 1007 |                                                  // does not point out of range. | 963 |                                                  // does not point out of range. | 
| 1008 | d->maxSymLen = *data++; | 964 | d->maxSymLen = *data++; | 
| 1009 | d->minSymLen = *data++; | 965 | d->minSymLen = *data++; | 
| Line 1032... | Line 988... | ||
| 1032 | 988 | ||
| 1033 | data += d->base64.size() * sizeof(Sym); | 989 | data += d->base64.size() * sizeof(Sym); | 
| 1034 | d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t); | 990 | d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t); | 
| 1035 | d->btree = (LR*)data; | 991 | d->btree = (LR*)data; | 
| 1036 | 992 | ||
| 1037 |     // The  | 993 |     // The compression scheme used is "Recursive Pairing", that replaces the most | 
| 1038 |     // frequent adjacent pair of symbols in the source message by a new symbol, | 994 |     // frequent adjacent pair of symbols in the source message by a new symbol, | 
| 1039 |     // reevaluating the frequencies of all of the symbol pairs with respect to | 995 |     // reevaluating the frequencies of all of the symbol pairs with respect to | 
| 1040 |     // the extended alphabet, and then repeating the process. | 996 |     // the extended alphabet, and then repeating the process. | 
| 1041 |     // See http://www.larsson.dogma.net/dcc99.pdf | 997 |     // See http://www.larsson.dogma.net/dcc99.pdf | 
| 1042 | std::vector<bool> visited(d->symlen.size()); | 998 | std::vector<bool> visited(d->symlen.size()); | 
| Line 1046... | Line 1002... | ||
| 1046 | d->symlen[sym] = set_symlen(d, sym, visited); | 1002 | d->symlen[sym] = set_symlen(d, sym, visited); | 
| 1047 | 1003 | ||
| 1048 | return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1); | 1004 | return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1); | 
| 1049 | } | 1005 | } | 
| 1050 | 1006 | ||
| 1051 | template<typename T> | - | |
| 1052 | uint8_t* set_dtz_map( | 1007 | uint8_t* set_dtz_map(TBTable<WDL>&, uint8_t* data, File) { return data; } | 
| 1053 | 1008 | ||
| 1054 | template<typename T> | - | |
| 1055 | uint8_t* set_dtz_map( | 1009 | uint8_t* set_dtz_map(TBTable<DTZ>& e, uint8_t* data, File maxFile) { | 
| 1056 | 1010 | ||
| 1057 | 
 | 1011 | e.map = data; | 
| 1058 | 1012 | ||
| 1059 | for (File f = FILE_A; f <= maxFile; ++f) { | 1013 | for (File f = FILE_A; f <= maxFile; ++f) { | 
| - | 1014 | auto flags = e.get(0, f)->flags; | |
| 1060 | if ( | 1015 | if (flags & TBFlag::Mapped) { | 
| - | 1016 | if (flags & TBFlag::Wide) { | |
| - | 1017 | data += (uintptr_t)data & 1; // Word alignment, we may have a mixed table | |
| 1061 | for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x | 1018 | for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x | 
| 1062 | 
 | 1019 | e.get(0, f)->map_idx[i] = (uint16_t)((uint16_t *)data - (uint16_t *)e.map + 1); | 
| - | 1020 | data += 2 * number<uint16_t, LittleEndian>(data) + 2; | |
| 1063 | 
 | 1021 |                 } | 
| 1064 |             } | 1022 |             } | 
| - | 1023 | else { | |
| - | 1024 | for (int i = 0; i < 4; ++i) { | |
| - | 1025 | e.get(0, f)->map_idx[i] = (uint16_t)(data - e.map + 1); | |
| - | 1026 | data += *data + 1; | |
| - | 1027 |                 } | |
| - | 1028 |             } | |
| - | 1029 |         } | |
| 1065 |     } | 1030 |     } | 
| 1066 | 1031 | ||
| 1067 | return data += (uintptr_t)data & 1; // Word alignment | 1032 | return data += (uintptr_t)data & 1; // Word alignment | 
| 1068 | } | 1033 | } | 
| 1069 | 1034 | ||
| - | 1035 | // Populate entry's PairsData records with data from the just memory mapped file. | |
| - | 1036 | // Called at first access. | |
| 1070 | template< | 1037 | template<typename T> | 
| 1071 | void | 1038 | void set(T& e, uint8_t* data) { | 
| 1072 | - | ||
| 1073 | const bool IsWDL = std::is_same<Entry, WDLEntry>::value; | - | |
| 1074 | 1039 | ||
| 1075 | PairsData* d; | 1040 | PairsData* d; | 
| 1076 | 1041 | ||
| 1077 | enum { Split = 1, HasPawns = 2 }; | 1042 | enum { Split = 1, HasPawns = 2 }; | 
| 1078 | 1043 | ||
| 1079 | assert(e.hasPawns == !!(*data & HasPawns)); | 1044 | assert(e.hasPawns == !!(*data & HasPawns)); | 
| 1080 | assert((e.key != e.key2) == !!(*data & Split)); | 1045 | assert((e.key != e.key2) == !!(*data & Split)); | 
| 1081 | 1046 | ||
| 1082 | data++; // First byte stores flags | 1047 | data++; // First byte stores flags | 
| 1083 | 1048 | ||
| 1084 | const int Sides | 1049 | const int sides = T::Sides == 2 && (e.key != e.key2) ? 2 : 1; | 
| 1085 | const File | 1050 | const File maxFile = e.hasPawns ? FILE_D : FILE_A; | 
| 1086 | 1051 | ||
| 1087 | bool pp = e.hasPawns && e | 1052 | bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides | 
| 1088 | 1053 | ||
| 1089 | assert(!pp || e | 1054 | assert(!pp || e.pawnCount[0]); | 
| 1090 | 1055 | ||
| 1091 | for (File f = FILE_A; f <= | 1056 | for (File f = FILE_A; f <= maxFile; ++f) { | 
| 1092 | 1057 | ||
| 1093 | for (int i = 0; i < | 1058 | for (int i = 0; i < sides; i++) | 
| 1094 | 
 | 1059 | *e.get(i, f) = PairsData(); | 
| 1095 | 1060 | ||
| 1096 | int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF }, | 1061 | int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF }, | 
| 1097 | { *data >> 4, pp ? *(data + 1) >> 4 : 0xF } }; | 1062 | { *data >> 4, pp ? *(data + 1) >> 4 : 0xF } }; | 
| 1098 | data += 1 + pp; | 1063 | data += 1 + pp; | 
| 1099 | 1064 | ||
| 1100 | for (int k = 0; k < e.pieceCount; ++k, ++data) | 1065 | for (int k = 0; k < e.pieceCount; ++k, ++data) | 
| 1101 | for (int i = 0; i < | 1066 | for (int i = 0; i < sides; i++) | 
| 1102 | 
 | 1067 | e.get(i, f)->pieces[k] = Piece(i ? *data >> 4 : *data & 0xF); | 
| 1103 | 1068 | ||
| 1104 | for (int i = 0; i < | 1069 | for (int i = 0; i < sides; ++i) | 
| 1105 | set_groups(e, | 1070 | set_groups(e, e.get(i, f), order[i], f); | 
| 1106 |     } | 1071 |     } | 
| 1107 | 1072 | ||
| 1108 | data += (uintptr_t)data & 1; // Word alignment | 1073 | data += (uintptr_t)data & 1; // Word alignment | 
| 1109 | 1074 | ||
| 1110 | for (File f = FILE_A; f <= | 1075 | for (File f = FILE_A; f <= maxFile; ++f) | 
| 1111 | for (int i = 0; i < | 1076 | for (int i = 0; i < sides; i++) | 
| 1112 | data = set_sizes( | 1077 | data = set_sizes(e.get(i, f), data); | 
| 1113 | 1078 | ||
| 1114 | if (!IsWDL) | - | |
| 1115 | 
 | 1079 | data = set_dtz_map(e, data, maxFile); | 
| 1116 | 1080 | ||
| 1117 | for (File f = FILE_A; f <= | 1081 | for (File f = FILE_A; f <= maxFile; ++f) | 
| 1118 | for (int i = 0; i < | 1082 | for (int i = 0; i < sides; i++) { | 
| 1119 | (d = | 1083 | (d = e.get(i, f))->sparseIndex = (SparseEntry*)data; | 
| 1120 | data += d->sparseIndexSize * sizeof(SparseEntry); | 1084 | data += d->sparseIndexSize * sizeof(SparseEntry); | 
| 1121 |         } | 1085 |         } | 
| 1122 | 1086 | ||
| 1123 | for (File f = FILE_A; f <= | 1087 | for (File f = FILE_A; f <= maxFile; ++f) | 
| 1124 | for (int i = 0; i < | 1088 | for (int i = 0; i < sides; i++) { | 
| 1125 | (d = | 1089 | (d = e.get(i, f))->blockLength = (uint16_t*)data; | 
| 1126 | data += d->blockLengthSize * sizeof(uint16_t); | 1090 | data += d->blockLengthSize * sizeof(uint16_t); | 
| 1127 |         } | 1091 |         } | 
| 1128 | 1092 | ||
| 1129 | for (File f = FILE_A; f <= | 1093 | for (File f = FILE_A; f <= maxFile; ++f) | 
| 1130 | for (int i = 0; i < | 1094 | for (int i = 0; i < sides; i++) { | 
| 1131 | data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment | 1095 | data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment | 
| 1132 | (d = | 1096 | (d = e.get(i, f))->data = data; | 
| 1133 | data += d->blocksNum * d->sizeofBlock; | 1097 | data += d->blocksNum * d->sizeofBlock; | 
| 1134 |         } | 1098 |         } | 
| 1135 | } | 1099 | } | 
| 1136 | 1100 | ||
| - | 1101 | // If the TB file corresponding to the given position is already memory mapped | |
| - | 1102 | // then return its base address, otherwise try to memory map and init it. Called | |
| - | 1103 | // at every probe, memory map and init only at first access. Function is thread | |
| - | 1104 | // safe and can be called concurrently. | |
| 1137 | template< | 1105 | template<TBType Type> | 
| 1138 | void* | 1106 | void* mapped(TBTable<Type>& e, const Position& pos) { | 
| 1139 | - | ||
| 1140 | const bool IsWDL = std::is_same<Entry, WDLEntry>::value; | - | |
| 1141 | 1107 | ||
| 1142 | static Mutex mutex; | 1108 | static Mutex mutex; | 
| 1143 | 1109 | ||
| 1144 |     //  | 1110 |     // Use 'aquire' to avoid a thread reads 'ready' == true while another is | 
| 1145 |     // this could happen due to compiler reordering. | 1111 |     // still working, this could happen due to compiler reordering. | 
| 1146 | if (e.ready.load(std::memory_order_acquire)) | 1112 | if (e.ready.load(std::memory_order_acquire)) | 
| 1147 | return e.baseAddress; | 1113 | return e.baseAddress; // Could be nullptr if file does not exsist | 
| 1148 | 1114 | ||
| 1149 | std::unique_lock<Mutex> lk(mutex); | 1115 | std::unique_lock<Mutex> lk(mutex); | 
| 1150 | 1116 | ||
| 1151 | if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock | 1117 | if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock | 
| 1152 | return e.baseAddress; | 1118 | return e.baseAddress; | 
| Line 1155... | Line 1121... | ||
| 1155 | std::string fname, w, b; | 1121 | std::string fname, w, b; | 
| 1156 | for (PieceType pt = KING; pt >= PAWN; --pt) { | 1122 | for (PieceType pt = KING; pt >= PAWN; --pt) { | 
| 1157 | w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]); | 1123 | w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]); | 
| 1158 | b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]); | 1124 | b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]); | 
| 1159 |     } | 1125 |     } | 
| 1160 | - | ||
| 1161 | const uint8_t TB_MAGIC[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 }, | - | |
| 1162 | { 0x71, 0xE8, 0x23, 0x5D } }; | - | |
| 1163 | 1126 | ||
| 1164 | fname = (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w) | 1127 | fname = (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w) | 
| 1165 | + ( | 1128 | + (Type == WDL ? ".rtbw" : ".rtbz"); | 
| - | 1129 | ||
| - | 1130 | uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, Type); | |
| 1166 | 1131 | ||
| 1167 | uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, TB_MAGIC[IsWDL]); | - | |
| 1168 | if (data) | 1132 | if (data) | 
| 1169 | 
 | 1133 | set(e, data); | 
| 1170 | 1134 | ||
| 1171 | e.ready.store(true, std::memory_order_release); | 1135 | e.ready.store(true, std::memory_order_release); | 
| 1172 | return e.baseAddress; | 1136 | return e.baseAddress; | 
| 1173 | } | 1137 | } | 
| 1174 | 1138 | ||
| 1175 | template< | 1139 | template<TBType Type, typename Ret = typename TBTable<Type>::Ret> | 
| 1176 | 
 | 1140 | Ret probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) { | 
| 1177 | 1141 | ||
| 1178 | if | 1142 | if (pos.count<ALL_PIECES>() == 2) // KvK | 
| 1179 | return | 1143 | return Ret(WDLDraw); | 
| 1180 | 1144 | ||
| 1181 | 
 | 1145 | TBTable<Type>* entry = TBTables.get<Type>(pos.material_key()); | 
| 1182 | 1146 | ||
| 1183 | if (!entry || ! | 1147 | if (!entry || !mapped(*entry, pos)) | 
| 1184 | return *result = FAIL, | 1148 | return *result = FAIL, Ret(); | 
| 1185 | 1149 | ||
| 1186 | return do_probe_table(pos, entry, wdl, result); | 1150 | return do_probe_table(pos, entry, wdl, result); | 
| 1187 | } | 1151 | } | 
| 1188 | 1152 | ||
| 1189 | // For a position where the side to move has a winning capture it is not necessary | 1153 | // For a position where the side to move has a winning capture it is not necessary | 
| Line 1193... | Line 1157... | ||
| 1193 | // If the position is won, then the TB needs to store a win value. But if the | 1157 | // If the position is won, then the TB needs to store a win value. But if the | 
| 1194 | // position is drawn, the TB may store a loss value if that is better for compression. | 1158 | // position is drawn, the TB may store a loss value if that is better for compression. | 
| 1195 | // All of this means that during probing, the engine must look at captures and probe | 1159 | // All of this means that during probing, the engine must look at captures and probe | 
| 1196 | // their results and must probe the position itself. The "best" result of these | 1160 | // their results and must probe the position itself. The "best" result of these | 
| 1197 | // probes is the correct result for the position. | 1161 | // probes is the correct result for the position. | 
| 1198 | // DTZ  | 1162 | // DTZ tables do not store values when a following move is a zeroing winning move | 
| 1199 | // (winning capture or winning pawn move). Also DTZ store wrong values for positions | 1163 | // (winning capture or winning pawn move). Also DTZ store wrong values for positions | 
| 1200 | // where the best move is an ep-move (even if losing). So in all these cases set | 1164 | // where the best move is an ep-move (even if losing). So in all these cases set | 
| 1201 | // the state to ZEROING_BEST_MOVE. | 1165 | // the state to ZEROING_BEST_MOVE. | 
| 1202 | template<bool CheckZeroingMoves | 1166 | template<bool CheckZeroingMoves> | 
| 1203 | WDLScore search(Position& pos, ProbeState* result) { | 1167 | WDLScore search(Position& pos, ProbeState* result) { | 
| 1204 | 1168 | ||
| 1205 | WDLScore value, bestValue = WDLLoss; | 1169 | WDLScore value, bestValue = WDLLoss; | 
| 1206 |     StateInfo st; | 1170 |     StateInfo st; | 
| 1207 | 1171 | ||
| Line 1215... | Line 1179... | ||
| 1215 | continue; | 1179 | continue; | 
| 1216 | 1180 | ||
| 1217 | moveCount++; | 1181 | moveCount++; | 
| 1218 | 1182 | ||
| 1219 | pos.do_move(move, st); | 1183 | pos.do_move(move, st); | 
| 1220 | value = -search(pos, result); | 1184 | value = -search<false>(pos, result); | 
| 1221 | pos.undo_move(move); | 1185 | pos.undo_move(move); | 
| 1222 | 1186 | ||
| 1223 | if (*result == FAIL) | 1187 | if (*result == FAIL) | 
| 1224 | return WDLDraw; | 1188 | return WDLDraw; | 
| 1225 | 1189 | ||
| Line 1245... | Line 1209... | ||
| 1245 | 1209 | ||
| 1246 | if (noMoreMoves) | 1210 | if (noMoreMoves) | 
| 1247 | value = bestValue; | 1211 | value = bestValue; | 
| 1248 |     else | 1212 |     else | 
| 1249 |     { | 1213 |     { | 
| 1250 | value = probe_table< | 1214 | value = probe_table<WDL>(pos, result); | 
| 1251 | 1215 | ||
| 1252 | if (*result == FAIL) | 1216 | if (*result == FAIL) | 
| 1253 | return WDLDraw; | 1217 | return WDLDraw; | 
| 1254 |     } | 1218 |     } | 
| 1255 | 1219 | ||
| Line 1261... | Line 1225... | ||
| 1261 | return *result = OK, value; | 1225 | return *result = OK, value; | 
| 1262 | } | 1226 | } | 
| 1263 | 1227 | ||
| 1264 | } // namespace | 1228 | } // namespace | 
| 1265 | 1229 | ||
| - | 1230 | ||
| - | 1231 | /// Tablebases::init() is called at startup and after every change to | |
| - | 1232 | /// "SyzygyPath" UCI option to (re)create the various tables. It is not thread | |
| - | 1233 | /// safe, nor it needs to be. | |
| 1266 | void Tablebases::init(const std::string& paths) { | 1234 | void Tablebases::init(const std::string& paths) { | 
| 1267 | 1235 | ||
| 1268 | 
 | 1236 | TBTables.clear(); | 
| 1269 | MaxCardinality = 0; | 1237 | MaxCardinality = 0; | 
| 1270 | TBFile::Paths = paths; | 1238 | TBFile::Paths = paths; | 
| 1271 | 1239 | ||
| 1272 | if (paths.empty() || paths == | 1240 | if (paths.empty() || paths == "<empty>") | 
| 1273 | return; | 1241 | return; | 
| 1274 | 1242 | ||
| 1275 |     // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27 | 1243 |     // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27 | 
| 1276 | int code = 0; | 1244 | int code = 0; | 
| 1277 | for (Square s = SQ_A1; s <= SQ_H8; ++s) | 1245 | for (Square s = SQ_A1; s <= SQ_H8; ++s) | 
| Line 1307... | Line 1275... | ||
| 1307 | 1275 | ||
| 1308 | else if (!off_A1H8(s1) && off_A1H8(s2) > 0) | 1276 | else if (!off_A1H8(s1) && off_A1H8(s2) > 0) | 
| 1309 | continue; // First on diagonal, second above | 1277 | continue; // First on diagonal, second above | 
| 1310 | 1278 | ||
| 1311 | else if (!off_A1H8(s1) && !off_A1H8(s2)) | 1279 | else if (!off_A1H8(s1) && !off_A1H8(s2)) | 
| 1312 | bothOnDiagonal. | 1280 | bothOnDiagonal.emplace_back(idx, s2); | 
| 1313 | 1281 | ||
| 1314 |                     else | 1282 |                     else | 
| 1315 | MapKK[idx][s2] = code++; | 1283 | MapKK[idx][s2] = code++; | 
| 1316 |             } | 1284 |             } | 
| 1317 | 1285 | ||
| Line 1332... | Line 1300... | ||
| 1332 |     // available squares when the leading one is in 's'. Moreover the pawn with | 1300 |     // available squares when the leading one is in 's'. Moreover the pawn with | 
| 1333 |     // highest MapPawns[] is the leading pawn, the one nearest the edge and, | 1301 |     // highest MapPawns[] is the leading pawn, the one nearest the edge and, | 
| 1334 |     // among pawns with same file, the one with lowest rank. | 1302 |     // among pawns with same file, the one with lowest rank. | 
| 1335 | int availableSquares = 47; // Available squares when lead pawn is in a2 | 1303 | int availableSquares = 47; // Available squares when lead pawn is in a2 | 
| 1336 | 1304 | ||
| 1337 |     // Init the tables for the encoding of leading pawns group: with  | 1305 |     // Init the tables for the encoding of leading pawns group: with 7-men TB we | 
| 1338 |     // can have up to  | 1306 |     // can have up to 5 leading pawns (KPPPPPK). | 
| 1339 | for (int leadPawnsCnt = 1; leadPawnsCnt <= | 1307 | for (int leadPawnsCnt = 1; leadPawnsCnt <= 5; ++leadPawnsCnt) | 
| 1340 | for (File f = FILE_A; f <= FILE_D; ++f) | 1308 | for (File f = FILE_A; f <= FILE_D; ++f) | 
| 1341 |         { | 1309 |         { | 
| 1342 |             // Restart the index at every file because TB table is splitted | 1310 |             // Restart the index at every file because TB table is splitted | 
| 1343 |             // by file, so we can reuse the same index for different files. | 1311 |             // by file, so we can reuse the same index for different files. | 
| 1344 | int idx = 0; | 1312 | int idx = 0; | 
| Line 1364... | Line 1332... | ||
| 1364 |             } | 1332 |             } | 
| 1365 |             // After a file is traversed, store the cumulated per-file index | 1333 |             // After a file is traversed, store the cumulated per-file index | 
| 1366 | LeadPawnsSize[leadPawnsCnt][f] = idx; | 1334 | LeadPawnsSize[leadPawnsCnt][f] = idx; | 
| 1367 |         } | 1335 |         } | 
| 1368 | 1336 | ||
| - | 1337 |     // Add entries in TB tables if the corresponding ".rtbw" file exsists | |
| 1369 | for (PieceType p1 = PAWN; p1 < KING; ++p1) { | 1338 | for (PieceType p1 = PAWN; p1 < KING; ++p1) { | 
| 1370 | 
 | 1339 | TBTables.add({KING, p1, KING}); | 
| 1371 | 1340 | ||
| 1372 | for (PieceType p2 = PAWN; p2 <= p1; ++p2) { | 1341 | for (PieceType p2 = PAWN; p2 <= p1; ++p2) { | 
| 1373 | 
 | 1342 | TBTables.add({KING, p1, p2, KING}); | 
| 1374 | 
 | 1343 | TBTables.add({KING, p1, KING, p2}); | 
| 1375 | 1344 | ||
| 1376 | for (PieceType p3 = PAWN; p3 < KING; ++p3) | 1345 | for (PieceType p3 = PAWN; p3 < KING; ++p3) | 
| 1377 | 
 | 1346 | TBTables.add({KING, p1, p2, KING, p3}); | 
| 1378 | 1347 | ||
| 1379 | for (PieceType p3 = PAWN; p3 <= p2; ++p3) { | 1348 | for (PieceType p3 = PAWN; p3 <= p2; ++p3) { | 
| 1380 | 
 | 1349 | TBTables.add({KING, p1, p2, p3, KING}); | 
| - | 1350 | ||
| - | 1351 | for (PieceType p4 = PAWN; p4 <= p3; ++p4) { | |
| - | 1352 | TBTables.add({KING, p1, p2, p3, p4, KING}); | |
| 1381 | 1353 | ||
| 1382 | for (PieceType | 1354 | for (PieceType p5 = PAWN; p5 <= p4; ++p5) | 
| 1383 | 
 | 1355 | TBTables.add({KING, p1, p2, p3, p4, p5, KING}); | 
| 1384 | 1356 | ||
| - | 1357 | for (PieceType p5 = PAWN; p5 < KING; ++p5) | |
| - | 1358 | TBTables.add({KING, p1, p2, p3, p4, KING, p5}); | |
| - | 1359 |                 } | |
| - | 1360 | ||
| 1385 | for (PieceType p4 = PAWN; p4 < KING; ++p4) | 1361 | for (PieceType p4 = PAWN; p4 < KING; ++p4) { | 
| 1386 | 
 | 1362 | TBTables.add({KING, p1, p2, p3, KING, p4}); | 
| - | 1363 | ||
| - | 1364 | for (PieceType p5 = PAWN; p5 <= p4; ++p5) | |
| - | 1365 | TBTables.add({KING, p1, p2, p3, KING, p4, p5}); | |
| - | 1366 |                 } | |
| 1387 |             } | 1367 |             } | 
| 1388 | 1368 | ||
| 1389 | for (PieceType p3 = PAWN; p3 <= p1; ++p3) | 1369 | for (PieceType p3 = PAWN; p3 <= p1; ++p3) | 
| 1390 | for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4) | 1370 | for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4) | 
| 1391 | 
 | 1371 | TBTables.add({KING, p1, p2, KING, p3, p4}); | 
| 1392 |         } | 1372 |         } | 
| 1393 |     } | 1373 |     } | 
| 1394 | 1374 | ||
| 1395 | sync_cout << "info string Found " << | 1375 | sync_cout << "info string Found " << TBTables.size() << " tablebases" << sync_endl; | 
| 1396 | } | 1376 | } | 
| 1397 | 1377 | ||
| 1398 | // Probe the WDL table for a particular position. | 1378 | // Probe the WDL table for a particular position. | 
| 1399 | // If *result != FAIL, the probe was successful. | 1379 | // If *result != FAIL, the probe was successful. | 
| 1400 | // The return value is from the point of view of the side to move: | 1380 | // The return value is from the point of view of the side to move: | 
| Line 1404... | Line 1384... | ||
| 1404 | //  1 : win, but draw under 50-move rule | 1384 | //  1 : win, but draw under 50-move rule | 
| 1405 | //  2 : win | 1385 | //  2 : win | 
| 1406 | WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) { | 1386 | WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) { | 
| 1407 | 1387 | ||
| 1408 | *result = OK; | 1388 | *result = OK; | 
| 1409 | return search(pos, result); | 1389 | return search<false>(pos, result); | 
| 1410 | } | 1390 | } | 
| 1411 | 1391 | ||
| 1412 | // Probe the DTZ table for a particular position. | 1392 | // Probe the DTZ table for a particular position. | 
| 1413 | // If *result != FAIL, the probe was successful. | 1393 | // If *result != FAIL, the probe was successful. | 
| 1414 | // The return value is from the point of view of the side to move: | 1394 | // The return value is from the point of view of the side to move: | 
| 1415 | //         n < -100 : loss, but draw under 50-move rule | 1395 | //         n < -100 : loss, but draw under 50-move rule | 
| 1416 | // -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0) | 1396 | // -100 <= n < -1   : loss in n ply (assuming 50-move counter == 0) | 
| - | 1397 | //        -1        : loss, the side to move is mated | |
| 1417 | //         0        : draw | 1398 | //         0        : draw | 
| 1418 | //     1 < n <= 100 : win in n ply (assuming 50-move counter == 0) | 1399 | //     1 < n <= 100 : win in n ply (assuming 50-move counter == 0) | 
| 1419 | //   100 < n        : win, but draw under 50-move rule | 1400 | //   100 < n        : win, but draw under 50-move rule | 
| 1420 | // | 1401 | // | 
| 1421 | // The return value n can be off by 1: a return value -n can mean a loss | 1402 | // The return value n can be off by 1: a return value -n can mean a loss | 
| Line 1445... | Line 1426... | ||
| 1445 |     // DTZ stores a 'don't care' value in this case, or even a plain wrong | 1426 |     // DTZ stores a 'don't care' value in this case, or even a plain wrong | 
| 1446 |     // one as in case the best move is a losing ep, so it cannot be probed. | 1427 |     // one as in case the best move is a losing ep, so it cannot be probed. | 
| 1447 | if (*result == ZEROING_BEST_MOVE) | 1428 | if (*result == ZEROING_BEST_MOVE) | 
| 1448 | return dtz_before_zeroing(wdl); | 1429 | return dtz_before_zeroing(wdl); | 
| 1449 | 1430 | ||
| 1450 | int dtz = probe_table< | 1431 | int dtz = probe_table<DTZ>(pos, result, wdl); | 
| 1451 | 1432 | ||
| 1452 | if (*result == FAIL) | 1433 | if (*result == FAIL) | 
| 1453 | return 0; | 1434 | return 0; | 
| 1454 | 1435 | ||
| 1455 | if (*result != CHANGE_STM) | 1436 | if (*result != CHANGE_STM) | 
| Line 1468... | Line 1449... | ||
| 1468 | 1449 | ||
| 1469 |         // For zeroing moves we want the dtz of the move _before_ doing it, | 1450 |         // For zeroing moves we want the dtz of the move _before_ doing it, | 
| 1470 |         // otherwise we will get the dtz of the next move sequence. Search the | 1451 |         // otherwise we will get the dtz of the next move sequence. Search the | 
| 1471 |         // position after the move to get the score sign (because even in a | 1452 |         // position after the move to get the score sign (because even in a | 
| 1472 |         // winning position we could make a losing capture or going for a draw). | 1453 |         // winning position we could make a losing capture or going for a draw). | 
| 1473 | dtz = zeroing ? -dtz_before_zeroing(search(pos, result)) | 1454 | dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result)) | 
| 1474 | : -probe_dtz(pos, result); | 1455 | : -probe_dtz(pos, result); | 
| 1475 | 1456 | ||
| 1476 | 
 | 1457 |         // If the move mates, force minDTZ to 1 | 
| 1477 | - | ||
| 1478 | if ( | 1458 | if (dtz == 1 && pos.checkers() && MoveList<LEGAL>(pos).size() == 0) | 
| 1479 | 
 | 1459 | minDTZ = 1; | 
| 1480 | 1460 | ||
| 1481 |         // Convert result from 1-ply search. Zeroing moves are already accounted | 1461 |         // Convert result from 1-ply search. Zeroing moves are already accounted | 
| 1482 |         // by dtz_before_zeroing() that returns the DTZ of the previous move. | 1462 |         // by dtz_before_zeroing() that returns the DTZ of the previous move. | 
| 1483 | if (!zeroing) | 1463 | if (!zeroing) | 
| 1484 | dtz += sign_of(dtz); | 1464 | dtz += sign_of(dtz); | 
| 1485 | 1465 | ||
| 1486 |         // Skip the draws and if we are winning only pick positive dtz | 1466 |         // Skip the draws and if we are winning only pick positive dtz | 
| 1487 | if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl)) | 1467 | if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl)) | 
| 1488 | minDTZ = dtz; | 1468 | minDTZ = dtz; | 
| - | 1469 | ||
| - | 1470 | pos.undo_move(move); | |
| - | 1471 | ||
| - | 1472 | if (*result == FAIL) | |
| - | 1473 | return 0; | |
| 1489 |     } | 1474 |     } | 
| 1490 | 1475 | ||
| 1491 |     //  | 1476 |     // When there are no legal moves, the position is mate: we return -1 | 
| 1492 |     // case return value is somewhat arbitrary, so stick to the original TB code | - | |
| 1493 |     // that returns -1 in this case. | - | |
| 1494 | return minDTZ == 0xFFFF ? -1 : minDTZ; | 1477 | return minDTZ == 0xFFFF ? -1 : minDTZ; | 
| 1495 | } | 1478 | } | 
| 1496 | 1479 | ||
| 1497 | // Check whether there has been at least one repetition of positions | - | |
| 1498 | // since the last capture or pawn move. | - | |
| 1499 | static int has_repeated(StateInfo *st) | - | |
| 1500 | { | - | |
| 1501 | while (1) { | - | |
| 1502 | int i = 4, e = std::min(st->rule50, st->pliesFromNull); | - | |
| 1503 | 1480 | ||
| 1504 | if (e < i) | - | |
| 1505 | return 0; | - | |
| 1506 | - | ||
| 1507 | StateInfo *stp = st->previous->previous; | - | |
| 1508 | - | ||
| 1509 | do { | - | |
| 1510 | stp = stp->previous->previous; | - | |
| 1511 | - | ||
| 1512 | if (stp->key == st->key) | - | |
| 1513 | return 1; | - | |
| 1514 | - | ||
| 1515 | i += 2; | - | |
| 1516 | } while (i <= e); | - | |
| 1517 | - | ||
| 1518 | st = st->previous; | - | |
| 1519 |     } | - | |
| 1520 | } | - | |
| 1521 | - | ||
| 1522 | // Use the DTZ tables to  | 1481 | // Use the DTZ tables to rank root moves. | 
| 1523 | // If the position is lost, but DTZ is fairly high, only keep moves that | - | |
| 1524 | // maximise DTZ. | - | |
| 1525 | // | 1482 | // | 
| 1526 | // A return value false indicates that not all probes were successful | 1483 | // A return value false indicates that not all probes were successful. | 
| 1527 | // no moves were filtered out. | - | |
| 1528 | bool Tablebases::root_probe(Position& pos, Search::RootMoves& | 1484 | bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves) { | 
| 1529 | { | - | |
| 1530 | assert(rootMoves.size()); | - | |
| 1531 | 1485 | ||
| 1532 |     ProbeState result; | 1486 |     ProbeState result; | 
| 1533 | 
 | 1487 |     StateInfo st; | 
| 1534 | 1488 | ||
| 1535 | 
 | 1489 |     // Obtain 50-move counter for the root position | 
| 1536 | 
 | 1490 | int cnt50 = pos.rule50_count(); | 
| 1537 | 1491 | ||
| - | 1492 |     // Check whether a position was repeated since the last zeroing move. | |
| 1538 | 
 | 1493 | bool rep = pos.has_repeated(); | 
| 1539 | 1494 | ||
| 1540 |     // Probe each move | - | |
| 1541 | 
 | 1495 | int dtz, bound = Options["Syzygy50MoveRule"] ? 900 : 1; | 
| 1542 | Move move = rootMoves[i].pv[0]; | - | |
| 1543 | pos.do_move(move, st); | - | |
| 1544 | int v = 0; | - | |
| 1545 | 1496 | ||
| 1546 | 
 | 1497 |     // Probe and rank each move | 
| - | 1498 | for (auto& m : rootMoves) | |
| - | 1499 |     { | |
| 1547 | 
 | 1500 | pos.do_move(m.pv[0], st); | 
| 1548 | 1501 | ||
| - | 1502 |         // Calculate dtz for the current move counting from the root position | |
| - | 1503 | if (pos.rule50_count() == 0) | |
| - | 1504 |         { | |
| - | 1505 |             // In case of a zeroing move, dtz is one of -101/-1/0/1/101 | |
| - | 1506 | WDLScore wdl = -probe_wdl(pos, &result); | |
| - | 1507 | dtz = dtz_before_zeroing(wdl); | |
| - | 1508 |         } | |
| - | 1509 |         else | |
| - | 1510 |         { | |
| - | 1511 |             // Otherwise, take dtz for the new position and correct by 1 ply | |
| 1549 | 
 | 1512 | dtz = -probe_dtz(pos, &result); | 
| 1550 | 
 | 1513 | dtz = dtz > 0 ? dtz + 1 | 
| - | 1514 | : dtz < 0 ? dtz - 1 : dtz; | |
| 1551 |         } | 1515 |         } | 
| 1552 | 1516 | ||
| - | 1517 |         // Make sure that a mating move is assigned a dtz value of 1 | |
| 1553 | if ( | 1518 | if ( pos.checkers() | 
| 1554 | 
 | 1519 | && dtz == 2 | 
| 1555 | 
 | 1520 | && MoveList<LEGAL>(pos).size() == 0) | 
| - | 1521 | dtz = 1; | |
| 1556 | 1522 | ||
| 1557 | if (v > 0) | - | |
| 1558 | ++v; | - | |
| 1559 | else if (v < 0) | - | |
| 1560 | --v; | - | |
| 1561 | } else { | - | |
| 1562 | v = -probe_wdl(pos, &result); | - | |
| 1563 | v = dtz_before_zeroing(WDLScore(v)); | - | |
| 1564 |             } | - | |
| 1565 |         } | - | |
| 1566 | - | ||
| 1567 | pos.undo_move( | 1523 | pos.undo_move(m.pv[0]); | 
| 1568 | 1524 | ||
| 1569 | if (result == FAIL) | 1525 | if (result == FAIL) | 
| 1570 | return false; | 1526 | return false; | 
| 1571 | 1527 | ||
| 1572 | 
 | 1528 |         // Better moves are ranked higher. Certain wins are ranked equally. | 
| - | 1529 |         // Losing moves are ranked equally unless a 50-move draw is in sight. | |
| - | 1530 | int r = dtz > 0 ? (dtz + cnt50 <= 99 && !rep ? 1000 : 1000 - (dtz + cnt50)) | |
| - | 1531 | : dtz < 0 ? (-dtz * 2 + cnt50 < 100 ? -1000 : -1000 + (-dtz + cnt50)) | |
| 1573 | 
 | 1532 | : 0; | 
| - | 1533 | m.tbRank = r; | |
| 1574 | 1534 | ||
| 1575 |     // Obtain 50-move counter for the root position. | - | |
| 1576 | 
 | 1535 | // Determine the score to be displayed for this move. Assign at least | 
| 1577 | int cnt50 = st.previous ? st.previous->rule50 : 0; | - | |
| 1578 | - | ||
| 1579 |     //  | 1536 |         // 1 cp to cursed wins and let it grow to 49 cp as the positions gets | 
| 1580 |     //  | 1537 |         // closer to a real win. | 
| 1581 | WDLScore wdl = WDLDraw; | - | |
| 1582 | - | ||
| 1583 | if (dtz > 0) | - | |
| 1584 | 
 | 1538 | m.tbScore = r >= bound ? VALUE_MATE - MAX_PLY - 1 | 
| 1585 | else if (dtz < 0) | - | |
| 1586 | wdl = (-dtz + cnt50 <= 100) ? WDLLoss : WDLBlessedLoss; | - | |
| 1587 | - | ||
| 1588 |     // Determine the score to report to the user. | - | |
| 1589 | score = WDL_to_value[wdl + 2]; | - | |
| 1590 | - | ||
| 1591 |     // If the position is winning or losing, but too few moves left, adjust the | - | |
| 1592 |     // score to show how close it is to winning or losing. | - | |
| 1593 |     // NOTE: int(PawnValueEg) is used as scaling factor in score_to_uci(). | - | |
| 1594 | if (wdl == WDLCursedWin && dtz <= 100) | - | |
| 1595 | 
 | 1539 | : r > 0 ? Value((std::max( 3, r - 800) * int(PawnValueEg)) / 200) | 
| 1596 | 
 | 1540 | : r == 0 ? VALUE_DRAW | 
| 1597 | 
 | 1541 | : r > -bound ? Value((std::min(-3, r + 800) * int(PawnValueEg)) / 200) | 
| 1598 | - | ||
| 1599 |     // Now be a bit smart about filtering out moves. | - | |
| 1600 | size_t j = 0; | - | |
| 1601 | - | ||
| 1602 | if (dtz > 0) { // winning (or 50-move rule draw) | - | |
| 1603 | int best = 0xffff; | - | |
| 1604 | - | ||
| 1605 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1606 | int v = rootMoves[i].score; | - | |
| 1607 | - | ||
| 1608 | if (v > 0 && v < best) | - | |
| 1609 | best = v; | - | |
| 1610 |         } | - | |
| 1611 | - | ||
| 1612 | int max = best; | - | |
| 1613 | - | ||
| 1614 |         // If the current phase has not seen repetitions, then try all moves | - | |
| 1615 |         // that stay safely within the 50-move budget, if there are any. | - | |
| 1616 | if (!has_repeated(st.previous) && best + cnt50 <= 99) | - | |
| 1617 | max = 99 - cnt50; | - | |
| 1618 | - | ||
| 1619 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1620 | int v = rootMoves[i].score; | - | |
| 1621 | - | ||
| 1622 | if (v > 0 && v <= max) | - | |
| 1623 | rootMoves[j++] = rootMoves[i]; | - | |
| 1624 |         } | - | |
| 1625 | } else if (dtz < 0) { // losing (or 50-move rule draw) | - | |
| 1626 | int best = 0; | - | |
| 1627 | - | ||
| 1628 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1629 | int v = rootMoves[i].score; | - | |
| 1630 | - | ||
| 1631 | if (v < best) | - | |
| 1632 | best = v; | - | |
| 1633 |         } | - | |
| 1634 | - | ||
| 1635 |         // Try all moves, unless we approach or have a 50-move rule draw. | - | |
| 1636 | if (-best * 2 + cnt50 < 100) | - | |
| 1637 | return true; | - | |
| 1638 | - | ||
| 1639 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1640 | if (rootMoves[i].score == best) | - | |
| 1641 | rootMoves[j++] = rootMoves[i]; | - | |
| 1642 |         } | - | |
| 1643 | } else { // drawing | - | |
| 1644 |         // Try all moves that preserve the draw. | - | |
| 1645 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1646 | if (rootMoves[i].score == 0) | - | |
| 1647 | 
 | 1542 | : -VALUE_MATE + MAX_PLY + 1; | 
| 1648 |         } | - | |
| 1649 |     } | 1543 |     } | 
| 1650 | - | ||
| 1651 | rootMoves.resize(j, Search::RootMove(MOVE_NONE)); | - | |
| 1652 | 1544 | ||
| 1653 | return true; | 1545 | return true; | 
| 1654 | } | 1546 | } | 
| 1655 | 1547 | ||
| - | 1548 | ||
| 1656 | // Use the WDL tables to  | 1549 | // Use the WDL tables to rank root moves. | 
| 1657 | // This is a fallback for the case that some or all DTZ tables are missing. | 1550 | // This is a fallback for the case that some or all DTZ tables are missing. | 
| 1658 | // | 1551 | // | 
| 1659 | // A return value false indicates that not all probes were successful | 1552 | // A return value false indicates that not all probes were successful. | 
| 1660 | // no moves were filtered out. | - | |
| 1661 | bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& | 1553 | bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves) { | 
| 1662 | { | - | |
| 1663 |     ProbeState result; | - | |
| 1664 | 1554 | ||
| 1665 | 
 | 1555 | static const int WDL_to_rank[] = { -1000, -899, 0, 899, 1000 }; | 
| 1666 | 1556 | ||
| 1667 | 
 | 1557 |     ProbeState result; | 
| 1668 | 
 | 1558 |     StateInfo st; | 
| 1669 | 1559 | ||
| 1670 | 
 | 1560 | bool rule50 = Options["Syzygy50MoveRule"]; | 
| 1671 | 1561 | ||
| - | 1562 |     // Probe and rank each move | |
| 1672 | 
 | 1563 | for (auto& m : rootMoves) | 
| - | 1564 |     { | |
| - | 1565 | pos.do_move(m.pv[0], st); | |
| 1673 | 1566 | ||
| 1674 | 
 | 1567 | WDLScore wdl = -probe_wdl(pos, &result); | 
| 1675 | 1568 | ||
| 1676 |     // Probe each move | - | |
| 1677 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1678 | Move move = rootMoves[i].pv[0]; | - | |
| 1679 | pos.do_move(move, st); | - | |
| 1680 | WDLScore v = -Tablebases::probe_wdl(pos, &result); | - | |
| 1681 | pos.undo_move( | 1569 | pos.undo_move(m.pv[0]); | 
| 1682 | 1570 | ||
| 1683 | if (result == FAIL) | 1571 | if (result == FAIL) | 
| 1684 | return false; | 1572 | return false; | 
| 1685 | 1573 | ||
| 1686 | 
 | 1574 | m.tbRank = WDL_to_rank[wdl + 2]; | 
| 1687 | 1575 | ||
| 1688 | if ( | 1576 | if (!rule50) | 
| 1689 | 
 | 1577 | wdl = wdl > WDLDraw ? WDLWin | 
| - | 1578 | : wdl < WDLDraw ? WDLLoss : WDLDraw; | |
| - | 1579 | m.tbScore = WDL_to_value[wdl + 2]; | |
| 1690 |     } | 1580 |     } | 
| 1691 | - | ||
| 1692 | size_t j = 0; | - | |
| 1693 | - | ||
| 1694 | for (size_t i = 0; i < rootMoves.size(); ++i) { | - | |
| 1695 | if (rootMoves[i].score == best) | - | |
| 1696 | rootMoves[j++] = rootMoves[i]; | - | |
| 1697 |     } | - | |
| 1698 | - | ||
| 1699 | rootMoves.resize(j, Search::RootMove(MOVE_NONE)); | - | |
| 1700 | 1581 | ||
| 1701 | return true; | 1582 | return true; | 
| 1702 | } | 1583 | } |