From b15e5d31e2944277f2d4120a47ee117729b91a66 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 05:12:05 +0300 Subject: [PATCH 1/3] [movegen] Generate moves into fixed-capacity inplace vectors Move generation wrote through PseudoLegalMove*& cursors into caller-owned std::array buffers, and legal moves came back in a heap-allocated std::vector. Add InplaceVector, a fixed-capacity vector with the subset of the std::inplace_vector interface the engine needs. std::inplace_vector itself needs libstdc++ 16, and GCC 16 currently builds this engine slower. GeneratePseudoLegalMoves and GenerateLegalMoves return PseudoLegalMoves and LegalMoves by value, the helpers append with unchecked_push_back, the en passant filter is erase_if, and callers use range-for, std::ranges::contains and views::concat instead of pointer loops. GenerateMoves duplicated GenerateLegalMoves and is gone. The principal variation gets its own type bounded by the deepest depth, so move generation and PV extraction no longer allocate. Search is unchanged: identical nodes and best moves on 30 positions, perft startpos d5 4865609 and kiwipete d4 4085603. The push loops keep the size in a register and store it once, and the returned lists are built in place without copies. Instructions per node +0.04% (11708-11719 vs 11714-11721), cycles within noise. Co-Authored-By: Claude Opus 5.5 --- Chess/InplaceVector.h | 83 ++++++++++++++++++ Chess/MoveGenerator.cpp | 143 ++++++++++++++++---------------- Chess/MoveGenerator.h | 31 ++++--- Chess/MovePicker.cpp | 32 +++---- Chess/Position.cpp | 10 +-- Chess/Searcher.h | 14 ++-- Chess/SimpleChessEngine.h | 4 +- Chess/UciCommunicator.h | 2 +- Tests/StagedMovePickerTests.cpp | 30 +++---- Tests/TypedMoveTests.cpp | 3 - Tools/TablebaseBenchmark.cpp | 2 +- 11 files changed, 216 insertions(+), 138 deletions(-) create mode 100644 Chess/InplaceVector.h diff --git a/Chess/InplaceVector.h b/Chess/InplaceVector.h new file mode 100644 index 0000000..68b4e63 --- /dev/null +++ b/Chess/InplaceVector.h @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +namespace SimpleChessEngine { + +template +using SmallestSizeType = std::conditional_t< + capacity <= std::numeric_limits::max(), std::uint8_t, + std::conditional_t::max(), + std::uint16_t, std::size_t>>; + +template + requires std::is_trivially_copyable_v && + std::is_trivially_default_constructible_v +class InplaceVector { + public: + using value_type = T; + using size_type = SmallestSizeType; + using difference_type = std::ptrdiff_t; + using reference = T&; + using const_reference = const T&; + using pointer = T*; + using const_pointer = const T*; + using iterator = T*; + using const_iterator = const T*; + + constexpr InplaceVector() noexcept = default; + + [[nodiscard]] static constexpr std::size_t capacity() noexcept { return N; } + [[nodiscard]] constexpr size_type size() const noexcept { return size_; } + [[nodiscard]] constexpr bool empty() const noexcept { return size_ == 0; } + + [[nodiscard]] constexpr iterator begin() noexcept { return elements_.data(); } + [[nodiscard]] constexpr const_iterator begin() const noexcept { + return elements_.data(); + } + [[nodiscard]] constexpr iterator end() noexcept { return begin() + size_; } + [[nodiscard]] constexpr const_iterator end() const noexcept { + return begin() + size_; + } + + [[nodiscard]] constexpr reference operator[](size_type index) noexcept { + assert(index < size_); + return elements_[index]; + } + [[nodiscard]] constexpr const_reference operator[]( + size_type index) const noexcept { + assert(index < size_); + return elements_[index]; + } + [[nodiscard]] constexpr reference front() noexcept { return (*this)[0]; } + [[nodiscard]] constexpr const_reference front() const noexcept { + return (*this)[0]; + } + + constexpr reference unchecked_push_back(const T& value) noexcept { + assert(size_ < N); + return elements_[size_++] = value; + } + + template + friend constexpr size_type erase_if(InplaceVector& vector, + Predicate predicate) { + const auto kept_end = + std::remove_if(vector.begin(), vector.end(), predicate); + const auto erased = static_cast(vector.end() - kept_end); + vector.size_ = static_cast(kept_end - vector.begin()); + return erased; + } + + private: + std::array elements_; + size_type size_ = 0; +}; + +} // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index 060012e..a7111a4 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -7,17 +7,17 @@ #include "BitBoard.h" namespace SimpleChessEngine { -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kAll>(Position& position) const; -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kQuiescence>(Position& position) const; -template MoveGenerator::Moves MoveGenerator::GenerateMoves< +template MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves< MoveGenerator::Type::kAddChecks>(Position& position) const; MoveGenerator::~MoveGenerator() = default; -void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, - const Position& position) { +void MoveGenerator::GenerateCastling(PseudoLegalMoves& moves, + const Position& position) { if (position.IsUnderCheck()) { return; } @@ -31,14 +31,15 @@ void MoveGenerator::GenerateCastling(PseudoLegalMove*& moves, const auto side_idx = static_cast(castling_side); const auto king_to = kKingCastlingDestination[color_idx][side_idx]; - *moves++ = PseudoLegalMove( - Move::Make(king_square, king_to)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(king_square, king_to))); } } } template -void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMoves& moves, + Position& position, const Bitboard target) const { static_assert(piece != Piece::kPawn && piece != Piece::kKing); @@ -53,7 +54,7 @@ void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, Position& pos template <> void MoveGenerator::GenerateMovesForPiece( - PseudoLegalMove*& moves, Position& position, const Bitboard target) const { + PseudoLegalMoves& moves, Position& position, const Bitboard target) const { const auto us = position.GetSideToMove(); const auto us_idx = static_cast(us); const auto them = Flip(us); @@ -78,7 +79,7 @@ void MoveGenerator::GenerateMovesForPiece( while (push.Any()) { const auto to = push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } auto double_push = Shift(double_push_pawns, direction) & valid_squares; @@ -87,7 +88,7 @@ void MoveGenerator::GenerateMovesForPiece( while (double_push.Any()) { const auto to = double_push.PopFirstBit(); const auto from = Shift(Shift(to, opposite_direction), opposite_direction); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } static constexpr std::array cant_attack_files = {kFileBB[0], kFileBB[7]}; @@ -117,7 +118,7 @@ void MoveGenerator::GenerateMovesForPiece( while (attack_squares.Any()) { const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } } @@ -130,7 +131,7 @@ void MoveGenerator::GenerateMovesForPiece( if (attack_to.Any()) { const auto to = en_croissant_square.value(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove(Move::Make(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move::Make(from, to))); } } } @@ -144,14 +145,14 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = promotion_push.PopFirstBit(); const auto from = Shift(to, opposite_direction); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kQueen)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kKnight)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kRook)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kBishop)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kQueen))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kKnight))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kRook))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kBishop))); } for (size_t attack_direction = 0; attack_direction < attacks.size(); @@ -165,21 +166,22 @@ void MoveGenerator::GenerateMovesForPiece( const auto to = attack_squares.PopFirstBit(); const auto from = Shift(to, opposite_attacks[attack_direction]); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kQueen)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kKnight)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kRook)); - *moves++ = PseudoLegalMove( - Move::Make(from, to, Piece::kBishop)); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kQueen))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kKnight))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kRook))); + moves.unchecked_push_back(PseudoLegalMove( + Move::Make(from, to, Piece::kBishop))); } } } template -PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, - PseudoLegalMove* moves) const { +MoveGenerator::PseudoLegalMoves MoveGenerator::GeneratePseudoLegalMoves( + Position& position) const { + PseudoLegalMoves moves; const auto us = position.GetSideToMove(); const auto them = Flip(us); auto target = ~position.GetPieces(us); @@ -208,24 +210,17 @@ PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, target &= ray; pawn_target &= ray; } - auto* pawn_begin = moves; GenerateMovesForPiece(moves, position, pawn_target & ~position.GetPieces(us)); - auto* pawn_end = moves; - moves = pawn_begin; - for (auto* p = pawn_begin; p != pawn_end; ++p) { - if constexpr (type == Type::kQuiets) { - if (p->IsEnPassant()) continue; - } - if (p->IsEnPassant() && checkers.Any()) { - const auto captured = - static_cast(p->To() + (us == Player::kWhite ? -8 : 8)); - if (!checkers.Test(captured) && - !Between(king_square, checkers.GetFirstBit()).Test(p->To())) - continue; - } - *moves++ = *p; - } + erase_if(moves, [&](const PseudoLegalMove move) { + if (!move.IsEnPassant()) return false; + if constexpr (type == Type::kQuiets) return true; + if (checkers.None()) return false; + const auto captured = + static_cast(move.To() + (us == Player::kWhite ? -8 : 8)); + return !checkers.Test(captured) && + !Between(king_square, checkers.GetFirstBit()).Test(move.To()); + }); auto generate = [&]() { auto piece_target = target; if constexpr (type == Type::kAddChecks) { @@ -248,40 +243,43 @@ PseudoLegalMove* MoveGenerator::GeneratePseudoLegal(Position& position, } template -MoveGenerator::Moves MoveGenerator::GenerateMoves(Position& position) const { - std::array moves; - auto* end = GeneratePseudoLegal(position, moves.data()); +MoveGenerator::LegalMoves MoveGenerator::GenerateLegalMoves( + Position& position) const { + const auto pseudo_legal = GeneratePseudoLegalMoves(position); position.ComputePins(position.GetSideToMove()); - Moves legal; - legal.reserve(end - moves.data()); - for (auto* p = moves.data(); p != end; ++p) { - if (position.IsLegal(*p)) legal.push_back(LegalMove(static_cast(*p))); + LegalMoves legal; + for (const auto move : pseudo_legal) { + if (position.IsLegal(move)) { + legal.unchecked_push_back(LegalMove(static_cast(move))); + } } return legal; } bool MoveGenerator::HasLegalMove(Position& position) const { - std::array moves; - auto* end = GeneratePseudoLegal(position, moves.data()); + const auto pseudo_legal = GeneratePseudoLegalMoves(position); position.ComputePins(position.GetSideToMove()); - return std::any_of(moves.data(), end, - [&position](Move move) { - return position.IsLegal(move); - }); + return std::ranges::any_of(pseudo_legal, + [&position](const PseudoLegalMove move) { + return position.IsLegal(move); + }); } -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( - Position&, PseudoLegalMove*) const; -template PseudoLegalMove* -MoveGenerator::GeneratePseudoLegal(Position&, - PseudoLegalMove*) const; -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal( - Position&, PseudoLegalMove*) const; -template PseudoLegalMove* MoveGenerator::GeneratePseudoLegal< - MoveGenerator::Type::kQuiescence>(Position&, PseudoLegalMove*) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; +template MoveGenerator::PseudoLegalMoves +MoveGenerator::GeneratePseudoLegalMoves( + Position&) const; template <> -void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, +void MoveGenerator::GenerateMovesForPiece(PseudoLegalMoves& moves, Position& position, Bitboard target) const { GenerateMovesFromSquare( @@ -290,7 +288,8 @@ void MoveGenerator::GenerateMovesForPiece(PseudoLegalMove*& moves, } template -void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, +void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMoves& moves, + Position& position, const BitIndex from, Bitboard target) const { assert(position.GetPieceAt(from) == piece); @@ -304,7 +303,7 @@ void MoveGenerator::GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& p while (valid_moves.Any()) { const auto to = valid_moves.PopFirstBit(); - *moves++ = PseudoLegalMove(Move(from, to)); + moves.unchecked_push_back(PseudoLegalMove(Move(from, to))); } } } // namespace SimpleChessEngine diff --git a/Chess/MoveGenerator.h b/Chess/MoveGenerator.h index cb8fb2c..c5c3d6b 100644 --- a/Chess/MoveGenerator.h +++ b/Chess/MoveGenerator.h @@ -1,8 +1,9 @@ #pragma once +#include #include -#include +#include "InplaceVector.h" #include "Move.h" #include "Position.h" @@ -22,12 +23,14 @@ class MoveGenerator { kQuiets = 8 }; - static constexpr size_t kMaxMovesPerPosition = 256; + static constexpr std::size_t kMaxMovesPerPosition = 256; + + using PseudoLegalMoves = InplaceVector; + using LegalMoves = InplaceVector; + MoveGenerator() = default; ~MoveGenerator(); - using Moves = std::vector; - /** * \brief Generates all possible moves for a given position. * @@ -36,16 +39,11 @@ class MoveGenerator { * \return All possible moves for the given position. */ template - [[nodiscard]] Moves GenerateMoves(Position& position) const; - - template - [[nodiscard, gnu::always_inline]] Moves GenerateLegalMoves(Position& position) const { - return GenerateMoves(position); - } + [[nodiscard]] LegalMoves GenerateLegalMoves(Position& position) const; template - [[nodiscard]] PseudoLegalMove* GeneratePseudoLegal(Position& position, - PseudoLegalMove* moves) const; + [[nodiscard]] PseudoLegalMoves GeneratePseudoLegalMoves( + Position& position) const; [[nodiscard]] bool HasLegalMove(Position& position) const; @@ -60,7 +58,7 @@ class MoveGenerator { * \return All possible moves for the given square. */ template - void GenerateMovesForPiece(PseudoLegalMove*& moves, Position& position, + void GenerateMovesForPiece(PseudoLegalMoves& moves, Position& position, Bitboard target) const; /** @@ -75,10 +73,11 @@ class MoveGenerator { * \return All possible moves for the given square and piece. */ template - void GenerateMovesFromSquare(PseudoLegalMove*& moves, Position& position, BitIndex from, - Bitboard target) const; + void GenerateMovesFromSquare(PseudoLegalMoves& moves, Position& position, + BitIndex from, Bitboard target) const; - static void GenerateCastling(PseudoLegalMove*& moves, const Position& position); + static void GenerateCastling(PseudoLegalMoves& moves, + const Position& position); }; } // namespace SimpleChessEngine diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index 54eca22..f2a8830 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -61,27 +61,21 @@ void MovePicker::InitPicker(Position& position, const Searcher* searcher, } void MovePicker::Generate(bool quiet) { - std::array generated; - auto* begin = generated.data(); - PseudoLegalMove* end; - const MoveGenerator generator; - if (quiet) { - end = generator.GeneratePseudoLegal( - *position_, begin); - } else if (!searcher_ && evasions_) { - end = generator.GeneratePseudoLegal(*position_, - begin); - } else if (!searcher_) { - end = generator.GeneratePseudoLegal( - *position_, begin); - } else { - end = generator.GeneratePseudoLegal( - *position_, begin); - } + const auto generated = [this, quiet] { + using enum MoveGenerator::Type; + const MoveGenerator generator; + if (quiet) return generator.GeneratePseudoLegalMoves(*position_); + if (!searcher_ && evasions_) { + return generator.GeneratePseudoLegalMoves(*position_); + } + if (!searcher_) { + return generator.GeneratePseudoLegalMoves(*position_); + } + return generator.GeneratePseudoLegalMoves(*position_); + }(); current_ = quiet ? bad_end_ : 0; end_ = current_; - for (auto* p = begin; p != end; ++p) { - const auto move = *p; + for (const auto move : generated) { if (move == tt_move_ || move == excluded_move_ || (quiet && std::ranges::find(killers_, move) != killers_.end())) continue; diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 52f209e..4648c72 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -1,5 +1,6 @@ #include "Position.h" +#include #include #include "Attacks.h" @@ -345,11 +346,10 @@ bool Position::IsPseudoLegal(const Move &move) { const auto to = move.To(); if (!GetPieces(side_to_move_).Test(from)) return false; if (!move.IsNormal()) { - std::array moves; - const auto *end = - MoveGenerator{}.GeneratePseudoLegal( - *this, moves.data()); - return std::find(static_cast(moves.data()), end, move) != end; + return std::ranges::contains( + MoveGenerator{}.GeneratePseudoLegalMoves( + *this), + move); } if ((move.Raw() & 0x3000) || from == to || GetPieces(side_to_move_).Test(to)) return false; diff --git a/Chess/Searcher.h b/Chess/Searcher.h index b8abeef..72c4bbc 100644 --- a/Chess/Searcher.h +++ b/Chess/Searcher.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -119,7 +120,10 @@ class Searcher { [[nodiscard]] std::int64_t GetQuietScore(const Move &move, Depth ply) const; [[nodiscard]] std::uint64_t GetRootEffort(const Move &move) const; - [[nodiscard]] MoveGenerator::Moves GetPrincipalVariation( + using PrincipalVariation = + InplaceVector::max()>; + + [[nodiscard]] PrincipalVariation GetPrincipalVariation( Depth max_depth, Position position) const; private: @@ -179,9 +183,9 @@ inline const Position &Searcher::GetPosition() const { return current_position_; inline const Move &Searcher::GetCurrentBestMove() const { return best_move_; } -inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, - Position position) const { - MoveGenerator::Moves answer; +inline Searcher::PrincipalVariation Searcher::GetPrincipalVariation( + Depth max_depth, Position position) const { + PrincipalVariation answer; for (Depth i = 0; i < max_depth; ++i) { const auto hashed_node = best_moves_->GetNode(position); if (!hashed_node.IsOccupied() || @@ -193,7 +197,7 @@ inline MoveGenerator::Moves Searcher::GetPrincipalVariation(Depth max_depth, if (found == legal_moves.end()) break; position.DoMove(*found); - answer.push_back(*found); + answer.unchecked_push_back(*found); } return answer; } diff --git a/Chess/SimpleChessEngine.h b/Chess/SimpleChessEngine.h index f3fe92e..74894f6 100644 --- a/Chess/SimpleChessEngine.h +++ b/Chess/SimpleChessEngine.h @@ -36,7 +36,7 @@ struct NodePerSecondInfo { struct PrincipalVariationInfo { size_t current_depth = 0; - MoveGenerator::Moves moves; + Searcher::PrincipalVariation moves; }; struct BestMoveInfo { @@ -257,7 +257,7 @@ inline void SimpleChessEngine::ChessEngine::ComputeBestMove( }; const auto legal_moves = - MoveGenerator{}.GenerateMoves(position_); + MoveGenerator{}.GenerateLegalMoves(position_); if (legal_moves.empty()) { finish(BestMoveInfo{Move::None(), std::nullopt}); return; diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index 22aefe8..f085b04 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -153,7 +153,7 @@ class SearchThread { Position position = info.position; if (MoveGenerator{} - .GenerateMoves(position) + .GenerateLegalMoves(position) .size() == 1) { optimum = std::min(optimum, kSingleMoveTime); } diff --git a/Tests/StagedMovePickerTests.cpp b/Tests/StagedMovePickerTests.cpp index 73e5177..574fc10 100644 --- a/Tests/StagedMovePickerTests.cpp +++ b/Tests/StagedMovePickerTests.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include "MoveGenerator.h" @@ -41,11 +42,12 @@ TEST(StagedMovePicker, PseudoLegalValidationMatchesGenerator) { for (const auto* fen : kPositions) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); - std::array generated; - auto* end = MoveGenerator{}.GeneratePseudoLegal( - position, generated.data()); std::set expected; - for (auto* p = generated.data(); p != end; ++p) expected.insert(p->Raw()); + for (const auto move : + MoveGenerator{}.GeneratePseudoLegalMoves( + position)) { + expected.insert(move.Raw()); + } for (unsigned raw = 0; raw < 65536; ++raw) { EXPECT_EQ(position.IsPseudoLegal(Move(static_cast(raw))), expected.contains(raw)) @@ -59,17 +61,17 @@ TEST(StagedMovePicker, CaptureAndQuietStagesPartitionLegalMoves) { SCOPED_TRACE(fen); auto position = PositionFactory{}(fen); const auto expected = LegalSet(position); - std::array generated; - auto* middle = - MoveGenerator{}.GeneratePseudoLegal( - position, generated.data()); - auto* end = - MoveGenerator{}.GeneratePseudoLegal( - position, middle); + const MoveGenerator generator; + const auto captures = + generator.GeneratePseudoLegalMoves( + position); + const auto quiets = + generator.GeneratePseudoLegalMoves( + position); std::set actual; - for (auto* p = generated.data(); p != end; ++p) { - if (!position.IsLegal(*p)) continue; - EXPECT_TRUE(actual.insert(p->Raw()).second); + for (const auto move : std::views::concat(captures, quiets)) { + if (!position.IsLegal(move)) continue; + EXPECT_TRUE(actual.insert(move.Raw()).second); } EXPECT_EQ(actual, expected); } diff --git a/Tests/TypedMoveTests.cpp b/Tests/TypedMoveTests.cpp index e4e80a9..0446fe2 100644 --- a/Tests/TypedMoveTests.cpp +++ b/Tests/TypedMoveTests.cpp @@ -81,9 +81,6 @@ TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { "4k3/8/8/8/8/8/8/6KR w H - 0 1"}) { auto position = PositionFactory{}(fen); const auto moves = MoveGenerator{}.GenerateLegalMoves(position); - const auto raw_moves = MoveGenerator{}.GenerateMoves(position); - ASSERT_EQ(moves.size(), raw_moves.size()); - for (size_t i = 0; i < moves.size(); ++i) EXPECT_EQ(moves[i], raw_moves[i]); for (const auto move : moves) { const Move raw = move; const PseudoLegalMove degraded = move; diff --git a/Tools/TablebaseBenchmark.cpp b/Tools/TablebaseBenchmark.cpp index 289eb6c..853f280 100644 --- a/Tools/TablebaseBenchmark.cpp +++ b/Tools/TablebaseBenchmark.cpp @@ -81,7 +81,7 @@ int main(int argc, char** argv) { continue; } const auto moves = - MoveGenerator{}.GenerateMoves(position); + MoveGenerator{}.GenerateLegalMoves(position); const auto root_move = tablebase->RootMove(position); if (tablebase->ProbeWdl(position) && root_move && std::ranges::find(moves, *root_move) != moves.end()) { From 8fb3af90b29fe83ca856328b92fc7d3007d83482 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 05:34:48 +0300 Subject: [PATCH 2/3] [movepicker] Sort and search scored moves through ranges PartialInsertionSort took raw begin/end pointers and a limit that was always INT64_MIN, so the partial part never applied. It becomes SortByScore over a ScoredRange, a std::ranges::subrange of the scored move array, written with iterators and std::prev. The killer lookup in bad captures uses std::ranges::find with a &ScoredMove::move projection instead of find_if over data() pointers. The range is a subrange of std::array iterators rather than a std::span: GCC 15 keeps an extra pointer copy per shifted element in loops over span iterators, while array iterators compile to the same 7-instruction inner loop as before. Search is unchanged (identical nodes and best moves on 30 positions); instructions per node 11712-11716 vs 11710-11713, cycles per node 13468-13524 vs 13590-13602. Co-Authored-By: Claude Opus 5.5 --- Chess/MovePicker.cpp | 35 ++++++++++++++++------------------- Chess/MovePicker.h | 10 +++++++--- 2 files changed, 23 insertions(+), 22 deletions(-) diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index f2a8830..686b3d7 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -1,7 +1,7 @@ #include "MovePicker.h" #include -#include +#include #include "Position.h" #include "Searcher.h" @@ -28,19 +28,16 @@ constexpr int PromotionRank(Piece promotion) { } } // namespace -void MovePicker::PartialInsertionSort(ScoredMove* begin, ScoredMove* end, - std::int64_t limit) { - if (begin == end) return; - for (auto *sorted_end = begin, *p = begin + 1; p < end; ++p) { - if (p->score >= limit) { - const auto tmp = *p; - *p = *++sorted_end; - auto* q = sorted_end; - for (; q != begin && (q - 1)->score < tmp.score; --q) { - *q = *(q - 1); - } - *q = tmp; +void MovePicker::SortByScore(ScoredRange moves) { + if (moves.empty()) return; + for (auto next = std::next(moves.begin()); next != moves.end(); ++next) { + const ScoredMove inserted = *next; + auto slot = next; + for (; slot != moves.begin() && std::prev(slot)->score < inserted.score; + --slot) { + *slot = *std::prev(slot); } + *slot = inserted; } } @@ -97,8 +94,7 @@ void MovePicker::Generate(bool quiet) { moves_[end_++] = {move, score}; } if (searcher_) { - PartialInsertionSort(moves_.data() + current_, moves_.data() + end_, - std::numeric_limits::min()); + SortByScore({moves_.begin() + current_, moves_.begin() + end_}); } } @@ -145,10 +141,11 @@ MaybeLegalMove MovePicker::SelectNextMove() { !position_->IsLegal(move, blockers_)) continue; if (!move.IsQuiet(*position_)) { - auto* found = std::find_if( - moves_.data(), moves_.data() + bad_end_, - [move](const auto& data) { return data.move == move; }); - if (found == moves_.data() + bad_end_) continue; + const ScoredRange bad_captures{moves_.begin(), + moves_.begin() + bad_end_}; + const auto found = + std::ranges::find(bad_captures, move, &ScoredMove::move); + if (found == bad_captures.end()) continue; found->move = Move::None(); } killers_[index] = move; diff --git a/Chess/MovePicker.h b/Chess/MovePicker.h index f2d18db..d3ac68f 100644 --- a/Chess/MovePicker.h +++ b/Chess/MovePicker.h @@ -2,6 +2,7 @@ #include #include #include +#include #include "Evaluation.h" #include "Move.h" @@ -38,12 +39,15 @@ class MovePicker { std::int64_t score; }; - static void PartialInsertionSort(ScoredMove* begin, ScoredMove* end, - std::int64_t limit); + using ScoredMoves = + std::array; + using ScoredRange = std::ranges::subrange; + + static void SortByScore(ScoredRange moves); void Generate(bool quiet); [[nodiscard]] LegalMove Emit(LegalMove move); - std::array moves_; + ScoredMoves moves_; std::array killers_{}; Position* position_ = nullptr; const Searcher* searcher_ = nullptr; From 4e51dca57dddf7608b161fe6a4e8ce0c011aa998 Mon Sep 17 00:00:00 2001 From: nook0110 Date: Mon, 9 Nov 2026 05:44:37 +0300 Subject: [PATCH 3/3] [core] Index per-color, per-piece and per-side tables by their enums Tables keyed by Player, Piece, CastlingSide and GamePhase were plain std::arrays indexed through static_cast(enum) and helper variables such as color_idx and piece_idx, so nothing stopped indexing a color table with a piece or a castling side with a raw 0/1. Add EnumArray, an array whose operator[] takes the enum itself, with ByPlayer, ByPiece, ByCastlingSide and ByGamePhase aliases and kPlayers, kCastlingSides and kPiecesByValue lists for loops. Board state, the castling, pawn and attack tables, Zobrist keys, PSQT, piece values, the evaluation tunables, the FEN parser and the time control use them; indexing with the wrong enum or an integer no longer compiles. The TaperedEval phase pair and NNUE are unchanged. 154 of the 201 size_t casts are gone. Search is unchanged: identical nodes and best moves on 30 positions, perft startpos d5 4865609 and kiwipete d4 4085603. Machine code differs only in index arithmetic (an imul instead of a lea/sub chain for the PSQT row, one fewer saved register); instructions per node 11736 vs 11728 (+0.07%), cycles per node 13478-13631 vs 13499-13715. Co-Authored-By: Claude Opus 5.5 --- Chess/EnumArray.h | 50 ++++++++ Chess/Evaluation.cpp | 47 ++++--- Chess/Evaluation.h | 23 ++-- Chess/Hasher.h | 4 +- Chess/Move.h | 11 ++ Chess/MoveGenerator.cpp | 10 +- Chess/MovePicker.cpp | 2 +- Chess/PSQT.h | 16 ++- Chess/Piece.h | 14 +++ Chess/Player.h | 12 ++ Chess/Position.cpp | 256 ++++++++++++++++++-------------------- Chess/Position.h | 49 +++----- Chess/PositionFactory.h | 93 +++++++------- Chess/Settings.h | 43 ++++--- Chess/StreamUtility.h | 6 +- Chess/SyzygyTablebase.cpp | 8 +- Chess/UciCommunicator.h | 36 +++--- Chess/Utility.h | 51 ++++---- Tests/EvaluationTests.cpp | 28 ++--- Tests/TypedMoveTests.cpp | 4 +- 20 files changed, 405 insertions(+), 358 deletions(-) create mode 100644 Chess/EnumArray.h diff --git a/Chess/EnumArray.h b/Chess/EnumArray.h new file mode 100644 index 0000000..b9abbb5 --- /dev/null +++ b/Chess/EnumArray.h @@ -0,0 +1,50 @@ +#pragma once + +#include +#include +#include +#include + +namespace SimpleChessEngine { + +template +inline constexpr std::size_t kEnumSize = 0; + +template +concept IndexEnum = std::is_enum_v && (kEnumSize > 0); + +template +struct EnumArray { + using value_type = Value; + using iterator = typename std::array>::iterator; + using const_iterator = + typename std::array>::const_iterator; + + std::array> values; + + [[nodiscard]] constexpr Value& operator[](Key key) noexcept { + return values[std::to_underlying(key)]; + } + [[nodiscard]] constexpr const Value& operator[](Key key) const noexcept { + return values[std::to_underlying(key)]; + } + + [[nodiscard]] static constexpr std::size_t size() noexcept { + return kEnumSize; + } + + [[nodiscard]] constexpr iterator begin() noexcept { return values.begin(); } + [[nodiscard]] constexpr const_iterator begin() const noexcept { + return values.begin(); + } + [[nodiscard]] constexpr iterator end() noexcept { return values.end(); } + [[nodiscard]] constexpr const_iterator end() const noexcept { + return values.end(); + } + + constexpr void fill(const Value& value) { values.fill(value); } + + [[nodiscard]] constexpr bool operator==(const EnumArray&) const = default; +}; + +} // namespace SimpleChessEngine diff --git a/Chess/Evaluation.cpp b/Chess/Evaluation.cpp index 2302c89..f3414ee 100644 --- a/Chess/Evaluation.cpp +++ b/Chess/Evaluation.cpp @@ -32,7 +32,7 @@ struct KingPawnHashEntry { Bitboard black_pawns{}; BitIndex white_king{-1}; BitIndex black_king{-1}; - std::array king_score{}; + ByPlayer king_score{}; }; struct KingPawnHashTable { @@ -44,10 +44,10 @@ thread_local KingPawnHashTable king_pawn_hash_table; struct PawnEvaluation { TaperedEval score{}; - std::array king_score{}; + ByPlayer king_score{}; }; -[[nodiscard]] const std::array& EvaluateKingPawns( +[[nodiscard]] const ByPlayer& EvaluateKingPawns( const Position& position, Bitboard white_pawns, Bitboard black_pawns, size_t pawn_hash_index); @@ -66,27 +66,25 @@ struct PawnEvaluation { [[nodiscard]] TaperedEval EvaluatePawns(const Bitboard pawns, const Bitboard enemy_pawns, const Player side) { - const auto side_index = static_cast(side); TaperedEval result{}; Bitboard remaining = pawns; while (remaining.Any()) { const BitIndex square = remaining.PopFirstBit(); - if ((pawns & kPawnSpans.rear[side_index][square]).Any()) { + if ((pawns & kPawnSpans.rear[side][square]).Any()) { result += Settings::EvaluationParameters::doubled_pawn; } if ((pawns & kPawnSpans.adjacent_files[square]).None()) { result += Settings::EvaluationParameters::isolated_pawn; } const auto [file_coordinate, rank_coordinate] = GetCoordinates(square); - const auto file = static_cast(file_coordinate); const auto rank = static_cast(rank_coordinate); const auto relative_rank = side == Player::kWhite ? rank : static_cast(7 - rank); result += Settings::EvaluationParameters::pawn_psqt_adjustment[relative_rank] - [file]; - if ((enemy_pawns & kPawnSpans.passed[side_index][square]).Any()) { + [file_coordinate]; + if ((enemy_pawns & kPawnSpans.passed[side][square]).Any()) { continue; } result += Settings::EvaluationParameters::passed_pawn[relative_rank]; @@ -128,7 +126,7 @@ void AddMobility(const Position& position, const Player side, const Bitboard occupied, const Bitboard mobility_area, TaperedEval& result) { const auto& weight = - Settings::EvaluationParameters::mobility[static_cast(piece)]; + Settings::EvaluationParameters::mobility[piece]; if (weight == TaperedEval{}) return; Bitboard pieces = position.GetPiecesByType(side); @@ -172,8 +170,8 @@ void AddPsqtAdjustment(const Position& position, const Player side, side == Player::kWhite ? rank : static_cast(7 - rank); const size_t mirrored_file = std::min(file, static_cast(7 - file)); result += - Settings::EvaluationParameters::psqt_adjustment[static_cast( - piece)][relative_rank][mirrored_file]; + Settings::EvaluationParameters::psqt_adjustment[ + piece][relative_rank][mirrored_file]; } } @@ -213,7 +211,7 @@ void AddPsqtAdjustment(const Position& position, const Player side, result += Settings::EvaluationParameters::king_shield_far; } - const Bitboard file_mask = kFileBB[static_cast(file)]; + const Bitboard file_mask = kFileBB[file]; if ((own_pawns & file_mask).None()) { result += Settings::EvaluationParameters::king_semi_open_file; if ((enemy_pawns & file_mask).None()) { @@ -240,7 +238,7 @@ void AddPsqtAdjustment(const Position& position, const Player side, return result; } -[[nodiscard]] const std::array& EvaluateKingPawns( +[[nodiscard]] const ByPlayer& EvaluateKingPawns( const Position& position, const Bitboard white_pawns, const Bitboard black_pawns, const size_t pawn_hash_index) { const BitIndex white_king = position.GetKingSquare(Player::kWhite); @@ -312,7 +310,7 @@ void AddKingTropism(const Position& position, const Player attacker, const size_t tropism = outer + (pieces & masks[0]).Count(); attack_units += static_cast(tropism) * - Settings::EvaluationParameters::king_attack[static_cast(piece)]; + Settings::EvaluationParameters::king_attack[piece]; } [[nodiscard]] Eval EvaluateKingAttack(const Position& position, @@ -353,9 +351,9 @@ void AddKingTropism(const Position& position, const Player attacker, [[nodiscard]] Eval TaperedEval::operator()(PhaseValue pv) const { const auto mg_limit = - kPhaseValueLimits[static_cast(GamePhase::kMiddleGame)]; + kPhaseValueLimits[GamePhase::kMiddleGame]; const auto eg_limit = - kPhaseValueLimits[static_cast(GamePhase::kEndGame)]; + kPhaseValueLimits[GamePhase::kEndGame]; pv = std::clamp(pv, eg_limit, mg_limit); return (eval[static_cast(GamePhase::kMiddleGame)] * (pv - eg_limit) + eval[static_cast(GamePhase::kEndGame)] * (mg_limit - pv)) / @@ -381,18 +379,15 @@ void AddKingTropism(const Position& position, const Player attacker, const auto us = side_to_move_; const auto them = Flip(us); - const auto us_idx = static_cast(us); - const auto them_idx = static_cast(them); TaperedEval result{}; result += - evaluation_data_.material[us_idx] - evaluation_data_.material[them_idx]; + evaluation_data_.material[us] - evaluation_data_.material[them]; if (Settings::EvaluationParameters::material_enabled) { - for (size_t piece = static_cast(Piece::kPawn); - piece <= static_cast(Piece::kQueen); ++piece) { + for (const auto piece : kPiecesByValue) { const int count_difference = - static_cast(evaluation_data_.piece_counts[us_idx][piece]) - - static_cast(evaluation_data_.piece_counts[them_idx][piece]); + static_cast(evaluation_data_.piece_counts[us][piece]) - + static_cast(evaluation_data_.piece_counts[them][piece]); const TaperedEval correction = Settings::EvaluationParameters::material_value[piece] - kPieceValues[piece]; @@ -400,7 +395,7 @@ void AddKingTropism(const Position& position, const Player attacker, result.eval[1] += count_difference * correction.eval[1]; } } - result += evaluation_data_.psqt[us_idx] - evaluation_data_.psqt[them_idx]; + result += evaluation_data_.psqt[us] - evaluation_data_.psqt[them]; const bool king_safety_active = Settings::EvaluationParameters::king_safety_enabled && (GetPiecesByType(Player::kWhite) | @@ -430,8 +425,8 @@ void AddKingTropism(const Position& position, const Player attacker, if (king_safety_active) { if (Settings::EvaluationParameters::king_pawns_enabled) { result += - EvaluateKingSafety(*this, us, pawn_evaluation.king_score[us_idx]) - - EvaluateKingSafety(*this, them, pawn_evaluation.king_score[them_idx]); + EvaluateKingSafety(*this, us, pawn_evaluation.king_score[us]) - + EvaluateKingSafety(*this, them, pawn_evaluation.king_score[them]); } else { result += EvaluateKingSafety(*this, us, 0) - EvaluateKingSafety(*this, them, 0); diff --git a/Chess/Evaluation.h b/Chess/Evaluation.h index 21b2c4d..5730eba 100644 --- a/Chess/Evaluation.h +++ b/Chess/Evaluation.h @@ -11,6 +11,12 @@ using SearchResult = std::optional; enum class GamePhase : std::uint8_t { kMiddleGame, kEndGame }; +template <> +inline constexpr std::size_t kEnumSize = 2; + +template +using ByGamePhase = EnumArray; + constexpr size_t kGamePhases = 2; using PhaseValue = int; @@ -46,32 +52,33 @@ struct TaperedEval { return copy; } -constexpr std::array kPieceValues = {{{0, 0}, +constexpr ByPiece kPieceValues = {{{{0, 0}, {82, 94}, {337, 281}, {365, 297}, {477, 512}, {1025, 936}, - {0, 0}}}; + {0, 0}}}}; constexpr Eval kFullNonPawnMaterial = - kPieceValues[static_cast(Piece::kKnight)] + kPieceValues[Piece::kKnight] .eval[static_cast(GamePhase::kMiddleGame)] * 4 + - kPieceValues[static_cast(Piece::kBishop)] + kPieceValues[Piece::kBishop] .eval[static_cast(GamePhase::kMiddleGame)] * 4 + - kPieceValues[static_cast(Piece::kRook)] + kPieceValues[Piece::kRook] .eval[static_cast(GamePhase::kMiddleGame)] * 4 + - kPieceValues[static_cast(Piece::kQueen)] + kPieceValues[Piece::kQueen] .eval[static_cast(GamePhase::kMiddleGame)] * 2; -constexpr std::array kPhaseValueLimits = {kFullNonPawnMaterial, 0}; +constexpr ByGamePhase kPhaseValueLimits = {{kFullNonPawnMaterial, 0}}; constexpr PhaseValue kLimitsDifference = - kPhaseValueLimits[0] - kPhaseValueLimits[1]; + kPhaseValueLimits[GamePhase::kMiddleGame] - + kPhaseValueLimits[GamePhase::kEndGame]; constexpr Eval kTempoBonus = 20; diff --git a/Chess/Hasher.h b/Chess/Hasher.h index 346dd93..c90cb32 100644 --- a/Chess/Hasher.h +++ b/Chess/Hasher.h @@ -30,10 +30,10 @@ struct Hasher { bool operator==(const Hasher&) const = default; - std::array, kColors>, kPieceTypes> + ByPiece>> psqt_hash{}; std::array en_croissant_hash{}; - std::array, kColors> cr_hash{}; + ByPlayer> cr_hash{}; Hash stm_hash; }; } // namespace SimpleChessEngine diff --git a/Chess/Move.h b/Chess/Move.h index 61a1990..bf4d524 100644 --- a/Chess/Move.h +++ b/Chess/Move.h @@ -1,8 +1,11 @@ #pragma once +#include +#include #include #include #include #include "BitBoard.h" +#include "EnumArray.h" #include "Piece.h" namespace SimpleChessEngine { @@ -93,6 +96,14 @@ class Move { enum class CastlingSide : std::uint8_t { k00, k000 }; +template <> +inline constexpr std::size_t kEnumSize = 2; + +inline constexpr std::array kCastlingSides{CastlingSide::k00, CastlingSide::k000}; + +template +using ByCastlingSide = EnumArray; + static_assert(sizeof(Move) == 2, "Move must be exactly 2 bytes"); static_assert(alignof(Move) == 2, "Move should be 2-byte aligned"); static_assert(std::is_trivially_copyable_v, "Move must be trivially copyable"); diff --git a/Chess/MoveGenerator.cpp b/Chess/MoveGenerator.cpp index a7111a4..48feb20 100644 --- a/Chess/MoveGenerator.cpp +++ b/Chess/MoveGenerator.cpp @@ -24,12 +24,10 @@ void MoveGenerator::GenerateCastling(PseudoLegalMoves& moves, const auto side_to_move = position.GetSideToMove(); const auto king_square = position.GetKingSquare(side_to_move); - const auto color_idx = static_cast(side_to_move); for (const auto castling_side : {CastlingSide::k00, CastlingSide::k000}) { if (position.CanPseudoCastle(castling_side)) { - const auto side_idx = static_cast(castling_side); - const auto king_to = kKingCastlingDestination[color_idx][side_idx]; + const auto king_to = kKingCastlingDestination[side_to_move][castling_side]; moves.unchecked_push_back(PseudoLegalMove( Move::Make(king_square, king_to))); @@ -56,14 +54,12 @@ template <> void MoveGenerator::GenerateMovesForPiece( PseudoLegalMoves& moves, Position& position, const Bitboard target) const { const auto us = position.GetSideToMove(); - const auto us_idx = static_cast(us); const auto them = Flip(us); - const auto them_idx = static_cast(them); const auto pawns = position.GetPiecesByType(us); const auto promotion_rank = us == Player::kWhite ? kRankBB[6] : kRankBB[1]; - const auto direction = kPawnMoveDirection[us_idx]; - const auto opposite_direction = kPawnMoveDirection[them_idx]; + const auto direction = kPawnMoveDirection[us]; + const auto opposite_direction = kPawnMoveDirection[them]; const auto non_promoting_pawns = pawns & ~promotion_rank; diff --git a/Chess/MovePicker.cpp b/Chess/MovePicker.cpp index 686b3d7..7913336 100644 --- a/Chess/MovePicker.cpp +++ b/Chess/MovePicker.cpp @@ -51,7 +51,7 @@ void MovePicker::InitPicker(Position& position, const Searcher* searcher, evasions_ = position.IsUnderCheck(); position.ComputePins(position.GetSideToMove()); blockers_ = position.GetIrreversibleData() - .blockers[static_cast(position.GetSideToMove())]; + .blockers[position.GetSideToMove()]; excluded_move_ = excluded_move; tt_move_ = position.IsPseudoLegal(tt_move) ? tt_move : Move::None(); stage_ = Stage::kTT; diff --git a/Chess/PSQT.h b/Chess/PSQT.h index 70fab4a..c42b4f4 100644 --- a/Chess/PSQT.h +++ b/Chess/PSQT.h @@ -4,11 +4,10 @@ namespace SimpleChessEngine { // clang-format off - inline std::array, kPieceTypes>, - kColors> - kPSQT = { { + inline ByPlayer>> + kPSQT = { { { // White pieces table - {{// Empty squares values are irrelevant since kNone is not being placed + {{{// Empty squares values are irrelevant since kNone is not being placed // or removed at any time {}, // Pawns @@ -77,10 +76,10 @@ namespace SimpleChessEngine { { 29 , -12 }, { -1 , 17 }, { -20 , 14 }, { -7 , 17 }, { -8 , 17 }, { -4 , 38 }, { -38 , 23 }, { -29 , 11 }, { -65 , -74 }, { 23 , -35 }, { 16 , -18 }, { -15 , -18 }, { -56 , -11 }, { -34 , 15 }, { 2 , 4 }, { 13 , -17 }, }} - }} + }}} // Black pieces table is initialized symmetrically to the white pieces // table -} }; +} } }; // clang-format on inline void InitPSQT() { @@ -90,9 +89,8 @@ inline void InitPSQT() { ++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)] - [static_cast(piece)][square]; + kPSQT[Player::kBlack][piece][new_square] = + kPSQT[Player::kWhite][piece][square]; } } } diff --git a/Chess/Piece.h b/Chess/Piece.h index 3429e0d..64a72ce 100644 --- a/Chess/Piece.h +++ b/Chess/Piece.h @@ -1,6 +1,10 @@ #pragma once +#include +#include #include +#include "EnumArray.h" + namespace SimpleChessEngine { /** @@ -21,4 +25,14 @@ enum class Piece : uint8_t { return piece == Piece::kNone; } + +template <> +inline constexpr std::size_t kEnumSize = 7; + +template +using ByPiece = EnumArray; + +inline constexpr std::array kPiecesByValue{Piece::kPawn, Piece::kKnight, + Piece::kBishop, Piece::kRook, + Piece::kQueen}; } // namespace SimpleChessEngine diff --git a/Chess/Player.h b/Chess/Player.h index e0843a9..1d62ebe 100644 --- a/Chess/Player.h +++ b/Chess/Player.h @@ -1,6 +1,10 @@ #pragma once +#include +#include #include +#include "EnumArray.h" + namespace SimpleChessEngine { /** @@ -16,4 +20,12 @@ enum class Player : std::uint8_t { return player == Player::kWhite ? Player::kBlack : Player::kWhite; } + +template <> +inline constexpr std::size_t kEnumSize = 2; + +inline constexpr std::array kPlayers{Player::kWhite, Player::kBlack}; + +template +using ByPlayer = EnumArray; } // namespace SimpleChessEngine diff --git a/Chess/Position.cpp b/Chess/Position.cpp index 4648c72..4da30a7 100644 --- a/Chess/Position.cpp +++ b/Chess/Position.cpp @@ -2,6 +2,7 @@ #include #include +#include #include "Attacks.h" #include "BitBoard.h" @@ -35,17 +36,15 @@ void Position::PlacePiece(const BitIndex square, const Piece piece, assert(IsOk(square)); assert(!board_[square]); assert(piece); - const auto piece_idx = static_cast(piece); - const auto color_idx = static_cast(color); board_[square] = piece; - pieces_by_type_[piece_idx].Set(square); - pieces_by_color_[color_idx].Set(square); - ++evaluation_data_.piece_counts[color_idx][piece_idx]; - evaluation_data_.material[color_idx] += kPieceValues[piece_idx]; - evaluation_data_.psqt[color_idx] += kPSQT[color_idx][piece_idx][square]; + pieces_by_type_[piece].Set(square); + pieces_by_color_[color].Set(square); + ++evaluation_data_.piece_counts[color][piece]; + evaluation_data_.material[color] += kPieceValues[piece]; + evaluation_data_.psqt[color] += kPSQT[color][piece][square]; if (piece != Piece::kPawn) - evaluation_data_.non_pawn_material += kPieceValues[piece_idx].eval[0]; - hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][square]; + evaluation_data_.non_pawn_material += kPieceValues[piece].eval[0]; + hash_ ^= hasher_.psqt_hash[piece][color][square]; } /** @@ -60,17 +59,15 @@ void Position::RemovePiece(const BitIndex square, const Player color) { assert(IsOk(square)); const auto piece = board_[square]; assert(!!piece); - const auto piece_idx = static_cast(piece); - const auto color_idx = static_cast(color); - pieces_by_type_[piece_idx].Reset(square); - pieces_by_color_[color_idx].Reset(square); - --evaluation_data_.piece_counts[color_idx][piece_idx]; + pieces_by_type_[piece].Reset(square); + pieces_by_color_[color].Reset(square); + --evaluation_data_.piece_counts[color][piece]; board_[square] = Piece::kNone; - evaluation_data_.material[color_idx] -= kPieceValues[piece_idx]; - evaluation_data_.psqt[color_idx] -= kPSQT[color_idx][piece_idx][square]; + evaluation_data_.material[color] -= kPieceValues[piece]; + evaluation_data_.psqt[color] -= kPSQT[color][piece][square]; if (piece != Piece::kPawn) - evaluation_data_.non_pawn_material -= kPieceValues[piece_idx].eval[0]; - hash_ ^= hasher_.psqt_hash[piece_idx][color_idx][square]; + evaluation_data_.non_pawn_material -= kPieceValues[piece].eval[0]; + hash_ ^= hasher_.psqt_hash[piece][color][square]; } void Position::MovePiece(const BitIndex from, const BitIndex to, @@ -80,18 +77,16 @@ void Position::MovePiece(const BitIndex from, const BitIndex to, const auto piece = board_[from]; assert(!!piece); assert(!board_[to]); - const auto piece_idx = static_cast(piece); - const auto color_idx = static_cast(color); - pieces_by_type_[piece_idx].Reset(from); - pieces_by_color_[color_idx].Reset(from); - pieces_by_type_[piece_idx].Set(to); - pieces_by_color_[color_idx].Set(to); + pieces_by_type_[piece].Reset(from); + pieces_by_color_[color].Reset(from); + pieces_by_type_[piece].Set(to); + pieces_by_color_[color].Set(to); board_[from] = Piece::kNone; 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]; + evaluation_data_.psqt[color] -= kPSQT[color][piece][from]; + evaluation_data_.psqt[color] += kPSQT[color][piece][to]; + hash_ ^= hasher_.psqt_hash[piece][color][from]; + hash_ ^= hasher_.psqt_hash[piece][color][to]; } void Position::DoMove(const LegalMove &move) { @@ -101,8 +96,8 @@ void Position::DoMove(const LegalMove &move) { irreversible_data_.en_croissant_square.reset(); } for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( - color)][irreversible_data_.castling_rights[static_cast(color)] + hash_ ^= hasher_.cr_hash[ + color][irreversible_data_.castling_rights[color] .to_ulong()]; } @@ -117,7 +112,7 @@ void Position::DoMove(const LegalMove &move) { auto &dirty = nnue_.Push(); if (move.IsEnPassant()) { - const auto capture_square = Shift(to, kPawnMoveDirection[static_cast(them)]); + const auto capture_square = Shift(to, kPawnMoveDirection[them]); irreversible_data_.captured_piece = Piece::kPawn; // En passant always captures a pawn dirty.Add(Piece::kPawn, us, from, to); dirty.Add(Piece::kPawn, them, capture_square, Nnue::kNoSquare); @@ -134,10 +129,10 @@ void Position::DoMove(const LegalMove &move) { PlacePiece(to, promoted_to, us); for (const auto castling_side : {CastlingSide::k00, CastlingSide::k000}) { - const auto their_rook = rook_positions_[static_cast(them)][static_cast(castling_side)]; + const auto their_rook = rook_positions_[them][castling_side]; if (to == their_rook) { - irreversible_data_.castling_rights[static_cast(them)] &= - ~static_cast(kCastlingRightsForSide[static_cast(castling_side)]); + irreversible_data_.castling_rights[them] &= + ~static_cast(kCastlingRightsForSide[castling_side]); } } } else if (move.IsCastling()) { @@ -147,30 +142,28 @@ void Position::DoMove(const LegalMove &move) { const auto king_from = from; // Determine which side based on king destination - const auto color_idx = static_cast(us); CastlingSide side; BitIndex rook_from; - if (king_to == kKingCastlingDestination[color_idx][0]) { + if (king_to == kKingCastlingDestination[us][CastlingSide::k00]) { side = CastlingSide::k00; - rook_from = rook_positions_[color_idx][0]; + rook_from = rook_positions_[us][CastlingSide::k00]; } else { side = CastlingSide::k000; - rook_from = rook_positions_[color_idx][1]; + rook_from = rook_positions_[us][CastlingSide::k000]; } - const auto side_idx = static_cast(side); dirty.Add(Piece::kKing, us, king_from, - kKingCastlingDestination[color_idx][side_idx]); + kKingCastlingDestination[us][side]); dirty.Add(Piece::kRook, us, rook_from, - kRookCastlingDestination[color_idx][side_idx]); + kRookCastlingDestination[us][side]); RemovePiece(king_from, us); RemovePiece(rook_from, us); - PlacePiece(kKingCastlingDestination[color_idx][side_idx], Piece::kKing, us); - PlacePiece(kRookCastlingDestination[color_idx][side_idx], Piece::kRook, us); + PlacePiece(kKingCastlingDestination[us][side], Piece::kKing, us); + PlacePiece(kRookCastlingDestination[us][side], Piece::kRook, us); - king_position_[color_idx] = kKingCastlingDestination[color_idx][side_idx]; - irreversible_data_.castling_rights[color_idx] = 0; + king_position_[us] = kKingCastlingDestination[us][side]; + irreversible_data_.castling_rights[us] = 0; } else { // Normal move (including pawn pushes and double pushes) const auto piece_to_move = board_[from]; @@ -193,27 +186,27 @@ void Position::DoMove(const LegalMove &move) { MovePiece(from, to, us); if (piece_to_move == Piece::kKing) { - king_position_[static_cast(us)] = to; - irreversible_data_.castling_rights[static_cast(us)] = 0; + king_position_[us] = to; + irreversible_data_.castling_rights[us] = 0; } for (auto castling_side : {CastlingSide::k00, CastlingSide::k000}) { - const auto our_rook = rook_positions_[static_cast(us)][static_cast(castling_side)]; - const auto their_rook = rook_positions_[static_cast(them)][static_cast(castling_side)]; + const auto our_rook = rook_positions_[us][castling_side]; + const auto their_rook = rook_positions_[them][castling_side]; if (from == our_rook) { - irreversible_data_.castling_rights[static_cast(us)] &= - ~static_cast(kCastlingRightsForSide[static_cast(castling_side)]); + irreversible_data_.castling_rights[us] &= + ~static_cast(kCastlingRightsForSide[castling_side]); } if (to == their_rook) { - irreversible_data_.castling_rights[static_cast(them)] &= - ~static_cast(kCastlingRightsForSide[static_cast(castling_side)]); + irreversible_data_.castling_rights[them] &= + ~static_cast(kCastlingRightsForSide[castling_side]); } } } for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( - color)][irreversible_data_.castling_rights[static_cast(color)] + hash_ ^= hasher_.cr_hash[ + color][irreversible_data_.castling_rights[color] .to_ulong()]; } side_to_move_ = Flip(side_to_move_); @@ -243,8 +236,8 @@ void SimpleChessEngine::Position::DoMove(NullMove) { void Position::UndoMove(const LegalMove &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( - color)][irreversible_data_.castling_rights[static_cast(color)] + hash_ ^= hasher_.cr_hash[ + color][irreversible_data_.castling_rights[color] .to_ulong()]; } if (ep_square.has_value()) { @@ -260,8 +253,8 @@ void Position::UndoMove(const LegalMove &move, const IrreversibleData &data) { irreversible_data_ = data; for (const auto color : {Player::kWhite, Player::kBlack}) { - hash_ ^= hasher_.cr_hash[static_cast( - color)][irreversible_data_.castling_rights[static_cast(color)] + hash_ ^= hasher_.cr_hash[ + color][irreversible_data_.castling_rights[color] .to_ulong()]; } if (irreversible_data_.en_croissant_square.has_value()) { @@ -271,7 +264,7 @@ void Position::UndoMove(const LegalMove &move, const IrreversibleData &data) { side_to_move_ = Flip(side_to_move_); if (move.IsEnPassant()) { - const auto capture_square = Shift(to, kPawnMoveDirection[static_cast(them)]); + const auto capture_square = Shift(to, kPawnMoveDirection[them]); MovePiece(to, from, us); PlacePiece(capture_square, Piece::kPawn, them); } else if (move.IsPromotion()) { @@ -279,25 +272,23 @@ void Position::UndoMove(const LegalMove &move, const IrreversibleData &data) { if (!!captured_piece) PlacePiece(to, captured_piece, them); PlacePiece(from, Piece::kPawn, us); } else if (move.IsCastling()) { - const auto color_idx = static_cast(us); CastlingSide side; - if (to == kKingCastlingDestination[color_idx][0]) { + if (to == kKingCastlingDestination[us][CastlingSide::k00]) { side = CastlingSide::k00; } else { side = CastlingSide::k000; } - const auto side_idx = static_cast(side); - const auto rook_from = rook_positions_[color_idx][side_idx]; + const auto rook_from = rook_positions_[us][side]; - RemovePiece(kKingCastlingDestination[color_idx][side_idx], us); - RemovePiece(kRookCastlingDestination[color_idx][side_idx], us); + RemovePiece(kKingCastlingDestination[us][side], us); + RemovePiece(kRookCastlingDestination[us][side], us); PlacePiece(from, Piece::kKing, us); PlacePiece(rook_from, Piece::kRook, us); - king_position_[color_idx] = from; + king_position_[us] = from; } else { // Normal move const auto piece_to_move = board_[to]; @@ -306,7 +297,7 @@ void Position::UndoMove(const LegalMove &move, const IrreversibleData &data) { if (!!captured_piece) PlacePiece(to, captured_piece, them); if (piece_to_move == Piece::kKing) { - king_position_[static_cast(us)] = from; + king_position_[us] = from; } } @@ -329,13 +320,14 @@ void SimpleChessEngine::Position::UndoMove(NullMove, } bool Position::CanPseudoCastle(CastlingSide side) const { - const auto us = static_cast(side_to_move_); - const auto cs = static_cast(side); - if (!irreversible_data_.castling_rights[us].test(cs)) return false; - const auto obstacles = GetAllPieces() & ~SingleSquare(king_position_[us]) & - ~SingleSquare(rook_positions_[us][cs]); - return ((castling_squares_for_king_[us][cs] | - castling_squares_for_rook_[us][cs]) & + if (!irreversible_data_.castling_rights[side_to_move_].test( + std::to_underlying(side))) { + return false; + } + const auto obstacles = GetAllPieces() & ~SingleSquare(king_position_[side_to_move_]) & + ~SingleSquare(rook_positions_[side_to_move_][side]); + return ((castling_squares_for_king_[side_to_move_][side] | + castling_squares_for_rook_[side_to_move_][side]) & obstacles) .None(); } @@ -401,7 +393,7 @@ bool Position::IsPseudoLegal(const Move &move) { bool Position::IsLegal(const Move &move) const { return IsLegal( - move, irreversible_data_.blockers[static_cast(side_to_move_)]); + move, irreversible_data_.blockers[side_to_move_]); } bool Position::IsLegal(const Move &move, Bitboard blockers) const { @@ -411,7 +403,7 @@ bool Position::IsLegal(const Move &move, Bitboard blockers) const { const auto to = move.To(); if (move.IsCastling()) { return !IsUnderCheck() && - CanCastle(to == kKingCastlingDestination[static_cast(us)][0] + CanCastle(to == kKingCastlingDestination[us][CastlingSide::k00] ? CastlingSide::k00 : CastlingSide::k000); } @@ -440,20 +432,20 @@ bool Position::IsLegal(const Move &move, Bitboard blockers) const { [[nodiscard]] bool Position::CanCastle( const CastlingSide castling_side) const { const auto us = side_to_move_; - const auto us_idx = static_cast(us); - const auto cs_idx = static_cast(castling_side); - - if (!irreversible_data_.castling_rights[us_idx].test(cs_idx)) return false; + if (!irreversible_data_.castling_rights[us].test( + std::to_underlying(castling_side))) { + return false; + } - const auto king_position = king_position_[us_idx]; - const auto rook_position = rook_positions_[us_idx][cs_idx]; + const auto king_position = king_position_[us]; + const auto rook_position = rook_positions_[us][castling_side]; const auto obstacles = GetAllPieces() & ~SingleSquare(king_position) & ~SingleSquare(rook_position); - auto king_path = castling_squares_for_king_[us_idx][cs_idx]; + auto king_path = castling_squares_for_king_[us][castling_side]; - if (((king_path | castling_squares_for_rook_[us_idx][cs_idx]) & obstacles) + if (((king_path | castling_squares_for_rook_[us][castling_side]) & obstacles) .Any()) return false; @@ -466,8 +458,8 @@ 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) { + const ByPlayer> &castling_rights) { + for (const auto color : kPlayers) { hash_ ^= hasher_.cr_hash[color][irreversible_data_.castling_rights[color] .to_ulong()]; hash_ ^= hasher_.cr_hash[color][castling_rights[color].to_ulong()]; @@ -490,40 +482,40 @@ void Position::SetEnCroissantSquare(std::optional square) { } } -void Position::SetKingPositions(const std::array &king_position) { +void Position::SetKingPositions(const ByPlayer &king_position) { king_position_ = king_position; } void Position::SetRookPositions( - const std::array, kColors> &rook_positions) { + const ByPlayer> &rook_positions) { rook_positions_ = rook_positions; } void Position::SetCastlingSquares( - const std::array, kColors> &cs_king, - const std::array, kColors> &cs_rook) { + const ByPlayer> &cs_king, + const ByPlayer> &cs_rook) { castling_squares_for_king_ = cs_king; castling_squares_for_rook_ = cs_rook; } Bitboard Position::GetAllPieces() const { - return pieces_by_color_[static_cast(Player::kWhite)] | - pieces_by_color_[static_cast(Player::kBlack)]; + return pieces_by_color_[Player::kWhite] | + pieces_by_color_[Player::kBlack]; } bool Position::IsInsufficientMaterial() const { constexpr Bitboard kDarkSquares{0xAA55AA55AA55AA55ULL}; constexpr Bitboard kLightSquares{0x55AA55AA55AA55AAULL}; - if (pieces_by_type_[static_cast(Piece::kPawn)].Any() || - pieces_by_type_[static_cast(Piece::kRook)].Any() || - pieces_by_type_[static_cast(Piece::kQueen)].Any()) { + if (pieces_by_type_[Piece::kPawn].Any() || + pieces_by_type_[Piece::kRook].Any() || + pieces_by_type_[Piece::kQueen].Any()) { return false; } const auto knights = - pieces_by_type_[static_cast(Piece::kKnight)]; - const auto bishops = pieces_by_type_[static_cast(Piece::kBishop)]; + pieces_by_type_[Piece::kKnight]; + const auto bishops = pieces_by_type_[Piece::kBishop]; if (knights.Any()) { return bishops.None() && !knights.MoreThanOne(); @@ -534,35 +526,34 @@ bool Position::IsInsufficientMaterial() const { } const Bitboard &Position::GetPieces(const Player player) const { - return pieces_by_color_[static_cast(player)]; + return pieces_by_color_[player]; } template Bitboard Position::GetPiecesByType(const Player player) const { - return pieces_by_color_[static_cast(player)] & - pieces_by_type_[static_cast(piece)]; + return pieces_by_color_[player] & + pieces_by_type_[piece]; } template Bitboard Position::GetCastlingSquares(CastlingSide side) const { static_assert(piece == Piece::kRook || piece == Piece::kKing); if constexpr (piece == Piece::kKing) { - return castling_squares_for_king_[static_cast(side_to_move_)] - [static_cast(side)]; + return castling_squares_for_king_[side_to_move_] + [side]; } if constexpr (piece == Piece::kRook) { - return castling_squares_for_rook_[static_cast(side_to_move_)] - [static_cast(side)]; + return castling_squares_for_rook_[side_to_move_] + [side]; } assert(false); return {}; } Bitboard Position::GetAllPawnAttacks(const Player player) const { - const auto us = static_cast(player); const auto pawns = GetPiecesByType(player); - return Shift(pawns, kPawnAttackDirections[us][0]) | - Shift(pawns, kPawnAttackDirections[us][1]); + return Shift(pawns, kPawnAttackDirections[player][0]) | + Shift(pawns, kPawnAttackDirections[player][1]); } Piece Position::GetPieceAt(const BitIndex index) const { @@ -571,20 +562,20 @@ Piece Position::GetPieceAt(const BitIndex index) const { } BitIndex Position::GetKingSquare(const Player player) const { - return king_position_[static_cast(player)]; + return king_position_[player]; } BitIndex Position::GetCastlingRookSquare(Player player, CastlingSide side) const { - return rook_positions_[static_cast(player)] - [static_cast(side)]; + return rook_positions_[player] + [side]; } bool Position::IsUnderAttack(const BitIndex square, const Player us, const Bitboard transparent) const { assert(IsOk(square)); return (Attackers(square, transparent) & - pieces_by_color_[static_cast(Flip(us))]) + pieces_by_color_[Flip(us)]) .Any(); } @@ -595,8 +586,7 @@ bool Position::IsUnderCheck(const Player player) const { } Eval Position::EstimatePiece(const Piece piece) const { - const auto piece_type_idx = static_cast(piece); - return kPieceValues[piece_type_idx](evaluation_data_.non_pawn_material); + return kPieceValues[piece](evaluation_data_.non_pawn_material); } bool Position::StaticExchangeEvaluation(const Move &move, @@ -643,18 +633,18 @@ bool Position::StaticExchangeEvaluation(const Move &move, Bitboard occupancy = GetAllPieces() ^ SingleSquare(from) ^ SingleSquare(to); [[unlikely]] if (move.IsEnPassant()) { - occupancy ^= Shift(SingleSquare(to), kPawnMoveDirection[static_cast(them)]); + occupancy ^= Shift(SingleSquare(to), kPawnMoveDirection[them]); } Bitboard attackers = Attackers(to, ~occupancy) & occupancy; auto color = them; - auto diagonal_xray = pieces_by_type_[static_cast(Piece::kBishop)] | - pieces_by_type_[static_cast(Piece::kQueen)]; + auto diagonal_xray = pieces_by_type_[Piece::kBishop] | + pieces_by_type_[Piece::kQueen]; - auto straight_xray = pieces_by_type_[static_cast(Piece::kRook)] | - pieces_by_type_[static_cast(Piece::kQueen)]; + auto straight_xray = pieces_by_type_[Piece::kRook] | + pieces_by_type_[Piece::kQueen]; for (;;) { Bitboard our_attackers = attackers & GetPieces(color); @@ -666,11 +656,10 @@ bool Position::StaticExchangeEvaluation(const Move &move, next_victim = Piece::kKing; - for (size_t attacker_idx = static_cast(Piece::kPawn); - attacker_idx <= static_cast(Piece::kQueen); ++attacker_idx) { - if (attacker_bitboard = our_attackers & pieces_by_type_[attacker_idx]; + for (const auto attacker : kPiecesByValue) { + if (attacker_bitboard = our_attackers & pieces_by_type_[attacker]; attacker_bitboard.Any()) { - next_victim = static_cast(attacker_idx); + next_victim = attacker; break; } } @@ -710,7 +699,7 @@ const std::optional &Position::GetEnCroissantSquare() const { return irreversible_data_.en_croissant_square; } -const std::array, kColors> &Position::GetCastlingRights() const { +const ByPlayer> &Position::GetCastlingRights() const { return irreversible_data_.castling_rights; } @@ -723,24 +712,23 @@ Bitboard Position::Attackers(const BitIndex square, (GetPawnAttacks(square, Player::kBlack) & GetPiecesByType(Player::kWhite)) | (AttackTable::GetAttackMap(square, occupancy) & - pieces_by_type_[static_cast(Piece::kKnight)]) | + pieces_by_type_[Piece::kKnight]) | (AttackTable::GetAttackMap(square, occupancy) & - pieces_by_type_[static_cast(Piece::kBishop)]) | + pieces_by_type_[Piece::kBishop]) | (AttackTable::GetAttackMap(square, occupancy) & - pieces_by_type_[static_cast(Piece::kRook)]) | + pieces_by_type_[Piece::kRook]) | (AttackTable::GetAttackMap(square, occupancy) & - pieces_by_type_[static_cast(Piece::kQueen)]) | + pieces_by_type_[Piece::kQueen]) | (AttackTable::GetAttackMap(square, occupancy) & - pieces_by_type_[static_cast(Piece::kKing)]); + pieces_by_type_[Piece::kKing]); } void Position::ComputePins(const Player us) { const Player them = Flip(us); - const auto us_idx = static_cast(us); - irreversible_data_.blockers[us_idx] = kEmptyBoard; - irreversible_data_.pinners[us_idx] = kEmptyBoard; + irreversible_data_.blockers[us] = kEmptyBoard; + irreversible_data_.pinners[us] = kEmptyBoard; const BitIndex king_square = GetKingSquare(us); @@ -764,9 +752,9 @@ void Position::ComputePins(const Player us) { GetPiecesByType(them)) & ~straight_blockers; - irreversible_data_.pinners[us_idx] = diagonal_pinners | straight_pinners; + irreversible_data_.pinners[us] = diagonal_pinners | straight_pinners; - Bitboard &blockers = irreversible_data_.blockers[us_idx]; + Bitboard &blockers = irreversible_data_.blockers[us]; while (diagonal_pinners.Any()) { const BitIndex square = diagonal_pinners.PopFirstBit(); diff --git a/Chess/Position.h b/Chess/Position.h index 6424fb0..6afd711 100644 --- a/Chess/Position.h +++ b/Chess/Position.h @@ -55,12 +55,9 @@ class Position { bool operator==(const EvaluationData &) const = default; Eval non_pawn_material{}; //!< Total material value excluding pawns. - std::array - material{}; //!< Material value for each color. - std::array - psqt{}; //!< Piece-square table scores for each color. - std::array, kColors> - piece_counts{}; + ByPlayer material{}; //!< Material value for each color. + ByPlayer psqt{}; //!< Piece-square table scores for each color. + ByPlayer> piece_counts{}; }; /** @@ -73,13 +70,10 @@ class Position { std::optional en_croissant_square{}; //!< Optional square for en passant. - std::array, kColors> - castling_rights{}; //!< Castling rights for each color. + ByPlayer> castling_rights{}; //!< Castling rights for each color. - std::array - pinners{}; //!< Pieces that are pinning opponent's pieces. - std::array - blockers{}; //!< Pieces that are blocking attacks on the king. + ByPlayer pinners{}; //!< Pieces that are pinning opponent's pieces. + ByPlayer blockers{}; //!< Pieces that are blocking attacks on the king. Piece captured_piece{Piece::kNone}; //!< Piece captured by the last move @@ -205,8 +199,8 @@ class Position { [[nodiscard]] Bitboard GetPiecesOf(const Player player, const Piece piece) const { - return pieces_by_color_[static_cast(player)] & - pieces_by_type_[static_cast(piece)]; + return pieces_by_color_[player] & + pieces_by_type_[piece]; } /** @@ -280,8 +274,7 @@ class Position { [[nodiscard]] const std::optional &GetEnCroissantSquare() const; - [[nodiscard]] const std::array, kColors> &GetCastlingRights() - const; + [[nodiscard]] const ByPlayer> &GetCastlingRights() const; template [[nodiscard]] Bitboard GetCastlingSquares(CastlingSide side) const; @@ -345,18 +338,18 @@ class Position { void MovePiece(const BitIndex from, const BitIndex to, const Player color); - void SetCastlingRights(const std::array, 2> &castling_rights); + void SetCastlingRights(const ByPlayer> &castling_rights); void SetEnCroissantSquare(std::optional square); - void SetKingPositions(const std::array &king_position); + void SetKingPositions(const ByPlayer &king_position); void SetRookPositions( - const std::array, kColors> &rook_positions); + const ByPlayer> &rook_positions); void SetCastlingSquares( - const std::array, kColors> &cs_king, - const std::array, kColors> &cs_rook); + const ByPlayer> &cs_king, + const ByPlayer> &cs_rook); [[nodiscard]] Eval EstimatePiece(Piece piece) const; @@ -371,19 +364,17 @@ class Position { Player side_to_move_{}; //!< Whose side to move. - std::array - pieces_by_type_{}; //!< Bitboard of pieces of certain type - std::array - pieces_by_color_{}; //!< Bitboard of pieces for each player + ByPiece pieces_by_type_{}; //!< Bitboard of pieces of certain type + ByPlayer pieces_by_color_{}; //!< Bitboard of pieces for each player std::array board_{}; //!< Current position of pieces - std::array king_position_{}; - std::array, kColors> + ByPlayer king_position_{}; + ByPlayer> rook_positions_{}; // doesn't need to be updated - std::array, kColors> castling_squares_for_king_{}; - std::array, kColors> castling_squares_for_rook_{}; + ByPlayer> castling_squares_for_king_{}; + ByPlayer> castling_squares_for_rook_{}; const static Hasher hasher_; Hash hash_{}; diff --git a/Chess/PositionFactory.h b/Chess/PositionFactory.h index 3a04035..4f0c111 100644 --- a/Chess/PositionFactory.h +++ b/Chess/PositionFactory.h @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -29,8 +30,8 @@ struct PositionFactory { static constexpr int kMaxPiecesPerSide = 16; static constexpr int kMaxPawnsPerSide = 8; - using CastlingRightsBySide = std::array, kColors>; - using RookSquares = std::array, 2>, kColors>; + using CastlingRightsBySide = ByPlayer>; + using RookSquares = ByPlayer>>; struct Fields { std::string board; @@ -42,8 +43,8 @@ struct PositionFactory { }; struct Placement { - std::array kings{}; - std::array, kColors> back_rank_rooks{}; + ByPlayer kings{}; + ByPlayer> back_rank_rooks{}; }; [[nodiscard]] static constexpr Rank BackRank(Player color) { @@ -90,9 +91,9 @@ inline std::optional PositionFactory::Split( inline std::optional PositionFactory::PlacePieces( std::string_view board, Position &position) { Placement placement; - std::array kings{}; - std::array pawns{}; - std::array pieces{}; + ByPlayer kings{}; + ByPlayer pawns{}; + ByPlayer pieces{}; Rank rank = kRanks - 1; File file = 0; @@ -112,27 +113,26 @@ inline std::optional PositionFactory::PlacePieces( const auto entry = kCharToPiece.find(symbol); if (entry == kCharToPiece.end() || file == kFiles) return std::nullopt; const auto [piece, color] = entry->second; - const auto us = static_cast(color); const auto square = GetSquareIndex(file, rank); - if (++pieces[us] > kMaxPiecesPerSide) return std::nullopt; + if (++pieces[color] > kMaxPiecesPerSide) return std::nullopt; if (piece == Piece::kKing) { - if (++kings[us] > 1) return std::nullopt; - placement.kings[us] = square; + if (++kings[color] > 1) return std::nullopt; + placement.kings[color] = square; } - if (piece == Piece::kPawn && - (rank == 0 || rank == kRanks - 1 || ++pawns[us] > kMaxPawnsPerSide)) { + if (piece == Piece::kPawn && (rank == 0 || rank == kRanks - 1 || + ++pawns[color] > kMaxPawnsPerSide)) { return std::nullopt; } if (piece == Piece::kRook && rank == BackRank(color)) { - placement.back_rank_rooks[us][file] = true; + placement.back_rank_rooks[color][file] = true; } position.PlacePiece(square, piece, color); ++file; } - if (rank != 0 || file != kFiles || kings != std::array{1, 1}) { + if (rank != 0 || file != kFiles || kings != ByPlayer{{1, 1}}) { return std::nullopt; } return placement; @@ -148,20 +148,19 @@ inline std::optional PositionFactory::ParseSideToMove( inline PositionFactory::RookSquares PositionFactory::FindCastlingRooks( const Placement &placement) { RookSquares rooks{}; - for (const auto color : {Player::kWhite, Player::kBlack}) { - const auto us = static_cast(color); - const auto &back_rank_rooks = placement.back_rank_rooks[us]; - const auto king_file = static_cast(placement.kings[us] % kFiles); + for (const auto color : kPlayers) { + const auto &back_rank_rooks = placement.back_rank_rooks[color]; + const auto king_file = static_cast(placement.kings[color] % kFiles); for (File file = 0; file < king_file; ++file) { if (back_rank_rooks[file]) { - rooks[us][static_cast(CastlingSide::k000)] = + rooks[color][CastlingSide::k000] = GetSquareIndex(file, BackRank(color)); break; } } for (File file = kFiles - 1; file > king_file; --file) { if (back_rank_rooks[file]) { - rooks[us][static_cast(CastlingSide::k00)] = + rooks[color][CastlingSide::k00] = GetSquareIndex(file, BackRank(color)); break; } @@ -190,14 +189,13 @@ PositionFactory::ParseCastlingRights(std::string_view text, const auto color = index < 2 ? Player::kWhite : Player::kBlack; const auto side = index % 2 == 0 ? CastlingSide::k00 : CastlingSide::k000; - const auto us = static_cast(color); - const auto bit = static_cast(side); + const auto bit = std::to_underlying(side); const bool king_on_back_rank = - placement.kings[us] / kFiles == BackRank(color); - if (rights[us].test(bit) || !king_on_back_rank || !rooks[us][bit]) { + placement.kings[color] / kFiles == BackRank(color); + if (rights[color].test(bit) || !king_on_back_rank || !rooks[color][side]) { return std::nullopt; } - rights[us].set(bit); + rights[color].set(bit); } return rights; } @@ -267,24 +265,20 @@ inline std::optional PositionFactory::TryParse( if (!halfmove_clock || !fullmove_number) return std::nullopt; const auto &kings = placement->kings; - std::array, kColors> rook_squares{}; - for (size_t us = 0; us < kColors; ++us) { - for (size_t side = 0; side < 2; ++side) { - rook_squares[us][side] = rooks[us][side].value_or(BitIndex{0}); + ByPlayer> rook_squares{}; + ByPlayer> cs_king{}; + ByPlayer> cs_rook{}; + for (const auto color : kPlayers) { + for (const auto side : kCastlingSides) { + rook_squares[color][side] = rooks[color][side].value_or(BitIndex{0}); + cs_king[color][side] = + rook_between[kings[color]][kKingCastlingDestination[color][side]]; + cs_rook[color][side] = rook_between[rook_squares[color][side]] + [kRookCastlingDestination[color][side]]; } } position.SetKingPositions(kings); position.SetRookPositions(rook_squares); - 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]]}}}; - std::array, kColors> cs_rook = { - {{rook_between[rook_squares[0][0]][kRookCastlingDestination[0][0]], - rook_between[rook_squares[0][1]][kRookCastlingDestination[0][1]]}, - {rook_between[rook_squares[1][0]][kRookCastlingDestination[1][0]], - rook_between[rook_squares[1][1]][kRookCastlingDestination[1][1]]}}}; position.SetCastlingSquares(cs_king, cs_rook); position.Init(*halfmove_clock, std::max(*fullmove_number, 1)); @@ -326,25 +320,24 @@ inline std::string SimpleChessEngine::FenFactory::operator()( const auto castling_rights = position.GetCastlingRights(); - if (castling_rights[static_cast(Player::kWhite)].test( - static_cast(CastlingSide::k00))) { + if (castling_rights[Player::kWhite].test( + std::to_underlying(CastlingSide::k00))) { ss << 'K'; } - if (castling_rights[static_cast(Player::kWhite)].test( - static_cast(CastlingSide::k000))) { + if (castling_rights[Player::kWhite].test( + std::to_underlying(CastlingSide::k000))) { ss << 'Q'; } - if (castling_rights[static_cast(Player::kBlack)].test( - static_cast(CastlingSide::k00))) { + if (castling_rights[Player::kBlack].test( + std::to_underlying(CastlingSide::k00))) { ss << 'k'; } - if (castling_rights[static_cast(Player::kBlack)].test( - static_cast(CastlingSide::k000))) { + if (castling_rights[Player::kBlack].test( + std::to_underlying(CastlingSide::k000))) { ss << 'q'; } - if ((castling_rights[static_cast(Player::kWhite)] | - castling_rights[static_cast(Player::kBlack)]) + if ((castling_rights[Player::kWhite] | castling_rights[Player::kBlack]) .none()) { ss << '-'; } diff --git a/Chess/Settings.h b/Chess/Settings.h index 5b67250..8392d35 100644 --- a/Chess/Settings.h +++ b/Chess/Settings.h @@ -7,16 +7,15 @@ namespace SimpleChessEngine { struct Settings { struct EvaluationParameters { - inline static std::array mobility = [] { - std::array values{}; - values[static_cast(Piece::kKnight)] = TaperedEval{{4, 2}}; - values[static_cast(Piece::kBishop)] = TaperedEval{{7, 3}}; - values[static_cast(Piece::kRook)] = TaperedEval{{2, 4}}; - values[static_cast(Piece::kQueen)] = TaperedEval{{2, 2}}; + inline static ByPiece mobility = [] { + ByPiece values{}; + values[Piece::kKnight] = TaperedEval{{4, 2}}; + values[Piece::kBishop] = TaperedEval{{7, 3}}; + values[Piece::kRook] = TaperedEval{{2, 4}}; + values[Piece::kQueen] = TaperedEval{{2, 2}}; return values; }(); - inline static std::array, 8>, - kPieceTypes> + inline static ByPiece, 8>> psqt_adjustment{}; inline static TaperedEval doubled_pawn{{-15, -15}}; inline static TaperedEval isolated_pawn{{-10, -10}}; @@ -45,11 +44,11 @@ struct Settings { }; return values; }(); - inline static std::array material_value = [] { + inline static ByPiece material_value = [] { auto values = kPieceValues; - values[static_cast(Piece::kKnight)] + values[Piece::kKnight] .eval[static_cast(GamePhase::kEndGame)] = 275; - values[static_cast(Piece::kBishop)] + values[Piece::kBishop] .eval[static_cast(GamePhase::kMiddleGame)] = 375; return values; }(); @@ -59,12 +58,12 @@ struct Settings { inline static Eval king_open_file = -14; inline static Eval king_pawn_storm_near = -12; inline static Eval king_pawn_storm_far = -8; - inline static std::array king_attack = [] { - std::array values{}; - values[static_cast(Piece::kKnight)] = 8; - values[static_cast(Piece::kBishop)] = 10; - values[static_cast(Piece::kRook)] = 18; - values[static_cast(Piece::kQueen)] = 20; + inline static ByPiece king_attack = [] { + ByPiece values{}; + values[Piece::kKnight] = 8; + values[Piece::kBishop] = 10; + values[Piece::kRook] = 18; + values[Piece::kQueen] = 20; return values; }(); inline static bool pawns_enabled = true; @@ -101,13 +100,13 @@ struct Settings { } static void SetMaterialValue(Piece piece, GamePhase phase, Eval value) { - material_value[static_cast(piece)] + material_value[piece] .eval[static_cast(phase)] = value; material_enabled = material_value != kPieceValues; } static void SetMobility(Piece piece, GamePhase phase, Eval value) { - mobility[static_cast(piece)].eval[static_cast(phase)] = + mobility[piece].eval[static_cast(phase)] = value; mobility_enabled = false; for (const auto& weight : mobility) { @@ -118,7 +117,7 @@ struct Settings { static void SetPsqtAdjustment(Piece piece, size_t relative_rank, size_t mirrored_file, GamePhase phase, Eval value) { - psqt_adjustment[static_cast(piece)][relative_rank][mirrored_file] + psqt_adjustment[piece][relative_rank][mirrored_file] .eval[static_cast(phase)] = value; psqt_adjustment_enabled = false; for (const auto& piece_values : psqt_adjustment) { @@ -164,7 +163,7 @@ struct Settings { static void SetKingAttack(Eval value) { static_assert(piece == Piece::kKnight || piece == Piece::kBishop || piece == Piece::kRook || piece == Piece::kQueen); - king_attack[static_cast(piece)] = value; + king_attack[piece] = value; RefreshKingSafetyEnabled(); } @@ -256,7 +255,7 @@ struct Settings { enum class Strategy { Linear, Exponential }; static constexpr bool kEnabled = false; static constexpr Eval kPawnValue = - kPieceValues[static_cast(Piece::kPawn)] + kPieceValues[Piece::kPawn] .eval[static_cast(GamePhase::kMiddleGame)]; static constexpr Eval kDelta = kPawnValue * 3 / 4; static constexpr Strategy kStrategy = Strategy::Linear; diff --git a/Chess/StreamUtility.h b/Chess/StreamUtility.h index af150e5..92ce4d3 100644 --- a/Chess/StreamUtility.h +++ b/Chess/StreamUtility.h @@ -22,10 +22,10 @@ inline static std::unordered_map> kCharToPiece = {'k', {Piece::kKing, Player::kBlack}}, {'K', {Piece::kKing, Player::kWhite}}}; -inline constexpr std::array kPiecesChars = {' ', 'p', 'n', 'b', 'r', 'q', 'k'}; +inline constexpr ByPiece kPiecesChars = {{' ', 'p', 'n', 'b', 'r', 'q', 'k'}}; inline char GetPieceChar(Piece piece, Player color) { - char piece_name = kPiecesChars[static_cast(piece)]; + char piece_name = kPiecesChars[piece]; return color == Player::kWhite ? toupper(piece_name) : piece_name; } @@ -57,7 +57,7 @@ inline std::ostream& operator<<(std::ostream& stream, const Move& move) { PrintCoordinates(to, stream); if (move.IsPromotion()) { - stream << kPiecesChars[static_cast(move.PromotionPiece())]; + stream << kPiecesChars[move.PromotionPiece()]; } return stream; diff --git a/Chess/SyzygyTablebase.cpp b/Chess/SyzygyTablebase.cpp index 40511d2..ce87b25 100644 --- a/Chess/SyzygyTablebase.cpp +++ b/Chess/SyzygyTablebase.cpp @@ -54,8 +54,8 @@ struct FathomPosition { result.rule50 = static_cast(std::min( position.GetHalfMoveClock(), std::numeric_limits::max())); const auto& rights = position.GetCastlingRights(); - result.castling = rights[static_cast(Player::kWhite)].any() || - rights[static_cast(Player::kBlack)].any() + result.castling = rights[Player::kWhite].any() || + rights[Player::kBlack].any() ? 1U : 0U; result.ep = position.GetEnCroissantSquare().has_value() @@ -130,8 +130,8 @@ void Syzygy::Disable() { bool Syzygy::CanProbe(const Position& position) const { if (position.GetAllPieces().Count() > max_pieces_) return false; const auto& rights = position.GetCastlingRights(); - return rights[static_cast(Player::kWhite)].none() && - rights[static_cast(Player::kBlack)].none(); + return rights[Player::kWhite].none() && + rights[Player::kBlack].none(); } std::optional Syzygy::Probe(const Position& position) const { diff --git a/Chess/UciCommunicator.h b/Chess/UciCommunicator.h index f085b04..4a623e2 100644 --- a/Chess/UciCommunicator.h +++ b/Chess/UciCommunicator.h @@ -27,11 +27,9 @@ namespace SimpleChessEngine { struct TournamentTime { - std::array player_time = { - std::chrono::milliseconds{0}, std::chrono::milliseconds{0}}; + ByPlayer player_time{}; - std::array player_inc = { - std::chrono::milliseconds{0}, std::chrono::milliseconds{0}}; + ByPlayer player_inc{}; std::optional moves_to_go; }; @@ -103,11 +101,10 @@ class SearchThread { constexpr double kSingleMoveTime = 500; const auto side = info.position.GetSideToMove(); - const auto side_idx = static_cast(side); const double time = - static_cast(tournament->player_time[side_idx].count()); + static_cast(tournament->player_time[side].count()); const double inc = - static_cast(tournament->player_inc[side_idx].count()); + static_cast(tournament->player_inc[side].count()); const double ply = 2.0 * (static_cast(info.position.GetFullMoveNumber()) - 1.0) + (side == Player::kBlack ? 1.0 : 0.0); @@ -476,10 +473,9 @@ struct EngineOptions { const std::string square = std::string{static_cast('A' + file)} + std::to_string(rank + 1); - const auto piece_index = static_cast(piece); options.emplace_back(std::make_unique( std::string{piece_names[piece_offset]} + "PSQT" + square + "MG", - Settings::EvaluationParameters::psqt_adjustment[piece_index][rank] + Settings::EvaluationParameters::psqt_adjustment[piece][rank] [file] .eval[0], -100, 100, [piece, rank, file](const int value) { @@ -488,7 +484,7 @@ struct EngineOptions { })); options.emplace_back(std::make_unique( std::string{piece_names[piece_offset]} + "PSQT" + square + "EG", - Settings::EvaluationParameters::psqt_adjustment[piece_index][rank] + Settings::EvaluationParameters::psqt_adjustment[piece][rank] [file] .eval[1], -100, 100, [piece, rank, file](const int value) { @@ -510,17 +506,16 @@ struct EngineOptions { template void AddMobilityOptions(const std::string& piece_name, const int minimum, const int maximum) { - constexpr auto piece_index = static_cast(piece); options.emplace_back(std::make_unique( piece_name + "MobilityMG", - Settings::EvaluationParameters::mobility[piece_index].eval[0], minimum, + Settings::EvaluationParameters::mobility[piece].eval[0], minimum, maximum, [](const int value) { Settings::EvaluationParameters::SetMobility( piece, GamePhase::kMiddleGame, value); })); options.emplace_back(std::make_unique( piece_name + "MobilityEG", - Settings::EvaluationParameters::mobility[piece_index].eval[1], minimum, + Settings::EvaluationParameters::mobility[piece].eval[1], minimum, maximum, [](const int value) { Settings::EvaluationParameters::SetMobility( piece, GamePhase::kEndGame, value); @@ -538,10 +533,9 @@ struct EngineOptions { template void AddMaterialValueOptions(const std::string& piece_name, const int minimum, const int maximum) { - constexpr auto piece_index = static_cast(piece); options.emplace_back(std::make_unique( piece_name + "ValueMG", - Settings::EvaluationParameters::material_value[piece_index] + Settings::EvaluationParameters::material_value[piece] .eval[static_cast(GamePhase::kMiddleGame)], minimum, maximum, [](const int value) { Settings::EvaluationParameters::SetMaterialValue( @@ -549,7 +543,7 @@ struct EngineOptions { })); options.emplace_back(std::make_unique( piece_name + "ValueEG", - Settings::EvaluationParameters::material_value[piece_index] + Settings::EvaluationParameters::material_value[piece] .eval[static_cast(GamePhase::kEndGame)], minimum, maximum, [](const int value) { Settings::EvaluationParameters::SetMaterialValue( @@ -674,7 +668,7 @@ struct EngineOptions { void AddKingAttackOption(const std::string& piece_name) { options.emplace_back(std::make_unique( piece_name + "KingAttackMG", - Settings::EvaluationParameters::king_attack[static_cast(piece)], + Settings::EvaluationParameters::king_attack[piece], 0, 50, [](const int value) { Settings::EvaluationParameters::SetKingAttack(value); })); @@ -1068,19 +1062,19 @@ inline void UciChessEngine::ParsePlayersTime(std::stringstream command) { std::size_t time; command >> time; if (token == "wtime") { - tournament_time.player_time[static_cast(kWhite)] = + tournament_time.player_time[kWhite] = std::chrono::milliseconds{time}; } if (token == "btime") { - tournament_time.player_time[static_cast(kBlack)] = + tournament_time.player_time[kBlack] = std::chrono::milliseconds{time}; } if (token == "winc") { - tournament_time.player_inc[static_cast(kWhite)] = + tournament_time.player_inc[kWhite] = std::chrono::milliseconds{time}; } if (token == "binc") { - tournament_time.player_inc[static_cast(kBlack)] = + tournament_time.player_inc[kBlack] = std::chrono::milliseconds{time}; } if (token == "movestogo" && time > 0) { diff --git a/Chess/Utility.h b/Chess/Utility.h index a4ec05f..fcb3781 100644 --- a/Chess/Utility.h +++ b/Chess/Utility.h @@ -9,6 +9,7 @@ #include #include "BitBoard.h" +#include "Move.h" #include "Piece.h" #include "Player.h" @@ -43,20 +44,20 @@ constexpr std::array kFileBB = {kFileA, kFileA << 1, kFileA << 2, constexpr std::array kCloseRanks = {kRankBB[2] | kRankBB[3], kRankBB[5] | kRankBB[4]}; -constexpr std::array, kColors> kDoubleMoveSpan = - {{{kCloseRanks[0] & kFileBB[0], kCloseRanks[0] & kFileBB[1], +constexpr ByPlayer> kDoubleMoveSpan = + {{{{kCloseRanks[0] & kFileBB[0], kCloseRanks[0] & kFileBB[1], kCloseRanks[0] & kFileBB[2], kCloseRanks[0] & kFileBB[3], kCloseRanks[0] & kFileBB[4], kCloseRanks[0] & kFileBB[5], kCloseRanks[0] & kFileBB[6], kCloseRanks[0] & kFileBB[7]}, {kCloseRanks[1] & kFileBB[0], kCloseRanks[1] & kFileBB[1], kCloseRanks[1] & kFileBB[2], kCloseRanks[1] & kFileBB[3], kCloseRanks[1] & kFileBB[4], kCloseRanks[1] & kFileBB[5], - kCloseRanks[1] & kFileBB[6], kCloseRanks[1] & kFileBB[7]}}}; + kCloseRanks[1] & kFileBB[6], kCloseRanks[1] & kFileBB[7]}}}}; -constexpr std::array, kColors> - kKingCastlingDestination = {{{6, 2}, {62, 58}}}; -constexpr std::array, kColors> - kRookCastlingDestination = {{{5, 3}, {61, 59}}}; +constexpr ByPlayer> kKingCastlingDestination = { + {{{{{6, 2}}}, {{{62, 58}}}}}}; +constexpr ByPlayer> kRookCastlingDestination = { + {{{{{5, 3}}}, {{{61, 59}}}}}}; using Rank = std::int8_t; using File = std::int8_t; @@ -94,8 +95,8 @@ enum class CastlingRights : std::uint8_t { kAll = k00 | k000 }; -constexpr std::array kCastlingRightsForSide = {CastlingRights::k00, - CastlingRights::k000}; +constexpr ByCastlingSide kCastlingRightsForSide = { + {CastlingRights::k00, CastlingRights::k000}}; enum class Compass : std::int8_t { kNorth = kLineSize, @@ -141,23 +142,23 @@ constexpr Compass Invert(const Compass direction) { return square + static_cast(direction); } -constexpr std::array kPawnMoveDirection = {Compass::kNorth, Compass::kSouth}; -constexpr std::array, kColors> kPawnAttackDirections = { - {{Compass::kNorthWest, Compass::kNorthEast}, - {Compass::kSouthWest, Compass::kSouthEast}}}; +constexpr ByPlayer kPawnMoveDirection = { + {Compass::kNorth, Compass::kSouth}}; +constexpr ByPlayer> kPawnAttackDirections = { + {{{Compass::kNorthWest, Compass::kNorthEast}, + {Compass::kSouthWest, Compass::kSouthEast}}}}; struct PawnSpanTables { - std::array, kColors> front{}; - std::array, kColors> rear{}; - std::array, kColors> passed{}; + ByPlayer> front{}; + ByPlayer> rear{}; + ByPlayer> passed{}; std::array adjacent_files{}; }; consteval PawnSpanTables MakePawnSpanTables() { PawnSpanTables tables{}; - for (size_t side = 0; side < kColors; ++side) { - const int forward = - side == static_cast(Player::kWhite) ? 1 : -1; + for (const auto side : kPlayers) { + const int forward = side == Player::kWhite ? 1 : -1; for (size_t square = 0; square < kBoardArea; ++square) { const int file = static_cast(square % kLineSize); const int rank = static_cast(square / kLineSize); @@ -188,7 +189,7 @@ consteval PawnSpanTables MakePawnSpanTables() { tables.front[side][square] = Bitboard{front}; tables.rear[side][square] = Bitboard{rear}; tables.passed[side][square] = Bitboard{passed}; - if (side == 0) { + if (side == Player::kWhite) { tables.adjacent_files[square] = Bitboard{adjacent_files}; } } @@ -267,25 +268,25 @@ inline Bitboard Ray(const BitIndex from, const BitIndex to) { return bishop_ray[from][to] | rook_ray[from][to]; } -inline std::array, kColors> pawn_attacks{}; +inline ByPlayer> pawn_attacks{}; inline void InitPawnAttacks() { - for (auto color : {Player::kWhite, Player::kBlack}) { + for (const auto color : kPlayers) { for (BitIndex square = 0; square < static_cast(kBoardArea); ++square) { Bitboard res{}; for (const auto step : - kPawnAttackDirections[static_cast(color)]) { + kPawnAttackDirections[color]) { res |= GetShiftIfValid(square, step).value_or(Bitboard{}); } - pawn_attacks[static_cast(color)][square] = res; + pawn_attacks[color][square] = res; } } } [[nodiscard]] inline Bitboard GetPawnAttacks(const BitIndex square, const Player side) { - return pawn_attacks[static_cast(side)][square]; + return pawn_attacks[side][square]; } [[nodiscard]] inline std::string DrawBitboard(const Bitboard b) { diff --git a/Tests/EvaluationTests.cpp b/Tests/EvaluationTests.cpp index dc1788b..62c1d56 100644 --- a/Tests/EvaluationTests.cpp +++ b/Tests/EvaluationTests.cpp @@ -10,13 +10,13 @@ using namespace SimpleChessEngine; namespace EvaluationTests { TEST(PawnSpans, FrontAndRearAreColorRelative) { const auto d4 = GetSquareIndex(3, 3); - EXPECT_EQ(kPawnSpans.front[static_cast(Player::kWhite)][d4], + EXPECT_EQ(kPawnSpans.front[Player::kWhite][d4], kFileBB[3] & (kRankBB[4] | kRankBB[5] | kRankBB[6] | kRankBB[7])); - EXPECT_EQ(kPawnSpans.rear[static_cast(Player::kWhite)][d4], + EXPECT_EQ(kPawnSpans.rear[Player::kWhite][d4], kFileBB[3] & (kRankBB[0] | kRankBB[1] | kRankBB[2])); - EXPECT_EQ(kPawnSpans.front[static_cast(Player::kBlack)][d4], + EXPECT_EQ(kPawnSpans.front[Player::kBlack][d4], kFileBB[3] & (kRankBB[0] | kRankBB[1] | kRankBB[2])); - EXPECT_EQ(kPawnSpans.rear[static_cast(Player::kBlack)][d4], + EXPECT_EQ(kPawnSpans.rear[Player::kBlack][d4], kFileBB[3] & (kRankBB[4] | kRankBB[5] | kRankBB[6] | kRankBB[7])); } @@ -51,11 +51,11 @@ TEST(PawnSpans, EveryPrecompiledSpanMatchesReference) { } } - EXPECT_EQ(kPawnSpans.front[side_index][square], expected_front) + EXPECT_EQ(kPawnSpans.front[side][square], expected_front) << "side=" << side_index << " square=" << static_cast(square); - EXPECT_EQ(kPawnSpans.rear[side_index][square], expected_rear) + EXPECT_EQ(kPawnSpans.rear[side][square], expected_rear) << "side=" << side_index << " square=" << static_cast(square); - EXPECT_EQ(kPawnSpans.passed[side_index][square], expected_passed) + EXPECT_EQ(kPawnSpans.passed[side][square], expected_passed) << "side=" << side_index << " square=" << static_cast(square); EXPECT_EQ(kPawnSpans.adjacent_files[square], expected_adjacent_files) << "side=" << side_index << " square=" << static_cast(square); @@ -149,8 +149,7 @@ TEST(Material, RawPawnEndgameValue) { const auto position = PositionFactory{}("7k/8/8/3P4/8/8/8/K7 w - - 0 1"); const Eval baseline = position.Evaluate(); const Eval original = - Settings::EvaluationParameters::material_value[static_cast( - Piece::kPawn)] + Settings::EvaluationParameters::material_value[Piece::kPawn] .eval[1]; Settings::EvaluationParameters::SetMaterialValue( @@ -162,7 +161,7 @@ TEST(Material, RawPawnEndgameValue) { TEST(Mobility, KnightExcludesSquaresAttackedByEnemyPawns) { const auto position = PositionFactory{}("7k/8/4p3/8/3N4/8/8/K7 w - - 0 1"); - const auto piece = static_cast(Piece::kKnight); + const auto piece = Piece::kKnight; const TaperedEval original = Settings::EvaluationParameters::mobility[piece]; const Eval baseline = position.Evaluate(); @@ -179,7 +178,7 @@ TEST(Mobility, KnightExcludesSquaresAttackedByEnemyPawns) { TEST(Mobility, BishopExcludesSquaresAttackedByEnemyPawns) { const auto position = PositionFactory{}("k7/8/1p6/8/3B4/8/8/7K w - - 0 1"); - const auto piece = static_cast(Piece::kBishop); + const auto piece = Piece::kBishop; const TaperedEval original = Settings::EvaluationParameters::mobility[piece]; const Eval baseline = position.Evaluate(); @@ -196,7 +195,7 @@ TEST(Mobility, BishopExcludesSquaresAttackedByEnemyPawns) { TEST(Mobility, RookKeepsSquaresAttackedByEnemyPawns) { const auto position = PositionFactory{}("7k/8/4p3/8/3R4/8/8/K7 w - - 0 1"); - const auto piece = static_cast(Piece::kRook); + const auto piece = Piece::kRook; const TaperedEval original = Settings::EvaluationParameters::mobility[piece]; const Eval baseline = position.Evaluate(); @@ -213,7 +212,7 @@ TEST(Mobility, RookKeepsSquaresAttackedByEnemyPawns) { TEST(Mobility, QueenKeepsSquaresAttackedByEnemyPawns) { const auto position = PositionFactory{}("7k/8/4p3/8/3Q4/8/8/K7 w - - 0 1"); - const auto piece = static_cast(Piece::kQueen); + const auto piece = Piece::kQueen; const TaperedEval original = Settings::EvaluationParameters::mobility[piece]; const Eval baseline = position.Evaluate(); @@ -266,8 +265,7 @@ TEST(KingSafety, MultipleZoneAttackersUsePieceWeights) { "rnbq2kr/pppp1ppp/5n2/7Q/2B5/8/PPPPPPPP/RNB1K1NR w KQ - 0 1"); const Eval baseline = position.Evaluate(); const Eval original = - Settings::EvaluationParameters::king_attack[static_cast( - Piece::kQueen)]; + Settings::EvaluationParameters::king_attack[Piece::kQueen]; Settings::EvaluationParameters::SetKingAttack(original + 10); EXPECT_GT(position.Evaluate(), baseline); diff --git a/Tests/TypedMoveTests.cpp b/Tests/TypedMoveTests.cpp index 0446fe2..929ea28 100644 --- a/Tests/TypedMoveTests.cpp +++ b/Tests/TypedMoveTests.cpp @@ -69,7 +69,7 @@ TEST(TypedMoves, RejectsExposingKing) { const auto pseudo = position.TryPseudoLegal(MoveFactory{}(position, "e2f2")); ASSERT_TRUE(pseudo); EXPECT_FALSE(position.TryLegal(*pseudo)); - EXPECT_FALSE(position.TryLegal(*pseudo, position.GetIrreversibleData().blockers[0])); + EXPECT_FALSE(position.TryLegal(*pseudo, position.GetIrreversibleData().blockers[Player::kWhite])); } TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { @@ -96,7 +96,7 @@ TEST(TypedMoves, AcceptsEveryGeneratedLegalMove) { ASSERT_TRUE(legal); EXPECT_EQ(*legal, move); const auto explicit_blockers = position.TryLegal( - *pseudo, position.GetIrreversibleData().blockers[static_cast(position.GetSideToMove())]); + *pseudo, position.GetIrreversibleData().blockers[position.GetSideToMove()]); ASSERT_TRUE(explicit_blockers); EXPECT_EQ(*explicit_blockers, move); }