From 718d5b0fc46fb25c7d0684a240c859e6899fec10 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Wed, 11 Nov 2026 18:28:36 +0300 Subject: [PATCH 1/4] [core] Make bitboards constexpr and iterable Add forward square iteration and enforce template-only node contracts with constexpr call-site guards. Capture exhaustive reference-table comparisons before replacing startup generators. --- Chess/BitBoard.h | 92 +++++++++----- Chess/MoveGenerator.cpp | 5 +- Chess/Position.cpp | 11 +- Chess/SearchImplementation.h | 115 ++++++++--------- Tests/BitboardTests.cpp | 39 ++++++ Tests/ConstantTableTests.cpp | 232 +++++++++++++++++++++++++++++++++++ 6 files changed, 401 insertions(+), 93 deletions(-) create mode 100644 Tests/BitboardTests.cpp create mode 100644 Tests/ConstantTableTests.cpp diff --git a/Chess/BitBoard.h b/Chess/BitBoard.h index c2b0f8e..ac2abf0 100644 --- a/Chess/BitBoard.h +++ b/Chess/BitBoard.h @@ -4,6 +4,7 @@ #include #include #include +#include using BitIndex = std::int8_t; @@ -32,27 +33,27 @@ class Bitboard { return !static_cast(value_); } - Bitboard &Set(const size_t pos) { + constexpr Bitboard &Set(const size_t pos) { value_ |= 1ull << pos; return *this; } - Bitboard &Set() { + constexpr Bitboard &Set() { value_ = ~0ull; return *this; } - Bitboard &Reset(const size_t pos) { + constexpr Bitboard &Reset(const size_t pos) { value_ &= ~(1ull << pos); return *this; } - Bitboard &Reset() { + constexpr Bitboard &Reset() { value_ = 0ull; return *this; } - Bitboard &Flip(const size_t pos) { + constexpr Bitboard &Flip(const size_t pos) { value_ ^= 1ull << pos; return *this; } @@ -63,63 +64,98 @@ class Bitboard { constexpr bool operator==(const Bitboard &other) const = default; - [[nodiscard]] size_t Count() const; + [[nodiscard]] constexpr size_t Count() const; - [[nodiscard]] BitIndex GetFirstBit() const; + [[nodiscard]] constexpr BitIndex GetFirstBit() const; - BitIndex PopFirstBit(); + constexpr BitIndex PopFirstBit(); - [[nodiscard]] bool MoreThanOne() const; + [[nodiscard]] constexpr bool MoreThanOne() const; constexpr Bitboard operator-() const; constexpr Bitboard operator-(const Bitboard &other) const; - Bitboard &operator-=(const Bitboard &other); + constexpr Bitboard &operator-=(const Bitboard &other); constexpr Bitboard operator*(const Bitboard &other) const; - Bitboard &operator*=(const Bitboard &other); + constexpr Bitboard &operator*=(const Bitboard &other); constexpr Bitboard operator&(const Bitboard &other) const; - Bitboard &operator&=(const Bitboard &other); + constexpr Bitboard &operator&=(const Bitboard &other); constexpr Bitboard operator|(const Bitboard &other) const; - Bitboard &operator|=(const Bitboard &other); + constexpr Bitboard &operator|=(const Bitboard &other); constexpr Bitboard operator^(const Bitboard &other) const; - Bitboard &operator^=(const Bitboard &other); + constexpr Bitboard &operator^=(const Bitboard &other); constexpr Bitboard operator~() const; constexpr Bitboard operator<<(size_t pos) const; - Bitboard &operator<<=(size_t pos); + constexpr Bitboard &operator<<=(size_t pos); constexpr Bitboard operator>>(size_t pos) const; - Bitboard &operator>>=(size_t pos); + constexpr Bitboard &operator>>=(size_t pos); [[nodiscard]] explicit constexpr operator std::uint64_t() const noexcept { return value_; } + class Iterator { + public: + using value_type = BitIndex; + using difference_type = std::ptrdiff_t; + using iterator_concept = std::forward_iterator_tag; + + constexpr Iterator() = default; + constexpr explicit Iterator(std::uint64_t remaining) : remaining_(remaining) {} + + [[nodiscard]] constexpr BitIndex operator*() const { + assert(remaining_ != 0); + return static_cast(std::countr_zero(remaining_)); + } + + constexpr Iterator& operator++() { + assert(remaining_ != 0); + remaining_ &= remaining_ - 1; + return *this; + } + + constexpr Iterator operator++(int) { + auto previous = *this; + ++*this; + return previous; + } + + constexpr bool operator==(const Iterator&) const = default; + + private: + std::uint64_t remaining_{}; + }; + + [[nodiscard]] constexpr Iterator begin() const { return Iterator{value_}; } + [[nodiscard]] constexpr Iterator end() const { return Iterator{}; } + private: std::uint64_t value_{}; }; -inline size_t Bitboard::Count() const { +constexpr size_t Bitboard::Count() const { return std::popcount(value_); } -inline BitIndex Bitboard::GetFirstBit() const { +constexpr BitIndex Bitboard::GetFirstBit() const { assert(Any()); return std::countr_zero(value_); } -inline BitIndex Bitboard::PopFirstBit() { +constexpr BitIndex Bitboard::PopFirstBit() { const BitIndex bit = GetFirstBit(); - Reset(bit); + value_ &= value_ - 1; return bit; } -inline bool Bitboard::MoreThanOne() const { +constexpr bool Bitboard::MoreThanOne() const { return value_ & (value_ - 1); // more effective than std::has_single_bit(value) && Any() } @@ -129,7 +165,7 @@ constexpr Bitboard Bitboard::operator-(const Bitboard &other) const { return Bitboard{value_ - other.value_}; // may (and will) overflow } -inline Bitboard &Bitboard::operator-=(const Bitboard &other) { +constexpr Bitboard &Bitboard::operator-=(const Bitboard &other) { value_ -= other.value_; return *this; } @@ -138,7 +174,7 @@ constexpr Bitboard Bitboard::operator*(const Bitboard &other) const { return Bitboard{value_ * other.value_}; // may (and will) overflow } -inline Bitboard &Bitboard::operator*=(const Bitboard &other) { +constexpr Bitboard &Bitboard::operator*=(const Bitboard &other) { value_ *= other.value_; return *this; } @@ -147,7 +183,7 @@ constexpr Bitboard Bitboard::operator&(const Bitboard &other) const { return Bitboard{value_ & other.value_}; } -inline Bitboard &Bitboard::operator&=(const Bitboard &other) { +constexpr Bitboard &Bitboard::operator&=(const Bitboard &other) { value_ &= other.value_; return *this; } @@ -156,7 +192,7 @@ constexpr Bitboard Bitboard::operator|(const Bitboard &other) const { return Bitboard{value_ | other.value_}; } -inline Bitboard &Bitboard::operator|=(const Bitboard &other) { +constexpr Bitboard &Bitboard::operator|=(const Bitboard &other) { value_ |= other.value_; return *this; } @@ -165,7 +201,7 @@ constexpr Bitboard Bitboard::operator^(const Bitboard &other) const { return Bitboard{value_ ^ other.value_}; } -inline Bitboard &Bitboard::operator^=(const Bitboard &other) { +constexpr Bitboard &Bitboard::operator^=(const Bitboard &other) { value_ ^= other.value_; return *this; } @@ -176,7 +212,7 @@ constexpr Bitboard Bitboard::operator<<(const size_t pos) const { return Bitboard{value_ << pos}; } -inline Bitboard &Bitboard::operator<<=(const size_t pos) { +constexpr Bitboard &Bitboard::operator<<=(const size_t pos) { value_ <<= pos; return *this; } @@ -185,7 +221,7 @@ constexpr Bitboard Bitboard::operator>>(const size_t pos) const { return Bitboard{value_ >> pos}; } -inline Bitboard &Bitboard::operator>>=(const size_t pos) { +constexpr Bitboard &Bitboard::operator>>=(const size_t pos) { value_ >>= pos; return *this; } diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index 2eded47..77e84f1 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -45,10 +45,7 @@ void MoveGenerator::GenerateMovesForPiece(Move*& moves, Position& position, static_assert(piece != Piece::kPawn && piece != Piece::kKing); const auto us = position.GetSideToMove(); - Bitboard pieces = position.GetPiecesByType(us); - - while (pieces.Any()) { - const auto from = pieces.PopFirstBit(); + for (const auto from : position.GetPiecesByType(us)) { GenerateMovesFromSquare(moves, position, from, target); } } diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 75939bf..0ffb09c 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -457,14 +457,14 @@ bool Position::IsLegal(const Move &move, Bitboard blockers) const { const auto obstacles = GetAllPieces() & ~SingleSquare(king_position) & ~SingleSquare(rook_position); - auto king_path = castling_squares_for_king_[us_idx][cs_idx]; + const auto king_path = castling_squares_for_king_[us_idx][cs_idx]; if (((king_path | castling_squares_for_rook_[us_idx][cs_idx]) & obstacles) .Any()) return false; - while (king_path.Any()) { - if (const auto square = king_path.PopFirstBit(); IsUnderAttack(square, us)) + for (const auto square : king_path) { + if (IsUnderAttack(square, us)) return false; } @@ -768,7 +768,7 @@ void Position::ComputePins(const Player us) const { const BitIndex king_square = GetKingSquare(us); - Bitboard snipers = + const Bitboard snipers = (AttackTable::GetAttackMap(king_square, kEmptyBoard) & (GetPiecesByType(them) | GetPiecesByType(them))) | @@ -777,8 +777,7 @@ void Position::ComputePins(const Player us) const { GetPiecesByType(them))); const Bitboard occupancy = GetAllPieces() ^ snipers; - while (snipers.Any()) { - const BitIndex square = snipers.PopFirstBit(); + for (const auto square : snipers) { const Bitboard blockers_between = Between(king_square, square) & occupancy; if (blockers_between.Any() && !blockers_between.MoreThanOne()) { irreversible_data_.blockers[us_idx] |= blockers_between; diff --git a/Chess/SearchImplementation.h b/Chess/SearchImplementation.h index 3d0acbe..f109acf 100644 --- a/Chess/SearchImplementation.h +++ b/Chess/SearchImplementation.h @@ -143,7 +143,7 @@ SearchNode::SearchNode( : state_(state), excluded_move_(excluded_move), exit_condition_(exit_condition), position_info_(searcher.GetPosition()), searcher_(searcher) { - assert(IsValidNodeType()); + static_assert(IsValidNodeType()); } template @@ -155,10 +155,12 @@ SearchResult SearchNode::StartSubsearch( (state.beta - state.alpha == 1)); assert(state.alpha < state.beta); - assert(expected_node_type != NodeType::kPV || node_type == NodeType::kPV); - assert(expected_node_type != NodeType::kCut || - (node_type == NodeType::kPV || node_type == NodeType::kAll)); - assert(expected_node_type != NodeType::kAll || node_type == NodeType::kCut); + static_assert(expected_node_type != NodeType::kPV || + node_type == NodeType::kPV); + static_assert(expected_node_type != NodeType::kCut || + (node_type == NodeType::kPV || node_type == NodeType::kAll)); + static_assert(expected_node_type != NodeType::kAll || + node_type == NodeType::kCut); return SearchNode{searcher_, state, exit_condition_}(); @@ -274,52 +276,54 @@ SearchResult SearchNode::operator()() { auto ¤t_position = GetCurrentPosition(); - if (CanNullMove()) { - searcher_.debug_info_.nmp_tries++; + if constexpr (node_type == NodeType::kCut) { + if (CanNullMove()) { + searcher_.debug_info_.nmp_tries++; - using NMPSettings = Settings::PruneParameters::NMPSettings; - const int reduction = - NMPSettings::kNullMoveReduction + - remaining_depth / NMPSettings::kDepthDivisor + - std::max((GetStaticEval() - beta) / NMPSettings::kEvalDivisor, 0); - const auto null_depth = - static_cast(std::max(0, remaining_depth - reduction)); + using NMPSettings = Settings::PruneParameters::NMPSettings; + const int reduction = + NMPSettings::kNullMoveReduction + + remaining_depth / NMPSettings::kDepthDivisor + + std::max((GetStaticEval() - beta) / NMPSettings::kEvalDivisor, 0); + const auto null_depth = + static_cast(std::max(0, remaining_depth - reduction)); - searcher_.SetPlayedNullMove(ply); - current_position.DoMove(NullMove{}); + searcher_.SetPlayedNullMove(ply); + current_position.DoMove(NullMove{}); - const auto eval_optional = - StartSubsearch({max_depth, null_depth, -beta, -beta + 1, - static_cast(ply + 1), true}); + const auto eval_optional = + StartSubsearch({max_depth, null_depth, -beta, -beta + 1, + static_cast(ply + 1), true}); - current_position.UndoMove(NullMove{}, position_info_.irreversible_data); + current_position.UndoMove(NullMove{}, position_info_.irreversible_data); - if (!eval_optional) return std::nullopt; + if (!eval_optional) return std::nullopt; - const auto &null_eval = -*eval_optional; - if (null_eval >= beta && - null_eval < kTablebaseWinValue - static_cast(kMaxSearchPly)) { - if (searcher_.nmp_min_ply_ || - remaining_depth < NMPSettings::kVerificationDepth) { - searcher_.debug_info_.nmp_cuts++; - return beta; - } + const auto &null_eval = -*eval_optional; + if (null_eval >= beta && + null_eval < kTablebaseWinValue - static_cast(kMaxSearchPly)) { + if (searcher_.nmp_min_ply_ || + remaining_depth < NMPSettings::kVerificationDepth) { + searcher_.debug_info_.nmp_cuts++; + return beta; + } - searcher_.nmp_min_ply_ = static_cast(ply + 3 * null_depth / 4); - ++searcher_.null_move_info_.verifications; - const auto verification = SearchNode{ - searcher_, - {max_depth, null_depth, beta - 1, beta, ply, - state_.was_previous_move_a_null}, - exit_condition_}(); - searcher_.nmp_min_ply_ = 0; - - if (!verification) return std::nullopt; - if (*verification >= beta) { - searcher_.debug_info_.nmp_cuts++; - return beta; + searcher_.nmp_min_ply_ = static_cast(ply + 3 * null_depth / 4); + ++searcher_.null_move_info_.verifications; + const auto verification = SearchNode{ + searcher_, + {max_depth, null_depth, beta - 1, beta, ply, + state_.was_previous_move_a_null}, + exit_condition_}(); + searcher_.nmp_min_ply_ = 0; + + if (!verification) return std::nullopt; + if (*verification >= beta) { + searcher_.debug_info_.nmp_cuts++; + return beta; + } + ++searcher_.null_move_info_.verification_fail_lows; } - ++searcher_.null_move_info_.verification_fail_lows; } } @@ -708,19 +712,20 @@ SearchResult SearchNode::PVSearch() { } assert(kIsPrincipalVariation || (beta - alpha == 1)); - if (kIsPrincipalVariation && - temp_eval > alpha) /* make a research (ZWS failed) */ - { - searcher_.debug_info_.zws_researches++; - temp_eval_optional = StartSubsearch( - {max_depth, static_cast(remaining_depth - 1), -beta, -alpha, - static_cast(ply + 1)}); - if (!temp_eval_optional) { - current_position.UndoMove(move, position_info_.irreversible_data); - return std::nullopt; - } + if constexpr (kIsPrincipalVariation) { + if (temp_eval > alpha) /* make a research (ZWS failed) */ + { + searcher_.debug_info_.zws_researches++; + temp_eval_optional = StartSubsearch( + {max_depth, static_cast(remaining_depth - 1), -beta, -alpha, + static_cast(ply + 1)}); + if (!temp_eval_optional) { + current_position.UndoMove(move, position_info_.irreversible_data); + return std::nullopt; + } - temp_eval = -*temp_eval_optional; + temp_eval = -*temp_eval_optional; + } } if (temp_eval > alpha) { diff --git a/Tests/BitboardTests.cpp b/Tests/BitboardTests.cpp new file mode 100644 index 0000000..c20934a --- /dev/null +++ b/Tests/BitboardTests.cpp @@ -0,0 +1,39 @@ +#include + +#include +#include + +#include "BitBoard.h" + +static_assert(sizeof(Bitboard) == sizeof(std::uint64_t)); +static_assert(std::ranges::forward_range); +static_assert(std::ranges::forward_range); +static_assert([] { + Bitboard board; + board.Set(0).Set(27).Set(63).Flip(27); + if (board.Count() != 2 || !board.MoreThanOne()) return false; + std::array squares{}; + size_t index = 0; + for (const auto square : board) squares[index++] = square; + if (squares != std::array{0, 63}) return false; + if (board.PopFirstBit() != 0 || board.GetFirstBit() != 63) return false; + board.Reset(63).Set().Reset(); + return board.None(); +}()); + +TEST(BitboardRange, MatchesPopFirstBitWithoutChangingBoard) { + for (const auto value : + {0ull, 1ull, 0x8000000000000000ull, 0xf00d0123456789abull, ~0ull}) { + const Bitboard board{value}; + auto remaining = board; + size_t count = 0; + for (const auto square : board) { + ASSERT_TRUE(remaining.Any()); + EXPECT_EQ(square, remaining.PopFirstBit()); + ++count; + } + EXPECT_TRUE(remaining.None()); + EXPECT_EQ(count, board.Count()); + EXPECT_EQ(static_cast(board), value); + } +} diff --git a/Tests/ConstantTableTests.cpp b/Tests/ConstantTableTests.cpp new file mode 100644 index 0000000..3017712 --- /dev/null +++ b/Tests/ConstantTableTests.cpp @@ -0,0 +1,232 @@ +#include + +#include + +#include "Attacks.h" +#include "Hasher.h" +#include "PSQT.h" + +using namespace SimpleChessEngine; + +namespace { +constexpr std::array kLegacyKing = {770ull, + 1797ull, + 3594ull, + 7188ull, + 14376ull, + 28752ull, + 57504ull, + 49216ull, + 197123ull, + 460039ull, + 920078ull, + 1840156ull, + 3680312ull, + 7360624ull, + 14721248ull, + 12599488ull, + 50463488ull, + 117769984ull, + 235539968ull, + 471079936ull, + 942159872ull, + 1884319744ull, + 3768639488ull, + 3225468928ull, + 12918652928ull, + 30149115904ull, + 60298231808ull, + 120596463616ull, + 241192927232ull, + 482385854464ull, + 964771708928ull, + 825720045568ull, + 3307175149568ull, + 7718173671424ull, + 15436347342848ull, + 30872694685696ull, + 61745389371392ull, + 123490778742784ull, + 246981557485568ull, + 211384331665408ull, + 846636838289408ull, + 1975852459884544ull, + 3951704919769088ull, + 7903409839538176ull, + 15806819679076352ull, + 31613639358152704ull, + 63227278716305408ull, + 54114388906344448ull, + 216739030602088448ull, + 505818229730443264ull, + 1011636459460886528ull, + 2023272918921773056ull, + 4046545837843546112ull, + 8093091675687092224ull, + 16186183351374184448ull, + 13853283560024178688ull, + 144959613005987840ull, + 362258295026614272ull, + 724516590053228544ull, + 1449033180106457088ull, + 2898066360212914176ull, + 5796132720425828352ull, + 11592265440851656704ull, + 4665729213955833856ull}; +constexpr std::array kLegacyKnight = {132096ull, + 329728ull, + 659712ull, + 1319424ull, + 2638848ull, + 5277696ull, + 10489856ull, + 4202496ull, + 33816580ull, + 84410376ull, + 168886289ull, + 337772578ull, + 675545156ull, + 1351090312ull, + 2685403152ull, + 1075839008ull, + 8657044482ull, + 21609056261ull, + 43234889994ull, + 86469779988ull, + 172939559976ull, + 345879119952ull, + 687463207072ull, + 275414786112ull, + 2216203387392ull, + 5531918402816ull, + 11068131838464ull, + 22136263676928ull, + 44272527353856ull, + 88545054707712ull, + 175990581010432ull, + 70506185244672ull, + 567348067172352ull, + 1416171111120896ull, + 2833441750646784ull, + 5666883501293568ull, + 11333767002587136ull, + 22667534005174272ull, + 45053588738670592ull, + 18049583422636032ull, + 145241105196122112ull, + 362539804446949376ull, + 725361088165576704ull, + 1450722176331153408ull, + 2901444352662306816ull, + 5802888705324613632ull, + 11533718717099671552ull, + 4620693356194824192ull, + 288234782788157440ull, + 576469569871282176ull, + 1224997833292120064ull, + 2449995666584240128ull, + 4899991333168480256ull, + 9799982666336960512ull, + 1152939783987658752ull, + 2305878468463689728ull, + 1128098930098176ull, + 2257297371824128ull, + 4796069720358912ull, + 9592139440717824ull, + 19184278881435648ull, + 38368557762871296ull, + 4679521487814656ull, + 9077567998918656ull}; + +constexpr std::array kDirections = {Compass::kNorthWest, Compass::kSouthWest, + Compass::kSouthEast, Compass::kNorthEast, + Compass::kNorth, Compass::kWest, + Compass::kSouth, Compass::kEast}; +} + +TEST(ConstantTables, LeapersMatchOriginalLiterals) { + for (BitIndex square = 0; square < 64; ++square) { + EXPECT_EQ(AttackTable::GetAttackMap(square, {}), + Bitboard{kLegacyKing[square]}); + EXPECT_EQ(AttackTable::GetAttackMap(square, {}), + Bitboard{kLegacyKnight[square]}); + } +} + +TEST(ConstantTables, GeometryMatchesOriginalGenerators) { + std::array, kBoardArea> between{}; + auto ray = between; + auto rook_between_reference = between; + for (BitIndex square = 0; square < 64; ++square) { + for (const auto direction : kDirections) { + const bool orthogonal = + direction == Compass::kNorth || direction == Compass::kSouth || + direction == Compass::kWest || direction == Compass::kEast; + Bitboard result{}; + BitIndex target = square; + for (Bitboard step{~kEmptyBoard}; step.Any(); result |= step) { + between[square][target] |= result; + if (orthogonal) rook_between_reference[square][target] = result; + step = DoShiftIfValid(target, direction).value_or(Bitboard{}); + } + target = square; + while (DoShiftIfValid(target, direction)) ray[square][target] |= result; + } + for (BitIndex target = 0; target < 64; ++target) { + EXPECT_EQ(Between(square, target), between[square][target]); + EXPECT_EQ(rook_between[square][target], + rook_between_reference[square][target]); + EXPECT_EQ(Ray(square, target), ray[square][target]); + } + } +} + +TEST(ConstantTables, PawnsMatchOriginalGenerator) { + for (auto color : {Player::kWhite, Player::kBlack}) { + for (BitIndex square = 0; square < 64; ++square) { + Bitboard expected{}; + for (const auto direction : + kPawnAttackDirections[static_cast(color)]) { + expected |= GetShiftIfValid(square, direction).value_or(Bitboard{}); + } + EXPECT_EQ(GetPawnAttacks(square, color), expected); + } + } +} + +TEST(ConstantTables, PsqtMatchesOriginalMirror) { + for (size_t piece = 0; piece < kPieceTypes; ++piece) { + for (BitIndex square = 0; square < 64; ++square) { + const auto [file, rank] = GetCoordinates(square); + EXPECT_EQ(kPSQT[1][piece][GetSquareIndex(file, 7 - rank)], + kPSQT[0][piece][square]); + } + } +} + +template +void CheckSliderSubsets() { + for (BitIndex square = 0; square < 64; ++square) { + Bitboard mask{}; + const size_t first = piece == Piece::kBishop ? 0 : 4; + for (size_t i = first; i < first + 4; ++i) { + auto target = square; + while (const auto step = DoShiftIfValid(target, kDirections[i])) { + if (GetShiftIfValid(target, kDirections[i])) mask |= *step; + } + } + Bitboard subset{}; + do { + ASSERT_EQ(AttackTable::GetAttackMap(square, subset), + GenerateAttackMask(square, subset)); + ASSERT_EQ(AttackTable::GetAttackMap(square, subset | ~mask), + GenerateAttackMask(square, subset)); + subset = (subset - mask) & mask; + } while (subset.Any()); + } +} + +TEST(ConstantTables, SliderSubsetsMatchOriginalGenerator) { + CheckSliderSubsets(); + CheckSliderSubsets(); +} From 5cfc99e8e310739c6e78b44e52f029f97463c33e Mon Sep 17 00:00:00 2001 From: nook0110 Date: Wed, 11 Nov 2026 18:58:42 +0300 Subject: [PATCH 2/4] [core] Generate fixed board and Zobrist tables at compile time Generate immutable leaper, pawn, geometry and mirrored PSQT tables and remove startup initialization calls. Preserve every original Zobrist key with constexpr MT19937-64 and independently verify the original output order against the standard generator. --- Chess/Attacks.cpp | 45 +++++----- Chess/Attacks.h | 162 +++++++---------------------------- Chess/Hasher.cpp | 5 ++ Chess/Hasher.h | 58 ++++++++++--- Chess/PSQT.h | 15 ++-- Chess/Position.cpp | 57 ++++++------ Chess/Position.h | 3 +- Chess/PositionFactory.h | 16 ++-- Chess/Utility.h | 82 +++++++++++------- Chess/main.cpp | 6 -- Tests/ConstantTableTests.cpp | 31 ++++++- Tests/Tests.cpp | 8 -- Tools/TablebaseBenchmark.cpp | 6 -- Tools/TablebaseProbe.cpp | 6 -- 14 files changed, 234 insertions(+), 266 deletions(-) create mode 100644 Chess/Hasher.cpp diff --git a/Chess/Attacks.cpp b/Chess/Attacks.cpp index 8e910bb..ba84d3e 100644 --- a/Chess/Attacks.cpp +++ b/Chess/Attacks.cpp @@ -39,33 +39,34 @@ Bitboard SimpleChessEngine::GenerateAttackMask(const BitIndex square, return result; } -template -void SimpleChessEngine::InitBetween() { - assert(IsWeakSlidingPiece(sliding_piece)); - for (BitIndex sq = 0; sq < static_cast(kBoardArea); ++sq) { - for (auto direction : GetStepDelta()) { - Bitboard result{}; - BitIndex temp = sq; - for (Bitboard step{~kEmptyBoard}; step.Any(); result |= step) { - if constexpr (sliding_piece == Piece::kBishop) - bishop_between[sq][temp] = result; - else - rook_between[sq][temp] = result; - step = DoShiftIfValid(temp, direction).value_or(Bitboard{}); - } - temp = sq; - while (DoShiftIfValid(temp, direction)) { - if constexpr (sliding_piece == Piece::kBishop) - bishop_ray[sq][temp] = result; - else - rook_ray[sq][temp] = result; +namespace { +consteval GeometryTables MakeGeometryTables() { + GeometryTables tables{}; + constexpr std::array directions = {Compass::kNorthWest, Compass::kSouthWest, + Compass::kSouthEast, Compass::kNorthEast, + Compass::kNorth, Compass::kWest, + Compass::kSouth, Compass::kEast}; + for (BitIndex square = 0; square < static_cast(kBoardArea); + ++square) { + for (const auto direction : directions) { + Bitboard between{}; + auto target = square; + while (const auto step = DoShiftIfValid(target, direction)) { + between |= *step; + tables.between[square][target] = between; } + target = square; + while (DoShiftIfValid(target, direction)) + tables.ray[square][target] = between; } } + return tables; } +} + +constinit const GeometryTables SimpleChessEngine::kGeometry = + MakeGeometryTables(); -template void SimpleChessEngine::InitBetween(); -template void SimpleChessEngine::InitBetween(); template Bitboard SimpleChessEngine::GenerateAttackMask( BitIndex, Bitboard); template Bitboard SimpleChessEngine::GenerateAttackMask( diff --git a/Chess/Attacks.h b/Chess/Attacks.h index e128139..b245e3c 100644 --- a/Chess/Attacks.h +++ b/Chess/Attacks.h @@ -8,6 +8,33 @@ #include "Utility.h" namespace SimpleChessEngine { +template + requires(piece == Piece::kKing || piece == Piece::kKnight) +consteval auto MakeLeaperAttacks() { + std::array attacks{}; + for (BitIndex square = 0; square < static_cast(kBoardArea); + ++square) { + const auto [file, rank] = GetCoordinates(square); + for (int df = -2; df <= 2; ++df) { + for (int dr = -2; dr <= 2; ++dr) { + const int file_distance = df < 0 ? -df : df; + const int rank_distance = dr < 0 ? -dr : dr; + const bool attacks_square = + piece == Piece::kKing ? std::max(file_distance, rank_distance) == 1 + : file_distance * rank_distance == 2; + if (attacks_square && file + df >= 0 && file + df < kLineSize && + rank + dr >= 0 && rank + dr < kLineSize) { + attacks[square].Set(GetSquareIndex(file + df, rank + dr)); + } + } + } + } + return attacks; +} + +inline constexpr auto kKingAttacks = MakeLeaperAttacks(); +inline constexpr auto kKnightAttacks = MakeLeaperAttacks(); + template constexpr size_t GetMagicShift() { assert(IsWeakSlidingPiece(sliding_piece)); @@ -60,139 +87,11 @@ size_t AttackTable::GetAttackTableAddress(const BitIndex square, template Bitboard AttackTable::GetAttackMap(const BitIndex square, const Bitboard occupied) { - static constexpr std::array king_attacks = {770ull, - 1797ull, - 3594ull, - 7188ull, - 14376ull, - 28752ull, - 57504ull, - 49216ull, - 197123ull, - 460039ull, - 920078ull, - 1840156ull, - 3680312ull, - 7360624ull, - 14721248ull, - 12599488ull, - 50463488ull, - 117769984ull, - 235539968ull, - 471079936ull, - 942159872ull, - 1884319744ull, - 3768639488ull, - 3225468928ull, - 12918652928ull, - 30149115904ull, - 60298231808ull, - 120596463616ull, - 241192927232ull, - 482385854464ull, - 964771708928ull, - 825720045568ull, - 3307175149568ull, - 7718173671424ull, - 15436347342848ull, - 30872694685696ull, - 61745389371392ull, - 123490778742784ull, - 246981557485568ull, - 211384331665408ull, - 846636838289408ull, - 1975852459884544ull, - 3951704919769088ull, - 7903409839538176ull, - 15806819679076352ull, - 31613639358152704ull, - 63227278716305408ull, - 54114388906344448ull, - 216739030602088448ull, - 505818229730443264ull, - 1011636459460886528ull, - 2023272918921773056ull, - 4046545837843546112ull, - 8093091675687092224ull, - 16186183351374184448ull, - 13853283560024178688ull, - 144959613005987840ull, - 362258295026614272ull, - 724516590053228544ull, - 1449033180106457088ull, - 2898066360212914176ull, - 5796132720425828352ull, - 11592265440851656704ull, - 4665729213955833856ull}; - static constexpr std::array knight_attacks = {132096ull, - 329728ull, - 659712ull, - 1319424ull, - 2638848ull, - 5277696ull, - 10489856ull, - 4202496ull, - 33816580ull, - 84410376ull, - 168886289ull, - 337772578ull, - 675545156ull, - 1351090312ull, - 2685403152ull, - 1075839008ull, - 8657044482ull, - 21609056261ull, - 43234889994ull, - 86469779988ull, - 172939559976ull, - 345879119952ull, - 687463207072ull, - 275414786112ull, - 2216203387392ull, - 5531918402816ull, - 11068131838464ull, - 22136263676928ull, - 44272527353856ull, - 88545054707712ull, - 175990581010432ull, - 70506185244672ull, - 567348067172352ull, - 1416171111120896ull, - 2833441750646784ull, - 5666883501293568ull, - 11333767002587136ull, - 22667534005174272ull, - 45053588738670592ull, - 18049583422636032ull, - 145241105196122112ull, - 362539804446949376ull, - 725361088165576704ull, - 1450722176331153408ull, - 2901444352662306816ull, - 5802888705324613632ull, - 11533718717099671552ull, - 4620693356194824192ull, - 288234782788157440ull, - 576469569871282176ull, - 1224997833292120064ull, - 2449995666584240128ull, - 4899991333168480256ull, - 9799982666336960512ull, - 1152939783987658752ull, - 2305878468463689728ull, - 1128098930098176ull, - 2257297371824128ull, - 4796069720358912ull, - 9592139440717824ull, - 19184278881435648ull, - 38368557762871296ull, - 4679521487814656ull, - 9077567998918656ull}; if constexpr (piece == Piece::kKnight) { - return Bitboard{knight_attacks[square]}; + return kKnightAttacks[square]; } if constexpr (piece == Piece::kKing) { - return Bitboard{king_attacks[square]}; + return kKingAttacks[square]; } if constexpr (piece == Piece::kQueen) { return AttackTable::GetAttackMap(square, occupied) | @@ -211,9 +110,6 @@ extern template class AttackTable; extern template class AttackTable; extern template class AttackTable; -template -void InitBetween(); - template [[nodiscard]] Bitboard GenerateAttackMask( const BitIndex square, const Bitboard occupancy = kEmptyBoard); diff --git a/Chess/Hasher.cpp b/Chess/Hasher.cpp new file mode 100644 index 0000000..6be2c65 --- /dev/null +++ b/Chess/Hasher.cpp @@ -0,0 +1,5 @@ +#include "Hasher.h" + +namespace SimpleChessEngine { +constinit const Hasher kZobristKeys{Mt19937_64{0xb00b1e5}}; +} diff --git a/Chess/Hasher.h b/Chess/Hasher.h index 346dd93..966e97d 100644 --- a/Chess/Hasher.h +++ b/Chess/Hasher.h @@ -1,7 +1,5 @@ #pragma once -#include #include -#include #include "Utility.h" @@ -10,25 +8,63 @@ class Position; using Hash = std::uint64_t; +class Mt19937_64 { + public: + constexpr explicit Mt19937_64(Hash seed) { + state_[0] = seed; + for (size_t i = 1; i < state_.size(); ++i) { + const auto previous = state_[i - 1]; + state_[i] = 6364136223846793005ull * (previous ^ (previous >> 62)) + i; + } + } + + [[nodiscard]] constexpr Hash operator()() { + if (index_ == state_.size()) Twist(); + auto value = state_[index_++]; + value ^= (value >> 29) & 0x5555555555555555ull; + value ^= (value << 17) & 0x71d67fffeda60000ull; + value ^= (value << 37) & 0xfff7eee000000000ull; + return value ^ (value >> 43); + } + + private: + constexpr void Twist() { + constexpr Hash kLowerMask = (Hash{1} << 31) - 1; + constexpr Hash kUpperMask = ~kLowerMask; + for (size_t i = 0; i < state_.size(); ++i) { + const auto joined = (state_[i] & kUpperMask) | + (state_[(i + 1) % state_.size()] & kLowerMask); + state_[i] = state_[(i + kRecurrenceOffset) % state_.size()] ^ + (joined >> 1) ^ ((joined & 1) ? 0xb5026f5aa96619e9ull : 0); + } + index_ = 0; + } + + static constexpr size_t kStateSize = 312; + static constexpr size_t kRecurrenceOffset = 156; + std::array state_{}; + size_t index_ = state_.size(); +}; + struct Hasher { template explicit constexpr Hasher(RNG generator) { - auto generator_reference = std::reference_wrapper(generator); + const auto fill = [&generator](auto& values) { + for (auto& value : values) value = generator(); + }; for (auto& piece_type : psqt_hash) { for (auto& colored_board : piece_type) { - std::generate(colored_board.begin(), colored_board.end(), - generator_reference); + fill(colored_board); } } - std::generate(en_croissant_hash.begin(), en_croissant_hash.end(), - generator_reference); + fill(en_croissant_hash); for (auto& color : cr_hash) { - std::generate(color.begin(), color.end(), generator_reference); + fill(color); } - stm_hash = generator_reference(); + stm_hash = generator(); } - bool operator==(const Hasher&) const = default; + constexpr bool operator==(const Hasher&) const = default; std::array, kColors>, kPieceTypes> psqt_hash{}; @@ -36,4 +72,6 @@ struct Hasher { std::array, kColors> cr_hash{}; Hash stm_hash; }; +extern const Hasher kZobristKeys; + } // namespace SimpleChessEngine diff --git a/Chess/PSQT.h b/Chess/PSQT.h index 70fab4a..f2e4ae8 100644 --- a/Chess/PSQT.h +++ b/Chess/PSQT.h @@ -4,9 +4,10 @@ namespace SimpleChessEngine { // clang-format off - inline std::array, kPieceTypes>, +consteval auto MakePSQT() { + std::array, kPieceTypes>, kColors> - kPSQT = { { + table = { { // White pieces table {{// Empty squares values are irrelevant since kNone is not being placed // or removed at any time @@ -81,19 +82,21 @@ namespace SimpleChessEngine { // Black pieces table is initialized symmetrically to the white pieces // table } }; -// clang-format on + // clang-format on -inline void InitPSQT() { for (auto piece : {Piece::kPawn, Piece::kKnight, Piece::kBishop, Piece::kRook, Piece::kQueen, Piece::kKing}) { for (BitIndex square = 0; square < static_cast(kBoardArea); ++square) { const auto [file, rank] = GetCoordinates(square); const BitIndex new_square = GetSquareIndex(file, 7 - rank); - kPSQT[static_cast(Player::kBlack)][static_cast(piece)] - [new_square] = kPSQT[static_cast(Player::kWhite)] + table[static_cast(Player::kBlack)][static_cast(piece)] + [new_square] = table[static_cast(Player::kWhite)] [static_cast(piece)][square]; } } + return table; } + +inline constexpr auto kPSQT = MakePSQT(); } // namespace SimpleChessEngine diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 0ffb09c..e2c1773 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -19,7 +19,6 @@ template Bitboard Position::GetPiecesByType(Player player) const; template Bitboard Position::GetPiecesByType(Player player) const; template Bitboard Position::GetPiecesByType(Player player) const; -const Hasher Position::hasher_{std::mt19937_64(0xb00b1e5)}; Eval Position::SimpleMaterialEval() const { return evaluation_data_.material[static_cast(side_to_move_)].eval[0] - @@ -49,7 +48,7 @@ void Position::PlacePiece(const BitIndex square, const Piece piece, evaluation_data_.psqt[color_idx] += kPSQT[color_idx][piece_idx][square]; if (piece != Piece::kPawn) evaluation_data_.non_pawn_material += kPieceValues[piece_idx].eval[0]; - hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][square]; + hash_ ^= kZobristKeys.psqt_hash[piece_idx][color_idx][square]; } /** @@ -74,7 +73,7 @@ void Position::RemovePiece(const BitIndex square, const Player color) { evaluation_data_.psqt[color_idx] -= kPSQT[color_idx][piece_idx][square]; if (piece != Piece::kPawn) evaluation_data_.non_pawn_material -= kPieceValues[piece_idx].eval[0]; - hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][square]; + hash_ ^= kZobristKeys.psqt_hash[piece_idx][color_idx][square]; } void Position::MovePiece(const BitIndex from, const BitIndex to, @@ -94,19 +93,20 @@ void Position::MovePiece(const BitIndex from, const BitIndex to, board_[to] = piece; evaluation_data_.psqt[color_idx] -= kPSQT[color_idx][piece_idx][from]; evaluation_data_.psqt[color_idx] += kPSQT[color_idx][piece_idx][to]; - hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][from]; - hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][to]; + hash_ ^= kZobristKeys.psqt_hash[piece_idx][color_idx][from]; + hash_ ^= kZobristKeys.psqt_hash[piece_idx][color_idx][to]; } void Position::DoMove(const Move &move) { irreversible_data_.pins_valid = {}; if (const auto &ep_square = irreversible_data_.en_croissant_square; ep_square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(ep_square.value()).first]; + hash_ ^= + kZobristKeys.en_croissant_hash[GetCoordinates(ep_square.value()).first]; irreversible_data_.en_croissant_square.reset(); } for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( + hash_ ^= kZobristKeys.cr_hash[static_cast( color)][irreversible_data_.castling_rights[static_cast(color)] .to_ulong()]; } @@ -185,7 +185,7 @@ void Position::DoMove(const Move &move) { if (piece_to_move == Piece::kPawn && std::abs(from - to) == 16) { const BitIndex passed_square = std::midpoint(from, to); if ((GetAllPawnAttacks(them) & SingleSquare(passed_square)).Any()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(from).first]; + hash_ ^= kZobristKeys.en_croissant_hash[GetCoordinates(from).first]; irreversible_data_.en_croissant_square = passed_square; } } @@ -217,12 +217,12 @@ void Position::DoMove(const Move &move) { } for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( + hash_ ^= kZobristKeys.cr_hash[static_cast( color)][irreversible_data_.castling_rights[static_cast(color)] .to_ulong()]; } side_to_move_ = Flip(side_to_move_); - hash_ ^= hasher_.stm_hash; + hash_ ^= kZobristKeys.stm_hash; // 50-move rule: reset counter if it's a pawn move or a capture const bool resets_fifty_move = @@ -234,11 +234,12 @@ void Position::DoMove(const Move &move) { void SimpleChessEngine::Position::DoMove(NullMove) { if (const auto &ep_square = irreversible_data_.en_croissant_square; ep_square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(ep_square.value()).first]; + hash_ ^= + kZobristKeys.en_croissant_hash[GetCoordinates(ep_square.value()).first]; irreversible_data_.en_croissant_square.reset(); } side_to_move_ = Flip(side_to_move_); - hash_ ^= hasher_.stm_hash; + hash_ ^= kZobristKeys.stm_hash; nnue_.Push(); history_stack_.Push(hash_, false); @@ -248,12 +249,13 @@ void SimpleChessEngine::Position::DoMove(NullMove) { void Position::UndoMove(const Move &move, const IrreversibleData &data) { const auto &ep_square = irreversible_data_.en_croissant_square; for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( + hash_ ^= kZobristKeys.cr_hash[static_cast( color)][irreversible_data_.castling_rights[static_cast(color)] .to_ulong()]; } if (ep_square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(ep_square.value()).first]; + hash_ ^= + kZobristKeys.en_croissant_hash[GetCoordinates(ep_square.value()).first]; } const auto from = move.From(); @@ -265,14 +267,16 @@ void Position::UndoMove(const Move &move, const IrreversibleData &data) { irreversible_data_ = data; for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( + hash_ ^= kZobristKeys.cr_hash[static_cast( color)][irreversible_data_.castling_rights[static_cast(color)] .to_ulong()]; } if (irreversible_data_.en_croissant_square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(irreversible_data_.en_croissant_square.value()).first]; + hash_ ^= kZobristKeys.en_croissant_hash + [GetCoordinates(irreversible_data_.en_croissant_square.value()) + .first]; } - hash_ ^= hasher_.stm_hash; + hash_ ^= kZobristKeys.stm_hash; side_to_move_ = Flip(side_to_move_); if (move.IsEnPassant()) { @@ -324,9 +328,10 @@ void SimpleChessEngine::Position::UndoMove(NullMove, irreversible_data_ = data; const auto &ep_square = irreversible_data_.en_croissant_square; if (ep_square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(ep_square.value()).first]; + hash_ ^= + kZobristKeys.en_croissant_hash[GetCoordinates(ep_square.value()).first]; } - hash_ ^= hasher_.stm_hash; + hash_ ^= kZobristKeys.stm_hash; side_to_move_ = Flip(side_to_move_); nnue_.Pop(); @@ -474,9 +479,10 @@ bool Position::IsLegal(const Move &move, Bitboard blockers) const { void Position::SetCastlingRights( const std::array, 2> &castling_rights) { for (size_t color = 0; color < kColors; ++color) { - hash_ ^= hasher_.cr_hash[color][irreversible_data_.castling_rights[color] - .to_ulong()]; - hash_ ^= hasher_.cr_hash[color][castling_rights[color].to_ulong()]; + hash_ ^= kZobristKeys + .cr_hash[color] + [irreversible_data_.castling_rights[color].to_ulong()]; + hash_ ^= kZobristKeys.cr_hash[color][castling_rights[color].to_ulong()]; } irreversible_data_.castling_rights = castling_rights; } @@ -487,12 +493,13 @@ void Position::SetEnCroissantSquare(std::optional square) { square.reset(); } if (irreversible_data_.en_croissant_square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates( - *irreversible_data_.en_croissant_square).first]; + hash_ ^= + kZobristKeys.en_croissant_hash + [GetCoordinates(*irreversible_data_.en_croissant_square).first]; } irreversible_data_.en_croissant_square = square; if (square.has_value()) { - hash_ ^= hasher_.en_croissant_hash[GetCoordinates(*square).first]; + hash_ ^= kZobristKeys.en_croissant_hash[GetCoordinates(*square).first]; } } diff --git a/Chess/Position.h b/Chess/Position.h index c2faaa7..1db523a 100644 --- a/Chess/Position.h +++ b/Chess/Position.h @@ -207,7 +207,7 @@ class Position { void SetSideToMove(const Player player) { if (side_to_move_ == player) return; side_to_move_ = player; - hash_ ^= hasher_.stm_hash; + hash_ ^= kZobristKeys.stm_hash; nnue_.InvalidateOutput(); } @@ -358,7 +358,6 @@ class Position { std::array, kColors> castling_squares_for_king_{}; std::array, kColors> castling_squares_for_rook_{}; - const static Hasher hasher_; Hash hash_{}; mutable Nnue::AccumulatorStack nnue_; diff --git a/Chess/PositionFactory.h b/Chess/PositionFactory.h index 8d9466a..822103f 100644 --- a/Chess/PositionFactory.h +++ b/Chess/PositionFactory.h @@ -148,15 +148,15 @@ inline Position PositionFactory::operator()(const std::string &fen) const { position.SetKingPositions(kings); position.SetRookPositions(rooks); std::array, kColors> cs_king = { - {{rook_between[kings[0]][kKingCastlingDestination[0][0]], - rook_between[kings[0]][kKingCastlingDestination[0][1]]}, - {rook_between[kings[1]][kKingCastlingDestination[1][0]], - rook_between[kings[1]][kKingCastlingDestination[1][1]]}}}; + {{RookBetween(kings[0], kKingCastlingDestination[0][0]), + RookBetween(kings[0], kKingCastlingDestination[0][1])}, + {RookBetween(kings[1], kKingCastlingDestination[1][0]), + RookBetween(kings[1], kKingCastlingDestination[1][1])}}}; std::array, kColors> cs_rook = { - {{rook_between[rooks[0][0]][kRookCastlingDestination[0][0]], - rook_between[rooks[0][1]][kRookCastlingDestination[0][1]]}, - {rook_between[rooks[1][0]][kRookCastlingDestination[1][0]], - rook_between[rooks[1][1]][kRookCastlingDestination[1][1]]}}}; + {{RookBetween(rooks[0][0], kRookCastlingDestination[0][0]), + RookBetween(rooks[0][1], kRookCastlingDestination[0][1])}, + {RookBetween(rooks[1][0], kRookCastlingDestination[1][0]), + RookBetween(rooks[1][1], kRookCastlingDestination[1][1])}}}; position.SetCastlingSquares(cs_king, cs_rook); position.Init(halfmove_clock, fullmove_number); diff --git a/Chess/Utility.h b/Chess/Utility.h index a4ec05f..af1780a 100644 --- a/Chess/Utility.h +++ b/Chess/Utility.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -80,11 +81,15 @@ using Coordinates = std::pair; return std::abs(x_first - x_second) + std::abs(y_first - y_second); } -[[nodiscard]] inline int KingDistance(const BitIndex first, - const BitIndex second) { +[[nodiscard]] constexpr int KingDistance(const BitIndex first, + const BitIndex second) { const auto [x_first, y_first] = GetCoordinates(first); const auto [x_second, y_second] = GetCoordinates(second); - return std::max(std::abs(x_first - x_second), std::abs(y_first - y_second)); + const int file_distance = + x_first > x_second ? x_first - x_second : x_second - x_first; + const int rank_distance = + y_first > y_second ? y_first - y_second : y_second - y_first; + return std::max(file_distance, rank_distance); } enum class CastlingRights : std::uint8_t { @@ -112,8 +117,8 @@ constexpr Compass Invert(const Compass direction) { return static_cast(-static_cast(direction)); } -[[nodiscard]] inline Bitboard Shift(const Bitboard bb, - const Compass direction) { +[[nodiscard]] constexpr Bitboard Shift(const Bitboard bb, + const Compass direction) { switch (direction) { case Compass::kNorth: return bb << kLineSize; @@ -198,25 +203,25 @@ consteval PawnSpanTables MakePawnSpanTables() { inline constexpr PawnSpanTables kPawnSpans = MakePawnSpanTables(); -[[nodiscard]] inline bool IsOk(const BitIndex square) { +[[nodiscard]] constexpr bool IsOk(const BitIndex square) { return 0 <= square && square < static_cast(kBoardArea); } -[[nodiscard]] inline Bitboard SingleSquare(const BitIndex square_index) { +[[nodiscard]] constexpr Bitboard SingleSquare(const BitIndex square_index) { return Bitboard{1ull << square_index}; } -[[nodiscard]] inline bool IsAdjacent(const BitIndex sq_first, - const BitIndex sq_second) { +[[nodiscard]] constexpr bool IsAdjacent(const BitIndex sq_first, + const BitIndex sq_second) { return KingDistance(sq_first, sq_second) == 1; } -[[nodiscard]] inline bool IsShiftValid(const BitIndex shifted_square, - const BitIndex square) { +[[nodiscard]] constexpr bool IsShiftValid(const BitIndex shifted_square, + const BitIndex square) { return IsOk(shifted_square) && IsAdjacent(square, shifted_square); } -[[nodiscard]] inline std::optional GetShiftIfValid( +[[nodiscard]] constexpr std::optional GetShiftIfValid( const BitIndex square, const Compass shift) { const BitIndex new_square = Shift(square, shift); return IsShiftValid(new_square, square) @@ -224,7 +229,7 @@ inline constexpr PawnSpanTables kPawnSpans = MakePawnSpanTables(); : std::nullopt; } -[[nodiscard]] inline std::optional DoShiftIfValid( +[[nodiscard]] constexpr std::optional DoShiftIfValid( BitIndex& square, const Compass shift) { const BitIndex copy = square; square += static_cast(shift); @@ -253,39 +258,50 @@ inline constexpr PawnSpanTables kPawnSpans = MakePawnSpanTables(); constexpr std::array kCheckers = {Piece::kKnight, Piece::kBishop, Piece::kRook, Piece::kQueen}; -inline std::array, kBoardArea> - bishop_between{}; -inline std::array, kBoardArea> rook_between{}; -inline std::array, kBoardArea> bishop_ray{}; -inline std::array, kBoardArea> rook_ray{}; +using SquareTable = std::array, kBoardArea>; + +struct GeometryTables { + SquareTable between{}; + SquareTable ray{}; +}; + +extern const GeometryTables kGeometry; -inline Bitboard Between(const BitIndex from, const BitIndex to) { - return bishop_between[from][to] | rook_between[from][to]; +[[nodiscard]] inline Bitboard Between(const BitIndex from, const BitIndex to) { + return kGeometry.between[from][to]; } -inline Bitboard Ray(const BitIndex from, const BitIndex to) { - return bishop_ray[from][to] | rook_ray[from][to]; +[[nodiscard]] inline Bitboard RookBetween(const BitIndex from, + const BitIndex to) { + const auto [from_file, from_rank] = GetCoordinates(from); + const auto [to_file, to_rank] = GetCoordinates(to); + if (from_file != to_file && from_rank != to_rank) return kEmptyBoard; + return Between(from, to); } -inline std::array, kColors> pawn_attacks{}; +[[nodiscard]] inline Bitboard Ray(const BitIndex from, const BitIndex to) { + return kGeometry.ray[from][to]; +} -inline void InitPawnAttacks() { - for (auto color : {Player::kWhite, Player::kBlack}) { +consteval auto MakePawnAttacks() { + std::array, kColors> attacks{}; + for (size_t color = 0; color < kColors; ++color) { for (BitIndex square = 0; square < static_cast(kBoardArea); ++square) { - Bitboard res{}; - for (const auto step : - kPawnAttackDirections[static_cast(color)]) { - res |= GetShiftIfValid(square, step).value_or(Bitboard{}); + for (const auto direction : kPawnAttackDirections[color]) { + attacks[color][square] |= + GetShiftIfValid(square, direction).value_or(Bitboard{}); } - pawn_attacks[static_cast(color)][square] = res; } } + return attacks; } -[[nodiscard]] inline Bitboard GetPawnAttacks(const BitIndex square, - const Player side) { - return pawn_attacks[static_cast(side)][square]; +inline constexpr auto kPawnAttacks = MakePawnAttacks(); + +[[nodiscard]] constexpr Bitboard GetPawnAttacks(const BitIndex square, + const Player side) { + return kPawnAttacks[static_cast(side)][square]; } [[nodiscard]] inline std::string DrawBitboard(const Bitboard b) { diff --git a/Chess/main.cpp b/Chess/main.cpp index eef419e..555b24c 100644 --- a/Chess/main.cpp +++ b/Chess/main.cpp @@ -1,8 +1,6 @@ #include -#include "Attacks.h" #include "Nnue/Nnue.h" -#include "PSQT.h" #include "Settings.h" #include "UciCommunicator.h" @@ -35,10 +33,6 @@ std::string program_info() { } int main(int argc, char **argv) { - SimpleChessEngine::InitBetween(); - SimpleChessEngine::InitBetween(); - SimpleChessEngine::InitPawnAttacks(); - SimpleChessEngine::InitPSQT(); static_cast( SimpleChessEngine::Nnue::Load(SimpleChessEngine::Nnue::kDefaultEvalFile)); diff --git a/Tests/ConstantTableTests.cpp b/Tests/ConstantTableTests.cpp index 3017712..d161c9f 100644 --- a/Tests/ConstantTableTests.cpp +++ b/Tests/ConstantTableTests.cpp @@ -138,6 +138,9 @@ constexpr std::array kLegacyKnight = {132096ull, 4679521487814656ull, 9077567998918656ull}; +static_assert(kLegacyKing.size() == kBoardArea); +static_assert(kLegacyKnight.size() == kBoardArea); + constexpr std::array kDirections = {Compass::kNorthWest, Compass::kSouthWest, Compass::kSouthEast, Compass::kNorthEast, Compass::kNorth, Compass::kWest, @@ -174,7 +177,7 @@ TEST(ConstantTables, GeometryMatchesOriginalGenerators) { } for (BitIndex target = 0; target < 64; ++target) { EXPECT_EQ(Between(square, target), between[square][target]); - EXPECT_EQ(rook_between[square][target], + EXPECT_EQ(RookBetween(square, target), rook_between_reference[square][target]); EXPECT_EQ(Ray(square, target), ray[square][target]); } @@ -230,3 +233,29 @@ TEST(ConstantTables, SliderSubsetsMatchOriginalGenerator) { CheckSliderSubsets(); CheckSliderSubsets(); } + +TEST(ConstantTables, ZobristMatchesStandardGeneratorIncludingUnusedEntries) { + constexpr Hasher keys{Mt19937_64{0xb00b1e5}}; + EXPECT_EQ(keys, kZobristKeys); + std::mt19937_64 expected{0xb00b1e5}; + for (const auto& piece : keys.psqt_hash) { + for (const auto& color : piece) { + for (const auto key : color) EXPECT_EQ(key, expected()); + } + } + for (const auto key : keys.en_croissant_hash) EXPECT_EQ(key, expected()); + for (const auto& color : keys.cr_hash) { + for (const auto key : color) EXPECT_EQ(key, expected()); + } + EXPECT_EQ(keys.stm_hash, expected()); +} + +TEST(ConstantTables, ConstexprMersenneTwisterMatchesStandardAcrossStateCycles) { + for (const Hash seed : {Hash{0}, Hash{0xb00b1e5}, ~Hash{0}}) { + Mt19937_64 actual{seed}; + std::mt19937_64 expected{seed}; + for (size_t i = 0; i < 5000; ++i) { + ASSERT_EQ(actual(), expected()) << "seed " << seed << ", output " << i; + } + } +} diff --git a/Tests/Tests.cpp b/Tests/Tests.cpp index 02fb9bb..cbc112c 100644 --- a/Tests/Tests.cpp +++ b/Tests/Tests.cpp @@ -1,15 +1,7 @@ #include -#include "Attacks.h" -#include "PSQT.h" - int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); - SimpleChessEngine::InitBetween(); - SimpleChessEngine::InitBetween(); - SimpleChessEngine::InitPawnAttacks(); - SimpleChessEngine::InitPSQT(); - return RUN_ALL_TESTS(); } \ No newline at end of file diff --git a/Tools/TablebaseBenchmark.cpp b/Tools/TablebaseBenchmark.cpp index 289eb6c..c880b1e 100644 --- a/Tools/TablebaseBenchmark.cpp +++ b/Tools/TablebaseBenchmark.cpp @@ -9,9 +9,7 @@ #include #include -#include "Attacks.h" #include "MoveGenerator.h" -#include "PSQT.h" #include "PositionFactory.h" #include "SyzygyTablebase.h" @@ -56,10 +54,6 @@ int main(int argc, char** argv) { const std::size_t threads = argc >= 4 ? std::stoull(argv[3]) : 1; if (probes == 0 || threads == 0) return 2; - InitBetween(); - InitBetween(); - InitPawnAttacks(); - InitPSQT(); const auto tablebase = Tablebase::Syzygy::Open(std::filesystem::path{argv[1]}); if (!tablebase) return 1; diff --git a/Tools/TablebaseProbe.cpp b/Tools/TablebaseProbe.cpp index 5b12cd6..74f2e10 100644 --- a/Tools/TablebaseProbe.cpp +++ b/Tools/TablebaseProbe.cpp @@ -3,18 +3,12 @@ #include #include -#include "Attacks.h" -#include "PSQT.h" #include "PositionFactory.h" #include "SyzygyTablebase.h" using namespace SimpleChessEngine; int main(int argc, char** argv) { - InitBetween(); - InitBetween(); - InitPawnAttacks(); - InitPSQT(); if (argc < 3) { std::cerr << "usage: SCE_tbprobe syzygy-path fen\n"; return 2; From d8ae2bcaa570954fafcb30e2a01a30498051b4fd Mon Sep 17 00:00:00 2001 From: nook0110 Date: Wed, 11 Nov 2026 20:05:38 +0300 Subject: [PATCH 3/4] [core] Generate slider attacks without heap ownership Preserve the original magic records and shared table layout in immutable static storage. Build and validate every entry during constant evaluation, with evaluator budgets scoped to the attack-table source file. --- CMakeLists.txt | 6 + Chess/Attacks.cpp | 559 ++++++++++++++++++++++------------------------ Chess/Attacks.h | 54 ++--- Chess/Utility.h | 1 + 4 files changed, 298 insertions(+), 322 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index ec2048b..3f64363 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,6 +42,12 @@ target_link_libraries(fathom PRIVATE Threads::Threads) FILE(GLOB CHESS_SOURCES CONFIGURE_DEPENDS Chess/*.cpp Chess/Nnue/*.cpp) list(REMOVE_ITEM CHESS_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/Chess/main.cpp) +set_property(SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/Chess/Attacks.cpp APPEND PROPERTY COMPILE_OPTIONS + "$<$:-fconstexpr-ops-limit=100000000>" + "$<$:-fconstexpr-cache-depth=0>" + "$<$:-fconstexpr-steps=20000000>" +) + include_directories(${CMAKE_CURRENT_SOURCE_DIR}/Chess) # Единая библиотека для основного проекта и тестов diff --git a/Chess/Attacks.cpp b/Chess/Attacks.cpp index ba84d3e..030723b 100644 --- a/Chess/Attacks.cpp +++ b/Chess/Attacks.cpp @@ -5,24 +5,21 @@ using namespace SimpleChessEngine; +namespace { template constexpr std::array GetStepDelta() { + static_assert(IsWeakSlidingPiece(sliding_piece)); if constexpr (sliding_piece == Piece::kBishop) { return {Compass::kNorthWest, Compass::kSouthWest, Compass::kSouthEast, Compass::kNorthEast}; } - if constexpr (sliding_piece == Piece::kRook) { - return {Compass::kNorth, Compass::kWest, Compass::kSouth, Compass::kEast}; - } - - assert(false); - std::unreachable(); + return {Compass::kNorth, Compass::kWest, Compass::kSouth, Compass::kEast}; } template -Bitboard SimpleChessEngine::GenerateAttackMask(const BitIndex square, - const Bitboard occupancy) { - assert(IsWeakSlidingPiece(sliding_piece)); +constexpr Bitboard GenerateSliderAttack(const BitIndex square, + const Bitboard occupancy) { + static_assert(IsWeakSlidingPiece(sliding_piece)); assert(IsOk(square)); Bitboard result = kEmptyBoard; @@ -39,7 +36,6 @@ Bitboard SimpleChessEngine::GenerateAttackMask(const BitIndex square, return result; } -namespace { consteval GeometryTables MakeGeometryTables() { GeometryTables tables{}; constexpr std::array directions = {Compass::kNorthWest, Compass::kSouthWest, @@ -67,299 +63,280 @@ consteval GeometryTables MakeGeometryTables() { constinit const GeometryTables SimpleChessEngine::kGeometry = MakeGeometryTables(); -template Bitboard SimpleChessEngine::GenerateAttackMask( - BitIndex, Bitboard); -template Bitboard SimpleChessEngine::GenerateAttackMask( - BitIndex, Bitboard); - template -const std::unique_ptr> - AttackTable::self_ = std::make_unique(); - -namespace { -std::array shared_table; + requires(IsWeakSlidingPiece(sliding_piece)) +Bitboard SimpleChessEngine::GenerateAttackMask(BitIndex square, + Bitboard occupancy) { + static_assert(IsWeakSlidingPiece(sliding_piece)); + return GenerateSliderAttack(square, occupancy); } -template -AttackTable::AttackTable() { - if constexpr (!IsWeakSlidingPiece(sliding_piece)) return; - - table_ = shared_table.data(); +template Bitboard SimpleChessEngine::GenerateAttackMask( + BitIndex, Bitboard); +template Bitboard SimpleChessEngine::GenerateAttackMask(BitIndex, + Bitboard); - if constexpr (sliding_piece == Piece::kBishop) { - magic_ = {{{Bitboard{0x0040201008040200}, Bitboard{0x007fbfbfbfbfbfff}, - size_t{5378}}, - {Bitboard{0x0000402010080400}, Bitboard{0x0000a060401007fc}, - size_t{4093}}, - {Bitboard{0x0000004020100a00}, Bitboard{0x0001004008020000}, - size_t{4314}}, - {Bitboard{0x0000000040221400}, Bitboard{0x0000806004000000}, - size_t{6587}}, - {Bitboard{0x0000000002442800}, Bitboard{0x0000100400000000}, - size_t{6491}}, - {Bitboard{0x0000000204085000}, Bitboard{0x000021c100b20000}, - size_t{6330}}, - {Bitboard{0x0000020408102000}, Bitboard{0x0000040041008000}, - size_t{5609}}, - {Bitboard{0x0002040810204000}, Bitboard{0x00000fb0203fff80}, - size_t{22236}}, - {Bitboard{0x0020100804020000}, Bitboard{0x0000040100401004}, - size_t{6106}}, - {Bitboard{0x0040201008040000}, Bitboard{0x0000020080200802}, - size_t{5625}}, - {Bitboard{0x00004020100a0000}, Bitboard{0x0000004010202000}, - size_t{16785}}, - {Bitboard{0x0000004022140000}, Bitboard{0x0000008060040000}, - size_t{16817}}, - {Bitboard{0x0000000244280000}, Bitboard{0x0000004402000000}, - size_t{6842}}, - {Bitboard{0x0000020408500000}, Bitboard{0x0000000801008000}, - size_t{7003}}, - {Bitboard{0x0002040810200000}, Bitboard{0x000007efe0bfff80}, - size_t{4197}}, - {Bitboard{0x0004081020400000}, Bitboard{0x0000000820820020}, - size_t{7356}}, - {Bitboard{0x0010080402000200}, Bitboard{0x0000400080808080}, - size_t{4602}}, - {Bitboard{0x0020100804000400}, Bitboard{0x00021f0100400808}, - size_t{4538}}, - {Bitboard{0x004020100a000a00}, Bitboard{0x00018000c06f3fff}, - size_t{29531}}, - {Bitboard{0x0000402214001400}, Bitboard{0x0000258200801000}, - size_t{45393}}, - {Bitboard{0x0000024428002800}, Bitboard{0x0000240080840000}, - size_t{12420}}, - {Bitboard{0x0002040850005000}, Bitboard{0x000018000c03fff8}, - size_t{15763}}, - {Bitboard{0x0004081020002000}, Bitboard{0x00000a5840208020}, - size_t{5050}}, - {Bitboard{0x0008102040004000}, Bitboard{0x0000020008208020}, - size_t{4346}}, - {Bitboard{0x0008040200020400}, Bitboard{0x0000804000810100}, - size_t{6074}}, - {Bitboard{0x0010080400040800}, Bitboard{0x0001011900802008}, - size_t{7866}}, - {Bitboard{0x0020100a000a1000}, Bitboard{0x0000804000810100}, - size_t{32139}}, - {Bitboard{0x0040221400142200}, Bitboard{0x000100403c0403ff}, - size_t{57673}}, - {Bitboard{0x0002442800284400}, Bitboard{0x00078402a8802000}, - size_t{55365}}, - {Bitboard{0x0004085000500800}, Bitboard{0x0000101000804400}, - size_t{15818}}, - {Bitboard{0x0008102000201000}, Bitboard{0x0000080800104100}, - size_t{5562}}, - {Bitboard{0x0010204000402000}, Bitboard{0x00004004c0082008}, - size_t{6390}}, - {Bitboard{0x0004020002040800}, Bitboard{0x0001010120008020}, - size_t{7930}}, - {Bitboard{0x0008040004081000}, Bitboard{0x000080809a004010}, - size_t{13329}}, - {Bitboard{0x00100a000a102000}, Bitboard{0x0007fefe08810010}, - size_t{7170}}, - {Bitboard{0x0022140014224000}, Bitboard{0x0003ff0f833fc080}, - size_t{27267}}, - {Bitboard{0x0044280028440200}, Bitboard{0x007fe08019003042}, - size_t{53787}}, - {Bitboard{0x0008500050080400}, Bitboard{0x003fffefea003000}, - size_t{5097}}, - {Bitboard{0x0010200020100800}, Bitboard{0x0000101010002080}, - size_t{6643}}, - {Bitboard{0x0020400040201000}, Bitboard{0x0000802005080804}, - size_t{6138}}, - {Bitboard{0x0002000204081000}, Bitboard{0x0000808080a80040}, - size_t{7418}}, - {Bitboard{0x0004000408102000}, Bitboard{0x0000104100200040}, - size_t{7898}}, - {Bitboard{0x000a000a10204000}, Bitboard{0x0003ffdf7f833fc0}, - size_t{42012}}, - {Bitboard{0x0014001422400000}, Bitboard{0x0000008840450020}, - size_t{57350}}, - {Bitboard{0x0028002844020000}, Bitboard{0x00007ffc80180030}, - size_t{22813}}, - {Bitboard{0x0050005008040200}, Bitboard{0x007fffdd80140028}, - size_t{56693}}, - {Bitboard{0x0020002010080400}, Bitboard{0x00020080200a0004}, - size_t{5818}}, - {Bitboard{0x0040004020100800}, Bitboard{0x0000101010100020}, - size_t{7098}}, - {Bitboard{0x0000020408102000}, Bitboard{0x0007ffdfc1805000}, - size_t{4451}}, - {Bitboard{0x0000040810204000}, Bitboard{0x0003ffefe0c02200}, - size_t{4709}}, - {Bitboard{0x00000a1020400000}, Bitboard{0x0000000820806000}, - size_t{4794}}, - {Bitboard{0x0000142240000000}, Bitboard{0x0000000008403000}, - size_t{13364}}, - {Bitboard{0x0000284402000000}, Bitboard{0x0000000100202000}, - size_t{4570}}, - {Bitboard{0x0000500804020000}, Bitboard{0x0000004040802000}, - size_t{4282}}, - {Bitboard{0x0000201008040200}, Bitboard{0x0004010040100400}, - size_t{14964}}, - {Bitboard{0x0000402010080400}, Bitboard{0x00006020601803f4}, - size_t{4026}}, - {Bitboard{0x0002040810204000}, Bitboard{0x0003ffdfdfc28048}, - size_t{4826}}, - {Bitboard{0x0004081020400000}, Bitboard{0x0000000820820020}, - size_t{7354}}, - {Bitboard{0x000a102040000000}, Bitboard{0x0000000008208060}, - size_t{4848}}, - {Bitboard{0x0014224000000000}, Bitboard{0x0000000000808020}, - size_t{15946}}, - {Bitboard{0x0028440200000000}, Bitboard{0x0000000001002020}, - size_t{14932}}, - {Bitboard{0x0050080402000000}, Bitboard{0x0000000401002008}, - size_t{16588}}, - {Bitboard{0x0020100804020000}, Bitboard{0x0000004040404040}, - size_t{6905}}, - {Bitboard{0x0040201008040200}, Bitboard{0x007fff9fdf7ff813}, - size_t{16076}}}}; - } +constexpr std::array SimpleChessEngine::kBishopMagics = { + {{Bitboard{0x0040201008040200}, Bitboard{0x007fbfbfbfbfbfff}, size_t{5378}}, + {Bitboard{0x0000402010080400}, Bitboard{0x0000a060401007fc}, size_t{4093}}, + {Bitboard{0x0000004020100a00}, Bitboard{0x0001004008020000}, size_t{4314}}, + {Bitboard{0x0000000040221400}, Bitboard{0x0000806004000000}, size_t{6587}}, + {Bitboard{0x0000000002442800}, Bitboard{0x0000100400000000}, size_t{6491}}, + {Bitboard{0x0000000204085000}, Bitboard{0x000021c100b20000}, size_t{6330}}, + {Bitboard{0x0000020408102000}, Bitboard{0x0000040041008000}, size_t{5609}}, + {Bitboard{0x0002040810204000}, Bitboard{0x00000fb0203fff80}, + size_t{22236}}, + {Bitboard{0x0020100804020000}, Bitboard{0x0000040100401004}, size_t{6106}}, + {Bitboard{0x0040201008040000}, Bitboard{0x0000020080200802}, size_t{5625}}, + {Bitboard{0x00004020100a0000}, Bitboard{0x0000004010202000}, + size_t{16785}}, + {Bitboard{0x0000004022140000}, Bitboard{0x0000008060040000}, + size_t{16817}}, + {Bitboard{0x0000000244280000}, Bitboard{0x0000004402000000}, size_t{6842}}, + {Bitboard{0x0000020408500000}, Bitboard{0x0000000801008000}, size_t{7003}}, + {Bitboard{0x0002040810200000}, Bitboard{0x000007efe0bfff80}, size_t{4197}}, + {Bitboard{0x0004081020400000}, Bitboard{0x0000000820820020}, size_t{7356}}, + {Bitboard{0x0010080402000200}, Bitboard{0x0000400080808080}, size_t{4602}}, + {Bitboard{0x0020100804000400}, Bitboard{0x00021f0100400808}, size_t{4538}}, + {Bitboard{0x004020100a000a00}, Bitboard{0x00018000c06f3fff}, + size_t{29531}}, + {Bitboard{0x0000402214001400}, Bitboard{0x0000258200801000}, + size_t{45393}}, + {Bitboard{0x0000024428002800}, Bitboard{0x0000240080840000}, + size_t{12420}}, + {Bitboard{0x0002040850005000}, Bitboard{0x000018000c03fff8}, + size_t{15763}}, + {Bitboard{0x0004081020002000}, Bitboard{0x00000a5840208020}, size_t{5050}}, + {Bitboard{0x0008102040004000}, Bitboard{0x0000020008208020}, size_t{4346}}, + {Bitboard{0x0008040200020400}, Bitboard{0x0000804000810100}, size_t{6074}}, + {Bitboard{0x0010080400040800}, Bitboard{0x0001011900802008}, size_t{7866}}, + {Bitboard{0x0020100a000a1000}, Bitboard{0x0000804000810100}, + size_t{32139}}, + {Bitboard{0x0040221400142200}, Bitboard{0x000100403c0403ff}, + size_t{57673}}, + {Bitboard{0x0002442800284400}, Bitboard{0x00078402a8802000}, + size_t{55365}}, + {Bitboard{0x0004085000500800}, Bitboard{0x0000101000804400}, + size_t{15818}}, + {Bitboard{0x0008102000201000}, Bitboard{0x0000080800104100}, size_t{5562}}, + {Bitboard{0x0010204000402000}, Bitboard{0x00004004c0082008}, size_t{6390}}, + {Bitboard{0x0004020002040800}, Bitboard{0x0001010120008020}, size_t{7930}}, + {Bitboard{0x0008040004081000}, Bitboard{0x000080809a004010}, + size_t{13329}}, + {Bitboard{0x00100a000a102000}, Bitboard{0x0007fefe08810010}, size_t{7170}}, + {Bitboard{0x0022140014224000}, Bitboard{0x0003ff0f833fc080}, + size_t{27267}}, + {Bitboard{0x0044280028440200}, Bitboard{0x007fe08019003042}, + size_t{53787}}, + {Bitboard{0x0008500050080400}, Bitboard{0x003fffefea003000}, size_t{5097}}, + {Bitboard{0x0010200020100800}, Bitboard{0x0000101010002080}, size_t{6643}}, + {Bitboard{0x0020400040201000}, Bitboard{0x0000802005080804}, size_t{6138}}, + {Bitboard{0x0002000204081000}, Bitboard{0x0000808080a80040}, size_t{7418}}, + {Bitboard{0x0004000408102000}, Bitboard{0x0000104100200040}, size_t{7898}}, + {Bitboard{0x000a000a10204000}, Bitboard{0x0003ffdf7f833fc0}, + size_t{42012}}, + {Bitboard{0x0014001422400000}, Bitboard{0x0000008840450020}, + size_t{57350}}, + {Bitboard{0x0028002844020000}, Bitboard{0x00007ffc80180030}, + size_t{22813}}, + {Bitboard{0x0050005008040200}, Bitboard{0x007fffdd80140028}, + size_t{56693}}, + {Bitboard{0x0020002010080400}, Bitboard{0x00020080200a0004}, size_t{5818}}, + {Bitboard{0x0040004020100800}, Bitboard{0x0000101010100020}, size_t{7098}}, + {Bitboard{0x0000020408102000}, Bitboard{0x0007ffdfc1805000}, size_t{4451}}, + {Bitboard{0x0000040810204000}, Bitboard{0x0003ffefe0c02200}, size_t{4709}}, + {Bitboard{0x00000a1020400000}, Bitboard{0x0000000820806000}, size_t{4794}}, + {Bitboard{0x0000142240000000}, Bitboard{0x0000000008403000}, + size_t{13364}}, + {Bitboard{0x0000284402000000}, Bitboard{0x0000000100202000}, size_t{4570}}, + {Bitboard{0x0000500804020000}, Bitboard{0x0000004040802000}, size_t{4282}}, + {Bitboard{0x0000201008040200}, Bitboard{0x0004010040100400}, + size_t{14964}}, + {Bitboard{0x0000402010080400}, Bitboard{0x00006020601803f4}, size_t{4026}}, + {Bitboard{0x0002040810204000}, Bitboard{0x0003ffdfdfc28048}, size_t{4826}}, + {Bitboard{0x0004081020400000}, Bitboard{0x0000000820820020}, size_t{7354}}, + {Bitboard{0x000a102040000000}, Bitboard{0x0000000008208060}, size_t{4848}}, + {Bitboard{0x0014224000000000}, Bitboard{0x0000000000808020}, + size_t{15946}}, + {Bitboard{0x0028440200000000}, Bitboard{0x0000000001002020}, + size_t{14932}}, + {Bitboard{0x0050080402000000}, Bitboard{0x0000000401002008}, + size_t{16588}}, + {Bitboard{0x0020100804020000}, Bitboard{0x0000004040404040}, size_t{6905}}, + {Bitboard{0x0040201008040200}, Bitboard{0x007fff9fdf7ff813}, + size_t{16076}}}}; - if constexpr (sliding_piece == Piece::kRook) { - magic_ = {{{Bitboard{0x000101010101017e}, Bitboard{0x00280077ffebfffe}, - size_t{26304}}, - {Bitboard{0x000202020202027c}, Bitboard{0x2004010201097fff}, - size_t{35520}}, - {Bitboard{0x000404040404047a}, Bitboard{0x0010020010053fff}, - size_t{38592}}, - {Bitboard{0x0008080808080876}, Bitboard{0x0040040008004002}, - size_t{8026}}, - {Bitboard{0x001010101010106e}, Bitboard{0x7fd00441ffffd003}, - size_t{22196}}, - {Bitboard{0x002020202020205e}, Bitboard{0x4020008887dffffe}, - size_t{80870}}, - {Bitboard{0x004040404040403e}, Bitboard{0x004000888847ffff}, - size_t{76747}}, - {Bitboard{0x008080808080807e}, Bitboard{0x006800fbff75fffd}, - size_t{30400}}, - {Bitboard{0x0001010101017e00}, Bitboard{0x000028010113ffff}, - size_t{11115}}, - {Bitboard{0x0002020202027c00}, Bitboard{0x0020040201fcffff}, - size_t{18205}}, - {Bitboard{0x0004040404047a00}, Bitboard{0x007fe80042ffffe8}, - size_t{53577}}, - {Bitboard{0x0008080808087600}, Bitboard{0x00001800217fffe8}, - size_t{62724}}, - {Bitboard{0x0010101010106e00}, Bitboard{0x00001800073fffe8}, - size_t{34282}}, - {Bitboard{0x0020202020205e00}, Bitboard{0x00001800e05fffe8}, - size_t{29196}}, - {Bitboard{0x0040404040403e00}, Bitboard{0x00001800602fffe8}, - size_t{23806}}, - {Bitboard{0x0080808080807e00}, Bitboard{0x000030002fffffa0}, - size_t{49481}}, - {Bitboard{0x00010101017e0100}, Bitboard{0x00300018010bffff}, - size_t{2410}}, - {Bitboard{0x00020202027c0200}, Bitboard{0x0003000c0085fffb}, - size_t{36498}}, - {Bitboard{0x00040404047a0400}, Bitboard{0x0004000802010008}, - size_t{24478}}, - {Bitboard{0x0008080808760800}, Bitboard{0x0004002020020004}, - size_t{10074}}, - {Bitboard{0x00101010106e1000}, Bitboard{0x0001002002002001}, - size_t{79315}}, - {Bitboard{0x00202020205e2000}, Bitboard{0x0001001000801040}, - size_t{51779}}, - {Bitboard{0x00404040403e4000}, Bitboard{0x0000004040008001}, - size_t{13586}}, - {Bitboard{0x00808080807e8000}, Bitboard{0x0000006800cdfff4}, - size_t{19323}}, - {Bitboard{0x000101017e010100}, Bitboard{0x0040200010080010}, - size_t{70612}}, - {Bitboard{0x000202027c020200}, Bitboard{0x0000080010040010}, - size_t{83652}}, - {Bitboard{0x000404047a040400}, Bitboard{0x0004010008020008}, - size_t{63110}}, - {Bitboard{0x0008080876080800}, Bitboard{0x0000040020200200}, - size_t{34496}}, - {Bitboard{0x001010106e101000}, Bitboard{0x0002008010100100}, - size_t{84966}}, - {Bitboard{0x002020205e202000}, Bitboard{0x0000008020010020}, - size_t{54341}}, - {Bitboard{0x004040403e404000}, Bitboard{0x0000008020200040}, - size_t{60421}}, - {Bitboard{0x008080807e808000}, Bitboard{0x0000820020004020}, - size_t{86402}}, - {Bitboard{0x0001017e01010100}, Bitboard{0x00fffd1800300030}, - size_t{50245}}, - {Bitboard{0x0002027c02020200}, Bitboard{0x007fff7fbfd40020}, - size_t{76622}}, - {Bitboard{0x0004047a04040400}, Bitboard{0x003fffbd00180018}, - size_t{84676}}, - {Bitboard{0x0008087608080800}, Bitboard{0x001fffde80180018}, - size_t{78757}}, - {Bitboard{0x0010106e10101000}, Bitboard{0x000fffe0bfe80018}, - size_t{37346}}, - {Bitboard{0x0020205e20202000}, Bitboard{0x0001000080202001}, - size_t{370}}, - {Bitboard{0x0040403e40404000}, Bitboard{0x0003fffbff980180}, - size_t{42182}}, - {Bitboard{0x0080807e80808000}, Bitboard{0x0001fffdff9000e0}, - size_t{45385}}, - {Bitboard{0x00017e0101010100}, Bitboard{0x00fffefeebffd800}, - size_t{61659}}, - {Bitboard{0x00027c0202020200}, Bitboard{0x007ffff7ffc01400}, - size_t{12790}}, - {Bitboard{0x00047a0404040400}, Bitboard{0x003fffbfe4ffe800}, - size_t{16762}}, - {Bitboard{0x0008760808080800}, Bitboard{0x001ffff01fc03000}, - size_t{0}}, - {Bitboard{0x00106e1010101000}, Bitboard{0x000fffe7f8bfe800}, - size_t{38380}}, - {Bitboard{0x00205e2020202000}, Bitboard{0x0007ffdfdf3ff808}, - size_t{11098}}, - {Bitboard{0x00403e4040404000}, Bitboard{0x0003fff85fffa804}, - size_t{21803}}, - {Bitboard{0x00807e8080808000}, Bitboard{0x0001fffd75ffa802}, - size_t{39189}}, - {Bitboard{0x007e010101010100}, Bitboard{0x00ffffd7ffebffd8}, - size_t{58628}}, - {Bitboard{0x007c020202020200}, Bitboard{0x007fff75ff7fbfd8}, - size_t{44116}}, - {Bitboard{0x007a040404040400}, Bitboard{0x003fff863fbf7fd8}, - size_t{78357}}, - {Bitboard{0x0076080808080800}, Bitboard{0x001fffbfdfd7ffd8}, - size_t{44481}}, - {Bitboard{0x006e101010101000}, Bitboard{0x000ffff810280028}, - size_t{64134}}, - {Bitboard{0x005e202020202000}, Bitboard{0x0007ffd7f7feffd8}, - size_t{41759}}, - {Bitboard{0x003e404040404000}, Bitboard{0x0003fffc0c480048}, - size_t{1394}}, - {Bitboard{0x007e808080808000}, Bitboard{0x0001ffffafd7ffd8}, - size_t{40910}}, - {Bitboard{0x7e01010101010100}, Bitboard{0x00ffffe4ffdfa3ba}, - size_t{66516}}, - {Bitboard{0x7c02020202020200}, Bitboard{0x007fffef7ff3d3da}, - size_t{3897}}, - {Bitboard{0x7a04040404040400}, Bitboard{0x003fffbfdfeff7fa}, - size_t{3930}}, - {Bitboard{0x7608080808080800}, Bitboard{0x001fffeff7fbfc22}, - size_t{72934}}, - {Bitboard{0x6e10101010101000}, Bitboard{0x0000020408001001}, - size_t{72662}}, - {Bitboard{0x5e20202020202000}, Bitboard{0x0007fffeffff77fd}, - size_t{56325}}, - {Bitboard{0x3e40404040404000}, Bitboard{0x0003ffffbf7dfeec}, - size_t{66501}}, - {Bitboard{0x7e80808080808000}, Bitboard{0x0001ffff9dffa333}, - size_t{14826}}}}; - } +constexpr std::array SimpleChessEngine::kRookMagics = { + {{Bitboard{0x000101010101017e}, Bitboard{0x00280077ffebfffe}, + size_t{26304}}, + {Bitboard{0x000202020202027c}, Bitboard{0x2004010201097fff}, + size_t{35520}}, + {Bitboard{0x000404040404047a}, Bitboard{0x0010020010053fff}, + size_t{38592}}, + {Bitboard{0x0008080808080876}, Bitboard{0x0040040008004002}, size_t{8026}}, + {Bitboard{0x001010101010106e}, Bitboard{0x7fd00441ffffd003}, + size_t{22196}}, + {Bitboard{0x002020202020205e}, Bitboard{0x4020008887dffffe}, + size_t{80870}}, + {Bitboard{0x004040404040403e}, Bitboard{0x004000888847ffff}, + size_t{76747}}, + {Bitboard{0x008080808080807e}, Bitboard{0x006800fbff75fffd}, + size_t{30400}}, + {Bitboard{0x0001010101017e00}, Bitboard{0x000028010113ffff}, + size_t{11115}}, + {Bitboard{0x0002020202027c00}, Bitboard{0x0020040201fcffff}, + size_t{18205}}, + {Bitboard{0x0004040404047a00}, Bitboard{0x007fe80042ffffe8}, + size_t{53577}}, + {Bitboard{0x0008080808087600}, Bitboard{0x00001800217fffe8}, + size_t{62724}}, + {Bitboard{0x0010101010106e00}, Bitboard{0x00001800073fffe8}, + size_t{34282}}, + {Bitboard{0x0020202020205e00}, Bitboard{0x00001800e05fffe8}, + size_t{29196}}, + {Bitboard{0x0040404040403e00}, Bitboard{0x00001800602fffe8}, + size_t{23806}}, + {Bitboard{0x0080808080807e00}, Bitboard{0x000030002fffffa0}, + size_t{49481}}, + {Bitboard{0x00010101017e0100}, Bitboard{0x00300018010bffff}, size_t{2410}}, + {Bitboard{0x00020202027c0200}, Bitboard{0x0003000c0085fffb}, + size_t{36498}}, + {Bitboard{0x00040404047a0400}, Bitboard{0x0004000802010008}, + size_t{24478}}, + {Bitboard{0x0008080808760800}, Bitboard{0x0004002020020004}, + size_t{10074}}, + {Bitboard{0x00101010106e1000}, Bitboard{0x0001002002002001}, + size_t{79315}}, + {Bitboard{0x00202020205e2000}, Bitboard{0x0001001000801040}, + size_t{51779}}, + {Bitboard{0x00404040403e4000}, Bitboard{0x0000004040008001}, + size_t{13586}}, + {Bitboard{0x00808080807e8000}, Bitboard{0x0000006800cdfff4}, + size_t{19323}}, + {Bitboard{0x000101017e010100}, Bitboard{0x0040200010080010}, + size_t{70612}}, + {Bitboard{0x000202027c020200}, Bitboard{0x0000080010040010}, + size_t{83652}}, + {Bitboard{0x000404047a040400}, Bitboard{0x0004010008020008}, + size_t{63110}}, + {Bitboard{0x0008080876080800}, Bitboard{0x0000040020200200}, + size_t{34496}}, + {Bitboard{0x001010106e101000}, Bitboard{0x0002008010100100}, + size_t{84966}}, + {Bitboard{0x002020205e202000}, Bitboard{0x0000008020010020}, + size_t{54341}}, + {Bitboard{0x004040403e404000}, Bitboard{0x0000008020200040}, + size_t{60421}}, + {Bitboard{0x008080807e808000}, Bitboard{0x0000820020004020}, + size_t{86402}}, + {Bitboard{0x0001017e01010100}, Bitboard{0x00fffd1800300030}, + size_t{50245}}, + {Bitboard{0x0002027c02020200}, Bitboard{0x007fff7fbfd40020}, + size_t{76622}}, + {Bitboard{0x0004047a04040400}, Bitboard{0x003fffbd00180018}, + size_t{84676}}, + {Bitboard{0x0008087608080800}, Bitboard{0x001fffde80180018}, + size_t{78757}}, + {Bitboard{0x0010106e10101000}, Bitboard{0x000fffe0bfe80018}, + size_t{37346}}, + {Bitboard{0x0020205e20202000}, Bitboard{0x0001000080202001}, size_t{370}}, + {Bitboard{0x0040403e40404000}, Bitboard{0x0003fffbff980180}, + size_t{42182}}, + {Bitboard{0x0080807e80808000}, Bitboard{0x0001fffdff9000e0}, + size_t{45385}}, + {Bitboard{0x00017e0101010100}, Bitboard{0x00fffefeebffd800}, + size_t{61659}}, + {Bitboard{0x00027c0202020200}, Bitboard{0x007ffff7ffc01400}, + size_t{12790}}, + {Bitboard{0x00047a0404040400}, Bitboard{0x003fffbfe4ffe800}, + size_t{16762}}, + {Bitboard{0x0008760808080800}, Bitboard{0x001ffff01fc03000}, size_t{0}}, + {Bitboard{0x00106e1010101000}, Bitboard{0x000fffe7f8bfe800}, + size_t{38380}}, + {Bitboard{0x00205e2020202000}, Bitboard{0x0007ffdfdf3ff808}, + size_t{11098}}, + {Bitboard{0x00403e4040404000}, Bitboard{0x0003fff85fffa804}, + size_t{21803}}, + {Bitboard{0x00807e8080808000}, Bitboard{0x0001fffd75ffa802}, + size_t{39189}}, + {Bitboard{0x007e010101010100}, Bitboard{0x00ffffd7ffebffd8}, + size_t{58628}}, + {Bitboard{0x007c020202020200}, Bitboard{0x007fff75ff7fbfd8}, + size_t{44116}}, + {Bitboard{0x007a040404040400}, Bitboard{0x003fff863fbf7fd8}, + size_t{78357}}, + {Bitboard{0x0076080808080800}, Bitboard{0x001fffbfdfd7ffd8}, + size_t{44481}}, + {Bitboard{0x006e101010101000}, Bitboard{0x000ffff810280028}, + size_t{64134}}, + {Bitboard{0x005e202020202000}, Bitboard{0x0007ffd7f7feffd8}, + size_t{41759}}, + {Bitboard{0x003e404040404000}, Bitboard{0x0003fffc0c480048}, size_t{1394}}, + {Bitboard{0x007e808080808000}, Bitboard{0x0001ffffafd7ffd8}, + size_t{40910}}, + {Bitboard{0x7e01010101010100}, Bitboard{0x00ffffe4ffdfa3ba}, + size_t{66516}}, + {Bitboard{0x7c02020202020200}, Bitboard{0x007fffef7ff3d3da}, size_t{3897}}, + {Bitboard{0x7a04040404040400}, Bitboard{0x003fffbfdfeff7fa}, size_t{3930}}, + {Bitboard{0x7608080808080800}, Bitboard{0x001fffeff7fbfc22}, + size_t{72934}}, + {Bitboard{0x6e10101010101000}, Bitboard{0x0000020408001001}, + size_t{72662}}, + {Bitboard{0x5e20202020202000}, Bitboard{0x0007fffeffff77fd}, + size_t{56325}}, + {Bitboard{0x3e40404040404000}, Bitboard{0x0003ffffbf7dfeec}, + size_t{66501}}, + {Bitboard{0x7e80808080808000}, Bitboard{0x0001ffff9dffa333}, + size_t{14826}}}}; +namespace { +template +consteval void FillSliderAttacks(std::array& table, + const std::array& magics) { + constexpr auto kMaxBlockers = 64 - GetMagicShift(); + std::array attacks_by_blocker{}; + std::array attacks_by_subset{}; for (BitIndex square = 0; square < static_cast(kBoardArea); ++square) { - Bitboard mask_subset(kEmptyBoard); + const auto& magic = magics[square]; + size_t blocker_index = 0; + for (const auto blocker : magic.mask) { + attacks_by_blocker[blocker_index++] = + GenerateSliderAttack(square, SingleSquare(blocker)); + } + attacks_by_subset[0] = GenerateSliderAttack(square, {}); + Bitboard subset{}; + size_t subset_index = 0; do { - table_[magic_[square].GetAddress(mask_subset)] = - GenerateAttackMask(square, mask_subset); - mask_subset -= magic_[square].mask; - mask_subset &= magic_[square].mask; - } while (mask_subset.Any()); + auto& attack = attacks_by_subset[subset_index]; + if (subset_index != 0) { + const auto without_first_blocker = subset_index & (subset_index - 1); + const auto first_blocker = std::countr_zero(subset_index); + attack = attacks_by_subset[without_first_blocker] & + attacks_by_blocker[first_blocker]; + } + const auto address = magic.GetAddress(subset); + if (address >= table.size()) std::unreachable(); + auto& entry = table[address]; + if (entry.Any() && entry != attack) std::unreachable(); + entry = attack; + ++subset_index; + subset = (subset - magic.mask) & magic.mask; + } while (subset.Any()); } } +consteval auto MakeSliderAttacks() { + std::array table{}; + FillSliderAttacks(table, kBishopMagics); + FillSliderAttacks(table, kRookMagics); + return table; +} +} + +constinit const std::array + SimpleChessEngine::kSliderAttacks = MakeSliderAttacks(); + template class SimpleChessEngine::AttackTable; template class SimpleChessEngine::AttackTable; template class SimpleChessEngine::AttackTable; diff --git a/Chess/Attacks.h b/Chess/Attacks.h index b245e3c..ca51b5a 100644 --- a/Chess/Attacks.h +++ b/Chess/Attacks.h @@ -1,7 +1,6 @@ #pragma once -#include -#include +#include #include "BitBoard.h" #include "Piece.h" @@ -37,11 +36,9 @@ inline constexpr auto kKnightAttacks = MakeLeaperAttacks(); template constexpr size_t GetMagicShift() { - assert(IsWeakSlidingPiece(sliding_piece)); + static_assert(IsWeakSlidingPiece(sliding_piece)); if constexpr (sliding_piece == Piece::kBishop) return 64 - 9; if constexpr (sliding_piece == Piece::kRook) return 64 - 12; - assert(false); - std::unreachable(); } /** @@ -53,38 +50,31 @@ struct Magic { Bitboard magic; size_t base_offset; template - size_t GetAddress(const Bitboard occupied) const { - assert(IsWeakSlidingPiece(sliding_piece)); + constexpr size_t GetAddress(const Bitboard occupied) const { + static_assert(IsWeakSlidingPiece(sliding_piece)); return base_offset + static_cast((mask & occupied) * magic >> GetMagicShift()); } }; -template +inline constexpr size_t kSliderTableSize = 88772; +extern const std::array kBishopMagics; +extern const std::array kRookMagics; +extern const std::array kSliderAttacks; + +template + requires(IsSlidingPiece(piece) || piece == Piece::kKnight || + piece == Piece::kKing) class AttackTable { public: - static Bitboard GetAttackMap(BitIndex square, Bitboard occupied); - - AttackTable(); - - private: - static size_t GetAttackTableAddress(BitIndex square, - Bitboard occupied = kEmptyBoard); - - Bitboard *table_ = nullptr; - std::array magic_ = {}; - - static const std::unique_ptr self_; + AttackTable() = delete; + [[nodiscard]] static Bitboard GetAttackMap(BitIndex square, + Bitboard occupied); }; template -size_t AttackTable::GetAttackTableAddress(const BitIndex square, - const Bitboard occupied) { - assert(IsWeakSlidingPiece(piece)); - return self_->magic_[square].template GetAddress(occupied); -} - -template + requires(IsSlidingPiece(piece) || piece == Piece::kKnight || + piece == Piece::kKing) Bitboard AttackTable::GetAttackMap(const BitIndex square, const Bitboard occupied) { if constexpr (piece == Piece::kKnight) { @@ -97,11 +87,12 @@ Bitboard AttackTable::GetAttackMap(const BitIndex square, return AttackTable::GetAttackMap(square, occupied) | AttackTable::GetAttackMap(square, occupied); } - if constexpr (IsWeakSlidingPiece(piece)) { - return self_->table_[GetAttackTableAddress(square, occupied)]; + if constexpr (piece == Piece::kBishop) { + return kSliderAttacks[kBishopMagics[square].GetAddress(occupied)]; + } + if constexpr (piece == Piece::kRook) { + return kSliderAttacks[kRookMagics[square].GetAddress(occupied)]; } - assert(false); - std::unreachable(); } extern template class AttackTable; @@ -111,6 +102,7 @@ extern template class AttackTable; extern template class AttackTable; template + requires(IsWeakSlidingPiece(sliding_piece)) [[nodiscard]] Bitboard GenerateAttackMask( const BitIndex square, const Bitboard occupancy = kEmptyBoard); } // namespace SimpleChessEngine diff --git a/Chess/Utility.h b/Chess/Utility.h index af1780a..adce335 100644 --- a/Chess/Utility.h +++ b/Chess/Utility.h @@ -8,6 +8,7 @@ #include #include #include +#include #include "BitBoard.h" #include "Piece.h" From 4a40f96e88392e9ee91984e370283b3524b91dcd Mon Sep 17 00:00:00 2001 From: nook0110 Date: Thu, 12 Nov 2026 04:55:26 +0300 Subject: [PATCH 4/4] [core] Keep generated magic descriptors within cache lines Use 32-byte magic descriptors and 64-byte boundaries for the immutable attack tables. Enforce the descriptor size at compile time while preserving the generated values and lookup arithmetic. Validate search identity and baseline-equivalent CPU throughput with eight alternating pairs in each order. The bench line records the requested CI reference. Bench: 696698 --- Chess/Attacks.cpp | 5 +++++ Chess/Attacks.h | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/Chess/Attacks.cpp b/Chess/Attacks.cpp index 030723b..482afe7 100644 --- a/Chess/Attacks.cpp +++ b/Chess/Attacks.cpp @@ -1,4 +1,5 @@ #include "Attacks.h" + #include #include "BitBoard.h" @@ -60,6 +61,7 @@ consteval GeometryTables MakeGeometryTables() { } } +alignas(kAttackTableAlignment) constinit const GeometryTables SimpleChessEngine::kGeometry = MakeGeometryTables(); @@ -76,6 +78,7 @@ template Bitboard SimpleChessEngine::GenerateAttackMask( template Bitboard SimpleChessEngine::GenerateAttackMask(BitIndex, Bitboard); +alignas(kAttackTableAlignment) constexpr std::array SimpleChessEngine::kBishopMagics = { {{Bitboard{0x0040201008040200}, Bitboard{0x007fbfbfbfbfbfff}, size_t{5378}}, {Bitboard{0x0000402010080400}, Bitboard{0x0000a060401007fc}, size_t{4093}}, @@ -166,6 +169,7 @@ constexpr std::array SimpleChessEngine::kBishopMagics = { {Bitboard{0x0040201008040200}, Bitboard{0x007fff9fdf7ff813}, size_t{16076}}}}; +alignas(kAttackTableAlignment) constexpr std::array SimpleChessEngine::kRookMagics = { {{Bitboard{0x000101010101017e}, Bitboard{0x00280077ffebfffe}, size_t{26304}}, @@ -334,6 +338,7 @@ consteval auto MakeSliderAttacks() { } } +alignas(kAttackTableAlignment) constinit const std::array SimpleChessEngine::kSliderAttacks = MakeSliderAttacks(); diff --git a/Chess/Attacks.h b/Chess/Attacks.h index ca51b5a..e902116 100644 --- a/Chess/Attacks.h +++ b/Chess/Attacks.h @@ -1,6 +1,7 @@ #pragma once #include +#include #include "BitBoard.h" #include "Piece.h" @@ -41,11 +42,13 @@ constexpr size_t GetMagicShift() { if constexpr (sliding_piece == Piece::kRook) return 64 - 12; } +inline constexpr std::size_t kAttackTableAlignment = 64; + /** * \brief * */ -struct Magic { +struct alignas(kAttackTableAlignment / 2) Magic { Bitboard mask; Bitboard magic; size_t base_offset; @@ -57,6 +60,8 @@ struct Magic { } }; +static_assert(sizeof(Magic) == kAttackTableAlignment / 2); + inline constexpr size_t kSliderTableSize = 88772; extern const std::array kBishopMagics; extern const std::array kRookMagics;