2 Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3 Copyright (c) 2013 Ronald de Man
4 Copyright (C) 2016-2017 Marco Costalba, Lucas Braesch
6 Stockfish is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or
9 (at your option) any later version.
11 Stockfish is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <cstring> // For std::memset
29 #include <type_traits>
31 #include "../bitboard.h"
32 #include "../movegen.h"
33 #include "../position.h"
34 #include "../search.h"
35 #include "../thread_win32.h"
46 #define WIN32_LEAN_AND_MEAN
51 using namespace Tablebases;
53 int Tablebases::MaxCardinality;
57 // 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 };
60 inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); }
61 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); }
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;
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));
79 // Numbers in little endian used by sparseIndex[] to point into blockLength[]
81 char block[4]; // Number of block
82 char offset[2]; // Offset within the block
85 static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes");
87 typedef uint16_t Sym; // Huffman symbol
90 enum Side { Left, Right, Value };
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.
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));
103 static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes");
105 const int TBPIECES = 6;
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)
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.
132 Atomic(const Atomic& e) { ready = e.ready.load(); } // MSVC 2013 wants assignment within body
133 std::atomic_bool ready;
136 // We define types for the different parts of the WLDEntry and DTZEntry with
137 // corresponding specializations for pieces or pawns.
139 struct WLDEntryPiece {
143 struct WDLEntryPawn {
144 uint8_t pawnCount[2]; // [Lead color / other color]
145 WLDEntryPiece file[2][4]; // [wtm / btm][FILE_A..FILE_D]
148 struct DTZEntryPiece {
150 uint16_t map_idx[4]; // WDLWin, WDLLoss, WDLCursedWin, WDLBlessedLoss
154 struct DTZEntryPawn {
155 uint8_t pawnCount[2];
156 DTZEntryPiece file[4];
160 struct TBEntry : public Atomic {
167 bool hasUniquePieces;
170 // Now the main types: WDLEntry and DTZEntry
171 struct WDLEntry : public TBEntry {
172 WDLEntry(const std::string& code);
175 WLDEntryPiece pieceTable[2]; // [wtm / btm]
176 WDLEntryPawn pawnTable;
180 struct DTZEntry : public TBEntry {
181 DTZEntry(const WDLEntry& wdl);
184 DTZEntryPiece pieceTable;
185 DTZEntryPawn pawnTable;
189 typedef decltype(WDLEntry::pieceTable) WDLPieceTable;
190 typedef decltype(DTZEntry::pieceTable) DTZPieceTable;
191 typedef decltype(WDLEntry::pawnTable ) WDLPawnTable;
192 typedef decltype(DTZEntry::pawnTable ) DTZPawnTable;
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]; }
199 template<typename E> struct Ret { typedef int type; };
200 template<> struct Ret<WDLEntry> { typedef WDLScore type; };
202 int MapPawns[SQUARE_NB];
203 int MapB1H1H7[SQUARE_NB];
204 int MapA1D1D4[SQUARE_NB];
205 int MapKK[10][SQUARE_NB]; // [MapA1D1D4][SQUARE_NB]
207 // Comparison function to sort leading pawns in ascending MapPawns[] order
208 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); }
211 const Value WDL_to_value[] = {
212 -VALUE_MATE + MAX_PLY + 1,
216 VALUE_MATE - MAX_PLY - 1
219 const std::string PieceToChar = " PNBRQK pnbrqk";
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]
225 enum { BigEndian, LittleEndian };
227 template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1>
228 inline void swap_byte(T& x)
230 char tmp, *c = (char*)&x;
231 for (int i = 0; i < Half; ++i)
232 tmp = c[i], c[i] = c[End - i], c[End - i] = tmp;
234 template<> inline void swap_byte<uint8_t, 0, 0>(uint8_t&) {}
236 template<typename T, int LE> T number(void* addr)
238 const union { uint32_t i; char c[4]; } Le = { 0x01020304 };
239 const bool IsLittleEndian = (Le.c[0] == 4);
243 if ((uintptr_t)addr & (alignof(T) - 1)) // Unaligned pointer (very rare)
244 std::memcpy(&v, addr, sizeof(T));
248 if (LE != IsLittleEndian)
255 typedef std::pair<WDLEntry*, DTZEntry*> EntryPair;
256 typedef std::pair<Key, EntryPair> Entry;
258 static const int TBHASHBITS = 10;
259 static const int HSHMAX = 5;
261 Entry hashTable[1 << TBHASHBITS][HSHMAX];
263 std::deque<WDLEntry> wdlTable;
264 std::deque<DTZEntry> dtzTable;
266 void insert(Key key, WDLEntry* wdl, DTZEntry* dtz) {
267 Entry* entry = hashTable[key >> (64 - TBHASHBITS)];
269 for (int i = 0; i < HSHMAX; ++i, ++entry)
270 if (!entry->second.first || entry->first == key) {
271 *entry = std::make_pair(key, std::make_pair(wdl, dtz));
275 std::cerr << "HSHMAX too low!" << std::endl;
280 template<typename E, int I = std::is_same<E, WDLEntry>::value ? 0 : 1>
282 Entry* entry = hashTable[key >> (64 - TBHASHBITS)];
284 for (int i = 0; i < HSHMAX; ++i, ++entry)
285 if (entry->first == key)
286 return std::get<I>(entry->second);
292 std::memset(hashTable, 0, sizeof(hashTable));
296 size_t size() const { return wdlTable.size(); }
297 void insert(const std::vector<PieceType>& pieces);
300 HashTable EntryTable;
302 class TBFile : public std::ifstream {
307 // Look for and open the file among the Paths directories where the .rtbw
308 // and .rtbz files can be found. Multiple directories are separated by ";"
309 // on Windows and by ":" on Unix-based operating systems.
312 // C:\tb\wdl345;C:\tb\wdl6;D:\tb\dtz345;D:\tb\dtz6
313 static std::string Paths;
315 TBFile(const std::string& f) {
318 const char SepChar = ':';
320 const char SepChar = ';';
322 std::stringstream ss(Paths);
325 while (std::getline(ss, path, SepChar)) {
326 fname = path + "/" + f;
327 std::ifstream::open(fname);
333 // Memory map the file and check it. File should be already open and will be
334 // closed after mapping.
335 uint8_t* map(void** baseAddress, uint64_t* mapping, const uint8_t* TB_MAGIC) {
339 close(); // Need to re-open to get native file descriptor
343 int fd = ::open(fname.c_str(), O_RDONLY);
345 *mapping = statbuf.st_size;
346 *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0);
349 if (*baseAddress == MAP_FAILED) {
350 std::cerr << "Could not mmap() " << fname << std::endl;
354 HANDLE fd = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
355 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
357 DWORD size_low = GetFileSize(fd, &size_high);
358 HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr);
362 std::cerr << "CreateFileMapping() failed" << std::endl;
366 *mapping = (uint64_t)mmap;
367 *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0);
370 std::cerr << "MapViewOfFile() failed, name = " << fname
371 << ", error = " << GetLastError() << std::endl;
375 uint8_t* data = (uint8_t*)*baseAddress;
377 if ( *data++ != *TB_MAGIC++
378 || *data++ != *TB_MAGIC++
379 || *data++ != *TB_MAGIC++
380 || *data++ != *TB_MAGIC) {
381 std::cerr << "Corrupted table in file " << fname << std::endl;
382 unmap(*baseAddress, *mapping);
383 *baseAddress = nullptr;
390 static void unmap(void* baseAddress, uint64_t mapping) {
393 munmap(baseAddress, mapping);
395 UnmapViewOfFile(baseAddress);
396 CloseHandle((HANDLE)mapping);
401 std::string TBFile::Paths;
403 WDLEntry::WDLEntry(const std::string& code) {
408 memset(this, 0, sizeof(WDLEntry));
411 key = pos.set(code, WHITE, &st).material_key();
412 pieceCount = popcount(pos.pieces());
413 hasPawns = pos.pieces(PAWN);
415 for (Color c = WHITE; c <= BLACK; ++c)
416 for (PieceType pt = PAWN; pt < KING; ++pt)
417 if (popcount(pos.pieces(c, pt)) == 1)
418 hasUniquePieces = true;
421 // Set the leading color. In case both sides have pawns the leading color
422 // is the side with less pawns because this leads to better compression.
423 bool c = !pos.count<PAWN>(BLACK)
424 || ( pos.count<PAWN>(WHITE)
425 && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE));
427 pawnTable.pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK);
428 pawnTable.pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE);
431 key2 = pos.set(code, BLACK, &st).material_key();
434 WDLEntry::~WDLEntry() {
437 TBFile::unmap(baseAddress, mapping);
439 for (int i = 0; i < 2; ++i)
441 for (File f = FILE_A; f <= FILE_D; ++f)
442 delete pawnTable.file[i][f].precomp;
444 delete pieceTable[i].precomp;
447 DTZEntry::DTZEntry(const WDLEntry& wdl) {
449 memset(this, 0, sizeof(DTZEntry));
454 pieceCount = wdl.pieceCount;
455 hasPawns = wdl.hasPawns;
456 hasUniquePieces = wdl.hasUniquePieces;
459 pawnTable.pawnCount[0] = wdl.pawnTable.pawnCount[0];
460 pawnTable.pawnCount[1] = wdl.pawnTable.pawnCount[1];
464 DTZEntry::~DTZEntry() {
467 TBFile::unmap(baseAddress, mapping);
470 for (File f = FILE_A; f <= FILE_D; ++f)
471 delete pawnTable.file[f].precomp;
473 delete pieceTable.precomp;
476 void HashTable::insert(const std::vector<PieceType>& pieces) {
480 for (PieceType pt : pieces)
481 code += PieceToChar[pt];
483 TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); // KRK -> KRvK
490 MaxCardinality = std::max((int)pieces.size(), MaxCardinality);
492 wdlTable.push_back(WDLEntry(code));
493 dtzTable.push_back(DTZEntry(wdlTable.back()));
495 insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back());
496 insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back());
499 // TB tables are compressed with canonical Huffman code. The compressed data is divided into
500 // blocks of size d->sizeofBlock, and each block stores a variable number of symbols.
501 // Each symbol represents either a WDL or a (remapped) DTZ value, or a pair of other symbols
502 // (recursively). If you keep expanding the symbols in a block, you end up with up to 65536
503 // WDL or DTZ values. Each symbol represents up to 256 values and will correspond after
504 // Huffman coding to at least 1 bit. So a block of 32 bytes corresponds to at most
505 // 32 x 8 x 256 = 65536 values. This maximum is only reached for tables that consist mostly
506 // of draws or mostly of wins, but such tables are actually quite common. In principle, the
507 // blocks in WDL tables are 64 bytes long (and will be aligned on cache lines). But for
508 // mostly-draw or mostly-win tables this can leave many 64-byte blocks only half-filled, so
509 // in such cases blocks are 32 bytes long. The blocks of DTZ tables are up to 1024 bytes long.
510 // The generator picks the size that leads to the smallest table. The "book" of symbols and
511 // Huffman codes is the same for all blocks in the table. A non-symmetric pawnless TB file
512 // will have one table for wtm and one for btm, a TB file with pawns will have tables per
513 // file a,b,c,d also in this case one set for wtm and one for btm.
514 int decompress_pairs(PairsData* d, uint64_t idx) {
516 // Special case where all table positions store the same value
517 if (d->flags & TBFlag::SingleValue)
520 // First we need to locate the right block that stores the value at index "idx".
521 // Because each block n stores blockLength[n] + 1 values, the index i of the block
522 // that contains the value at position idx is:
524 // for (i = -1, sum = 0; sum <= idx; i++)
525 // sum += blockLength[i + 1] + 1;
527 // This can be slow, so we use SparseIndex[] populated with a set of SparseEntry that
528 // point to known indices into blockLength[]. Namely SparseIndex[k] is a SparseEntry
529 // that stores the blockLength[] index and the offset within that block of the value
530 // with index I(k), where:
532 // I(k) = k * d->span + d->span / 2 (1)
534 // First step is to get the 'k' of the I(k) nearest to our idx, using definition (1)
535 uint32_t k = idx / d->span;
537 // Then we read the corresponding SparseIndex[] entry
538 uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block);
539 int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset);
541 // Now compute the difference idx - I(k). From definition of k we know that
543 // idx = k * d->span + idx % d->span (2)
545 // So from (1) and (2) we can compute idx - I(K):
546 int diff = idx % d->span - d->span / 2;
548 // Sum the above to offset to find the offset corresponding to our idx
551 // Move to previous/next block, until we reach the correct block that contains idx,
552 // that is when 0 <= offset <= d->blockLength[block]
554 offset += d->blockLength[--block] + 1;
556 while (offset > d->blockLength[block])
557 offset -= d->blockLength[block++] + 1;
559 // Finally, we find the start address of our block of canonical Huffman symbols
560 uint32_t* ptr = (uint32_t*)(d->data + block * d->sizeofBlock);
562 // Read the first 64 bits in our block, this is a (truncated) sequence of
563 // unknown number of symbols of unknown length but we know the first one
564 // is at the beginning of this 64 bits sequence.
565 uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2;
570 int len = 0; // This is the symbol length - d->min_sym_len
572 // Now get the symbol length. For any symbol s64 of length l right-padded
573 // to 64 bits we know that d->base64[l-1] >= s64 >= d->base64[l] so we
574 // can find the symbol length iterating through base64[].
575 while (buf64 < d->base64[len])
578 // All the symbols of a given length are consecutive integers (numerical
579 // sequence property), so we can compute the offset of our symbol of
580 // length len, stored at the beginning of buf64.
581 sym = (buf64 - d->base64[len]) >> (64 - len - d->minSymLen);
583 // Now add the value of the lowest symbol of length len to get our symbol
584 sym += number<Sym, LittleEndian>(&d->lowestSym[len]);
586 // If our offset is within the number of values represented by symbol sym
588 if (offset < d->symlen[sym] + 1)
591 // ...otherwise update the offset and continue to iterate
592 offset -= d->symlen[sym] + 1;
593 len += d->minSymLen; // Get the real length
594 buf64 <<= len; // Consume the just processed symbol
597 if (buf64Size <= 32) { // Refill the buffer
599 buf64 |= (uint64_t)number<uint32_t, BigEndian>(ptr++) << (64 - buf64Size);
603 // Ok, now we have our symbol that expands into d->symlen[sym] + 1 symbols.
604 // We binary-search for our value recursively expanding into the left and
605 // right child symbols until we reach a leaf node where symlen[sym] + 1 == 1
606 // that will store the value we need.
607 while (d->symlen[sym]) {
609 Sym left = d->btree[sym].get<LR::Left>();
611 // If a symbol contains 36 sub-symbols (d->symlen[sym] + 1 = 36) and
612 // expands in a pair (d->symlen[left] = 23, d->symlen[right] = 11), then
613 // we know that, for instance the ten-th value (offset = 10) will be on
614 // the left side because in Recursive Pairing child symbols are adjacent.
615 if (offset < d->symlen[left] + 1)
618 offset -= d->symlen[left] + 1;
619 sym = d->btree[sym].get<LR::Right>();
623 return d->btree[sym].get<LR::Value>();
626 bool check_dtz_stm(WDLEntry*, int, File) { return true; }
628 bool check_dtz_stm(DTZEntry* entry, int stm, File f) {
630 int flags = entry->hasPawns ? entry->pawnTable.file[f].precomp->flags
631 : entry->pieceTable.precomp->flags;
633 return (flags & TBFlag::STM) == stm
634 || ((entry->key == entry->key2) && !entry->hasPawns);
637 // DTZ scores are sorted by frequency of occurrence and then assigned the
638 // values 0, 1, 2, ... in order of decreasing frequency. This is done for each
639 // of the four WDLScore values. The mapping information necessary to reconstruct
640 // the original values is stored in the TB file and read during map[] init.
641 WDLScore map_score(WDLEntry*, File, int value, WDLScore) { return WDLScore(value - 2); }
643 int map_score(DTZEntry* entry, File f, int value, WDLScore wdl) {
645 const int WDLMap[] = { 1, 3, 0, 2, 0 };
647 int flags = entry->hasPawns ? entry->pawnTable.file[f].precomp->flags
648 : entry->pieceTable.precomp->flags;
650 uint8_t* map = entry->hasPawns ? entry->pawnTable.map
651 : entry->pieceTable.map;
653 uint16_t* idx = entry->hasPawns ? entry->pawnTable.file[f].map_idx
654 : entry->pieceTable.map_idx;
655 if (flags & TBFlag::Mapped)
656 value = map[idx[WDLMap[wdl + 2]] + value];
658 // DTZ tables store distance to zero in number of moves or plies. We
659 // want to return plies, so we have convert to plies when needed.
660 if ( (wdl == WDLWin && !(flags & TBFlag::WinPlies))
661 || (wdl == WDLLoss && !(flags & TBFlag::LossPlies))
662 || wdl == WDLCursedWin
663 || wdl == WDLBlessedLoss)
669 // Compute a unique index out of a position and use it to probe the TB file. To
670 // encode k pieces of same type and color, first sort the pieces by square in
671 // ascending order s1 <= s2 <= ... <= sk then compute the unique index as:
673 // idx = Binomial[1][s1] + Binomial[2][s2] + ... + Binomial[k][sk]
675 template<typename Entry, typename T = typename Ret<Entry>::type>
676 T do_probe_table(const Position& pos, Entry* entry, WDLScore wdl, ProbeState* result) {
678 const bool IsWDL = std::is_same<Entry, WDLEntry>::value;
680 Square squares[TBPIECES];
681 Piece pieces[TBPIECES];
683 int next = 0, size = 0, leadPawnsCnt = 0;
685 Bitboard b, leadPawns = 0;
686 File tbFile = FILE_A;
688 // A given TB entry like KRK has associated two material keys: KRvk and Kvkr.
689 // If both sides have the same pieces keys are equal. In this case TB tables
690 // only store the 'white to move' case, so if the position to lookup has black
691 // to move, we need to switch the color and flip the squares before to lookup.
692 bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move());
694 // TB files are calculated for white as stronger side. For instance we have
695 // KRvK, not KvKR. A position where stronger side is white will have its
696 // material key == entry->key, otherwise we have to switch the color and
697 // flip the squares before to lookup.
698 bool blackStronger = (pos.material_key() != entry->key);
700 int flipColor = (symmetricBlackToMove || blackStronger) * 8;
701 int flipSquares = (symmetricBlackToMove || blackStronger) * 070;
702 int stm = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move();
704 // For pawns, TB files store 4 separate tables according if leading pawn is on
705 // file a, b, c or d after reordering. The leading pawn is the one with maximum
706 // MapPawns[] value, that is the one most toward the edges and with lowest rank.
707 if (entry->hasPawns) {
709 // In all the 4 tables, pawns are at the beginning of the piece sequence and
710 // their color is the reference one. So we just pick the first one.
711 Piece pc = Piece(item(entry->pawnTable, 0, 0).precomp->pieces[0] ^ flipColor);
713 assert(type_of(pc) == PAWN);
715 leadPawns = b = pos.pieces(color_of(pc), PAWN);
717 squares[size++] = pop_lsb(&b) ^ flipSquares;
722 std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp));
724 tbFile = file_of(squares[0]);
726 tbFile = file_of(squares[0] ^ 7); // Horizontal flip: SQ_H1 -> SQ_A1
728 d = item(entry->pawnTable , stm, tbFile).precomp;
730 d = item(entry->pieceTable, stm, tbFile).precomp;
732 // DTZ tables are one-sided, i.e. they store positions only for white to
733 // move or only for black to move, so check for side to move to be stm,
734 // early exit otherwise.
735 if (!IsWDL && !check_dtz_stm(entry, stm, tbFile))
736 return *result = CHANGE_STM, T();
738 // Now we are ready to get all the position pieces (but the lead pawns) and
739 // directly map them to the correct color and square.
740 b = pos.pieces() ^ leadPawns;
742 Square s = pop_lsb(&b);
743 squares[size] = s ^ flipSquares;
744 pieces[size++] = Piece(pos.piece_on(s) ^ flipColor);
749 // Then we reorder the pieces to have the same sequence as the one stored
750 // in precomp->pieces[i]: the sequence that ensures the best compression.
751 for (int i = leadPawnsCnt; i < size; ++i)
752 for (int j = i; j < size; ++j)
753 if (d->pieces[i] == pieces[j])
755 std::swap(pieces[i], pieces[j]);
756 std::swap(squares[i], squares[j]);
760 // Now we map again the squares so that the square of the lead piece is in
761 // the triangle A1-D1-D4.
762 if (file_of(squares[0]) > FILE_D)
763 for (int i = 0; i < size; ++i)
764 squares[i] ^= 7; // Horizontal flip: SQ_H1 -> SQ_A1
766 // Encode leading pawns starting with the one with minimum MapPawns[] and
767 // proceeding in ascending order.
768 if (entry->hasPawns) {
769 idx = LeadPawnIdx[leadPawnsCnt][squares[0]];
771 std::sort(squares + 1, squares + leadPawnsCnt, pawns_comp);
773 for (int i = 1; i < leadPawnsCnt; ++i)
774 idx += Binomial[i][MapPawns[squares[i]]];
776 goto encode_remaining; // With pawns we have finished special treatments
779 // In positions withouth pawns, we further flip the squares to ensure leading
780 // piece is below RANK_5.
781 if (rank_of(squares[0]) > RANK_4)
782 for (int i = 0; i < size; ++i)
783 squares[i] ^= 070; // Vertical flip: SQ_A8 -> SQ_A1
785 // Look for the first piece of the leading group not on the A1-D4 diagonal
786 // and ensure it is mapped below the diagonal.
787 for (int i = 0; i < d->groupLen[0]; ++i) {
788 if (!off_A1H8(squares[i]))
791 if (off_A1H8(squares[i]) > 0) // A1-H8 diagonal flip: SQ_A3 -> SQ_C3
792 for (int j = i; j < size; ++j)
793 squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63);
797 // Encode the leading group.
799 // Suppose we have KRvK. Let's say the pieces are on square numbers wK, wR
800 // and bK (each 0...63). The simplest way to map this position to an index
803 // index = wK * 64 * 64 + wR * 64 + bK;
805 // But this way the TB is going to have 64*64*64 = 262144 positions, with
806 // lots of positions being equivalent (because they are mirrors of each
807 // other) and lots of positions being invalid (two pieces on one square,
808 // adjacent kings, etc.).
809 // Usually the first step is to take the wK and bK together. There are just
810 // 462 ways legal and not-mirrored ways to place the wK and bK on the board.
811 // Once we have placed the wK and bK, there are 62 squares left for the wR
812 // Mapping its square from 0..63 to available squares 0..61 can be done like:
814 // wR -= (wR > wK) + (wR > bK);
816 // In words: if wR "comes later" than wK, we deduct 1, and the same if wR
817 // "comes later" than bK. In case of two same pieces like KRRvK we want to
818 // place the two Rs "together". If we have 62 squares left, we can place two
819 // Rs "together" in 62 * 61 / 2 ways (we divide by 2 because rooks can be
820 // swapped and still get the same position.)
822 // In case we have at least 3 unique pieces (inlcuded kings) we encode them
824 if (entry->hasUniquePieces) {
826 int adjust1 = squares[1] > squares[0];
827 int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]);
829 // First piece is below a1-h8 diagonal. MapA1D1D4[] maps the b1-d1-d3
830 // triangle to 0...5. There are 63 squares for second piece and and 62
831 // (mapped to 0...61) for the third.
832 if (off_A1H8(squares[0]))
833 idx = ( MapA1D1D4[squares[0]] * 63
834 + (squares[1] - adjust1)) * 62
835 + squares[2] - adjust2;
837 // First piece is on a1-h8 diagonal, second below: map this occurence to
838 // 6 to differentiate from the above case, rank_of() maps a1-d4 diagonal
839 // to 0...3 and finally MapB1H1H7[] maps the b1-h1-h7 triangle to 0..27.
840 else if (off_A1H8(squares[1]))
841 idx = ( 6 * 63 + rank_of(squares[0]) * 28
842 + MapB1H1H7[squares[1]]) * 62
843 + squares[2] - adjust2;
845 // First two pieces are on a1-h8 diagonal, third below
846 else if (off_A1H8(squares[2]))
847 idx = 6 * 63 * 62 + 4 * 28 * 62
848 + rank_of(squares[0]) * 7 * 28
849 + (rank_of(squares[1]) - adjust1) * 28
850 + MapB1H1H7[squares[2]];
852 // All 3 pieces on the diagonal a1-h8
854 idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28
855 + rank_of(squares[0]) * 7 * 6
856 + (rank_of(squares[1]) - adjust1) * 6
857 + (rank_of(squares[2]) - adjust2);
859 // We don't have at least 3 unique pieces, like in KRRvKBB, just map
861 idx = MapKK[MapA1D1D4[squares[0]]][squares[1]];
864 idx *= d->groupIdx[0];
865 Square* groupSq = squares + d->groupLen[0];
867 // Encode remainig pawns then pieces according to square, in ascending order
868 bool remainingPawns = entry->hasPawns && entry->pawnTable.pawnCount[1];
870 while (d->groupLen[++next])
872 std::sort(groupSq, groupSq + d->groupLen[next]);
875 // Map down a square if "comes later" than a square in the previous
876 // groups (similar to what done earlier for leading group pieces).
877 for (int i = 0; i < d->groupLen[next]; ++i)
879 auto f = [&](Square s) { return groupSq[i] > s; };
880 auto adjust = std::count_if(squares, groupSq, f);
881 n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns];
884 remainingPawns = false;
885 idx += n * d->groupIdx[next];
886 groupSq += d->groupLen[next];
889 // Now that we have the index, decompress the pair and get the score
890 return map_score(entry, tbFile, decompress_pairs(d, idx), wdl);
893 // Group together pieces that will be encoded together. The general rule is that
894 // a group contains pieces of same type and color. The exception is the leading
895 // group that, in case of positions withouth pawns, can be formed by 3 different
896 // pieces (default) or by the king pair when there is not a unique piece apart
897 // from the kings. When there are pawns, pawns are always first in pieces[].
899 // As example KRKN -> KRK + N, KNNK -> KK + NN, KPPKP -> P + PP + K + K
901 // The actual grouping depends on the TB generator and can be inferred from the
902 // sequence of pieces in piece[] array.
904 void set_groups(T& e, PairsData* d, int order[], File f) {
906 int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2;
909 // Number of pieces per group is stored in groupLen[], for instance in KRKN
910 // the encoder will default on '111', so groupLen[] will be (3, 1).
911 for (int i = 1; i < e.pieceCount; ++i)
912 if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1])
915 d->groupLen[++n] = 1;
917 d->groupLen[++n] = 0; // Zero-terminated
919 // The sequence in pieces[] defines the groups, but not the order in which
920 // they are encoded. If the pieces in a group g can be combined on the board
921 // in N(g) different ways, then the position encoding will be of the form:
923 // g1 * N(g2) * N(g3) + g2 * N(g3) + g3
925 // This ensures unique encoding for the whole position. The order of the
926 // groups is a per-table parameter and could not follow the canonical leading
927 // pawns/pieces -> remainig pawns -> remaining pieces. In particular the
928 // first group is at order[0] position and the remaining pawns, when present,
929 // are at order[1] position.
930 bool pp = e.hasPawns && e.pawnTable.pawnCount[1]; // Pawns on both sides
931 int next = pp ? 2 : 1;
932 int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0);
935 for (int k = 0; next < n || k == order[0] || k == order[1]; ++k)
936 if (k == order[0]) // Leading pawns or pieces
938 d->groupIdx[0] = idx;
939 idx *= e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f]
940 : e.hasUniquePieces ? 31332 : 462;
942 else if (k == order[1]) // Remaining pawns
944 d->groupIdx[1] = idx;
945 idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]];
947 else // Remainig pieces
949 d->groupIdx[next] = idx;
950 idx *= Binomial[d->groupLen[next]][freeSquares];
951 freeSquares -= d->groupLen[next++];
954 d->groupIdx[n] = idx;
957 // In Recursive Pairing each symbol represents a pair of childern symbols. So
958 // read d->btree[] symbols data and expand each one in his left and right child
959 // symbol until reaching the leafs that represent the symbol value.
960 uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) {
962 visited[s] = true; // We can set it now because tree is acyclic
963 Sym sr = d->btree[s].get<LR::Right>();
968 Sym sl = d->btree[s].get<LR::Left>();
971 d->symlen[sl] = set_symlen(d, sl, visited);
974 d->symlen[sr] = set_symlen(d, sr, visited);
976 return d->symlen[sl] + d->symlen[sr] + 1;
979 uint8_t* set_sizes(PairsData* d, uint8_t* data) {
983 if (d->flags & TBFlag::SingleValue) {
984 d->blocksNum = d->blockLengthSize = 0;
985 d->span = d->sparseIndexSize = 0; // Broken MSVC zero-init
986 d->minSymLen = *data++; // Here we store the single value
990 // groupLen[] is a zero-terminated list of group lengths, the last groupIdx[]
991 // element stores the biggest index that is the tb size.
992 uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen];
994 d->sizeofBlock = 1ULL << *data++;
995 d->span = 1ULL << *data++;
996 d->sparseIndexSize = (tbSize + d->span - 1) / d->span; // Round up
997 int padding = number<uint8_t, LittleEndian>(data++);
998 d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t);
999 d->blockLengthSize = d->blocksNum + padding; // Padded to ensure SparseIndex[]
1000 // does not point out of range.
1001 d->maxSymLen = *data++;
1002 d->minSymLen = *data++;
1003 d->lowestSym = (Sym*)data;
1004 d->base64.resize(d->maxSymLen - d->minSymLen + 1);
1006 // The canonical code is ordered such that longer symbols (in terms of
1007 // the number of bits of their Huffman code) have lower numeric value,
1008 // so that d->lowestSym[i] >= d->lowestSym[i+1] (when read as LittleEndian).
1009 // Starting from this we compute a base64[] table indexed by symbol length
1010 // and containing 64 bit values so that d->base64[i] >= d->base64[i+1].
1011 // See http://www.eecs.harvard.edu/~michaelm/E210/huffman.pdf
1012 for (int i = d->base64.size() - 2; i >= 0; --i) {
1013 d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i])
1014 - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2;
1016 assert(d->base64[i] * 2 >= d->base64[i+1]);
1019 // Now left-shift by an amount so that d->base64[i] gets shifted 1 bit more
1020 // than d->base64[i+1] and given the above assert condition, we ensure that
1021 // d->base64[i] >= d->base64[i+1]. Moreover for any symbol s64 of length i
1022 // and right-padded to 64 bits holds d->base64[i-1] >= s64 >= d->base64[i].
1023 for (size_t i = 0; i < d->base64.size(); ++i)
1024 d->base64[i] <<= 64 - i - d->minSymLen; // Right-padding to 64 bits
1026 data += d->base64.size() * sizeof(Sym);
1027 d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t);
1028 d->btree = (LR*)data;
1030 // The comrpession scheme used is "Recursive Pairing", that replaces the most
1031 // frequent adjacent pair of symbols in the source message by a new symbol,
1032 // reevaluating the frequencies of all of the symbol pairs with respect to
1033 // the extended alphabet, and then repeating the process.
1034 // See http://www.larsson.dogma.net/dcc99.pdf
1035 std::vector<bool> visited(d->symlen.size());
1037 for (Sym sym = 0; sym < d->symlen.size(); ++sym)
1039 d->symlen[sym] = set_symlen(d, sym, visited);
1041 return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1);
1044 template<typename T>
1045 uint8_t* set_dtz_map(WDLEntry&, T&, uint8_t*, File) { return nullptr; }
1047 template<typename T>
1048 uint8_t* set_dtz_map(DTZEntry&, T& p, uint8_t* data, File maxFile) {
1052 for (File f = FILE_A; f <= maxFile; ++f) {
1053 if (item(p, 0, f).precomp->flags & TBFlag::Mapped)
1054 for (int i = 0; i < 4; ++i) { // Sequence like 3,x,x,x,1,x,0,2,x,x
1055 item(p, 0, f).map_idx[i] = (uint16_t)(data - p.map + 1);
1060 return data += (uintptr_t)data & 1; // Word alignment
1063 template<typename Entry, typename T>
1064 void do_init(Entry& e, T& p, uint8_t* data) {
1066 const bool IsWDL = std::is_same<Entry, WDLEntry>::value;
1070 enum { Split = 1, HasPawns = 2 };
1072 assert(e.hasPawns == !!(*data & HasPawns));
1073 assert((e.key != e.key2) == !!(*data & Split));
1075 data++; // First byte stores flags
1077 const int Sides = IsWDL && (e.key != e.key2) ? 2 : 1;
1078 const File MaxFile = e.hasPawns ? FILE_D : FILE_A;
1080 bool pp = e.hasPawns && e.pawnTable.pawnCount[1]; // Pawns on both sides
1082 assert(!pp || e.pawnTable.pawnCount[0]);
1084 for (File f = FILE_A; f <= MaxFile; ++f) {
1086 for (int i = 0; i < Sides; i++)
1087 item(p, i, f).precomp = new PairsData();
1089 int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF },
1090 { *data >> 4, pp ? *(data + 1) >> 4 : 0xF } };
1093 for (int k = 0; k < e.pieceCount; ++k, ++data)
1094 for (int i = 0; i < Sides; i++)
1095 item(p, i, f).precomp->pieces[k] = Piece(i ? *data >> 4 : *data & 0xF);
1097 for (int i = 0; i < Sides; ++i)
1098 set_groups(e, item(p, i, f).precomp, order[i], f);
1101 data += (uintptr_t)data & 1; // Word alignment
1103 for (File f = FILE_A; f <= MaxFile; ++f)
1104 for (int i = 0; i < Sides; i++)
1105 data = set_sizes(item(p, i, f).precomp, data);
1108 data = set_dtz_map(e, p, data, MaxFile);
1110 for (File f = FILE_A; f <= MaxFile; ++f)
1111 for (int i = 0; i < Sides; i++) {
1112 (d = item(p, i, f).precomp)->sparseIndex = (SparseEntry*)data;
1113 data += d->sparseIndexSize * sizeof(SparseEntry);
1116 for (File f = FILE_A; f <= MaxFile; ++f)
1117 for (int i = 0; i < Sides; i++) {
1118 (d = item(p, i, f).precomp)->blockLength = (uint16_t*)data;
1119 data += d->blockLengthSize * sizeof(uint16_t);
1122 for (File f = FILE_A; f <= MaxFile; ++f)
1123 for (int i = 0; i < Sides; i++) {
1124 data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); // 64 byte alignment
1125 (d = item(p, i, f).precomp)->data = data;
1126 data += d->blocksNum * d->sizeofBlock;
1130 template<typename Entry>
1131 void* init(Entry& e, const Position& pos) {
1133 const bool IsWDL = std::is_same<Entry, WDLEntry>::value;
1137 // Avoid a thread reads 'ready' == true while another is still in do_init(),
1138 // this could happen due to compiler reordering.
1139 if (e.ready.load(std::memory_order_acquire))
1140 return e.baseAddress;
1142 std::unique_lock<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 const uint8_t TB_MAGIC[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 },
1155 { 0x71, 0xE8, 0x23, 0x5D } };
1157 fname = (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w)
1158 + (IsWDL ? ".rtbw" : ".rtbz");
1160 uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, TB_MAGIC[IsWDL]);
1162 e.hasPawns ? do_init(e, e.pawnTable, data) : do_init(e, e.pieceTable, data);
1164 e.ready.store(true, std::memory_order_release);
1165 return e.baseAddress;
1168 template<typename E, typename T = typename Ret<E>::type>
1169 T probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) {
1171 if (!(pos.pieces() ^ pos.pieces(KING)))
1172 return T(WDLDraw); // KvK
1174 E* entry = EntryTable.get<E>(pos.material_key());
1176 if (!entry || !init(*entry, pos))
1177 return *result = FAIL, T();
1179 return do_probe_table(pos, entry, wdl, result);
1182 // For a position where the side to move has a winning capture it is not necessary
1183 // to store a winning value so the generator treats such positions as "don't cares"
1184 // and tries to assign to it a value that improves the compression ratio. Similarly,
1185 // if the side to move has a drawing capture, then the position is at least drawn.
1186 // If the position is won, then the TB needs to store a win value. But if the
1187 // position is drawn, the TB may store a loss value if that is better for compression.
1188 // All of this means that during probing, the engine must look at captures and probe
1189 // their results and must probe the position itself. The "best" result of these
1190 // probes is the correct result for the position.
1191 // DTZ table don't store values when a following move is a zeroing winning move
1192 // (winning capture or winning pawn move). Also DTZ store wrong values for positions
1193 // where the best move is an ep-move (even if losing). So in all these cases set
1194 // the state to ZEROING_BEST_MOVE.
1195 template<bool CheckZeroingMoves = false>
1196 WDLScore search(Position& pos, ProbeState* result) {
1198 WDLScore value, bestValue = WDLLoss;
1201 auto moveList = MoveList<LEGAL>(pos);
1202 size_t totalCount = moveList.size(), moveCount = 0;
1204 for (const Move& move : moveList)
1206 if ( !pos.capture(move)
1207 && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN))
1212 pos.do_move(move, st);
1213 value = -search(pos, result);
1214 pos.undo_move(move);
1216 if (*result == FAIL)
1219 if (value > bestValue)
1223 if (value >= WDLWin)
1225 *result = ZEROING_BEST_MOVE; // Winning DTZ-zeroing move
1231 // In case we have already searched all the legal moves we don't have to probe
1232 // the TB because the stored score could be wrong. For instance TB tables
1233 // do not contain information on position with ep rights, so in this case
1234 // the result of probe_wdl_table is wrong. Also in case of only capture
1235 // moves, for instance here 4K3/4q3/6p1/2k5/6p1/8/8/8 w - - 0 7, we have to
1236 // return with ZEROING_BEST_MOVE set.
1237 bool noMoreMoves = (moveCount && moveCount == totalCount);
1243 value = probe_table<WDLEntry>(pos, result);
1245 if (*result == FAIL)
1249 // DTZ stores a "don't care" value if bestValue is a win
1250 if (bestValue >= value)
1251 return *result = ( bestValue > WDLDraw
1252 || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue;
1254 return *result = OK, value;
1259 void Tablebases::init(const std::string& paths) {
1263 TBFile::Paths = paths;
1265 if (paths.empty() || paths == "<empty>")
1268 // MapB1H1H7[] encodes a square below a1-h8 diagonal to 0..27
1270 for (Square s = SQ_A1; s <= SQ_H8; ++s)
1271 if (off_A1H8(s) < 0)
1272 MapB1H1H7[s] = code++;
1274 // MapA1D1D4[] encodes a square in the a1-d1-d4 triangle to 0..9
1275 std::vector<Square> diagonal;
1277 for (Square s = SQ_A1; s <= SQ_D4; ++s)
1278 if (off_A1H8(s) < 0 && file_of(s) <= FILE_D)
1279 MapA1D1D4[s] = code++;
1281 else if (!off_A1H8(s) && file_of(s) <= FILE_D)
1282 diagonal.push_back(s);
1284 // Diagonal squares are encoded as last ones
1285 for (auto s : diagonal)
1286 MapA1D1D4[s] = code++;
1288 // MapKK[] encodes all the 461 possible legal positions of two kings where
1289 // the first is in the a1-d1-d4 triangle. If the first king is on the a1-d4
1290 // diagonal, the other one shall not to be above the a1-h8 diagonal.
1291 std::vector<std::pair<int, Square>> bothOnDiagonal;
1293 for (int idx = 0; idx < 10; idx++)
1294 for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1)
1295 if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) // SQ_B1 is mapped to 0
1297 for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2)
1298 if ((PseudoAttacks[KING][s1] | s1) & s2)
1299 continue; // Illegal position
1301 else if (!off_A1H8(s1) && off_A1H8(s2) > 0)
1302 continue; // First on diagonal, second above
1304 else if (!off_A1H8(s1) && !off_A1H8(s2))
1305 bothOnDiagonal.push_back(std::make_pair(idx, s2));
1308 MapKK[idx][s2] = code++;
1311 // Legal positions with both kings on diagonal are encoded as last ones
1312 for (auto p : bothOnDiagonal)
1313 MapKK[p.first][p.second] = code++;
1315 // Binomial[] stores the Binomial Coefficents using Pascal rule. There
1316 // are Binomial[k][n] ways to choose k elements from a set of n elements.
1319 for (int n = 1; n < 64; n++) // Squares
1320 for (int k = 0; k < 6 && k <= n; ++k) // Pieces
1321 Binomial[k][n] = (k > 0 ? Binomial[k - 1][n - 1] : 0)
1322 + (k < n ? Binomial[k ][n - 1] : 0);
1324 // MapPawns[s] encodes squares a2-h7 to 0..47. This is the number of possible
1325 // available squares when the leading one is in 's'. Moreover the pawn with
1326 // highest MapPawns[] is the leading pawn, the one nearest the edge and,
1327 // among pawns with same file, the one with lowest rank.
1328 int availableSquares = 47; // Available squares when lead pawn is in a2
1330 // Init the tables for the encoding of leading pawns group: with 6-men TB we
1331 // can have up to 4 leading pawns (KPPPPK).
1332 for (int leadPawnsCnt = 1; leadPawnsCnt <= 4; ++leadPawnsCnt)
1333 for (File f = FILE_A; f <= FILE_D; ++f)
1335 // Restart the index at every file because TB table is splitted
1336 // by file, so we can reuse the same index for different files.
1339 // Sum all possible combinations for a given file, starting with
1340 // the leading pawn on rank 2 and increasing the rank.
1341 for (Rank r = RANK_2; r <= RANK_7; ++r)
1343 Square sq = make_square(f, r);
1345 // Compute MapPawns[] at first pass.
1346 // If sq is the leading pawn square, any other pawn cannot be
1347 // below or more toward the edge of sq. There are 47 available
1348 // squares when sq = a2 and reduced by 2 for any rank increase
1349 // due to mirroring: sq == a3 -> no a2, h2, so MapPawns[a3] = 45
1350 if (leadPawnsCnt == 1)
1352 MapPawns[sq] = availableSquares--;
1353 MapPawns[sq ^ 7] = availableSquares--; // Horizontal flip
1355 LeadPawnIdx[leadPawnsCnt][sq] = idx;
1356 idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]];
1358 // After a file is traversed, store the cumulated per-file index
1359 LeadPawnsSize[leadPawnsCnt][f] = idx;
1362 for (PieceType p1 = PAWN; p1 < KING; ++p1) {
1363 EntryTable.insert({KING, p1, KING});
1365 for (PieceType p2 = PAWN; p2 <= p1; ++p2) {
1366 EntryTable.insert({KING, p1, p2, KING});
1367 EntryTable.insert({KING, p1, KING, p2});
1369 for (PieceType p3 = PAWN; p3 < KING; ++p3)
1370 EntryTable.insert({KING, p1, p2, KING, p3});
1372 for (PieceType p3 = PAWN; p3 <= p2; ++p3) {
1373 EntryTable.insert({KING, p1, p2, p3, KING});
1375 for (PieceType p4 = PAWN; p4 <= p3; ++p4)
1376 EntryTable.insert({KING, p1, p2, p3, p4, KING});
1378 for (PieceType p4 = PAWN; p4 < KING; ++p4)
1379 EntryTable.insert({KING, p1, p2, p3, KING, p4});
1382 for (PieceType p3 = PAWN; p3 <= p1; ++p3)
1383 for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4)
1384 EntryTable.insert({KING, p1, p2, KING, p3, p4});
1388 sync_cout << "info string Found " << EntryTable.size() << " tablebases" << sync_endl;
1391 // Probe the WDL table for a particular position.
1392 // If *result != FAIL, the probe was successful.
1393 // The return value is from the point of view of the side to move:
1395 // -1 : loss, but draw under 50-move rule
1397 // 1 : win, but draw under 50-move rule
1399 WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) {
1402 return search(pos, result);
1405 // Probe the DTZ 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:
1408 // n < -100 : loss, but draw under 50-move rule
1409 // -100 <= n < -1 : loss in n ply (assuming 50-move counter == 0)
1411 // 1 < n <= 100 : win in n ply (assuming 50-move counter == 0)
1412 // 100 < n : win, but draw under 50-move rule
1414 // The return value n can be off by 1: a return value -n can mean a loss
1415 // in n+1 ply and a return value +n can mean a win in n+1 ply. This
1416 // cannot happen for tables with positions exactly on the "edge" of
1417 // the 50-move rule.
1419 // This implies that if dtz > 0 is returned, the position is certainly
1420 // a win if dtz + 50-move-counter <= 99. Care must be taken that the engine
1421 // picks moves that preserve dtz + 50-move-counter <= 99.
1423 // If n = 100 immediately after a capture or pawn move, then the position
1424 // is also certainly a win, and during the whole phase until the next
1425 // capture or pawn move, the inequality to be preserved is
1426 // dtz + 50-movecounter <= 100.
1428 // In short, if a move is available resulting in dtz + 50-move-counter <= 99,
1429 // then do not accept moves leading to dtz + 50-move-counter == 100.
1430 int Tablebases::probe_dtz(Position& pos, ProbeState* result) {
1433 WDLScore wdl = search<true>(pos, result);
1435 if (*result == FAIL || wdl == WDLDraw) // DTZ tables don't store draws
1438 // DTZ stores a 'don't care' value in this case, or even a plain wrong
1439 // one as in case the best move is a losing ep, so it cannot be probed.
1440 if (*result == ZEROING_BEST_MOVE)
1441 return dtz_before_zeroing(wdl);
1443 int dtz = probe_table<DTZEntry>(pos, result, wdl);
1445 if (*result == FAIL)
1448 if (*result != CHANGE_STM)
1449 return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl);
1451 // DTZ stores results for the other side, so we need to do a 1-ply search and
1452 // find the winning move that minimizes DTZ.
1454 int minDTZ = 0xFFFF;
1456 for (const Move& move : MoveList<LEGAL>(pos))
1458 bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN;
1460 pos.do_move(move, st);
1462 // For zeroing moves we want the dtz of the move _before_ doing it,
1463 // otherwise we will get the dtz of the next move sequence. Search the
1464 // position after the move to get the score sign (because even in a
1465 // winning position we could make a losing capture or going for a draw).
1466 dtz = zeroing ? -dtz_before_zeroing(search(pos, result))
1467 : -probe_dtz(pos, result);
1469 pos.undo_move(move);
1471 if (*result == FAIL)
1474 // Convert result from 1-ply search. Zeroing moves are already accounted
1475 // by dtz_before_zeroing() that returns the DTZ of the previous move.
1477 dtz += sign_of(dtz);
1479 // Skip the draws and if we are winning only pick positive dtz
1480 if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl))
1484 // Special handle a mate position, when there are no legal moves, in this
1485 // case return value is somewhat arbitrary, so stick to the original TB code
1486 // that returns -1 in this case.
1487 return minDTZ == 0xFFFF ? -1 : minDTZ;
1490 // Check whether there has been at least one repetition of positions
1491 // since the last capture or pawn move.
1492 static int has_repeated(StateInfo *st)
1495 int i = 4, e = std::min(st->rule50, st->pliesFromNull);
1500 StateInfo *stp = st->previous->previous;
1503 stp = stp->previous->previous;
1505 if (stp->key == st->key)
1515 // Use the DTZ tables to filter out moves that don't preserve the win or draw.
1516 // If the position is lost, but DTZ is fairly high, only keep moves that
1519 // A return value false indicates that not all probes were successful and that
1520 // no moves were filtered out.
1521 bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves, Value& score)
1523 assert(rootMoves.size());
1526 int dtz = probe_dtz(pos, &result);
1534 for (size_t i = 0; i < rootMoves.size(); ++i) {
1535 Move move = rootMoves[i].pv[0];
1536 pos.do_move(move, st);
1539 if (pos.checkers() && dtz > 0) {
1540 ExtMove s[MAX_MOVES];
1542 if (generate<LEGAL>(pos, s) == s)
1547 if (st.rule50 != 0) {
1548 v = -probe_dtz(pos, &result);
1555 v = -probe_wdl(pos, &result);
1556 v = dtz_before_zeroing(WDLScore(v));
1560 pos.undo_move(move);
1565 rootMoves[i].score = (Value)v;
1568 // Obtain 50-move counter for the root position.
1569 // In Stockfish there seems to be no clean way, so we do it like this:
1570 int cnt50 = st.previous ? st.previous->rule50 : 0;
1572 // Use 50-move counter to determine whether the root position is
1573 // won, lost or drawn.
1574 WDLScore wdl = WDLDraw;
1577 wdl = (dtz + cnt50 <= 100) ? WDLWin : WDLCursedWin;
1579 wdl = (-dtz + cnt50 <= 100) ? WDLLoss : WDLBlessedLoss;
1581 // Determine the score to report to the user.
1582 score = WDL_to_value[wdl + 2];
1584 // If the position is winning or losing, but too few moves left, adjust the
1585 // score to show how close it is to winning or losing.
1586 // NOTE: int(PawnValueEg) is used as scaling factor in score_to_uci().
1587 if (wdl == WDLCursedWin && dtz <= 100)
1588 score = (Value)(((200 - dtz - cnt50) * int(PawnValueEg)) / 200);
1589 else if (wdl == WDLBlessedLoss && dtz >= -100)
1590 score = -(Value)(((200 + dtz - cnt50) * int(PawnValueEg)) / 200);
1592 // Now be a bit smart about filtering out moves.
1595 if (dtz > 0) { // winning (or 50-move rule draw)
1598 for (size_t i = 0; i < rootMoves.size(); ++i) {
1599 int v = rootMoves[i].score;
1601 if (v > 0 && v < best)
1607 // If the current phase has not seen repetitions, then try all moves
1608 // that stay safely within the 50-move budget, if there are any.
1609 if (!has_repeated(st.previous) && best + cnt50 <= 99)
1612 for (size_t i = 0; i < rootMoves.size(); ++i) {
1613 int v = rootMoves[i].score;
1615 if (v > 0 && v <= max)
1616 rootMoves[j++] = rootMoves[i];
1618 } else if (dtz < 0) { // losing (or 50-move rule draw)
1621 for (size_t i = 0; i < rootMoves.size(); ++i) {
1622 int v = rootMoves[i].score;
1628 // Try all moves, unless we approach or have a 50-move rule draw.
1629 if (-best * 2 + cnt50 < 100)
1632 for (size_t i = 0; i < rootMoves.size(); ++i) {
1633 if (rootMoves[i].score == best)
1634 rootMoves[j++] = rootMoves[i];
1637 // Try all moves that preserve the draw.
1638 for (size_t i = 0; i < rootMoves.size(); ++i) {
1639 if (rootMoves[i].score == 0)
1640 rootMoves[j++] = rootMoves[i];
1644 rootMoves.resize(j, Search::RootMove(MOVE_NONE));
1649 // Use the WDL tables to filter out moves that don't preserve the win or draw.
1650 // This is a fallback for the case that some or all DTZ tables are missing.
1652 // A return value false indicates that not all probes were successful and that
1653 // no moves were filtered out.
1654 bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves, Value& score)
1658 WDLScore wdl = Tablebases::probe_wdl(pos, &result);
1663 score = WDL_to_value[wdl + 2];
1670 for (size_t i = 0; i < rootMoves.size(); ++i) {
1671 Move move = rootMoves[i].pv[0];
1672 pos.do_move(move, st);
1673 WDLScore v = -Tablebases::probe_wdl(pos, &result);
1674 pos.undo_move(move);
1679 rootMoves[i].score = (Value)v;
1687 for (size_t i = 0; i < rootMoves.size(); ++i) {
1688 if (rootMoves[i].score == best)
1689 rootMoves[j++] = rootMoves[i];
1692 rootMoves.resize(j, Search::RootMove(MOVE_NONE));