2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (C) 2004-2020 The Stockfish developers (see AUTHORS file)
5 Stockfish is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 Stockfish is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>.
22 #include <cstring> // For std::memset and std::memcpy
28 #include <type_traits>
31 #include "../bitboard.h"
32 #include "../movegen.h"
33 #include "../position.h"
34 #include "../search.h"
46 #define WIN32_LEAN_AND_MEAN
48 # define NOMINMAX // Disable macros min() and max()
53 using namespace Tablebases;
55 int Tablebases::MaxCardinality;
59 constexpr int TBPIECES = 7; // Max number of supported pieces
61 enum { BigEndian, LittleEndian };
62 enum TBType { WDL, DTZ }; // Used as template parameter
64 // Each table has a set of flags: all of them refer to DTZ tables, the last one to WDL tables
65 enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, Wide = 16, SingleValue = 128 };
67 inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
68 inline Square operator^(Square s, int i) { return Square(int(s) ^ i); }
70 const std::string PieceToChar = " PNBRQK pnbrqk";
72 int MapPawns[SQUARE_NB];
73 int MapB1H1H7[SQUARE_NB];
74 int MapA1D1D4[SQUARE_NB];
75 int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
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]
81 // Comparison function to sort leading pawns in ascending MapPawns[] order
82 bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; }
83 int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); }
85 constexpr Value WDL_to_value[] = {
86 -VALUE_MATE + MAX_PLY + 1,
90 VALUE_MATE - MAX_PLY - 1
93 template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
94 inline void swap_endian(T& x)
96 static_assert(std::is_unsigned<T>::value, "Argument of swap_endian not unsigned");
98 uint8_t tmp, *c = (uint8_t*)&x;
99 for (int i = 0; i < Half; ++i)
100 tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
102 template<> inline void swap_endian<uint8_t>(uint8_t&) {}
104 template<typename T, int LE> T number(void* addr)
106 static const union { uint32_t i; char c[4]; } Le = { 0x01020304 };
107 static const bool IsLittleEndian = (Le.c[0] == 4);
111 if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare)
112 std::memcpy(&v, addr, sizeof(T));
116 if (LE != IsLittleEndian)
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 :
127 wdl == WDLBlessedLoss ? -101 :
128 wdl == WDLLoss ? -1 : 0;
131 // Return the sign of a number (-1, 0, 1)
132 template <typename T> int sign_of(T val) {
133 return (T(0) < val) - (val < T(0));
136 // Numbers in little endian used by sparseIndex[] to point into blockLength[]
138 char block[4]; // Number of block
139 char offset[2]; // Offset within the block
142 static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
144 typedef uint16_t Sym; // Huffman symbol
147 enum Side { Left, Right };
149 uint8_t lr[3]; // The first 12 bits is the left-hand symbol, the second 12
150 // bits is the right-hand symbol. If symbol has length 1,
151 // then the left-hand symbol is the stored value.
154 return S == Left ? ((lr[1] & 0xF) << 8) | lr[0] :
155 S == Right ? (lr[2] << 4) | (lr[1] >> 4) : (assert(false), Sym(-1));
159 static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
161 // Tablebases data layout is structured as following:
163 // TBFile: memory maps/unmaps the physical .rtbw and .rtbz files
164 // TBTable: one object for each file with corresponding indexing information
165 // TBTables: has ownership of TBTable objects, keeping a list and a hash
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.
170 class TBFile : public std::ifstream {
175 // Look for and open the file among the Paths directories where the .rtbw
176 // and .rtbz files can be found. Multiple directories are separated by ";"
177 // on Windows and by ":" on Unix-based operating systems.
180 // C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
181 static std::string Paths;
183 TBFile(const std::string& f) {
186 constexpr char SepChar = ':';
188 constexpr char SepChar = ';';
190 std::stringstream ss(Paths);
193 while (std::getline(ss, path, SepChar)) {
194 fname = path + "/" + f;
195 std::ifstream::open(fname);
201 // Memory map the file and check it. File should be already open and will be
202 // closed after mapping.
203 uint8_t* map(void** baseAddress, uint64_t* mapping, TBType type) {
207 close(); // Need to re-open to get native file descriptor
211 int fd = ::open(fname.c_str(), O_RDONLY);
214 return *baseAddress = nullptr, nullptr;
218 if (statbuf.st_size % 64 != 16)
220 std::cerr << "Corrupt tablebase file " << fname << std::endl;
224 *mapping = statbuf.st_size;
225 *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
226 madvise(*baseAddress, statbuf.st_size, MADV_RANDOM);
229 if (*baseAddress == MAP_FAILED)
231 std::cerr << "Could not mmap() " << fname << std::endl;
235 // Note FILE_FLAG_RANDOM_ACCESS is only a hint to Windows and as such may get ignored.
236 HANDLE fd = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
237 OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, nullptr);
239 if (fd == INVALID_HANDLE_VALUE)
240 return *baseAddress = nullptr, nullptr;
243 DWORD size_low = GetFileSize(fd, &size_high);
245 if (size_low % 64 != 16)
247 std::cerr << "Corrupt tablebase file " << fname << std::endl;
251 HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
256 std::cerr << "CreateFileMapping() failed" << std::endl;
260 *mapping = (uint64_t)mmap;
261 *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
265 std::cerr << "MapViewOfFile() failed, name = " << fname
266 << ", error = " << GetLastError() << std::endl;
270 uint8_t* data = (uint8_t*)*baseAddress;
272 constexpr uint8_t Magics[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 },
273 { 0x71, 0xE8, 0x23, 0x5D } };
275 if (memcmp(data, Magics[type == WDL], 4))
277 std::cerr << "Corrupted table in file " << fname << std::endl;
278 unmap(*baseAddress, *mapping);
279 return *baseAddress = nullptr, nullptr;
282 return data + 4; // Skip Magics's header
285 static void unmap(void* baseAddress, uint64_t mapping) {
288 munmap(baseAddress, mapping);
290 UnmapViewOfFile(baseAddress);
291 CloseHandle((HANDLE)mapping);
296 std::string TBFile::Paths;
298 // struct PairsData contains low level indexing information to access TB data.
299 // There are 8, 4 or 2 PairsData records for each TBTable, according to type of
300 // table and if positions have pawns or not. It is populated at first access.
302 uint8_t flags; // Table flags, see enum TBFlag
303 uint8_t maxSymLen; // Maximum length in bits of the Huffman symbols
304 uint8_t minSymLen; // Minimum length in bits of the Huffman symbols
305 uint32_t blocksNum; // Number of blocks in the TB file
306 size_t sizeofBlock; // Block size in bytes
307 size_t span; // About every span values there is a SparseIndex[] entry
308 Sym* lowestSym; // lowestSym[l] is the symbol of length l with the lowest value
309 LR* btree; // btree[sym] stores the left and right symbols that expand sym
310 uint16_t* blockLength; // Number of stored positions (minus one) for each block: 1..65536
311 uint32_t blockLengthSize; // Size of blockLength[] table: padded so it's bigger than blocksNum
312 SparseEntry* sparseIndex; // Partial indices into blockLength[]
313 size_t sparseIndexSize; // Size of SparseIndex[] table
314 uint8_t* data; // Start of Huffman compressed data
315 std::vector<uint64_t> base64; // base64[l - min_sym_len] is the 64bit-padded lowest symbol of length l
316 std::vector<uint8_t> symlen; // Number of values (-1) represented by a given Huffman symbol: 1..256
317 Piece pieces[TBPIECES]; // Position pieces: the order of pieces defines the groups
318 uint64_t groupIdx[TBPIECES+1]; // Start index used for the encoding of the group's pieces
319 int groupLen[TBPIECES+1]; // Number of pieces in a given group: KRKN -> (3, 1)
320 uint16_t map_idx[4]; // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss (used in DTZ)
323 // struct TBTable contains indexing information to access the corresponding TBFile.
324 // There are 2 types of TBTable, corresponding to a WDL or a DTZ file. TBTable
325 // is populated at init time but the nested PairsData records are populated at
326 // first access, when the corresponding file is memory mapped.
327 template<TBType Type>
329 typedef typename std::conditional<Type == WDL, WDLScore, int>::type Ret;
331 static constexpr int Sides = Type == WDL ? 2 : 1;
333 std::atomic_bool ready;
341 bool hasUniquePieces;
342 uint8_t pawnCount[2]; // [Lead color / other color]
343 PairsData items[Sides][4]; // [wtm / btm][FILE_A..FILE_D or 0]
345 PairsData* get(int stm, int f) {
346 return &items[stm % Sides][hasPawns ? f : 0];
349 TBTable() : ready(false), baseAddress(nullptr) {}
350 explicit TBTable(const std::string& code);
351 explicit TBTable(const TBTable<WDL>& wdl);
355 TBFile::unmap(baseAddress, mapping);
360 TBTable<WDL>::TBTable(const std::string& code) : TBTable() {
365 key = pos.set(code, WHITE, &st).material_key();
366 pieceCount = pos.count<ALL_PIECES>();
367 hasPawns = pos.pieces(PAWN);
369 hasUniquePieces = false;
370 for (Color c : { WHITE, BLACK })
371 for (PieceType pt = PAWN; pt < KING; ++pt)
372 if (popcount(pos.pieces(c, pt)) == 1)
373 hasUniquePieces = true;
375 // Set the leading color. In case both sides have pawns the leading color
376 // is the side with less pawns because this leads to better compression.
377 bool c = !pos.count<PAWN>(BLACK)
378 || ( pos.count<PAWN>(WHITE)
379 && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
381 pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
382 pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
384 key2 = pos.set(code, BLACK, &st).material_key();
388 TBTable<DTZ>::TBTable(const TBTable<WDL>& wdl) : TBTable() {
390 // Use the corresponding WDL table to avoid recalculating all from scratch
393 pieceCount = wdl.pieceCount;
394 hasPawns = wdl.hasPawns;
395 hasUniquePieces = wdl.hasUniquePieces;
396 pawnCount[0] = wdl.pawnCount[0];
397 pawnCount[1] = wdl.pawnCount[1];
400 // class TBTables creates and keeps ownership of the TBTable objects, one for
401 // each TB file found. It supports a fast, hash based, table lookup. Populated
402 // at init time, accessed at probe time.
411 template <TBType Type>
412 TBTable<Type>* get() const {
413 return (TBTable<Type>*)(Type == WDL ? (void*)wdl : (void*)dtz);
417 static constexpr int Size = 1 << 12; // 4K table, indexed by key's 12 lsb
418 static constexpr int Overflow = 1; // Number of elements allowed to map to the last bucket
420 Entry hashTable[Size + Overflow];
422 std::deque<TBTable<WDL>> wdlTable;
423 std::deque<TBTable<DTZ>> dtzTable;
425 void insert(Key key, TBTable<WDL>* wdl, TBTable<DTZ>* dtz) {
426 uint32_t homeBucket = (uint32_t)key & (Size - 1);
427 Entry entry{ key, wdl, dtz };
429 // Ensure last element is empty to avoid overflow when looking up
430 for (uint32_t bucket = homeBucket; bucket < Size + Overflow - 1; ++bucket) {
431 Key otherKey = hashTable[bucket].key;
432 if (otherKey == key || !hashTable[bucket].get<WDL>()) {
433 hashTable[bucket] = entry;
437 // Robin Hood hashing: If we've probed for longer than this element,
438 // insert here and search for a new spot for the other element instead.
439 uint32_t otherHomeBucket = (uint32_t)otherKey & (Size - 1);
440 if (otherHomeBucket > homeBucket) {
441 std::swap(entry, hashTable[bucket]);
443 homeBucket = otherHomeBucket;
446 std::cerr << "TB hash table size too low!" << std::endl;
451 template<TBType Type>
452 TBTable<Type>* get(Key key) {
453 for (const Entry* entry = &hashTable[(uint32_t)key & (Size - 1)]; ; ++entry) {
454 if (entry->key == key || !entry->get<Type>())
455 return entry->get<Type>();
460 memset(hashTable, 0, sizeof(hashTable));
464 size_t size() const { return wdlTable.size(); }
465 void add(const std::vector<PieceType>& pieces);
470 // If the corresponding file exists two new objects TBTable<WDL> and TBTable<DTZ>
471 // are created and added to the lists and hash table. Called at init time.
472 void TBTables::add(const std::vector<PieceType>& pieces) {
476 for (PieceType pt : pieces)
477 code += PieceToChar[pt];
479 TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); // KRK -> KRvK
481 if (!file.is_open()) // Only WDL file is checked
486 MaxCardinality = std::max((int)pieces.size(), MaxCardinality);
488 wdlTable.emplace_back(code);
489 dtzTable.emplace_back(wdlTable.back());
491 // Insert into the hash keys for both colors: KRvK with KR white and black
492 insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back());
493 insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
496 // TB tables are compressed with canonical Huffman code. The compressed data is divided into
497 // blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
498 // Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
499 // (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
500 // WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
501 // Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
502 // 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
503 // of draws or mostly of wins, but such tables are actually quite common. In principle, the
504 // blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
505 // mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
506 // in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
507 // The generator picks the size that leads to the smallest table. The "book" of symbols and
508 // Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
509 // will have one table for wtm and one for btm, a TB file with pawns will have tables per
510 // file a,b,c,d also in this case one set for wtm and one for btm.
511 int decompress_pairs(PairsData* d, uint64_t idx) {
513 // Special case where all table positions store the same value
514 if (d->flags & TBFlag::SingleValue)
517 // First we need to locate the right block that stores the value at index "idx".
518 // Because each block n stores blockLength[n] + 1 values, the index i of the block
519 // that contains the value at position idx is:
521 // for (i = -1, sum = 0; sum <= idx; i++)
522 // sum += blockLength[i + 1] + 1;
524 // This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
525 // point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
526 // that stores the blockLength[] index and the offset within that block of the value
527 // with index I(k), where:
529 // I(k) = k * d->span + d->span / 2 (1)
531 // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
532 uint32_t k = uint32_t(idx / d->span);
534 // Then we read the corresponding SparseIndex[] entry
535 uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
536 int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
538 // Now compute the difference idx - I(k). From definition of k we know that
540 // idx = k * d->span + idx % d->span (2)
542 // So from (1) and (2) we can compute idx - I(K):
543 int diff = idx % d->span - d->span / 2;
545 // Sum the above to offset to find the offset corresponding to our idx
548 // Move to previous/next block, until we reach the correct block that contains idx,
549 // that is when 0 <= offset <= d->blockLength[block]
551 offset += d->blockLength[--block] + 1;
553 while (offset > d->blockLength[block])
554 offset -= d->blockLength[block++] + 1;
556 // Finally, we find the start address of our block of canonical Huffman symbols
557 uint32_t* ptr = (uint32_t*)(d->data + ((uint64_t)block * d->sizeofBlock));
559 // Read the first 64 bits in our block, this is a (truncated) sequence of
560 // unknown number of symbols of unknown length but we know the first one
561 // is at the beginning of this 64 bits sequence.
562 uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
567 int len = 0; // This is the symbol length - d->min_sym_len
569 // Now get the symbol length. For any symbol s64 of length l right-padded
570 // to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
571 // can find the symbol length iterating through base64[].
572 while (buf64 < d->base64[len])
575 // All the symbols of a given length are consecutive integers (numerical
576 // sequence property), so we can compute the offset of our symbol of
577 // length len, stored at the beginning of buf64.
578 sym = Sym((buf64 - d->base64[len]) >> (64 - len - d->minSymLen));
580 // Now add the value of the lowest symbol of length len to get our symbol
581 sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
583 // If our offset is within the number of values represented by symbol sym
585 if (offset < d->symlen[sym] + 1)
588 // ...otherwise update the offset and continue to iterate
589 offset -= d->symlen[sym] + 1;
590 len += d->minSymLen; // Get the real length
591 buf64 <<= len; // Consume the just processed symbol
594 if (buf64Size <= 32) { // Refill the buffer
596 buf64 |= (uint64_t)number<uint32_t, BigEndian>(ptr++) << (64 - buf64Size);
600 // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
601 // We binary-search for our value recursively expanding into the left and
602 // right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
603 // that will store the value we need.
604 while (d->symlen[sym]) {
606 Sym left = d->btree[sym].get<LR::Left>();
608 // If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
609 // expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
610 // we know that, for instance the ten-th value (offset = 10) will be on
611 // the left side because in Recursive Pairing child symbols are adjacent.
612 if (offset < d->symlen[left] + 1)
615 offset -= d->symlen[left] + 1;
616 sym = d->btree[sym].get<LR::Right>();
620 return d->btree[sym].get<LR::Left>();
623 bool check_dtz_stm(TBTable<WDL>*, int, File) { return true; }
625 bool check_dtz_stm(TBTable<DTZ>* entry, int stm, File f) {
627 auto flags = entry->get(stm, f)->flags;
628 return (flags & TBFlag::STM) == stm
629 || ((entry->key == entry->key2) && !entry->hasPawns);
632 // DTZ scores are sorted by frequency of occurrence and then assigned the
633 // values 0, 1, 2, ... in order of decreasing frequency. This is done for each
634 // of the four WDLScore values. The mapping information necessary to reconstruct
635 // the original values is stored in the TB file and read during map[] init.
636 WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); }
638 int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) {
640 constexpr int WDLMap[] = { 1, 3, 0, 2, 0 };
642 auto flags = entry->get(0, f)->flags;
644 uint8_t* map = entry->map;
645 uint16_t* idx = entry->get(0, f)->map_idx;
646 if (flags & TBFlag::Mapped) {
647 if (flags & TBFlag::Wide)
648 value = ((uint16_t *)map)[idx[WDLMap[wdl + 2]] + value];
650 value = map[idx[WDLMap[wdl + 2]] + value];
653 // DTZ tables store distance to zero in number of moves or plies. We
654 // want to return plies, so we have convert to plies when needed.
655 if ( (wdl == WDLWin && !(flags & TBFlag::WinPlies))
656 || (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
657 || wdl == WDLCursedWin
658 || wdl == WDLBlessedLoss)
664 // Compute a unique index out of a position and use it to probe the TB file. To
665 // encode k pieces of same type and color, first sort the pieces by square in
666 // ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
668 // idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
670 template<typename T, typename Ret = typename T::Ret>
671 Ret do_probe_table(const Position& pos, T* entry, WDLScore wdl, ProbeState* result) {
673 Square squares[TBPIECES];
674 Piece pieces[TBPIECES];
676 int next = 0, size = 0, leadPawnsCnt = 0;
678 Bitboard b, leadPawns = 0;
679 File tbFile = FILE_A;
681 // A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
682 // If both sides have the same pieces keys are equal. In this case TB tables
683 // only store the 'white to move' case, so if the position to lookup has black
684 // to move, we need to switch the color and flip the squares before to lookup.
685 bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
687 // TB files are calculated for white as stronger side. For instance we have
688 // KRvK, not KvKR. A position where stronger side is white will have its
689 // material key == entry->key, otherwise we have to switch the color and
690 // flip the squares before to lookup.
691 bool blackStronger = (pos.material_key() != entry->key);
693 int flipColor = (symmetricBlackToMove || blackStronger) * 8;
694 int flipSquares = (symmetricBlackToMove || blackStronger) * 56;
695 int stm = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
697 // For pawns, TB files store 4 separate tables according if leading pawn is on
698 // file a, b, c or d after reordering. The leading pawn is the one with maximum
699 // MapPawns[] value, that is the one most toward the edges and with lowest rank.
700 if (entry->hasPawns) {
702 // In all the 4 tables, pawns are at the beginning of the piece sequence and
703 // their color is the reference one. So we just pick the first one.
704 Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor);
706 assert(type_of(pc) == PAWN);
708 leadPawns = b = pos.pieces(color_of(pc), PAWN);
710 squares[size++] = pop_lsb(&b) ^ flipSquares;
715 std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
717 tbFile = File(edge_distance(file_of(squares[0])));
720 // DTZ tables are one-sided, i.e. they store positions only for white to
721 // move or only for black to move, so check for side to move to be stm,
722 // early exit otherwise.
723 if (!check_dtz_stm(entry, stm, tbFile))
724 return *result = CHANGE_STM, Ret();
726 // Now we are ready to get all the position pieces (but the lead pawns) and
727 // directly map them to the correct color and square.
728 b = pos.pieces() ^ leadPawns;
730 Square s = pop_lsb(&b);
731 squares[size] = s ^ flipSquares;
732 pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
737 d = entry->get(stm, tbFile);
739 // Then we reorder the pieces to have the same sequence as the one stored
740 // in pieces[i]: the sequence that ensures the best compression.
741 for (int i = leadPawnsCnt; i < size - 1; ++i)
742 for (int j = i + 1; j < size; ++j)
743 if (d->pieces[i] == pieces[j])
745 std::swap(pieces[i], pieces[j]);
746 std::swap(squares[i], squares[j]);
750 // Now we map again the squares so that the square of the lead piece is in
751 // the triangle A1-D1-D4.
752 if (file_of(squares[0]) > FILE_D)
753 for (int i = 0; i < size; ++i)
754 squares[i] = flip_file(squares[i]);
756 // Encode leading pawns starting with the one with minimum MapPawns[] and
757 // proceeding in ascending order.
758 if (entry->hasPawns) {
759 idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
761 std::sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
763 for (int i = 1; i < leadPawnsCnt; ++i)
764 idx += Binomial[i][MapPawns[squares[i]]];
766 goto encode_remaining; // With pawns we have finished special treatments
769 // In positions withouth pawns, we further flip the squares to ensure leading
770 // piece is below RANK_5.
771 if (rank_of(squares[0]) > RANK_4)
772 for (int i = 0; i < size; ++i)
773 squares[i] = flip_rank(squares[i]);
775 // Look for the first piece of the leading group not on the A1-D4 diagonal
776 // and ensure it is mapped below the diagonal.
777 for (int i = 0; i < d->groupLen[0]; ++i) {
778 if (!off_A1H8(squares[i]))
781 if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C1
782 for (int j = i; j < size; ++j)
783 squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
787 // Encode the leading group.
789 // Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
790 // and bK (each 0...63). The simplest way to map this position to an index
793 // index = wK * 64 * 64 + wR * 64 + bK;
795 // But this way the TB is going to have 64*64*64 = 262144 positions, with
796 // lots of positions being equivalent (because they are mirrors of each
797 // other) and lots of positions being invalid (two pieces on one square,
798 // adjacent kings, etc.).
799 // Usually the first step is to take the wK and bK together. There are just
800 // 462 ways legal and not-mirrored ways to place the wK and bK on the board.
801 // Once we have placed the wK and bK, there are 62 squares left for the wR
802 // Mapping its square from 0..63 to available squares 0..61 can be done like:
804 // wR -= (wR > wK) + (wR > bK);
806 // In words: if wR "comes later" than wK, we deduct 1, and the same if wR
807 // "comes later" than bK. In case of two same pieces like KRRvK we want to
808 // place the two Rs "together". If we have 62 squares left, we can place two
809 // Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
810 // swapped and still get the same position.)
812 // In case we have at least 3 unique pieces (inlcuded kings) we encode them
814 if (entry->hasUniquePieces) {
816 int adjust1 = squares[1] > squares[0];
817 int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
819 // First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
820 // triangle to 0...5. There are 63 squares for second piece and and 62
821 // (mapped to 0...61) for the third.
822 if (off_A1H8(squares[0]))
823 idx = ( MapA1D1D4[squares[0]] * 63
824 + (squares[1] - adjust1)) * 62
825 + squares[2] - adjust2;
827 // First piece is on a1-h8 diagonal, second below: map this occurence to
828 // 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
829 // to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
830 else if (off_A1H8(squares[1]))
831 idx = ( 6 * 63 + rank_of(squares[0]) * 28
832 + MapB1H1H7[squares[1]]) * 62
833 + squares[2] - adjust2;
835 // First two pieces are on a1-h8 diagonal, third below
836 else if (off_A1H8(squares[2]))
837 idx = 6 * 63 * 62 + 4 * 28 * 62
838 + rank_of(squares[0]) * 7 * 28
839 + (rank_of(squares[1]) - adjust1) * 28
840 + MapB1H1H7[squares[2]];
842 // All 3 pieces on the diagonal a1-h8
844 idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28
845 + rank_of(squares[0]) * 7 * 6
846 + (rank_of(squares[1]) - adjust1) * 6
847 + (rank_of(squares[2]) - adjust2);
849 // We don't have at least 3 unique pieces, like in KRRvKBB, just map
851 idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
854 idx *= d->groupIdx[0];
855 Square* groupSq = squares + d->groupLen[0];
857 // Encode remainig pawns then pieces according to square, in ascending order
858 bool remainingPawns = entry->hasPawns && entry->pawnCount[1];
860 while (d->groupLen[++next])
862 std::sort(groupSq, groupSq + d->groupLen[next]);
865 // Map down a square if "comes later" than a square in the previous
866 // groups (similar to what done earlier for leading group pieces).
867 for (int i = 0; i < d->groupLen[next]; ++i)
869 auto f = [&](Square s) { return groupSq[i] > s; };
870 auto adjust = std::count_if(squares, groupSq, f);
871 n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
874 remainingPawns = false;
875 idx += n * d->groupIdx[next];
876 groupSq += d->groupLen[next];
879 // Now that we have the index, decompress the pair and get the score
880 return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
883 // Group together pieces that will be encoded together. The general rule is that
884 // a group contains pieces of same type and color. The exception is the leading
885 // group that, in case of positions withouth pawns, can be formed by 3 different
886 // pieces (default) or by the king pair when there is not a unique piece apart
887 // from the kings. When there are pawns, pawns are always first in pieces[].
889 // As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
891 // The actual grouping depends on the TB generator and can be inferred from the
892 // sequence of pieces in piece[] array.
894 void set_groups(T& e, PairsData* d, int order[], File f) {
896 int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
899 // Number of pieces per group is stored in groupLen[], for instance in KRKN
900 // the encoder will default on '111', so groupLen[] will be (3, 1).
901 for (int i = 1; i < e.pieceCount; ++i)
902 if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
905 d->groupLen[++n] = 1;
907 d->groupLen[++n] = 0; // Zero-terminated
909 // The sequence in pieces[] defines the groups, but not the order in which
910 // they are encoded. If the pieces in a group g can be combined on the board
911 // in N(g) different ways, then the position encoding will be of the form:
913 // g1 * N(g2) * N(g3) + g2 * N(g3) + g3
915 // This ensures unique encoding for the whole position. The order of the
916 // groups is a per-table parameter and could not follow the canonical leading
917 // pawns/pieces -> remainig pawns -> remaining pieces. In particular the
918 // first group is at order[0] position and the remaining pawns, when present,
919 // are at order[1] position.
920 bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
921 int next = pp ? 2 : 1;
922 int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
925 for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
926 if (k == order[0]) // Leading pawns or pieces
928 d->groupIdx[0] = idx;
929 idx *= e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f]
930 : e.hasUniquePieces ? 31332 : 462;
932 else if (k == order[1]) // Remaining pawns
934 d->groupIdx[1] = idx;
935 idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
937 else // Remainig pieces
939 d->groupIdx[next] = idx;
940 idx *= Binomial[d->groupLen[next]][freeSquares];
941 freeSquares -= d->groupLen[next++];
944 d->groupIdx[n] = idx;
947 // In Recursive Pairing each symbol represents a pair of childern symbols. So
948 // read d->btree[] symbols data and expand each one in his left and right child
949 // symbol until reaching the leafs that represent the symbol value.
950 uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
952 visited[s] = true; // We can set it now because tree is acyclic
953 Sym sr = d->btree[s].get<LR::Right>();
958 Sym sl = d->btree[s].get<LR::Left>();
961 d->symlen[sl] = set_symlen(d, sl, visited);
964 d->symlen[sr] = set_symlen(d, sr, visited);
966 return d->symlen[sl] + d->symlen[sr] + 1;
969 uint8_t* set_sizes(PairsData* d, uint8_t* data) {
973 if (d->flags & TBFlag::SingleValue) {
974 d->blocksNum = d->blockLengthSize = 0;
975 d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
976 d->minSymLen = *data++; // Here we store the single value
980 // groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
981 // element stores the biggest index that is the tb size.
982 uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
984 d->sizeofBlock = 1ULL << *data++;
985 d->span = 1ULL << *data++;
986 d->sparseIndexSize = size_t((tbSize + d->span - 1) / d->span); // Round up
987 auto padding = number<uint8_t, LittleEndian>(data++);
988 d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t);
989 d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
990 // does not point out of range.
991 d->maxSymLen = *data++;
992 d->minSymLen = *data++;
993 d->lowestSym = (Sym*)data;
994 d->base64.resize(d->maxSymLen - d->minSymLen + 1);
996 // The canonical code is ordered such that longer symbols (in terms of
997 // the number of bits of their Huffman code) have lower numeric value,
998 // so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
999 // Starting from this we compute a base64[] table indexed by symbol length
1000 // and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
1001 // See http://www.eecs.harvard.edu/~michaelm/E210/huffman.pdf
1002 for (int i = d->base64.size() - 2; i >= 0; --i) {
1003 d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
1004 - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2;
1006 assert(d->base64[i] * 2 >= d->base64[i+1]);
1009 // Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
1010 // than d->base64[i+1] and given the above assert condition, we ensure that
1011 // d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
1012 // and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
1013 for (size_t i = 0; i < d->base64.size(); ++i)
1014 d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
1016 data += d->base64.size() * sizeof(Sym);
1017 d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t);
1018 d->btree = (LR*)data;
1020 // The compression scheme used is "Recursive Pairing", that replaces the most
1021 // frequent adjacent pair of symbols in the source message by a new symbol,
1022 // reevaluating the frequencies of all of the symbol pairs with respect to
1023 // the extended alphabet, and then repeating the process.
1024 // See http://www.larsson.dogma.net/dcc99.pdf
1025 std::vector<bool> visited(d->symlen.size());
1027 for (Sym sym = 0; sym < d->symlen.size(); ++sym)
1029 d->symlen[sym] = set_symlen(d, sym, visited);
1031 return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
1034 uint8_t* set_dtz_map(TBTable<WDL>&, uint8_t* data, File) { return data; }
1036 uint8_t* set_dtz_map(TBTable<DTZ>& e, uint8_t* data, File maxFile) {
1040 for (File f = FILE_A; f <= maxFile; ++f) {
1041 auto flags = e.get(0, f)->flags;
1042 if (flags & TBFlag::Mapped) {
1043 if (flags & TBFlag::Wide) {
1044 data += (uintptr_t)data & 1; // Word alignment, we may have a mixed table
1045 for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x
1046 e.get(0, f)->map_idx[i] = (uint16_t)((uint16_t *)data - (uint16_t *)e.map + 1);
1047 data += 2 * number<uint16_t, LittleEndian>(data) + 2;
1051 for (int i = 0; i < 4; ++i) {
1052 e.get(0, f)->map_idx[i] = (uint16_t)(data - e.map + 1);
1059 return data += (uintptr_t)data & 1; // Word alignment
1062 // Populate entry's PairsData records with data from the just memory mapped file.
1063 // Called at first access.
1064 template<typename T>
1065 void set(T& e, uint8_t* data) {
1069 enum { Split = 1, HasPawns = 2 };
1071 assert(e.hasPawns == bool(*data & HasPawns));
1072 assert((e.key != e.key2) == bool(*data & Split));
1074 data++; // First byte stores flags
1076 const int sides = T::Sides == 2 && (e.key != e.key2) ? 2 : 1;
1077 const File maxFile = e.hasPawns ? FILE_D : FILE_A;
1079 bool pp = e.hasPawns && e.pawnCount[1]; // Pawns on both sides
1081 assert(!pp || e.pawnCount[0]);
1083 for (File f = FILE_A; f <= maxFile; ++f) {
1085 for (int i = 0; i < sides; i++)
1086 *e.get(i, f) = PairsData();
1088 int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF },
1089 { *data >> 4, pp ? *(data + 1) >> 4 : 0xF } };
1092 for (int k = 0; k < e.pieceCount; ++k, ++data)
1093 for (int i = 0; i < sides; i++)
1094 e.get(i, f)->pieces[k] = Piece(i ? *data >> 4 : *data & 0xF);
1096 for (int i = 0; i < sides; ++i)
1097 set_groups(e, e.get(i, f), order[i], f);
1100 data += (uintptr_t)data & 1; // Word alignment
1102 for (File f = FILE_A; f <= maxFile; ++f)
1103 for (int i = 0; i < sides; i++)
1104 data = set_sizes(e.get(i, f), data);
1106 data = set_dtz_map(e, data, maxFile);
1108 for (File f = FILE_A; f <= maxFile; ++f)
1109 for (int i = 0; i < sides; i++) {
1110 (d = e.get(i, f))->sparseIndex = (SparseEntry*)data;
1111 data += d->sparseIndexSize * sizeof(SparseEntry);
1114 for (File f = FILE_A; f <= maxFile; ++f)
1115 for (int i = 0; i < sides; i++) {
1116 (d = e.get(i, f))->blockLength = (uint16_t*)data;
1117 data += d->blockLengthSize * sizeof(uint16_t);
1120 for (File f = FILE_A; f <= maxFile; ++f)
1121 for (int i = 0; i < sides; i++) {
1122 data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment
1123 (d = e.get(i, f))->data = data;
1124 data += d->blocksNum * d->sizeofBlock;
1128 // If the TB file corresponding to the given position is already memory mapped
1129 // then return its base address, otherwise try to memory map and init it. Called
1130 // at every probe, memory map and init only at first access. Function is thread
1131 // safe and can be called concurrently.
1132 template<TBType Type>
1133 void* mapped(TBTable<Type>& e, const Position& pos) {
1135 static std::mutex mutex;
1137 // Use 'acquire' to avoid a thread reading 'ready' == true while
1138 // another is still working. (compiler reordering may cause this).
1139 if (e.ready.load(std::memory_order_acquire))
1140 return e.baseAddress; // Could be nullptr if file does not exist
1142 std::unique_lock<std::mutex> lk(mutex);
1144 if (e.ready.load(std::memory_order_relaxed)) // Recheck under lock
1145 return e.baseAddress;
1147 // Pieces strings in decreasing order for each color, like ("KPP","KR")
1148 std::string fname, w, b;
1149 for (PieceType pt = KING; pt >= PAWN; --pt) {
1150 w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]);
1151 b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]);
1154 fname = (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w)
1155 + (Type == WDL ? ".rtbw" : ".rtbz");
1157 uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, Type);
1162 e.ready.store(true, std::memory_order_release);
1163 return e.baseAddress;
1166 template<TBType Type, typename Ret = typename TBTable<Type>::Ret>
1167 Ret probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
1169 if (pos.count<ALL_PIECES>() == 2) // KvK
1170 return Ret(WDLDraw);
1172 TBTable<Type>* entry = TBTables.get<Type>(pos.material_key());
1174 if (!entry || !mapped(*entry, pos))
1175 return *result = FAIL, Ret();
1177 return do_probe_table(pos, entry, wdl, result);
1180 // For a position where the side to move has a winning capture it is not necessary
1181 // to store a winning value so the generator treats such positions as "don't cares"
1182 // and tries to assign to it a value that improves the compression ratio. Similarly,
1183 // if the side to move has a drawing capture, then the position is at least drawn.
1184 // If the position is won, then the TB needs to store a win value. But if the
1185 // position is drawn, the TB may store a loss value if that is better for compression.
1186 // All of this means that during probing, the engine must look at captures and probe
1187 // their results and must probe the position itself. The "best" result of these
1188 // probes is the correct result for the position.
1189 // DTZ tables do not store values when a following move is a zeroing winning move
1190 // (winning capture or winning pawn move). Also DTZ store wrong values for positions
1191 // where the best move is an ep-move (even if losing). So in all these cases set
1192 // the state to ZEROING_BEST_MOVE.
1193 template<bool CheckZeroingMoves>
1194 WDLScore search(Position& pos, ProbeState* result) {
1196 WDLScore value, bestValue = WDLLoss;
1199 auto moveList = MoveList<LEGAL>(pos);
1200 size_t totalCount = moveList.size(), moveCount = 0;
1202 for (const Move move : moveList)
1204 if ( !pos.capture(move)
1205 && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
1210 pos.do_move(move, st);
1211 value = -search<false>(pos, result);
1212 pos.undo_move(move);
1214 if (*result == FAIL)
1217 if (value > bestValue)
1221 if (value >= WDLWin)
1223 *result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
1229 // In case we have already searched all the legal moves we don't have to probe
1230 // the TB because the stored score could be wrong. For instance TB tables
1231 // do not contain information on position with ep rights, so in this case
1232 // the result of probe_wdl_table is wrong. Also in case of only capture
1233 // moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
1234 // return with ZEROING_BEST_MOVE set.
1235 bool noMoreMoves = (moveCount && moveCount == totalCount);
1241 value = probe_table<WDL>(pos, result);
1243 if (*result == FAIL)
1247 // DTZ stores a "don't care" value if bestValue is a win
1248 if (bestValue >= value)
1249 return *result = ( bestValue > WDLDraw
1250 || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
1252 return *result = OK, value;
1258 /// Tablebases::init() is called at startup and after every change to
1259 /// "SyzygyPath" UCI option to (re)create the various tables. It is not thread
1260 /// safe, nor it needs to be.
1261 void Tablebases::init(const std::string& paths) {
1265 TBFile::Paths = paths;
1267 if (paths.empty() || paths == "<empty>")
1270 // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
1272 for (Square s = SQ_A1; s <= SQ_H8; ++s)
1273 if (off_A1H8(s) < 0)
1274 MapB1H1H7[s] = code++;
1276 // MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
1277 std::vector<Square> diagonal;
1279 for (Square s = SQ_A1; s <= SQ_D4; ++s)
1280 if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
1281 MapA1D1D4[s] = code++;
1283 else if (!off_A1H8(s) && file_of(s) <= FILE_D)
1284 diagonal.push_back(s);
1286 // Diagonal squares are encoded as last ones
1287 for (auto s : diagonal)
1288 MapA1D1D4[s] = code++;
1290 // MapKK[] encodes all the 461 possible legal positions of two kings where
1291 // the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
1292 // diagonal, the other one shall not to be above the a1-h8 diagonal.
1293 std::vector<std::pair<int, Square>> bothOnDiagonal;
1295 for (int idx = 0; idx < 10; idx++)
1296 for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
1297 if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
1299 for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
1300 if ((PseudoAttacks[KING][s1] | s1) & s2)
1301 continue; // Illegal position
1303 else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
1304 continue; // First on diagonal, second above
1306 else if (!off_A1H8(s1) && !off_A1H8(s2))
1307 bothOnDiagonal.emplace_back(idx, s2);
1310 MapKK[idx][s2] = code++;
1313 // Legal positions with both kings on diagonal are encoded as last ones
1314 for (auto p : bothOnDiagonal)
1315 MapKK[p.first][p.second] = code++;
1317 // Binomial[] stores the Binomial Coefficents using Pascal rule. There
1318 // are Binomial[k][n] ways to choose k elements from a set of n elements.
1321 for (int n = 1; n < 64; n++) // Squares
1322 for (int k = 0; k < 6 && k <= n; ++k) // Pieces
1323 Binomial[k][n] = (k > 0 ? Binomial[k - 1][n - 1] : 0)
1324 + (k < n ? Binomial[k ][n - 1] : 0);
1326 // MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
1327 // available squares when the leading one is in 's'. Moreover the pawn with
1328 // highest MapPawns[] is the leading pawn, the one nearest the edge and,
1329 // among pawns with same file, the one with lowest rank.
1330 int availableSquares = 47; // Available squares when lead pawn is in a2
1332 // Init the tables for the encoding of leading pawns group: with 7-men TB we
1333 // can have up to 5 leading pawns (KPPPPPK).
1334 for (int leadPawnsCnt = 1; leadPawnsCnt <= 5; ++leadPawnsCnt)
1335 for (File f = FILE_A; f <= FILE_D; ++f)
1337 // Restart the index at every file because TB table is splitted
1338 // by file, so we can reuse the same index for different files.
1341 // Sum all possible combinations for a given file, starting with
1342 // the leading pawn on rank 2 and increasing the rank.
1343 for (Rank r = RANK_2; r <= RANK_7; ++r)
1345 Square sq = make_square(f, r);
1347 // Compute MapPawns[] at first pass.
1348 // If sq is the leading pawn square, any other pawn cannot be
1349 // below or more toward the edge of sq. There are 47 available
1350 // squares when sq = a2 and reduced by 2 for any rank increase
1351 // due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
1352 if (leadPawnsCnt == 1)
1354 MapPawns[sq] = availableSquares--;
1355 MapPawns[flip_file(sq)] = availableSquares--;
1357 LeadPawnIdx[leadPawnsCnt][sq] = idx;
1358 idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
1360 // After a file is traversed, store the cumulated per-file index
1361 LeadPawnsSize[leadPawnsCnt][f] = idx;
1364 // Add entries in TB tables if the corresponding ".rtbw" file exists
1365 for (PieceType p1 = PAWN; p1 < KING; ++p1) {
1366 TBTables.add({KING, p1, KING});
1368 for (PieceType p2 = PAWN; p2 <= p1; ++p2) {
1369 TBTables.add({KING, p1, p2, KING});
1370 TBTables.add({KING, p1, KING, p2});
1372 for (PieceType p3 = PAWN; p3 < KING; ++p3)
1373 TBTables.add({KING, p1, p2, KING, p3});
1375 for (PieceType p3 = PAWN; p3 <= p2; ++p3) {
1376 TBTables.add({KING, p1, p2, p3, KING});
1378 for (PieceType p4 = PAWN; p4 <= p3; ++p4) {
1379 TBTables.add({KING, p1, p2, p3, p4, KING});
1381 for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1382 TBTables.add({KING, p1, p2, p3, p4, p5, KING});
1384 for (PieceType p5 = PAWN; p5 < KING; ++p5)
1385 TBTables.add({KING, p1, p2, p3, p4, KING, p5});
1388 for (PieceType p4 = PAWN; p4 < KING; ++p4) {
1389 TBTables.add({KING, p1, p2, p3, KING, p4});
1391 for (PieceType p5 = PAWN; p5 <= p4; ++p5)
1392 TBTables.add({KING, p1, p2, p3, KING, p4, p5});
1396 for (PieceType p3 = PAWN; p3 <= p1; ++p3)
1397 for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
1398 TBTables.add({KING, p1, p2, KING, p3, p4});
1402 sync_cout << "info string Found " << TBTables.size() << " tablebases" << sync_endl;
1405 // Probe the WDL table for a particular position.
1406 // If *result != FAIL, the probe was successful.
1407 // The return value is from the point of view of the side to move:
1409 // -1 : loss, but draw under 50-move rule
1411 // 1 : win, but draw under 50-move rule
1413 WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
1416 return search<false>(pos, result);
1419 // Probe the DTZ table for a particular position.
1420 // If *result != FAIL, the probe was successful.
1421 // The return value is from the point of view of the side to move:
1422 // n < -100 : loss, but draw under 50-move rule
1423 // -100 <= n < -1 : loss in n ply (assuming 50-move counter == 0)
1424 // -1 : loss, the side to move is mated
1426 // 1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1427 // 100 < n : win, but draw under 50-move rule
1429 // The return value n can be off by 1: a return value -n can mean a loss
1430 // in n+1 ply and a return value +n can mean a win in n+1 ply. This
1431 // cannot happen for tables with positions exactly on the "edge" of
1432 // the 50-move rule.
1434 // This implies that if dtz > 0 is returned, the position is certainly
1435 // a win if dtz + 50-move-counter <= 99. Care must be taken that the engine
1436 // picks moves that preserve dtz + 50-move-counter <= 99.
1438 // If n = 100 immediately after a capture or pawn move, then the position
1439 // is also certainly a win, and during the whole phase until the next
1440 // capture or pawn move, the inequality to be preserved is
1441 // dtz + 50-movecounter <= 100.
1443 // In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1444 // then do not accept moves leading to dtz + 50-move-counter == 100.
1445 int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
1448 WDLScore wdl = search<true>(pos, result);
1450 if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
1453 // DTZ stores a 'don't care' value in this case, or even a plain wrong
1454 // one as in case the best move is a losing ep, so it cannot be probed.
1455 if (*result == ZEROING_BEST_MOVE)
1456 return dtz_before_zeroing(wdl);
1458 int dtz = probe_table<DTZ>(pos, result, wdl);
1460 if (*result == FAIL)
1463 if (*result != CHANGE_STM)
1464 return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
1466 // DTZ stores results for the other side, so we need to do a 1-ply search and
1467 // find the winning move that minimizes DTZ.
1469 int minDTZ = 0xFFFF;
1471 for (const Move move : MoveList<LEGAL>(pos))
1473 bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
1475 pos.do_move(move, st);
1477 // For zeroing moves we want the dtz of the move _before_ doing it,
1478 // otherwise we will get the dtz of the next move sequence. Search the
1479 // position after the move to get the score sign (because even in a
1480 // winning position we could make a losing capture or going for a draw).
1481 dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result))
1482 : -probe_dtz(pos, result);
1484 // If the move mates, force minDTZ to 1
1485 if (dtz == 1 && pos.checkers() && MoveList<LEGAL>(pos).size() == 0)
1488 // Convert result from 1-ply search. Zeroing moves are already accounted
1489 // by dtz_before_zeroing() that returns the DTZ of the previous move.
1491 dtz += sign_of(dtz);
1493 // Skip the draws and if we are winning only pick positive dtz
1494 if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
1497 pos.undo_move(move);
1499 if (*result == FAIL)
1503 // When there are no legal moves, the position is mate: we return -1
1504 return minDTZ == 0xFFFF ? -1 : minDTZ;
1508 // Use the DTZ tables to rank root moves.
1510 // A return value false indicates that not all probes were successful.
1511 bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves) {
1516 // Obtain 50-move counter for the root position
1517 int cnt50 = pos.rule50_count();
1519 // Check whether a position was repeated since the last zeroing move.
1520 bool rep = pos.has_repeated();
1522 int dtz, bound = Options["Syzygy50MoveRule"] ? 900 : 1;
1524 // Probe and rank each move
1525 for (auto& m : rootMoves)
1527 pos.do_move(m.pv[0], st);
1529 // Calculate dtz for the current move counting from the root position
1530 if (pos.rule50_count() == 0)
1532 // In case of a zeroing move, dtz is one of -101/-1/0/1/101
1533 WDLScore wdl = -probe_wdl(pos, &result);
1534 dtz = dtz_before_zeroing(wdl);
1538 // Otherwise, take dtz for the new position and correct by 1 ply
1539 dtz = -probe_dtz(pos, &result);
1540 dtz = dtz > 0 ? dtz + 1
1541 : dtz < 0 ? dtz - 1 : dtz;
1544 // Make sure that a mating move is assigned a dtz value of 1
1547 && MoveList<LEGAL>(pos).size() == 0)
1550 pos.undo_move(m.pv[0]);
1555 // Better moves are ranked higher. Certain wins are ranked equally.
1556 // Losing moves are ranked equally unless a 50-move draw is in sight.
1557 int r = dtz > 0 ? (dtz + cnt50 <= 99 && !rep ? 1000 : 1000 - (dtz + cnt50))
1558 : dtz < 0 ? (-dtz * 2 + cnt50 < 100 ? -1000 : -1000 + (-dtz + cnt50))
1562 // Determine the score to be displayed for this move. Assign at least
1563 // 1 cp to cursed wins and let it grow to 49 cp as the positions gets
1564 // closer to a real win.
1565 m.tbScore = r >= bound ? VALUE_MATE - MAX_PLY - 1
1566 : r > 0 ? Value((std::max( 3, r - 800) * int(PawnValueEg)) / 200)
1567 : r == 0 ? VALUE_DRAW
1568 : r > -bound ? Value((std::min(-3, r + 800) * int(PawnValueEg)) / 200)
1569 : -VALUE_MATE + MAX_PLY + 1;
1576 // Use the WDL tables to rank root moves.
1577 // This is a fallback for the case that some or all DTZ tables are missing.
1579 // A return value false indicates that not all probes were successful.
1580 bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves) {
1582 static const int WDL_to_rank[] = { -1000, -899, 0, 899, 1000 };
1587 bool rule50 = Options["Syzygy50MoveRule"];
1589 // Probe and rank each move
1590 for (auto& m : rootMoves)
1592 pos.do_move(m.pv[0], st);
1594 WDLScore wdl = -probe_wdl(pos, &result);
1596 pos.undo_move(m.pv[0]);
1601 m.tbRank = WDL_to_rank[wdl + 2];
1604 wdl = wdl > WDLDraw ? WDLWin
1605 : wdl < WDLDraw ? WDLLoss : WDLDraw;
1606 m.tbScore = WDL_to_value[wdl + 2];