From a9f466b37bd4f1349f3c5a84f56330cb5e9681bd Mon Sep 17 00:00:00 2001 From: Mark <115177215+rektdie@users.noreply.github.com> Date: Wed, 18 Feb 2026 11:48:07 +0100 Subject: [PATCH 1/2] Add fast Board::IsLegal move validation --- source/board.cpp | 1249 +++++++++++++++++++++++--------------------- source/board.h | 6 +- source/datagen.cpp | 11 +- source/perft.cpp | 12 +- source/search.cpp | 18 +- 5 files changed, 694 insertions(+), 602 deletions(-) diff --git a/source/board.cpp b/source/board.cpp index bdb8a16..26f0167 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -1,582 +1,667 @@ -#include "board.h" -#include "movegen.h" -#include "tt.h" -#include -#include -#include -#include "utils.h" - -void Board::Reset() { - castlingRights = 0; - enPassantTarget = noEPTarget; - - halfMoves = 0; - fullMoves = 1; - - sideToMove = White; - occupied = 0ULL; - - pieces = std::array(); - colors = std::array(); - - accPair = ACC::AccumulatorPair(); - - pieceThreats = std::array(); - colorThreats = std::array(); - - moveList = std::array(); - - positionIndex = 0; - - currentMoveIndex = 0; - - hashKey = 0ULL; - pawnKey = 0ULL; - nonPawnKey = 0ULL; -} - -void Board::SetByFen(std::string_view fen) { - Reset(); - - // Starting from top left - int currSquare = a8; - - std::vector tokens = UTILS::split(fen, ' '); - std::vector pieceTokens = UTILS::split(tokens[0], '/'); - - constexpr std::string_view pieceTypes = "pnbrqk"; - - for (std::string_view rank : pieceTokens) { - for (const char piece : rank) { - if (std::isdigit(piece)) { - currSquare += piece - '0'; - continue; - } - - bool side = std::islower(piece); - int pieceType = pieceTypes.find(std::tolower(piece)); - - colors[side].SetBit(currSquare); - pieces[pieceType].SetBit(currSquare); - - currSquare++; - } - currSquare -= 16; - } - - sideToMove = tokens[1] == "b"; - - for (const char piece : tokens[2]) { - if (piece == 'K') castlingRights |= whiteKingRight; - else if (piece == 'Q') castlingRights |= whiteQueenRight; - else if (piece == 'k') castlingRights |= blackKingRight; - else if (piece == 'q') castlingRights |= blackQueenRight; - } - - if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]); - - // full and half move - if (tokens.size() > 4) { - halfMoves = std::stoi(tokens[4]); - fullMoves = std::stoi(tokens[5]); - } - - occupied = colors[White] | colors[Black]; - hashKey = UTILS::GetHashKey(*this); - MOVEGEN::GenThreatMaps(*this); - MOVEGEN::GenerateMoves(*this, true); - - int whiteKingFile = (pieces[King] & colors[White]).getLS1BIndex() % 8; - int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8; - - if (whiteKingFile > 3) { - accPair.mirroredWhite = true; - } - if (blackKingFile > 3) { - accPair.mirroredBlack = true; - } - - ResetAccPair(); -} - -std::string Board::GetFen() { - std::ostringstream fen; - - for (int rank = 7; rank >= 0; --rank) { - int emptyCount = 0; - - for (int file = 0; file < 8; ++file) { - int square = rank * 8 + file; - const uint64_t squareBit = 1ULL << square; - - if (!(occupied & squareBit)) { - ++emptyCount; - continue; - } - - if (emptyCount > 0) { - fen << emptyCount; - emptyCount = 0; - } - - static constexpr std::array pieceChars = {'p', 'n', 'b', 'r', 'q', 'k'}; - char pieceChar = '?'; - - for (size_t pieceType = 0; pieceType < pieceChars.size(); ++pieceType) { - if (pieces[pieceType] & squareBit) { - pieceChar = pieceChars[pieceType]; - break; - } - } - - fen << (colors[White] & squareBit ? static_cast(std::toupper(pieceChar)) : pieceChar); - } - - if (emptyCount > 0) { - fen << emptyCount; - } - - if (rank > 0) { - fen << '/'; - } - } - - fen << ' ' << (sideToMove ? 'b' : 'w'); - - fen << ' '; - bool hasCastlingRights = false; - - const std::array, 4> castlingOptions = { - {{whiteKingRight, 'K'}, {whiteQueenRight, 'Q'}, {blackKingRight, 'k'}, {blackQueenRight, 'q'}} - }; - - for (const auto& [right, symbol] : castlingOptions) { - if (castlingRights & right) { - fen << symbol; - hasCastlingRights = true; - } - } - - if (!hasCastlingRights) { - fen << '-'; - } - - fen << ' '; - if (enPassantTarget == noEPTarget) { - fen << '-'; - } else { - const int file = enPassantTarget % 8; - const int rank = enPassantTarget / 8; - fen << static_cast('a' + file) << (rank + 1); - } - - fen << ' ' << halfMoves; - - fen << ' ' << fullMoves; - - return fen.str(); -} - -void Board::PrintBoard() { - - for (int rank = 7; rank >= 0; rank--) { - - std::cout << "+---+---+---+---+---+---+---+---+" << std::endl; - std::cout << "| "; - - for (int file = 0; file < 8; file++) { - int square = rank * 8 + file; - bool pieceSet = false; - - for (int i = Pawn; i <= King; i++) { - if ((colors[White] & pieces[i]).IsSet(square)) { - std::cout << PIECE_LETTERS[i * 2 + White] << " | "; - pieceSet = true; - } else if ((colors[Black] & pieces[i]).IsSet(square)) { - std::cout << PIECE_LETTERS[i * 2 + Black] << " | "; - pieceSet = true; - } - } - - if (!pieceSet) { - std::cout << " | "; - } - } - std::cout << ' ' << rank + 1 << std::endl; - } - - std::cout << "+---+---+---+---+---+---+---+---+" << std::endl; - std::cout << " a b c d e f g h" << std::endl << std::endl; - std::cout << " Side to move: "; - if (!sideToMove) { - std::cout << "White" << std::endl; - } else { - std::cout << "Black" << std::endl; - } - if (enPassantTarget != noEPTarget) { - std::cout << " En Passant square: " << squareCoords[enPassantTarget] << std::endl; - } else { - std::cout << " En Passant square: None" << std::endl; - } - - std::cout << " Castling rights: "; - if (castlingRights & whiteKingRight) std::cout << "K"; else std::cout << "-"; - if (castlingRights & whiteQueenRight) std::cout << "Q"; else std::cout << "-"; - if (castlingRights & blackKingRight) std::cout << "k"; else std::cout << "-"; - if (castlingRights & blackQueenRight) std::cout << "q"; else std::cout << "-"; - std::cout << std::endl << std::endl; - - std::cout << " Hashkey: 0x" << std::hex << hashKey << std::dec << std::endl; - std::cout << " Fen: " << GetFen() << std::endl; -} - -void Board::PrintNNUE() { - std::cout << "Final eval: " << NNUE::net.Evaluate(*this) << std::endl; -} - -void Board::AddMove(Move move) { - moveList[currentMoveIndex] = move; - currentMoveIndex++; -} - -void Board::ResetMoves() { - currentMoveIndex = 0; -} - -void Board::ListMoves() { - int moveCount = 1; - for (int i = 0; i < currentMoveIndex; i++) { - Board copy = *this; - bool isLegal = copy.MakeMove(moveList[i]); - - if (!isLegal) - continue; - - std::cout << moveCount << ". "; - moveList[i].PrintMove(); - std::cout << "( " << moveTypes[moveList[i].GetFlags()] << " )"; - std::cout << std::endl; - moveCount++; - } -} - -int Board::GetPieceType(int square) { - for (int piece = Pawn; piece <= King; piece++) { - if (pieces[piece].IsSet(square)) return piece; - } - - return nullPieceType; -} - -int Board::GetPieceColor(int square) { - return (colors[Black].IsSet(square)); -} - -bool Board::InCheck() { - Bitboard myKingSquare = colors[sideToMove] & pieces[King]; - - return colorThreats[!sideToMove] & myKingSquare; -} - -void Board::SetPiece(int piece, int square, bool color) { - pieces[piece].SetBit(square); - colors[color].SetBit(square); - occupied.SetBit(square); - - hashKey ^= UTILS::zKeys[color][piece][square]; - - if (piece == Pawn) { - pawnKey ^= UTILS::zKeys[color][Pawn][square]; - } else { - nonPawnKey ^= UTILS::zKeys[color][piece][square]; - } -} - -void Board::RemovePiece(int piece, int square, bool color) { - pieces[piece].PopBit(square); - colors[color].PopBit(square); - occupied.PopBit(square); - - hashKey ^= UTILS::zKeys[color][piece][square]; - - if (piece == Pawn) { - pawnKey ^= UTILS::zKeys[color][Pawn][square]; - } else { - nonPawnKey ^= UTILS::zKeys[color][piece][square]; - } -} - -// Updates castling rights -static void UpdateCastlingRights(Board &board, int square, int type, int color) { - if (type == Rook) { - // Removing old rights - board.hashKey ^= UTILS::zCastle[board.castlingRights]; - int queenSideRook = color ? a8 : a1; - int kingSideRook = color ? h8 : h1; - - if (square == queenSideRook) { - board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight; - } else if (square == kingSideRook) { - board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; - } - - board.hashKey ^= UTILS::zCastle[board.castlingRights]; - } else if (type == King) { - // Removing old rights - board.hashKey ^= UTILS::zCastle[board.castlingRights]; - - board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; - board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight; - - board.hashKey ^= UTILS::zCastle[board.castlingRights]; - } -} - -void Board::Promote(int square, int pieceType, int color, bool isCapture) { - if (isCapture) { - int targetType = GetPieceType(square); - RemovePiece(targetType, square, !color); - UpdateCastlingRights(*this, square, targetType, !color); - } - - SetPiece(pieceType, square, color); -} - -bool Board::MakeMove(Move move) { - Board save = *this; - // Null Move - if (!move) { - int newEpTarget = noEPTarget; - - sideToMove = !sideToMove; - hashKey ^= UTILS::zSide; - - if (enPassantTarget != noEPTarget) { - hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; - } - - enPassantTarget = newEpTarget; - - return true; - } - - int newEpTarget = noEPTarget; - - int attackerPiece = GetPieceType(move.MoveFrom()); - int attackerColor = GetPieceColor(move.MoveFrom()); - - int targetPiece = GetPieceType(move.MoveTo()); - int direction = attackerColor ? south : north; - - int endPiece = attackerPiece; - - // Removing attacker piece from old position - RemovePiece(attackerPiece, move.MoveFrom(), attackerColor); - - if (move.IsPromo()) { - if (move.IsCapture()) { - endPiece = move.GetFlags() - 9; - Promote(move.MoveTo(), endPiece, sideToMove, true); - } else { - endPiece = move.GetFlags() - 5; - Promote(move.MoveTo(), endPiece, sideToMove, false); - } - } - - if (move.IsCapture()) { - if (move.GetFlags() != epCapture) { - accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece); - } else { - accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn); - } - } else { - if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) { - accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece); - } - } - - switch (move.GetFlags()) - { - case quiet: - SetPiece(attackerPiece, move.MoveTo(), attackerColor); - break; - case doublePawnPush: - SetPiece(attackerPiece, move.MoveTo(), attackerColor); - newEpTarget = move.MoveFrom() + direction; - break; - case capture: - RemovePiece(targetPiece, move.MoveTo(), !attackerColor); - SetPiece(attackerPiece, move.MoveTo(), attackerColor); - - UpdateCastlingRights(*this, move.MoveTo(), targetPiece, !attackerColor); - - break; - case epCapture: - RemovePiece(Pawn, move.MoveTo() - direction, !attackerColor); - SetPiece(attackerPiece, move.MoveTo(), attackerColor); - break; - case kingCastle: - { - int rookSquare = attackerColor ? h8 : h1; - - // Removing rook from old position - RemovePiece(Rook, rookSquare, attackerColor); - - // Setting rook on new position - SetPiece(Rook, rookSquare - 2, attackerColor); - - SetPiece(attackerPiece, move.MoveTo(), attackerColor); - - accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook); - break; - } - case queenCastle: - { - int rookSquare = attackerColor ? a8 : a1; - - // Removing rook from old position - RemovePiece(Rook, rookSquare, attackerColor); - - // Setting rook on new position - SetPiece(Rook, rookSquare + 3, attackerColor); - - SetPiece(attackerPiece, move.MoveTo(), attackerColor); - accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook); - break; - } - default: - break; - } - - if (attackerPiece == King) { - const int toFile = move.MoveTo() % 8; - - if (attackerColor == White) { - if ((toFile > 3) != accPair.mirroredWhite) { - accPair.mirroredWhite = !accPair.mirroredWhite; - ResetAccPair(); - } - } else { - if ((toFile > 3) != accPair.mirroredBlack) { - accPair.mirroredBlack = !accPair.mirroredBlack; - ResetAccPair(); - } - } - } - - // Removing the right to castle on king and rook movement - UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor); - - sideToMove = !attackerColor; - hashKey ^= UTILS::zSide; - - if (enPassantTarget != noEPTarget) { - hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; - } - - if (newEpTarget != noEPTarget) { - hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; - } - - enPassantTarget = newEpTarget; - - MOVEGEN::GenThreatMaps(*this); - - sideToMove = !sideToMove; - if (InCheck()) { - *this = save; - return false; - } - sideToMove = !sideToMove; - - if (attackerColor == Black) fullMoves++; - if (attackerPiece == Pawn || move.IsCapture()) { - halfMoves = 0; - } else { - halfMoves++; - } - - positionIndex++; - - return true; -} - -bool Board::InPossibleZug() { - Bitboard toCheck; - - // For all pieces other than pawns and king - for (int piece = Knight; piece <= Queen; piece++) { - toCheck |= (pieces[piece] & colors[sideToMove]); - } - - return !toCheck; -} - -void Board::ResetAccPair() { - Bitboard whitePieces = colors[White]; - Bitboard blackPieces = colors[Black]; - - accPair.white = NNUE::net.accumulator_biases; - accPair.black = NNUE::net.accumulator_biases; - - while (whitePieces) { - int square = whitePieces.getLS1BIndex(); - - int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square, accPair.mirroredWhite); - int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square, accPair.mirroredBlack); - - for (int i = 0; i < NNUE::HL_SIZE; i++) { - accPair.white[i] += NNUE::net.accumulator_weights[wInput * NNUE::HL_SIZE + i]; - accPair.black[i] += NNUE::net.accumulator_weights[bInput * NNUE::HL_SIZE + i]; - } - - whitePieces.PopBit(square); - } - - while (blackPieces) { - int square = blackPieces.getLS1BIndex(); - - int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square, accPair.mirroredWhite); - int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square, accPair.mirroredBlack); - - for (int i = 0; i < NNUE::HL_SIZE; i++) { - accPair.white[i] += NNUE::net.accumulator_weights[wInput * NNUE::HL_SIZE + i]; - accPair.black[i] += NNUE::net.accumulator_weights[bInput * NNUE::HL_SIZE + i]; - } - - blackPieces.PopBit(square); - } -} - -Bitboard Board::AttacksTo(int square, Bitboard occupancy) { - Bitboard attacks; - - // Pawn attacks - - // Opponent attacks - attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]); - - // Own piece attacks - attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]); - - // Knight - attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]); - - // King - attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]); - - Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy); - Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy); - - // Rook or queen - attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen])); - - // Bishop or queen - attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen])); - - return attacks; -} - -bool Board::IsSquareThreatened(bool side, int square) { - return colorThreats[!side].IsSet(square); -} +#include "board.h" +#include "movegen.h" +#include "tt.h" +#include +#include +#include +#include "utils.h" + +void Board::Reset() { + castlingRights = 0; + enPassantTarget = noEPTarget; + + halfMoves = 0; + fullMoves = 1; + + sideToMove = White; + occupied = 0ULL; + + pieces = std::array(); + colors = std::array(); + + accPair = ACC::AccumulatorPair(); + + pieceThreats = std::array(); + colorThreats = std::array(); + + moveList = std::array(); + + positionIndex = 0; + + currentMoveIndex = 0; + + hashKey = 0ULL; + pawnKey = 0ULL; + nonPawnKey = 0ULL; +} + +void Board::SetByFen(std::string_view fen) { + Reset(); + + // Starting from top left + int currSquare = a8; + + std::vector tokens = UTILS::split(fen, ' '); + std::vector pieceTokens = UTILS::split(tokens[0], '/'); + + constexpr std::string_view pieceTypes = "pnbrqk"; + + for (std::string_view rank : pieceTokens) { + for (const char piece : rank) { + if (std::isdigit(piece)) { + currSquare += piece - '0'; + continue; + } + + bool side = std::islower(piece); + int pieceType = pieceTypes.find(std::tolower(piece)); + + colors[side].SetBit(currSquare); + pieces[pieceType].SetBit(currSquare); + + currSquare++; + } + currSquare -= 16; + } + + sideToMove = tokens[1] == "b"; + + for (const char piece : tokens[2]) { + if (piece == 'K') castlingRights |= whiteKingRight; + else if (piece == 'Q') castlingRights |= whiteQueenRight; + else if (piece == 'k') castlingRights |= blackKingRight; + else if (piece == 'q') castlingRights |= blackQueenRight; + } + + if (tokens[3] != "-") enPassantTarget = UTILS::parseSquare(tokens[3]); + + // full and half move + if (tokens.size() > 4) { + halfMoves = std::stoi(tokens[4]); + fullMoves = std::stoi(tokens[5]); + } + + occupied = colors[White] | colors[Black]; + hashKey = UTILS::GetHashKey(*this); + MOVEGEN::GenThreatMaps(*this); + MOVEGEN::GenerateMoves(*this, true); + + int whiteKingFile = (pieces[King] & colors[White]).getLS1BIndex() % 8; + int blackKingFile = (pieces[King] & colors[Black]).getLS1BIndex() % 8; + + if (whiteKingFile > 3) { + accPair.mirroredWhite = true; + } + if (blackKingFile > 3) { + accPair.mirroredBlack = true; + } + + ResetAccPair(); +} + +std::string Board::GetFen() { + std::ostringstream fen; + + for (int rank = 7; rank >= 0; --rank) { + int emptyCount = 0; + + for (int file = 0; file < 8; ++file) { + int square = rank * 8 + file; + const uint64_t squareBit = 1ULL << square; + + if (!(occupied & squareBit)) { + ++emptyCount; + continue; + } + + if (emptyCount > 0) { + fen << emptyCount; + emptyCount = 0; + } + + static constexpr std::array pieceChars = {'p', 'n', 'b', 'r', 'q', 'k'}; + char pieceChar = '?'; + + for (size_t pieceType = 0; pieceType < pieceChars.size(); ++pieceType) { + if (pieces[pieceType] & squareBit) { + pieceChar = pieceChars[pieceType]; + break; + } + } + + fen << (colors[White] & squareBit ? static_cast(std::toupper(pieceChar)) : pieceChar); + } + + if (emptyCount > 0) { + fen << emptyCount; + } + + if (rank > 0) { + fen << '/'; + } + } + + fen << ' ' << (sideToMove ? 'b' : 'w'); + + fen << ' '; + bool hasCastlingRights = false; + + const std::array, 4> castlingOptions = { + {{whiteKingRight, 'K'}, {whiteQueenRight, 'Q'}, {blackKingRight, 'k'}, {blackQueenRight, 'q'}} + }; + + for (const auto& [right, symbol] : castlingOptions) { + if (castlingRights & right) { + fen << symbol; + hasCastlingRights = true; + } + } + + if (!hasCastlingRights) { + fen << '-'; + } + + fen << ' '; + if (enPassantTarget == noEPTarget) { + fen << '-'; + } else { + const int file = enPassantTarget % 8; + const int rank = enPassantTarget / 8; + fen << static_cast('a' + file) << (rank + 1); + } + + fen << ' ' << halfMoves; + + fen << ' ' << fullMoves; + + return fen.str(); +} + +void Board::PrintBoard() { + + for (int rank = 7; rank >= 0; rank--) { + + std::cout << "+---+---+---+---+---+---+---+---+" << std::endl; + std::cout << "| "; + + for (int file = 0; file < 8; file++) { + int square = rank * 8 + file; + bool pieceSet = false; + + for (int i = Pawn; i <= King; i++) { + if ((colors[White] & pieces[i]).IsSet(square)) { + std::cout << PIECE_LETTERS[i * 2 + White] << " | "; + pieceSet = true; + } else if ((colors[Black] & pieces[i]).IsSet(square)) { + std::cout << PIECE_LETTERS[i * 2 + Black] << " | "; + pieceSet = true; + } + } + + if (!pieceSet) { + std::cout << " | "; + } + } + std::cout << ' ' << rank + 1 << std::endl; + } + + std::cout << "+---+---+---+---+---+---+---+---+" << std::endl; + std::cout << " a b c d e f g h" << std::endl << std::endl; + std::cout << " Side to move: "; + if (!sideToMove) { + std::cout << "White" << std::endl; + } else { + std::cout << "Black" << std::endl; + } + if (enPassantTarget != noEPTarget) { + std::cout << " En Passant square: " << squareCoords[enPassantTarget] << std::endl; + } else { + std::cout << " En Passant square: None" << std::endl; + } + + std::cout << " Castling rights: "; + if (castlingRights & whiteKingRight) std::cout << "K"; else std::cout << "-"; + if (castlingRights & whiteQueenRight) std::cout << "Q"; else std::cout << "-"; + if (castlingRights & blackKingRight) std::cout << "k"; else std::cout << "-"; + if (castlingRights & blackQueenRight) std::cout << "q"; else std::cout << "-"; + std::cout << std::endl << std::endl; + + std::cout << " Hashkey: 0x" << std::hex << hashKey << std::dec << std::endl; + std::cout << " Fen: " << GetFen() << std::endl; +} + +void Board::PrintNNUE() { + std::cout << "Final eval: " << NNUE::net.Evaluate(*this) << std::endl; +} + +void Board::AddMove(Move move) { + moveList[currentMoveIndex] = move; + currentMoveIndex++; +} + +void Board::ResetMoves() { + currentMoveIndex = 0; +} + +void Board::ListMoves() { + int moveCount = 1; + for (int i = 0; i < currentMoveIndex; i++) { + if (!IsLegal(moveList[i])) + continue; + + std::cout << moveCount << ". "; + moveList[i].PrintMove(); + std::cout << "( " << moveTypes[moveList[i].GetFlags()] << " )"; + std::cout << std::endl; + moveCount++; + } +} + +int Board::GetPieceType(int square) { + for (int piece = Pawn; piece <= King; piece++) { + if (pieces[piece].IsSet(square)) return piece; + } + + return nullPieceType; +} + +int Board::GetPieceColor(int square) { + return (colors[Black].IsSet(square)); +} + +bool Board::InCheck() { + Bitboard myKingSquare = colors[sideToMove] & pieces[King]; + + return colorThreats[!sideToMove] & myKingSquare; +} + +void Board::SetPiece(int piece, int square, bool color) { + pieces[piece].SetBit(square); + colors[color].SetBit(square); + occupied.SetBit(square); + + hashKey ^= UTILS::zKeys[color][piece][square]; + + if (piece == Pawn) { + pawnKey ^= UTILS::zKeys[color][Pawn][square]; + } else { + nonPawnKey ^= UTILS::zKeys[color][piece][square]; + } +} + +void Board::RemovePiece(int piece, int square, bool color) { + pieces[piece].PopBit(square); + colors[color].PopBit(square); + occupied.PopBit(square); + + hashKey ^= UTILS::zKeys[color][piece][square]; + + if (piece == Pawn) { + pawnKey ^= UTILS::zKeys[color][Pawn][square]; + } else { + nonPawnKey ^= UTILS::zKeys[color][piece][square]; + } +} + +// Updates castling rights +static void UpdateCastlingRights(Board &board, int square, int type, int color) { + if (type == Rook) { + // Removing old rights + board.hashKey ^= UTILS::zCastle[board.castlingRights]; + int queenSideRook = color ? a8 : a1; + int kingSideRook = color ? h8 : h1; + + if (square == queenSideRook) { + board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight; + } else if (square == kingSideRook) { + board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; + } + + board.hashKey ^= UTILS::zCastle[board.castlingRights]; + } else if (type == King) { + // Removing old rights + board.hashKey ^= UTILS::zCastle[board.castlingRights]; + + board.castlingRights &= color ? ~blackKingRight : ~whiteKingRight; + board.castlingRights &= color ? ~blackQueenRight : ~whiteQueenRight; + + board.hashKey ^= UTILS::zCastle[board.castlingRights]; + } +} + +void Board::Promote(int square, int pieceType, int color, bool isCapture) { + if (isCapture) { + int targetType = GetPieceType(square); + RemovePiece(targetType, square, !color); + UpdateCastlingRights(*this, square, targetType, !color); + } + + SetPiece(pieceType, square, color); +} + +bool Board::MakeMove(Move move) { + Board save = *this; + // Null Move + if (!move) { + int newEpTarget = noEPTarget; + + sideToMove = !sideToMove; + hashKey ^= UTILS::zSide; + + if (enPassantTarget != noEPTarget) { + hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; + } + + enPassantTarget = newEpTarget; + + return true; + } + + int newEpTarget = noEPTarget; + + int attackerPiece = GetPieceType(move.MoveFrom()); + int attackerColor = GetPieceColor(move.MoveFrom()); + + int targetPiece = GetPieceType(move.MoveTo()); + int direction = attackerColor ? south : north; + + int endPiece = attackerPiece; + + // Removing attacker piece from old position + RemovePiece(attackerPiece, move.MoveFrom(), attackerColor); + + if (move.IsPromo()) { + if (move.IsCapture()) { + endPiece = move.GetFlags() - 9; + Promote(move.MoveTo(), endPiece, sideToMove, true); + } else { + endPiece = move.GetFlags() - 5; + Promote(move.MoveTo(), endPiece, sideToMove, false); + } + } + + if (move.IsCapture()) { + if (move.GetFlags() != epCapture) { + accPair.addSubSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece, move.MoveTo(), targetPiece); + } else { + accPair.addSubSub(sideToMove, enPassantTarget, endPiece, move.MoveFrom(), attackerPiece, move.MoveTo() - direction, Pawn); + } + } else { + if (move.GetFlags() != kingCastle && move.GetFlags() != queenCastle) { + accPair.addSub(sideToMove, move.MoveTo(), endPiece, move.MoveFrom(), attackerPiece); + } + } + + switch (move.GetFlags()) + { + case quiet: + SetPiece(attackerPiece, move.MoveTo(), attackerColor); + break; + case doublePawnPush: + SetPiece(attackerPiece, move.MoveTo(), attackerColor); + newEpTarget = move.MoveFrom() + direction; + break; + case capture: + RemovePiece(targetPiece, move.MoveTo(), !attackerColor); + SetPiece(attackerPiece, move.MoveTo(), attackerColor); + + UpdateCastlingRights(*this, move.MoveTo(), targetPiece, !attackerColor); + + break; + case epCapture: + RemovePiece(Pawn, move.MoveTo() - direction, !attackerColor); + SetPiece(attackerPiece, move.MoveTo(), attackerColor); + break; + case kingCastle: + { + int rookSquare = attackerColor ? h8 : h1; + + // Removing rook from old position + RemovePiece(Rook, rookSquare, attackerColor); + + // Setting rook on new position + SetPiece(Rook, rookSquare - 2, attackerColor); + + SetPiece(attackerPiece, move.MoveTo(), attackerColor); + + accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare - 2, Rook, move.MoveFrom(), King, rookSquare, Rook); + break; + } + case queenCastle: + { + int rookSquare = attackerColor ? a8 : a1; + + // Removing rook from old position + RemovePiece(Rook, rookSquare, attackerColor); + + // Setting rook on new position + SetPiece(Rook, rookSquare + 3, attackerColor); + + SetPiece(attackerPiece, move.MoveTo(), attackerColor); + accPair.addAddSubSub(sideToMove, move.MoveTo(), King, rookSquare + 3, Rook, move.MoveFrom(), King, rookSquare, Rook); + break; + } + default: + break; + } + + if (attackerPiece == King) { + const int toFile = move.MoveTo() % 8; + + if (attackerColor == White) { + if ((toFile > 3) != accPair.mirroredWhite) { + accPair.mirroredWhite = !accPair.mirroredWhite; + ResetAccPair(); + } + } else { + if ((toFile > 3) != accPair.mirroredBlack) { + accPair.mirroredBlack = !accPair.mirroredBlack; + ResetAccPair(); + } + } + } + + // Removing the right to castle on king and rook movement + UpdateCastlingRights(*this, move.MoveFrom(), attackerPiece, attackerColor); + + sideToMove = !attackerColor; + hashKey ^= UTILS::zSide; + + if (enPassantTarget != noEPTarget) { + hashKey ^= UTILS::zEnPassant[enPassantTarget % 8]; + } + + if (newEpTarget != noEPTarget) { + hashKey ^= UTILS::zEnPassant[newEpTarget % 8]; + } + + enPassantTarget = newEpTarget; + + MOVEGEN::GenThreatMaps(*this); + + sideToMove = !sideToMove; + if (InCheck()) { + *this = save; + return false; + } + sideToMove = !sideToMove; + + if (attackerColor == Black) fullMoves++; + if (attackerPiece == Pawn || move.IsCapture()) { + halfMoves = 0; + } else { + halfMoves++; + } + + positionIndex++; + + return true; +} + +bool Board::IsLegal(Move move) { + if (!move) { + return true; + } + + const int from = move.MoveFrom(); + const int to = move.MoveTo(); + const int piece = GetPieceType(from); + + if (piece == nullPieceType || GetPieceColor(from) != sideToMove) { + return false; + } + + if (colors[sideToMove].IsSet(to)) { + return false; + } + + const bool enemy = !sideToMove; + const int direction = sideToMove ? south : north; + + int kingSquare = (pieces[King] & colors[sideToMove]).getLS1BIndex(); + int kingTarget = kingSquare; + + Bitboard postMoveOccupancy = occupied; + postMoveOccupancy.PopBit(from); + + if (move.GetFlags() == epCapture) { + postMoveOccupancy.PopBit(to - direction); + } else if (move.IsCapture()) { + postMoveOccupancy.PopBit(to); + } + + if (move.GetFlags() == kingCastle || move.GetFlags() == queenCastle) { + const int rookFrom = move.GetFlags() == kingCastle ? (sideToMove ? h8 : h1) : (sideToMove ? a8 : a1); + const int rookTo = move.GetFlags() == kingCastle ? rookFrom - 2 : rookFrom + 3; + const int kingMid = from + (to > from ? 1 : -1); + + if (IsSquareAttackedBy(enemy, from, occupied)) { + return false; + } + + Bitboard midOccupancy = occupied; + midOccupancy.PopBit(from); + midOccupancy.SetBit(kingMid); + + if (IsSquareAttackedBy(enemy, kingMid, midOccupancy)) { + return false; + } + + postMoveOccupancy.PopBit(rookFrom); + postMoveOccupancy.PopBit(from); + postMoveOccupancy.SetBit(rookTo); + } + + postMoveOccupancy.SetBit(to); + + if (piece == King) { + kingTarget = to; + } + + return !IsSquareAttackedBy(enemy, kingTarget, postMoveOccupancy); +} + +bool Board::InPossibleZug() { + Bitboard toCheck; + + // For all pieces other than pawns and king + for (int piece = Knight; piece <= Queen; piece++) { + toCheck |= (pieces[piece] & colors[sideToMove]); + } + + return !toCheck; +} + +void Board::ResetAccPair() { + Bitboard whitePieces = colors[White]; + Bitboard blackPieces = colors[Black]; + + accPair.white = NNUE::net.accumulator_biases; + accPair.black = NNUE::net.accumulator_biases; + + while (whitePieces) { + int square = whitePieces.getLS1BIndex(); + + int wInput = ACC::CalculateIndex(White, White, GetPieceType(square), square, accPair.mirroredWhite); + int bInput = ACC::CalculateIndex(Black, White, GetPieceType(square), square, accPair.mirroredBlack); + + for (int i = 0; i < NNUE::HL_SIZE; i++) { + accPair.white[i] += NNUE::net.accumulator_weights[wInput * NNUE::HL_SIZE + i]; + accPair.black[i] += NNUE::net.accumulator_weights[bInput * NNUE::HL_SIZE + i]; + } + + whitePieces.PopBit(square); + } + + while (blackPieces) { + int square = blackPieces.getLS1BIndex(); + + int wInput = ACC::CalculateIndex(White, Black, GetPieceType(square), square, accPair.mirroredWhite); + int bInput = ACC::CalculateIndex(Black, Black, GetPieceType(square), square, accPair.mirroredBlack); + + for (int i = 0; i < NNUE::HL_SIZE; i++) { + accPair.white[i] += NNUE::net.accumulator_weights[wInput * NNUE::HL_SIZE + i]; + accPair.black[i] += NNUE::net.accumulator_weights[bInput * NNUE::HL_SIZE + i]; + } + + blackPieces.PopBit(square); + } +} + +Bitboard Board::AttacksTo(int square, Bitboard occupancy) { + Bitboard attacks; + + // Pawn attacks + + // Opponent attacks + attacks |= (MOVEGEN::pawnAttacks[sideToMove][square] & colors[!sideToMove] & pieces[Pawn]); + + // Own piece attacks + attacks |= (MOVEGEN::pawnAttacks[!sideToMove][square] & colors[sideToMove] & pieces[Pawn]); + + // Knight + attacks |= (MOVEGEN::knightAttacks[square] & pieces[Knight]); + + // King + attacks |= (MOVEGEN::kingAttacks[square] & pieces[King]); + + Bitboard bishopAttacks = MOVEGEN::getBishopAttack(square, occupancy); + Bitboard rookAttacks = MOVEGEN::getRookAttack(square, occupancy); + + // Rook or queen + attacks |= (rookAttacks & (pieces[Rook] | pieces[Queen])); + + // Bishop or queen + attacks |= (bishopAttacks & (pieces[Bishop] | pieces[Queen])); + + return attacks; +} + +bool Board::IsSquareAttackedBy(bool attackerSide, int square, Bitboard occupancy) { + const Bitboard pawns = pieces[Pawn] & colors[attackerSide]; + if (MOVEGEN::pawnAttacks[!attackerSide][square] & pawns) { + return true; + } + + if (MOVEGEN::knightAttacks[square] & pieces[Knight] & colors[attackerSide]) { + return true; + } + + if (MOVEGEN::kingAttacks[square] & pieces[King] & colors[attackerSide]) { + return true; + } + + if (MOVEGEN::getBishopAttack(square, occupancy) & (pieces[Bishop] | pieces[Queen]) & colors[attackerSide]) { + return true; + } + + if (MOVEGEN::getRookAttack(square, occupancy) & (pieces[Rook] | pieces[Queen]) & colors[attackerSide]) { + return true; + } + + return false; +} + +bool Board::IsSquareThreatened(bool side, int square) { + return colorThreats[!side].IsSet(square); +} diff --git a/source/board.h b/source/board.h index e254044..9a3c3e5 100644 --- a/source/board.h +++ b/source/board.h @@ -65,11 +65,13 @@ public: void RemovePiece(int piece, int square, bool color); void Promote(int square, int pieceType, int color, bool isCapture); - bool MakeMove(Move move); + bool MakeMove(Move move); + bool IsLegal(Move move); bool InPossibleZug(); - Bitboard AttacksTo(int square, Bitboard occupancy); + Bitboard AttacksTo(int square, Bitboard occupancy); + bool IsSquareAttackedBy(bool attackerSide, int square, Bitboard occupancy); bool IsSquareThreatened(bool side, int square); }; diff --git a/source/datagen.cpp b/source/datagen.cpp index 8fc0c1c..4d43682 100644 --- a/source/datagen.cpp +++ b/source/datagen.cpp @@ -206,10 +206,7 @@ static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) { int moveSeen = 0; for (int i = 0; i < board.currentMoveIndex; i++) { - Board copy = board; - bool isLegal = copy.MakeMove(board.moveList[i]); - - if (!isLegal) continue; + if (!board.IsLegal(board.moveList[i])) continue; moveSeen++; } @@ -227,12 +224,14 @@ static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) { MOVEGEN::GenerateMoves(board, true); std::uniform_int_distribution dist(0, board.currentMoveIndex - 1); - bool isLegal = board.MakeMove(board.moveList[dist(rng)]); + Move move = board.moveList[dist(rng)]; - if (!isLegal) { + if (!board.IsLegal(move)) { count--; continue; } + + board.MakeMove(move); ctx->positionHistory[board.positionIndex] = board.hashKey; MOVEGEN::GenerateMoves(board, true); if (IsGameOver(board, ctx)) break; diff --git a/source/perft.cpp b/source/perft.cpp index 263fd2a..a841e93 100644 --- a/source/perft.cpp +++ b/source/perft.cpp @@ -10,9 +10,11 @@ static U64 HelperPerft(Board board, int depth) { U64 nodes = 0; for (int i = 0; i < board.currentMoveIndex; i++) { + Move move = board.moveList[i]; + if (!board.IsLegal(move)) continue; + Board copy = board; - bool isLegal = copy.MakeMove(board.moveList[i]); - if (!isLegal) continue; + copy.MakeMove(move); nodes += HelperPerft(copy, depth - 1); } return nodes; @@ -25,9 +27,11 @@ void Perft(Board &board, int depth) { Stopwatch sw; for (int i = 0; i < board.currentMoveIndex; i++) { + Move move = board.moveList[i]; + if (!board.IsLegal(move)) continue; + Board copy = board; - bool isLegal = copy.MakeMove(board.moveList[i]); - if (!isLegal) continue; + copy.MakeMove(move); U64 nodeCount = HelperPerft(copy, depth - 1); totalNodes += nodeCount; board.moveList[i].PrintMove(); diff --git a/source/search.cpp b/source/search.cpp index 455a2c1..30e5800 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -358,9 +358,11 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear continue; } + Move move = board.moveList[i]; + if (!board.IsLegal(move)) continue; + Board copy = board; - int isLegal = copy.MakeMove(board.moveList[i]); - if (!isLegal) continue; + copy.MakeMove(move); ctx->ss[ply].pieceType = board.GetPieceType(board.moveList[i].MoveFrom()); ctx->ss[ply].moveTo = board.moveList[i].MoveTo(); @@ -523,10 +525,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC if (!SEE(board, currMove, seeThreshold)) continue; - Board copy = board; - bool isLegal = copy.MakeMove(currMove); + if (!board.IsLegal(currMove)) continue; - if (!isLegal) continue; + Board copy = board; + copy.MakeMove(currMove); if (copy.positionIndex >= ctx->positionHistory.size()) { ctx->positionHistory.resize(copy.positionIndex + 100); @@ -610,10 +612,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC continue; } - Board copy = board; - bool isLegal = copy.MakeMove(currMove); + if (!board.IsLegal(currMove)) continue; - if (!isLegal) continue; + Board copy = board; + copy.MakeMove(currMove); ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom()); ctx->ss[ply].moveTo = currMove.MoveTo(); -- 2.47.3 From d6c10b8da6ca0f0eb337365c0f15beff19e9d081 Mon Sep 17 00:00:00 2001 From: Mark <115177215+rektdie@users.noreply.github.com> Date: Wed, 18 Feb 2026 11:59:48 +0100 Subject: [PATCH 2/2] Fix attack occupancy in IsLegal and restore perft parity --- source/board.cpp | 12 +++++++----- source/perft.cpp | 12 ++++-------- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/source/board.cpp b/source/board.cpp index 26f0167..707a220 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -638,24 +638,26 @@ Bitboard Board::AttacksTo(int square, Bitboard occupancy) { } bool Board::IsSquareAttackedBy(bool attackerSide, int square, Bitboard occupancy) { - const Bitboard pawns = pieces[Pawn] & colors[attackerSide]; + const Bitboard attackers = colors[attackerSide] & occupancy; + + const Bitboard pawns = pieces[Pawn] & attackers; if (MOVEGEN::pawnAttacks[!attackerSide][square] & pawns) { return true; } - if (MOVEGEN::knightAttacks[square] & pieces[Knight] & colors[attackerSide]) { + if (MOVEGEN::knightAttacks[square] & pieces[Knight] & attackers) { return true; } - if (MOVEGEN::kingAttacks[square] & pieces[King] & colors[attackerSide]) { + if (MOVEGEN::kingAttacks[square] & pieces[King] & attackers) { return true; } - if (MOVEGEN::getBishopAttack(square, occupancy) & (pieces[Bishop] | pieces[Queen]) & colors[attackerSide]) { + if (MOVEGEN::getBishopAttack(square, occupancy) & (pieces[Bishop] | pieces[Queen]) & attackers) { return true; } - if (MOVEGEN::getRookAttack(square, occupancy) & (pieces[Rook] | pieces[Queen]) & colors[attackerSide]) { + if (MOVEGEN::getRookAttack(square, occupancy) & (pieces[Rook] | pieces[Queen]) & attackers) { return true; } diff --git a/source/perft.cpp b/source/perft.cpp index a841e93..263fd2a 100644 --- a/source/perft.cpp +++ b/source/perft.cpp @@ -10,11 +10,9 @@ static U64 HelperPerft(Board board, int depth) { U64 nodes = 0; for (int i = 0; i < board.currentMoveIndex; i++) { - Move move = board.moveList[i]; - if (!board.IsLegal(move)) continue; - Board copy = board; - copy.MakeMove(move); + bool isLegal = copy.MakeMove(board.moveList[i]); + if (!isLegal) continue; nodes += HelperPerft(copy, depth - 1); } return nodes; @@ -27,11 +25,9 @@ void Perft(Board &board, int depth) { Stopwatch sw; for (int i = 0; i < board.currentMoveIndex; i++) { - Move move = board.moveList[i]; - if (!board.IsLegal(move)) continue; - Board copy = board; - copy.MakeMove(move); + bool isLegal = copy.MakeMove(board.moveList[i]); + if (!isLegal) continue; U64 nodeCount = HelperPerft(copy, depth - 1); totalNodes += nodeCount; board.moveList[i].PrintMove(); -- 2.47.3