| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| #include <algorithm> |
| #include <atomic> |
| #include <cstdint> |
| #include <cstring> |
| #include <deque> |
| #include <fstream> |
| #include <iostream> |
| #include <list> |
| #include <sstream> |
| #include <type_traits> |
| #include <mutex> |
|
|
| #include "../bitboard.h" |
| #include "../movegen.h" |
| #include "../position.h" |
| #include "../search.h" |
| #include "../types.h" |
| #include "../uci.h" |
|
|
| #include "tbprobe.h" |
|
|
| #ifndef _WIN32 |
| #include <fcntl.h> |
| #include <unistd.h> |
| #include <sys/mman.h> |
| #include <sys/stat.h> |
| #else |
| #define WIN32_LEAN_AND_MEAN |
| #ifndef NOMINMAX |
| # define NOMINMAX |
| #endif |
| #include <windows.h> |
| #endif |
|
|
| using namespace Stockfish::Tablebases; |
|
|
| int Stockfish::Tablebases::MaxCardinality; |
|
|
| namespace Stockfish { |
|
|
| namespace { |
|
|
| constexpr int TBPIECES = 7; |
| constexpr int MAX_DTZ = 1 << 18; |
|
|
| enum { BigEndian, LittleEndian }; |
| enum TBType { WDL, DTZ }; |
|
|
| |
| enum TBFlag { STM = 1, Mapped = 2, WinPlies = 4, LossPlies = 8, Wide = 16, SingleValue = 128 }; |
|
|
| inline WDLScore operator-(WDLScore d) { return WDLScore(-int(d)); } |
| inline Square operator^(Square s, int i) { return Square(int(s) ^ i); } |
|
|
| const std::string PieceToChar = " PNBRQK pnbrqk"; |
|
|
| int MapPawns[SQUARE_NB]; |
| int MapB1H1H7[SQUARE_NB]; |
| int MapA1D1D4[SQUARE_NB]; |
| int MapKK[10][SQUARE_NB]; |
|
|
| int Binomial[6][SQUARE_NB]; |
| int LeadPawnIdx[6][SQUARE_NB]; |
| int LeadPawnsSize[6][4]; |
|
|
| |
| bool pawns_comp(Square i, Square j) { return MapPawns[i] < MapPawns[j]; } |
| int off_A1H8(Square sq) { return int(rank_of(sq)) - file_of(sq); } |
|
|
| constexpr Value WDL_to_value[] = { |
| -VALUE_MATE + MAX_PLY + 1, |
| VALUE_DRAW - 2, |
| VALUE_DRAW, |
| VALUE_DRAW + 2, |
| VALUE_MATE - MAX_PLY - 1 |
| }; |
|
|
| template<typename T, int Half = sizeof(T) / 2, int End = sizeof(T) - 1> |
| inline void swap_endian(T& x) |
| { |
| static_assert(std::is_unsigned<T>::value, "Argument of swap_endian not unsigned"); |
|
|
| uint8_t tmp, *c = (uint8_t*)&x; |
| for (int i = 0; i < Half; ++i) |
| tmp = c[i], c[i] = c[End - i], c[End - i] = tmp; |
| } |
| template<> inline void swap_endian<uint8_t>(uint8_t&) {} |
|
|
| template<typename T, int LE> T number(void* addr) |
| { |
| T v; |
|
|
| if ((uintptr_t)addr & (alignof(T) - 1)) |
| std::memcpy(&v, addr, sizeof(T)); |
| else |
| v = *((T*)addr); |
|
|
| if (LE != IsLittleEndian) |
| swap_endian(v); |
| return v; |
| } |
|
|
| |
| |
| |
| int dtz_before_zeroing(WDLScore wdl) { |
| return wdl == WDLWin ? 1 : |
| wdl == WDLCursedWin ? 101 : |
| wdl == WDLBlessedLoss ? -101 : |
| wdl == WDLLoss ? -1 : 0; |
| } |
|
|
| |
| template <typename T> int sign_of(T val) { |
| return (T(0) < val) - (val < T(0)); |
| } |
|
|
| |
| struct SparseEntry { |
| char block[4]; |
| char offset[2]; |
| }; |
|
|
| static_assert(sizeof(SparseEntry) == 6, "SparseEntry must be 6 bytes"); |
|
|
| typedef uint16_t Sym; |
|
|
| struct LR { |
| enum Side { Left, Right }; |
|
|
| uint8_t lr[3]; |
| |
| |
| template<Side S> |
| Sym get() { |
| return S == Left ? ((lr[1] & 0xF) << 8) | lr[0] : |
| S == Right ? (lr[2] << 4) | (lr[1] >> 4) : (assert(false), Sym(-1)); |
| } |
| }; |
|
|
| static_assert(sizeof(LR) == 3, "LR tree entry must be 3 bytes"); |
|
|
| |
| |
| |
| |
| |
|
|
| |
| |
| |
| class TBFile : public std::ifstream { |
|
|
| std::string fname; |
|
|
| public: |
| |
| |
| |
| |
| |
| |
| static std::string Paths; |
|
|
| TBFile(const std::string& f) { |
|
|
| #ifndef _WIN32 |
| constexpr char SepChar = ':'; |
| #else |
| constexpr char SepChar = ';'; |
| #endif |
| std::stringstream ss(Paths); |
| std::string path; |
|
|
| while (std::getline(ss, path, SepChar)) |
| { |
| fname = path + "/" + f; |
| std::ifstream::open(fname); |
| if (is_open()) |
| return; |
| } |
| } |
|
|
| |
| |
| uint8_t* map(void** baseAddress, uint64_t* mapping, TBType type) { |
|
|
| assert(is_open()); |
|
|
| close(); |
|
|
| #ifndef _WIN32 |
| struct stat statbuf; |
| int fd = ::open(fname.c_str(), O_RDONLY); |
|
|
| if (fd == -1) |
| return *baseAddress = nullptr, nullptr; |
|
|
| fstat(fd, &statbuf); |
|
|
| if (statbuf.st_size % 64 != 16) |
| { |
| std::cerr << "Corrupt tablebase file " << fname << std::endl; |
| exit(EXIT_FAILURE); |
| } |
|
|
| *mapping = statbuf.st_size; |
| *baseAddress = mmap(nullptr, statbuf.st_size, PROT_READ, MAP_SHARED, fd, 0); |
| #if defined(MADV_RANDOM) |
| madvise(*baseAddress, statbuf.st_size, MADV_RANDOM); |
| #endif |
| ::close(fd); |
|
|
| if (*baseAddress == MAP_FAILED) |
| { |
| std::cerr << "Could not mmap() " << fname << std::endl; |
| exit(EXIT_FAILURE); |
| } |
| #else |
| |
| HANDLE fd = CreateFile(fname.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, |
| OPEN_EXISTING, FILE_FLAG_RANDOM_ACCESS, nullptr); |
|
|
| if (fd == INVALID_HANDLE_VALUE) |
| return *baseAddress = nullptr, nullptr; |
|
|
| DWORD size_high; |
| DWORD size_low = GetFileSize(fd, &size_high); |
|
|
| if (size_low % 64 != 16) |
| { |
| std::cerr << "Corrupt tablebase file " << fname << std::endl; |
| exit(EXIT_FAILURE); |
| } |
|
|
| HANDLE mmap = CreateFileMapping(fd, nullptr, PAGE_READONLY, size_high, size_low, nullptr); |
| CloseHandle(fd); |
|
|
| if (!mmap) |
| { |
| std::cerr << "CreateFileMapping() failed" << std::endl; |
| exit(EXIT_FAILURE); |
| } |
|
|
| *mapping = (uint64_t)mmap; |
| *baseAddress = MapViewOfFile(mmap, FILE_MAP_READ, 0, 0, 0); |
|
|
| if (!*baseAddress) |
| { |
| std::cerr << "MapViewOfFile() failed, name = " << fname |
| << ", error = " << GetLastError() << std::endl; |
| exit(EXIT_FAILURE); |
| } |
| #endif |
| uint8_t* data = (uint8_t*)*baseAddress; |
|
|
| constexpr uint8_t Magics[][4] = { { 0xD7, 0x66, 0x0C, 0xA5 }, |
| { 0x71, 0xE8, 0x23, 0x5D } }; |
|
|
| if (memcmp(data, Magics[type == WDL], 4)) |
| { |
| std::cerr << "Corrupted table in file " << fname << std::endl; |
| unmap(*baseAddress, *mapping); |
| return *baseAddress = nullptr, nullptr; |
| } |
|
|
| return data + 4; |
| } |
|
|
| static void unmap(void* baseAddress, uint64_t mapping) { |
|
|
| #ifndef _WIN32 |
| munmap(baseAddress, mapping); |
| #else |
| UnmapViewOfFile(baseAddress); |
| CloseHandle((HANDLE)mapping); |
| #endif |
| } |
| }; |
|
|
| std::string TBFile::Paths; |
|
|
| |
| |
| |
| struct PairsData { |
| uint8_t flags; |
| uint8_t maxSymLen; |
| uint8_t minSymLen; |
| uint32_t blocksNum; |
| size_t sizeofBlock; |
| size_t span; |
| Sym* lowestSym; |
| LR* btree; |
| uint16_t* blockLength; |
| uint32_t blockLengthSize; |
| SparseEntry* sparseIndex; |
| size_t sparseIndexSize; |
| uint8_t* data; |
| std::vector<uint64_t> base64; |
| std::vector<uint8_t> symlen; |
| Piece pieces[TBPIECES]; |
| uint64_t groupIdx[TBPIECES+1]; |
| int groupLen[TBPIECES+1]; |
| uint16_t map_idx[4]; |
| }; |
|
|
| |
| |
| |
| |
| template<TBType Type> |
| struct TBTable { |
| typedef typename std::conditional<Type == WDL, WDLScore, int>::type Ret; |
|
|
| static constexpr int Sides = Type == WDL ? 2 : 1; |
|
|
| std::atomic_bool ready; |
| void* baseAddress; |
| uint8_t* map; |
| uint64_t mapping; |
| Key key; |
| Key key2; |
| int pieceCount; |
| bool hasPawns; |
| bool hasUniquePieces; |
| uint8_t pawnCount[2]; |
| PairsData items[Sides][4]; |
|
|
| PairsData* get(int stm, int f) { |
| return &items[stm % Sides][hasPawns ? f : 0]; |
| } |
|
|
| TBTable() : ready(false), baseAddress(nullptr) {} |
| explicit TBTable(const std::string& code); |
| explicit TBTable(const TBTable<WDL>& wdl); |
|
|
| ~TBTable() { |
| if (baseAddress) |
| TBFile::unmap(baseAddress, mapping); |
| } |
| }; |
|
|
| template<> |
| TBTable<WDL>::TBTable(const std::string& code) : TBTable() { |
|
|
| StateInfo st; |
| Position pos; |
|
|
| key = pos.set(code, WHITE, &st).material_key(); |
| pieceCount = pos.count<ALL_PIECES>(); |
| hasPawns = pos.pieces(PAWN); |
|
|
| hasUniquePieces = false; |
| for (Color c : { WHITE, BLACK }) |
| for (PieceType pt = PAWN; pt < KING; ++pt) |
| if (popcount(pos.pieces(c, pt)) == 1) |
| hasUniquePieces = true; |
|
|
| |
| |
| bool c = !pos.count<PAWN>(BLACK) |
| || ( pos.count<PAWN>(WHITE) |
| && pos.count<PAWN>(BLACK) >= pos.count<PAWN>(WHITE)); |
|
|
| pawnCount[0] = pos.count<PAWN>(c ? WHITE : BLACK); |
| pawnCount[1] = pos.count<PAWN>(c ? BLACK : WHITE); |
|
|
| key2 = pos.set(code, BLACK, &st).material_key(); |
| } |
|
|
| template<> |
| TBTable<DTZ>::TBTable(const TBTable<WDL>& wdl) : TBTable() { |
|
|
| |
| key = wdl.key; |
| key2 = wdl.key2; |
| pieceCount = wdl.pieceCount; |
| hasPawns = wdl.hasPawns; |
| hasUniquePieces = wdl.hasUniquePieces; |
| pawnCount[0] = wdl.pawnCount[0]; |
| pawnCount[1] = wdl.pawnCount[1]; |
| } |
|
|
| |
| |
| |
| class TBTables { |
|
|
| struct Entry |
| { |
| Key key; |
| TBTable<WDL>* wdl; |
| TBTable<DTZ>* dtz; |
|
|
| template <TBType Type> |
| TBTable<Type>* get() const { |
| return (TBTable<Type>*)(Type == WDL ? (void*)wdl : (void*)dtz); |
| } |
| }; |
|
|
| static constexpr int Size = 1 << 12; |
| static constexpr int Overflow = 1; |
|
|
| Entry hashTable[Size + Overflow]; |
|
|
| std::deque<TBTable<WDL>> wdlTable; |
| std::deque<TBTable<DTZ>> dtzTable; |
|
|
| void insert(Key key, TBTable<WDL>* wdl, TBTable<DTZ>* dtz) { |
| uint32_t homeBucket = (uint32_t)key & (Size - 1); |
| Entry entry{ key, wdl, dtz }; |
|
|
| |
| for (uint32_t bucket = homeBucket; bucket < Size + Overflow - 1; ++bucket) { |
| Key otherKey = hashTable[bucket].key; |
| if (otherKey == key || !hashTable[bucket].get<WDL>()) { |
| hashTable[bucket] = entry; |
| return; |
| } |
|
|
| |
| |
| uint32_t otherHomeBucket = (uint32_t)otherKey & (Size - 1); |
| if (otherHomeBucket > homeBucket) { |
| std::swap(entry, hashTable[bucket]); |
| key = otherKey; |
| homeBucket = otherHomeBucket; |
| } |
| } |
| std::cerr << "TB hash table size too low!" << std::endl; |
| exit(EXIT_FAILURE); |
| } |
|
|
| public: |
| template<TBType Type> |
| TBTable<Type>* get(Key key) { |
| for (const Entry* entry = &hashTable[(uint32_t)key & (Size - 1)]; ; ++entry) { |
| if (entry->key == key || !entry->get<Type>()) |
| return entry->get<Type>(); |
| } |
| } |
|
|
| void clear() { |
| memset(hashTable, 0, sizeof(hashTable)); |
| wdlTable.clear(); |
| dtzTable.clear(); |
| } |
| size_t size() const { return wdlTable.size(); } |
| void add(const std::vector<PieceType>& pieces); |
| }; |
|
|
| TBTables TBTables; |
|
|
| |
| |
| void TBTables::add(const std::vector<PieceType>& pieces) { |
|
|
| std::string code; |
|
|
| for (PieceType pt : pieces) |
| code += PieceToChar[pt]; |
|
|
| TBFile file(code.insert(code.find('K', 1), "v") + ".rtbw"); |
|
|
| if (!file.is_open()) |
| return; |
|
|
| file.close(); |
|
|
| MaxCardinality = std::max((int)pieces.size(), MaxCardinality); |
|
|
| wdlTable.emplace_back(code); |
| dtzTable.emplace_back(wdlTable.back()); |
|
|
| |
| insert(wdlTable.back().key , &wdlTable.back(), &dtzTable.back()); |
| insert(wdlTable.back().key2, &wdlTable.back(), &dtzTable.back()); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| int decompress_pairs(PairsData* d, uint64_t idx) { |
|
|
| |
| if (d->flags & TBFlag::SingleValue) |
| return d->minSymLen; |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| |
| uint32_t k = uint32_t(idx / d->span); |
|
|
| |
| uint32_t block = number<uint32_t, LittleEndian>(&d->sparseIndex[k].block); |
| int offset = number<uint16_t, LittleEndian>(&d->sparseIndex[k].offset); |
|
|
| |
| |
| |
| |
| |
| int diff = idx % d->span - d->span / 2; |
|
|
| |
| offset += diff; |
|
|
| |
| |
| while (offset < 0) |
| offset += d->blockLength[--block] + 1; |
|
|
| while (offset > d->blockLength[block]) |
| offset -= d->blockLength[block++] + 1; |
|
|
| |
| uint32_t* ptr = (uint32_t*)(d->data + ((uint64_t)block * d->sizeofBlock)); |
|
|
| |
| |
| |
| uint64_t buf64 = number<uint64_t, BigEndian>(ptr); ptr += 2; |
| int buf64Size = 64; |
| Sym sym; |
|
|
| while (true) |
| { |
| int len = 0; |
|
|
| |
| |
| |
| while (buf64 < d->base64[len]) |
| ++len; |
|
|
| |
| |
| |
| sym = Sym((buf64 - d->base64[len]) >> (64 - len - d->minSymLen)); |
|
|
| |
| sym += number<Sym, LittleEndian>(&d->lowestSym[len]); |
|
|
| |
| |
| if (offset < d->symlen[sym] + 1) |
| break; |
|
|
| |
| offset -= d->symlen[sym] + 1; |
| len += d->minSymLen; |
| buf64 <<= len; |
| buf64Size -= len; |
|
|
| if (buf64Size <= 32) { |
| buf64Size += 32; |
| buf64 |= (uint64_t)number<uint32_t, BigEndian>(ptr++) << (64 - buf64Size); |
| } |
| } |
|
|
| |
| |
| |
| |
| while (d->symlen[sym]) |
| { |
| Sym left = d->btree[sym].get<LR::Left>(); |
|
|
| |
| |
| |
| |
| if (offset < d->symlen[left] + 1) |
| sym = left; |
| else { |
| offset -= d->symlen[left] + 1; |
| sym = d->btree[sym].get<LR::Right>(); |
| } |
| } |
|
|
| return d->btree[sym].get<LR::Left>(); |
| } |
|
|
| bool check_dtz_stm(TBTable<WDL>*, int, File) { return true; } |
|
|
| bool check_dtz_stm(TBTable<DTZ>* entry, int stm, File f) { |
|
|
| auto flags = entry->get(stm, f)->flags; |
| return (flags & TBFlag::STM) == stm |
| || ((entry->key == entry->key2) && !entry->hasPawns); |
| } |
|
|
| |
| |
| |
| |
| WDLScore map_score(TBTable<WDL>*, File, int value, WDLScore) { return WDLScore(value - 2); } |
|
|
| int map_score(TBTable<DTZ>* entry, File f, int value, WDLScore wdl) { |
|
|
| constexpr int WDLMap[] = { 1, 3, 0, 2, 0 }; |
|
|
| auto flags = entry->get(0, f)->flags; |
|
|
| uint8_t* map = entry->map; |
| uint16_t* idx = entry->get(0, f)->map_idx; |
| if (flags & TBFlag::Mapped) { |
| if (flags & TBFlag::Wide) |
| value = ((uint16_t *)map)[idx[WDLMap[wdl + 2]] + value]; |
| else |
| value = map[idx[WDLMap[wdl + 2]] + value]; |
| } |
|
|
| |
| |
| if ( (wdl == WDLWin && !(flags & TBFlag::WinPlies)) |
| || (wdl == WDLLoss && !(flags & TBFlag::LossPlies)) |
| || wdl == WDLCursedWin |
| || wdl == WDLBlessedLoss) |
| value *= 2; |
|
|
| return value + 1; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| template<typename T, typename Ret = typename T::Ret> |
| Ret do_probe_table(const Position& pos, T* entry, WDLScore wdl, ProbeState* result) { |
|
|
| Square squares[TBPIECES]; |
| Piece pieces[TBPIECES]; |
| uint64_t idx; |
| int next = 0, size = 0, leadPawnsCnt = 0; |
| PairsData* d; |
| Bitboard b, leadPawns = 0; |
| File tbFile = FILE_A; |
|
|
| |
| |
| |
| |
| bool symmetricBlackToMove = (entry->key == entry->key2 && pos.side_to_move()); |
|
|
| |
| |
| |
| |
| bool blackStronger = (pos.material_key() != entry->key); |
|
|
| int flipColor = (symmetricBlackToMove || blackStronger) * 8; |
| int flipSquares = (symmetricBlackToMove || blackStronger) * 56; |
| int stm = (symmetricBlackToMove || blackStronger) ^ pos.side_to_move(); |
|
|
| |
| |
| |
| if (entry->hasPawns) { |
|
|
| |
| |
| Piece pc = Piece(entry->get(0, 0)->pieces[0] ^ flipColor); |
|
|
| assert(type_of(pc) == PAWN); |
|
|
| leadPawns = b = pos.pieces(color_of(pc), PAWN); |
| do |
| squares[size++] = pop_lsb(b) ^ flipSquares; |
| while (b); |
|
|
| leadPawnsCnt = size; |
|
|
| std::swap(squares[0], *std::max_element(squares, squares + leadPawnsCnt, pawns_comp)); |
|
|
| tbFile = File(edge_distance(file_of(squares[0]))); |
| } |
|
|
| |
| |
| |
| if (!check_dtz_stm(entry, stm, tbFile)) |
| return *result = CHANGE_STM, Ret(); |
|
|
| |
| |
| b = pos.pieces() ^ leadPawns; |
| do { |
| Square s = pop_lsb(b); |
| squares[size] = s ^ flipSquares; |
| pieces[size++] = Piece(pos.piece_on(s) ^ flipColor); |
| } while (b); |
|
|
| assert(size >= 2); |
|
|
| d = entry->get(stm, tbFile); |
|
|
| |
| |
| for (int i = leadPawnsCnt; i < size - 1; ++i) |
| for (int j = i + 1; j < size; ++j) |
| if (d->pieces[i] == pieces[j]) |
| { |
| std::swap(pieces[i], pieces[j]); |
| std::swap(squares[i], squares[j]); |
| break; |
| } |
|
|
| |
| |
| if (file_of(squares[0]) > FILE_D) |
| for (int i = 0; i < size; ++i) |
| squares[i] = flip_file(squares[i]); |
|
|
| |
| |
| if (entry->hasPawns) { |
| idx = LeadPawnIdx[leadPawnsCnt][squares[0]]; |
|
|
| std::stable_sort(squares + 1, squares + leadPawnsCnt, pawns_comp); |
|
|
| for (int i = 1; i < leadPawnsCnt; ++i) |
| idx += Binomial[i][MapPawns[squares[i]]]; |
|
|
| goto encode_remaining; |
| } |
|
|
| |
| |
| if (rank_of(squares[0]) > RANK_4) |
| for (int i = 0; i < size; ++i) |
| squares[i] = flip_rank(squares[i]); |
|
|
| |
| |
| for (int i = 0; i < d->groupLen[0]; ++i) { |
| if (!off_A1H8(squares[i])) |
| continue; |
|
|
| if (off_A1H8(squares[i]) > 0) |
| for (int j = i; j < size; ++j) |
| squares[j] = Square(((squares[j] >> 3) | (squares[j] << 3)) & 63); |
| break; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| if (entry->hasUniquePieces) { |
|
|
| int adjust1 = squares[1] > squares[0]; |
| int adjust2 = (squares[2] > squares[0]) + (squares[2] > squares[1]); |
|
|
| |
| |
| |
| if (off_A1H8(squares[0])) |
| idx = ( MapA1D1D4[squares[0]] * 63 |
| + (squares[1] - adjust1)) * 62 |
| + squares[2] - adjust2; |
|
|
| |
| |
| |
| else if (off_A1H8(squares[1])) |
| idx = ( 6 * 63 + rank_of(squares[0]) * 28 |
| + MapB1H1H7[squares[1]]) * 62 |
| + squares[2] - adjust2; |
|
|
| |
| else if (off_A1H8(squares[2])) |
| idx = 6 * 63 * 62 + 4 * 28 * 62 |
| + rank_of(squares[0]) * 7 * 28 |
| + (rank_of(squares[1]) - adjust1) * 28 |
| + MapB1H1H7[squares[2]]; |
|
|
| |
| else |
| idx = 6 * 63 * 62 + 4 * 28 * 62 + 4 * 7 * 28 |
| + rank_of(squares[0]) * 7 * 6 |
| + (rank_of(squares[1]) - adjust1) * 6 |
| + (rank_of(squares[2]) - adjust2); |
| } else |
| |
| |
| idx = MapKK[MapA1D1D4[squares[0]]][squares[1]]; |
|
|
| encode_remaining: |
| idx *= d->groupIdx[0]; |
| Square* groupSq = squares + d->groupLen[0]; |
|
|
| |
| bool remainingPawns = entry->hasPawns && entry->pawnCount[1]; |
|
|
| while (d->groupLen[++next]) |
| { |
| std::stable_sort(groupSq, groupSq + d->groupLen[next]); |
| uint64_t n = 0; |
|
|
| |
| |
| for (int i = 0; i < d->groupLen[next]; ++i) |
| { |
| auto f = [&](Square s) { return groupSq[i] > s; }; |
| auto adjust = std::count_if(squares, groupSq, f); |
| n += Binomial[i + 1][groupSq[i] - adjust - 8 * remainingPawns]; |
| } |
|
|
| remainingPawns = false; |
| idx += n * d->groupIdx[next]; |
| groupSq += d->groupLen[next]; |
| } |
|
|
| |
| return map_score(entry, tbFile, decompress_pairs(d, idx), wdl); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| template<typename T> |
| void set_groups(T& e, PairsData* d, int order[], File f) { |
|
|
| int n = 0, firstLen = e.hasPawns ? 0 : e.hasUniquePieces ? 3 : 2; |
| d->groupLen[n] = 1; |
|
|
| |
| |
| for (int i = 1; i < e.pieceCount; ++i) |
| if (--firstLen > 0 || d->pieces[i] == d->pieces[i - 1]) |
| d->groupLen[n]++; |
| else |
| d->groupLen[++n] = 1; |
|
|
| d->groupLen[++n] = 0; |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| bool pp = e.hasPawns && e.pawnCount[1]; |
| int next = pp ? 2 : 1; |
| int freeSquares = 64 - d->groupLen[0] - (pp ? d->groupLen[1] : 0); |
| uint64_t idx = 1; |
|
|
| for (int k = 0; next < n || k == order[0] || k == order[1]; ++k) |
| if (k == order[0]) |
| { |
| d->groupIdx[0] = idx; |
| idx *= e.hasPawns ? LeadPawnsSize[d->groupLen[0]][f] |
| : e.hasUniquePieces ? 31332 : 462; |
| } |
| else if (k == order[1]) |
| { |
| d->groupIdx[1] = idx; |
| idx *= Binomial[d->groupLen[1]][48 - d->groupLen[0]]; |
| } |
| else |
| { |
| d->groupIdx[next] = idx; |
| idx *= Binomial[d->groupLen[next]][freeSquares]; |
| freeSquares -= d->groupLen[next++]; |
| } |
|
|
| d->groupIdx[n] = idx; |
| } |
|
|
| |
| |
| |
| uint8_t set_symlen(PairsData* d, Sym s, std::vector<bool>& visited) { |
|
|
| visited[s] = true; |
| Sym sr = d->btree[s].get<LR::Right>(); |
|
|
| if (sr == 0xFFF) |
| return 0; |
|
|
| Sym sl = d->btree[s].get<LR::Left>(); |
|
|
| if (!visited[sl]) |
| d->symlen[sl] = set_symlen(d, sl, visited); |
|
|
| if (!visited[sr]) |
| d->symlen[sr] = set_symlen(d, sr, visited); |
|
|
| return d->symlen[sl] + d->symlen[sr] + 1; |
| } |
|
|
| uint8_t* set_sizes(PairsData* d, uint8_t* data) { |
|
|
| d->flags = *data++; |
|
|
| if (d->flags & TBFlag::SingleValue) { |
| d->blocksNum = d->blockLengthSize = 0; |
| d->span = d->sparseIndexSize = 0; |
| d->minSymLen = *data++; |
| return data; |
| } |
|
|
| |
| |
| uint64_t tbSize = d->groupIdx[std::find(d->groupLen, d->groupLen + 7, 0) - d->groupLen]; |
|
|
| d->sizeofBlock = 1ULL << *data++; |
| d->span = 1ULL << *data++; |
| d->sparseIndexSize = size_t((tbSize + d->span - 1) / d->span); |
| auto padding = number<uint8_t, LittleEndian>(data++); |
| d->blocksNum = number<uint32_t, LittleEndian>(data); data += sizeof(uint32_t); |
| d->blockLengthSize = d->blocksNum + padding; |
| |
| d->maxSymLen = *data++; |
| d->minSymLen = *data++; |
| d->lowestSym = (Sym*)data; |
| d->base64.resize(d->maxSymLen - d->minSymLen + 1); |
|
|
| |
| |
| |
| |
| |
| |
| for (int i = d->base64.size() - 2; i >= 0; --i) { |
| d->base64[i] = (d->base64[i + 1] + number<Sym, LittleEndian>(&d->lowestSym[i]) |
| - number<Sym, LittleEndian>(&d->lowestSym[i + 1])) / 2; |
|
|
| assert(d->base64[i] * 2 >= d->base64[i+1]); |
| } |
|
|
| |
| |
| |
| |
| for (size_t i = 0; i < d->base64.size(); ++i) |
| d->base64[i] <<= 64 - i - d->minSymLen; |
|
|
| data += d->base64.size() * sizeof(Sym); |
| d->symlen.resize(number<uint16_t, LittleEndian>(data)); data += sizeof(uint16_t); |
| d->btree = (LR*)data; |
|
|
| |
| |
| |
| |
| |
| std::vector<bool> visited(d->symlen.size()); |
|
|
| for (Sym sym = 0; sym < d->symlen.size(); ++sym) |
| if (!visited[sym]) |
| d->symlen[sym] = set_symlen(d, sym, visited); |
|
|
| return data + d->symlen.size() * sizeof(LR) + (d->symlen.size() & 1); |
| } |
|
|
| uint8_t* set_dtz_map(TBTable<WDL>&, uint8_t* data, File) { return data; } |
|
|
| uint8_t* set_dtz_map(TBTable<DTZ>& e, uint8_t* data, File maxFile) { |
|
|
| e.map = data; |
|
|
| for (File f = FILE_A; f <= maxFile; ++f) { |
| auto flags = e.get(0, f)->flags; |
| if (flags & TBFlag::Mapped) { |
| if (flags & TBFlag::Wide) { |
| data += (uintptr_t)data & 1; |
| for (int i = 0; i < 4; ++i) { |
| e.get(0, f)->map_idx[i] = (uint16_t)((uint16_t *)data - (uint16_t *)e.map + 1); |
| data += 2 * number<uint16_t, LittleEndian>(data) + 2; |
| } |
| } |
| else { |
| for (int i = 0; i < 4; ++i) { |
| e.get(0, f)->map_idx[i] = (uint16_t)(data - e.map + 1); |
| data += *data + 1; |
| } |
| } |
| } |
| } |
|
|
| return data += (uintptr_t)data & 1; |
| } |
|
|
| |
| |
| template<typename T> |
| void set(T& e, uint8_t* data) { |
|
|
| PairsData* d; |
|
|
| enum { Split = 1, HasPawns = 2 }; |
|
|
| assert(e.hasPawns == bool(*data & HasPawns)); |
| assert((e.key != e.key2) == bool(*data & Split)); |
|
|
| data++; |
|
|
| const int sides = T::Sides == 2 && (e.key != e.key2) ? 2 : 1; |
| const File maxFile = e.hasPawns ? FILE_D : FILE_A; |
|
|
| bool pp = e.hasPawns && e.pawnCount[1]; |
|
|
| assert(!pp || e.pawnCount[0]); |
|
|
| for (File f = FILE_A; f <= maxFile; ++f) { |
|
|
| for (int i = 0; i < sides; i++) |
| *e.get(i, f) = PairsData(); |
|
|
| int order[][2] = { { *data & 0xF, pp ? *(data + 1) & 0xF : 0xF }, |
| { *data >> 4, pp ? *(data + 1) >> 4 : 0xF } }; |
| data += 1 + pp; |
|
|
| for (int k = 0; k < e.pieceCount; ++k, ++data) |
| for (int i = 0; i < sides; i++) |
| e.get(i, f)->pieces[k] = Piece(i ? *data >> 4 : *data & 0xF); |
|
|
| for (int i = 0; i < sides; ++i) |
| set_groups(e, e.get(i, f), order[i], f); |
| } |
|
|
| data += (uintptr_t)data & 1; |
|
|
| for (File f = FILE_A; f <= maxFile; ++f) |
| for (int i = 0; i < sides; i++) |
| data = set_sizes(e.get(i, f), data); |
|
|
| data = set_dtz_map(e, data, maxFile); |
|
|
| for (File f = FILE_A; f <= maxFile; ++f) |
| for (int i = 0; i < sides; i++) { |
| (d = e.get(i, f))->sparseIndex = (SparseEntry*)data; |
| data += d->sparseIndexSize * sizeof(SparseEntry); |
| } |
|
|
| for (File f = FILE_A; f <= maxFile; ++f) |
| for (int i = 0; i < sides; i++) { |
| (d = e.get(i, f))->blockLength = (uint16_t*)data; |
| data += d->blockLengthSize * sizeof(uint16_t); |
| } |
|
|
| for (File f = FILE_A; f <= maxFile; ++f) |
| for (int i = 0; i < sides; i++) { |
| data = (uint8_t*)(((uintptr_t)data + 0x3F) & ~0x3F); |
| (d = e.get(i, f))->data = data; |
| data += d->blocksNum * d->sizeofBlock; |
| } |
| } |
|
|
| |
| |
| |
| |
| template<TBType Type> |
| void* mapped(TBTable<Type>& e, const Position& pos) { |
|
|
| static std::mutex mutex; |
|
|
| |
| |
| if (e.ready.load(std::memory_order_acquire)) |
| return e.baseAddress; |
|
|
| std::scoped_lock<std::mutex> lk(mutex); |
|
|
| if (e.ready.load(std::memory_order_relaxed)) |
| return e.baseAddress; |
|
|
| |
| std::string fname, w, b; |
| for (PieceType pt = KING; pt >= PAWN; --pt) { |
| w += std::string(popcount(pos.pieces(WHITE, pt)), PieceToChar[pt]); |
| b += std::string(popcount(pos.pieces(BLACK, pt)), PieceToChar[pt]); |
| } |
|
|
| fname = (e.key == pos.material_key() ? w + 'v' + b : b + 'v' + w) |
| + (Type == WDL ? ".rtbw" : ".rtbz"); |
|
|
| uint8_t* data = TBFile(fname).map(&e.baseAddress, &e.mapping, Type); |
|
|
| if (data) |
| set(e, data); |
|
|
| e.ready.store(true, std::memory_order_release); |
| return e.baseAddress; |
| } |
|
|
| template<TBType Type, typename Ret = typename TBTable<Type>::Ret> |
| Ret probe_table(const Position& pos, ProbeState* result, WDLScore wdl = WDLDraw) { |
|
|
| if (pos.count<ALL_PIECES>() == 2) |
| return Ret(WDLDraw); |
|
|
| TBTable<Type>* entry = TBTables.get<Type>(pos.material_key()); |
|
|
| if (!entry || !mapped(*entry, pos)) |
| return *result = FAIL, Ret(); |
|
|
| return do_probe_table(pos, entry, wdl, result); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| template<bool CheckZeroingMoves> |
| WDLScore search(Position& pos, ProbeState* result) { |
|
|
| WDLScore value, bestValue = WDLLoss; |
| StateInfo st; |
|
|
| auto moveList = MoveList<LEGAL>(pos); |
| size_t totalCount = moveList.size(), moveCount = 0; |
|
|
| for (const Move move : moveList) |
| { |
| if ( !pos.capture(move) |
| && (!CheckZeroingMoves || type_of(pos.moved_piece(move)) != PAWN)) |
| continue; |
|
|
| moveCount++; |
|
|
| pos.do_move(move, st); |
| value = -search<false>(pos, result); |
| pos.undo_move(move); |
|
|
| if (*result == FAIL) |
| return WDLDraw; |
|
|
| if (value > bestValue) |
| { |
| bestValue = value; |
|
|
| if (value >= WDLWin) |
| { |
| *result = ZEROING_BEST_MOVE; |
| return value; |
| } |
| } |
| } |
|
|
| |
| |
| |
| |
| |
| |
| bool noMoreMoves = (moveCount && moveCount == totalCount); |
|
|
| if (noMoreMoves) |
| value = bestValue; |
| else |
| { |
| value = probe_table<WDL>(pos, result); |
|
|
| if (*result == FAIL) |
| return WDLDraw; |
| } |
|
|
| |
| if (bestValue >= value) |
| return *result = ( bestValue > WDLDraw |
| || noMoreMoves ? ZEROING_BEST_MOVE : OK), bestValue; |
|
|
| return *result = OK, value; |
| } |
|
|
| } |
|
|
|
|
| |
| |
| |
| void Tablebases::init(const std::string& paths) { |
|
|
| TBTables.clear(); |
| MaxCardinality = 0; |
| TBFile::Paths = paths; |
|
|
| if (paths.empty() || paths == "<empty>") |
| return; |
|
|
| |
| int code = 0; |
| for (Square s = SQ_A1; s <= SQ_H8; ++s) |
| if (off_A1H8(s) < 0) |
| MapB1H1H7[s] = code++; |
|
|
| |
| std::vector<Square> diagonal; |
| code = 0; |
| for (Square s = SQ_A1; s <= SQ_D4; ++s) |
| if (off_A1H8(s) < 0 && file_of(s) <= FILE_D) |
| MapA1D1D4[s] = code++; |
|
|
| else if (!off_A1H8(s) && file_of(s) <= FILE_D) |
| diagonal.push_back(s); |
|
|
| |
| for (auto s : diagonal) |
| MapA1D1D4[s] = code++; |
|
|
| |
| |
| |
| std::vector<std::pair<int, Square>> bothOnDiagonal; |
| code = 0; |
| for (int idx = 0; idx < 10; idx++) |
| for (Square s1 = SQ_A1; s1 <= SQ_D4; ++s1) |
| if (MapA1D1D4[s1] == idx && (idx || s1 == SQ_B1)) |
| { |
| for (Square s2 = SQ_A1; s2 <= SQ_H8; ++s2) |
| if ((PseudoAttacks[KING][s1] | s1) & s2) |
| continue; |
|
|
| else if (!off_A1H8(s1) && off_A1H8(s2) > 0) |
| continue; |
|
|
| else if (!off_A1H8(s1) && !off_A1H8(s2)) |
| bothOnDiagonal.emplace_back(idx, s2); |
|
|
| else |
| MapKK[idx][s2] = code++; |
| } |
|
|
| |
| for (auto p : bothOnDiagonal) |
| MapKK[p.first][p.second] = code++; |
|
|
| |
| |
| Binomial[0][0] = 1; |
|
|
| for (int n = 1; n < 64; n++) |
| for (int k = 0; k < 6 && k <= n; ++k) |
| Binomial[k][n] = (k > 0 ? Binomial[k - 1][n - 1] : 0) |
| + (k < n ? Binomial[k ][n - 1] : 0); |
|
|
| |
| |
| |
| |
| int availableSquares = 47; |
|
|
| |
| |
| for (int leadPawnsCnt = 1; leadPawnsCnt <= 5; ++leadPawnsCnt) |
| for (File f = FILE_A; f <= FILE_D; ++f) |
| { |
| |
| |
| int idx = 0; |
|
|
| |
| |
| for (Rank r = RANK_2; r <= RANK_7; ++r) |
| { |
| Square sq = make_square(f, r); |
|
|
| |
| |
| |
| |
| |
| if (leadPawnsCnt == 1) |
| { |
| MapPawns[sq] = availableSquares--; |
| MapPawns[flip_file(sq)] = availableSquares--; |
| } |
| LeadPawnIdx[leadPawnsCnt][sq] = idx; |
| idx += Binomial[leadPawnsCnt - 1][MapPawns[sq]]; |
| } |
| |
| LeadPawnsSize[leadPawnsCnt][f] = idx; |
| } |
|
|
| |
| for (PieceType p1 = PAWN; p1 < KING; ++p1) { |
| TBTables.add({KING, p1, KING}); |
|
|
| for (PieceType p2 = PAWN; p2 <= p1; ++p2) { |
| TBTables.add({KING, p1, p2, KING}); |
| TBTables.add({KING, p1, KING, p2}); |
|
|
| for (PieceType p3 = PAWN; p3 < KING; ++p3) |
| TBTables.add({KING, p1, p2, KING, p3}); |
|
|
| for (PieceType p3 = PAWN; p3 <= p2; ++p3) { |
| TBTables.add({KING, p1, p2, p3, KING}); |
|
|
| for (PieceType p4 = PAWN; p4 <= p3; ++p4) { |
| TBTables.add({KING, p1, p2, p3, p4, KING}); |
|
|
| for (PieceType p5 = PAWN; p5 <= p4; ++p5) |
| TBTables.add({KING, p1, p2, p3, p4, p5, KING}); |
|
|
| for (PieceType p5 = PAWN; p5 < KING; ++p5) |
| TBTables.add({KING, p1, p2, p3, p4, KING, p5}); |
| } |
|
|
| for (PieceType p4 = PAWN; p4 < KING; ++p4) { |
| TBTables.add({KING, p1, p2, p3, KING, p4}); |
|
|
| for (PieceType p5 = PAWN; p5 <= p4; ++p5) |
| TBTables.add({KING, p1, p2, p3, KING, p4, p5}); |
| } |
| } |
|
|
| for (PieceType p3 = PAWN; p3 <= p1; ++p3) |
| for (PieceType p4 = PAWN; p4 <= (p1 == p3 ? p2 : p3); ++p4) |
| TBTables.add({KING, p1, p2, KING, p3, p4}); |
| } |
| } |
|
|
| sync_cout << "info string Found " << TBTables.size() << " tablebases" << sync_endl; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| WDLScore Tablebases::probe_wdl(Position& pos, ProbeState* result) { |
|
|
| *result = OK; |
| return search<false>(pos, result); |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| int Tablebases::probe_dtz(Position& pos, ProbeState* result) { |
|
|
| *result = OK; |
| WDLScore wdl = search<true>(pos, result); |
|
|
| if (*result == FAIL || wdl == WDLDraw) |
| return 0; |
|
|
| |
| |
| if (*result == ZEROING_BEST_MOVE) |
| return dtz_before_zeroing(wdl); |
|
|
| int dtz = probe_table<DTZ>(pos, result, wdl); |
|
|
| if (*result == FAIL) |
| return 0; |
|
|
| if (*result != CHANGE_STM) |
| return (dtz + 100 * (wdl == WDLBlessedLoss || wdl == WDLCursedWin)) * sign_of(wdl); |
|
|
| |
| |
| StateInfo st; |
| int minDTZ = 0xFFFF; |
|
|
| for (const Move move : MoveList<LEGAL>(pos)) |
| { |
| bool zeroing = pos.capture(move) || type_of(pos.moved_piece(move)) == PAWN; |
|
|
| pos.do_move(move, st); |
|
|
| |
| |
| |
| |
| dtz = zeroing ? -dtz_before_zeroing(search<false>(pos, result)) |
| : -probe_dtz(pos, result); |
|
|
| |
| if (dtz == 1 && pos.checkers() && MoveList<LEGAL>(pos).size() == 0) |
| minDTZ = 1; |
|
|
| |
| |
| if (!zeroing) |
| dtz += sign_of(dtz); |
|
|
| |
| if (dtz < minDTZ && sign_of(dtz) == sign_of(wdl)) |
| minDTZ = dtz; |
|
|
| pos.undo_move(move); |
|
|
| if (*result == FAIL) |
| return 0; |
| } |
|
|
| |
| return minDTZ == 0xFFFF ? -1 : minDTZ; |
| } |
|
|
|
|
| |
| |
| |
| bool Tablebases::root_probe(Position& pos, Search::RootMoves& rootMoves) { |
|
|
| ProbeState result; |
| StateInfo st; |
|
|
| |
| int cnt50 = pos.rule50_count(); |
|
|
| |
| bool rep = pos.has_repeated(); |
|
|
| int dtz, bound = Options["Syzygy50MoveRule"] ? (MAX_DTZ - 100) : 1; |
|
|
| |
| for (auto& m : rootMoves) |
| { |
| pos.do_move(m.pv[0], st); |
|
|
| |
| if (pos.rule50_count() == 0) |
| { |
| |
| WDLScore wdl = -probe_wdl(pos, &result); |
| dtz = dtz_before_zeroing(wdl); |
| } |
| else if (pos.is_draw(1)) |
| { |
| |
| |
| |
| |
| dtz = 0; |
| } |
| else |
| { |
| |
| dtz = -probe_dtz(pos, &result); |
| dtz = dtz > 0 ? dtz + 1 |
| : dtz < 0 ? dtz - 1 : dtz; |
| } |
|
|
| |
| if ( pos.checkers() |
| && dtz == 2 |
| && MoveList<LEGAL>(pos).size() == 0) |
| dtz = 1; |
|
|
| pos.undo_move(m.pv[0]); |
|
|
| if (result == FAIL) |
| return false; |
|
|
| |
| |
| int r = dtz > 0 ? (dtz + cnt50 <= 99 && !rep ? MAX_DTZ : MAX_DTZ - (dtz + cnt50)) |
| : dtz < 0 ? (-dtz * 2 + cnt50 < 100 ? -MAX_DTZ : -MAX_DTZ + (-dtz + cnt50)) |
| : 0; |
| m.tbRank = r; |
|
|
| |
| |
| |
| m.tbScore = r >= bound ? VALUE_MATE - MAX_PLY - 1 |
| : r > 0 ? Value((std::max( 3, r - (MAX_DTZ - 200)) * int(PawnValueEg)) / 200) |
| : r == 0 ? VALUE_DRAW |
| : r > -bound ? Value((std::min(-3, r + (MAX_DTZ - 200)) * int(PawnValueEg)) / 200) |
| : -VALUE_MATE + MAX_PLY + 1; |
| } |
|
|
| return true; |
| } |
|
|
|
|
| |
| |
| |
| |
| bool Tablebases::root_probe_wdl(Position& pos, Search::RootMoves& rootMoves) { |
|
|
| static const int WDL_to_rank[] = { -MAX_DTZ, -MAX_DTZ + 101, 0, MAX_DTZ - 101, MAX_DTZ }; |
|
|
| ProbeState result; |
| StateInfo st; |
| WDLScore wdl; |
|
|
| bool rule50 = Options["Syzygy50MoveRule"]; |
|
|
| |
| for (auto& m : rootMoves) |
| { |
| pos.do_move(m.pv[0], st); |
|
|
| if (pos.is_draw(1)) |
| wdl = WDLDraw; |
| else |
| wdl = -probe_wdl(pos, &result); |
|
|
| pos.undo_move(m.pv[0]); |
|
|
| if (result == FAIL) |
| return false; |
|
|
| m.tbRank = WDL_to_rank[wdl + 2]; |
|
|
| if (!rule50) |
| wdl = wdl > WDLDraw ? WDLWin |
| : wdl < WDLDraw ? WDLLoss : WDLDraw; |
| m.tbScore = WDL_to_value[wdl + 2]; |
| } |
|
|
| return true; |
| } |
|
|
| } |
|
|