diff --git a/Makefile b/Makefile index 9d74e96..b30ddc8 100644 --- a/Makefile +++ b/Makefile @@ -30,7 +30,7 @@ $(EXE)$(EXE_EXT): $(OBJS) # Compile .cpp -> .o $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR) - $(CXX) -std=c++20 -c -o $@ $< -O3 -march=native -fuse-ld=lld -flto -static + $(CXX) -std=c++20 -c -o $@ $< -O3 -march=native -flto -static # Create object directory $(OBJ_DIR): diff --git a/source/benchmark.cpp b/source/benchmark.cpp index 120024e..4c24ac1 100644 --- a/source/benchmark.cpp +++ b/source/benchmark.cpp @@ -65,29 +65,21 @@ void RunBenchmark() { Board board; int depth = BENCH_DEPTH; int ply = 0; - benchStarted = true; - searchStopped = false; positionIndex = 0; // Clearing TT.Clear(); - std::memset(killerMoves, 0, sizeof(killerMoves)); - - history.Clear(); - nodes = 0; + SearchContext ctx; + Stopwatch sw; for (int i = 0; i < fenPositions.size(); i++) { board.SetByFen(fenPositions[i]); - SearchPosition(board, SearchParams()); + SearchPosition(board, SearchParams(), ctx); } - std::cout << nodes << " nodes " << int(nodes/sw.GetElapsedSec()) << " nps" << std::endl; - nodes = 0; + std::cout << ctx.nodes << " nodes " << int(ctx.nodes/sw.GetElapsedSec()) << " nps" << std::endl; TT.Clear(); - benchStarted = false; - std::memset(killerMoves, 0, sizeof(killerMoves)); - history.Clear(); positionIndex = 0; } diff --git a/source/board.cpp b/source/board.cpp index e796708..eabfae5 100644 --- a/source/board.cpp +++ b/source/board.cpp @@ -393,7 +393,6 @@ bool Board::MakeMove(Move move) { positionIndex++; positionHistory[positionIndex] = hashKey; - SEARCH::nodes++; return true; } diff --git a/source/datagen.cpp b/source/datagen.cpp index 1bc1425..573f47a 100644 --- a/source/datagen.cpp +++ b/source/datagen.cpp @@ -102,8 +102,7 @@ void PlayGame(std::atomic& positions, U64 targetPositions, std::vector& positions, U64 targetPositions, std::vector(board); while (!IsGameOver(board)) { - SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams()); + SEARCH::SearchResults results = SEARCH::SearchPosition(board, SearchParams(), ctx); if (!results.bestMove) break; safeResults = results; diff --git a/source/search.cpp b/source/search.cpp index ebe253c..a850ee6 100644 --- a/source/search.cpp +++ b/source/search.cpp @@ -4,23 +4,11 @@ #include #include #include "tt.h" -#include "stopwatch.h" #include "datagen.h" #include "benchmark.h" namespace SEARCH { -U64 nodes = 0; -U64 nodesToGo = 0; -bool benchStarted = false; - -static inline int timeToSearch = 0; -static inline bool doingNullMove = false; - -inline PVLine pvLine; - -Stopwatch sw; - void InitLMRTable() { for (int depth = 0; depth <= MAX_DEPTH; depth++) { for (int move = 0; move < MAX_MOVES; move++) { @@ -36,7 +24,7 @@ void InitLMRTable() { } } -static int ScoreMove(Board &board, Move &move, int ply) { +static int ScoreMove(Board &board, Move &move, int ply, SearchContext& ctx) { TTEntry *current = TT.GetRawEntry(board.hashKey); if (current->bestMove == move) { return 50000; @@ -52,26 +40,26 @@ static int ScoreMove(Board &board, Move &move, int ply) { return moveScoreTable[attackerType][targetType] + 30000; } else { - if (killerMoves[0][ply] == move) { + if (ctx.killerMoves[0][ply] == move) { return 20000; - } else if (killerMoves[1][ply] == move) { + } else if (ctx.killerMoves[1][ply] == move) { return 18000; } else { // Max 16384 - return history[board.sideToMove][move.MoveFrom()][move.MoveTo()]; + return ctx.history[board.sideToMove][move.MoveFrom()][move.MoveTo()]; } } return 0; } -static void SortMoves(Board &board, int ply) { +static void SortMoves(Board &board, int ply, SearchContext& ctx) { std::array scores; std::array indices; // Initialize scores and indices for (int i = 0; i < board.currentMoveIndex; i++) { - scores[i] = ScoreMove(board, board.moveList[i], ply); + scores[i] = ScoreMove(board, board.moveList[i], ply, ctx); indices[i] = i; } @@ -93,14 +81,14 @@ static void SortMoves(Board &board, int ply) { } } -void ListScores(Board &board, int ply) { - SortMoves(board, ply); +void ListScores(Board &board, int ply, SearchContext& ctx) { + SortMoves(board, ply, ctx); for (int i = 0; i < board.currentMoveIndex; i++) { Move currentMove = board.moveList[i]; std::cout << squareCoords[currentMove.MoveFrom()] << squareCoords[currentMove.MoveTo()]; - std::cout << ": " << ScoreMove(board, currentMove, ply) << '\n'; + std::cout << ": " << ScoreMove(board, currentMove, ply, ctx) << '\n'; } } @@ -141,17 +129,19 @@ static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int } template -static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { +static SearchResults Quiescence(Board board, int alpha, int beta, int ply, SearchContext& ctx) { if constexpr (mode != nodesMode) { - if (!benchStarted && nodes % 1024 == 0) { - if (sw.GetElapsedMS() >= timeToSearch) { - StopSearch(); - return 0; + if constexpr (mode != bench) { + if (ctx.nodes % 1024 == 0) { + if (ctx.sw.GetElapsedMS() >= ctx.timeToSearch) { + ctx.searchStopped = true; + return 0; + } } } } else { - if (nodes > nodesToGo) { - StopSearch(); + if (ctx.nodes > ctx.nodesToGo) { + ctx.searchStopped = true; return 0; } } @@ -174,7 +164,7 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { MOVEGEN::GenerateMoves(board); - SortMoves(board, ply); + SortMoves(board, ply, ctx); SearchResults results; @@ -182,7 +172,8 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { Board copy = board; int isLegal = copy.MakeMove(board.moveList[i]); if (!isLegal) continue; - int score = -Quiescence(copy, -beta, -alpha, ply + 1).score; + ctx.nodes++; + int score = -Quiescence(copy, -beta, -alpha, ply + 1, ctx).score; positionIndex--; if (score >= beta) { @@ -198,34 +189,34 @@ static SearchResults Quiescence(Board board, int alpha, int beta, int ply) { } results.score = bestScore; - if (searchStopped) return 0; + if (ctx.searchStopped) return 0; return results; } template -SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { +SearchResults PVS(Board board, int depth, int alpha, int beta, int ply, SearchContext& ctx) { if constexpr (mode != bench || mode != nodesMode) { - if (nodes % 1024 == 0) { + if (ctx.nodes % 1024 == 0) { if constexpr (mode == normal) { - if (sw.GetElapsedMS() >= timeToSearch) { - StopSearch(); + if (ctx.sw.GetElapsedMS() >= ctx.timeToSearch) { + ctx.searchStopped = true; return 0; } } else if constexpr (mode == datagen) { - if (nodes >= DATAGEN::HARD_NODES) { - StopSearch(); + if (ctx.nodes >= DATAGEN::HARD_NODES) { + ctx.searchStopped = true; return 0; } } } } else if constexpr (mode == nodesMode) { - if (nodes > nodesToGo) { - StopSearch(); + if (ctx.nodes > ctx.nodesToGo) { + ctx.searchStopped = true; return 0; } } - pvLine.SetLength(ply); + ctx.pvLine.SetLength(ply); if (ply && (IsThreefold(board) || IsFifty(board) || IsInsuffMat(board))) return 0; @@ -237,7 +228,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { } } - if (depth <= 0) return Quiescence(board, alpha, beta, ply); + if (depth <= 0) return Quiescence(board, alpha, beta, ply, ctx); const int staticEval = HCE::Evaluate(board); @@ -250,17 +241,17 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { } // Null Move Pruning - if (!doingNullMove && staticEval >= beta) { + if (!ctx.doingNullMove && staticEval >= beta) { if (depth >= 3 && !board.InPossibleZug()) { Board copy = board; bool isLegal = copy.MakeMove(Move()); // Always legal so we dont check it - doingNullMove = true; - int score = -PVS(copy, depth - 3, -beta, -beta + 1, ply + 1).score; - doingNullMove = false; + ctx.doingNullMove = true; + int score = -PVS(copy, depth - 3, -beta, -beta + 1, ply + 1, ctx).score; + ctx.doingNullMove = false; - if (searchStopped) return 0; + if (ctx.searchStopped) return 0; if (score >= beta) return score; } } @@ -269,7 +260,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { MOVEGEN::GenerateMoves(board); - SortMoves(board, ply); + SortMoves(board, ply, ctx); int score = -inf; int nodeType = AllNode; @@ -296,6 +287,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { bool isLegal = copy.MakeMove(currMove); if (!isLegal) continue; + ctx.nodes++; int reductions = GetReductions(board, currMove, depth, moveSeen, ply); @@ -304,29 +296,29 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { // First move (suspected PV node) if (!moveSeen) { // Full search - score = -PVS(copy, newDepth, -beta, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -beta, -alpha, ply + 1, ctx).score; } else if (reductions) { // Null-window search with reductions - score = -PVS(copy, newDepth - reductions, -alpha-1, -alpha, ply + 1).score; + score = -PVS(copy, newDepth - reductions, -alpha-1, -alpha, ply + 1, ctx).score; if (score > alpha) { // Null-window search now without the reduction - score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1, ctx).score; } } else { // Null-window search - score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -alpha-1, -alpha, ply + 1, ctx).score; } // Check if we need to do full window re-search if (moveSeen && score > alpha && score < beta) { - score = -PVS(copy, newDepth, -beta, -alpha, ply + 1).score; + score = -PVS(copy, newDepth, -beta, -alpha, ply + 1, ctx).score; } moveSeen++; positionIndex--; - if (searchStopped) return 0; + if (ctx.searchStopped) return 0; if (currMove.IsQuiet()) { seenQuiets[seenQuietsCount] = currMove; @@ -336,15 +328,15 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { // Fail high (beta cutoff) if (score >= beta) { if (!currMove.IsCapture()) { - killerMoves[1][ply] = killerMoves[0][ply]; - killerMoves[0][ply] = currMove; + ctx.killerMoves[1][ply] = ctx.killerMoves[0][ply]; + ctx.killerMoves[0][ply] = currMove; int bonus = depth * depth; - history.Update(board.sideToMove, currMove, bonus); + ctx.history.Update(board.sideToMove, currMove, bonus); for (int moveIndex = 0; moveIndex < seenQuietsCount - 1; moveIndex++) { - history.Update(board.sideToMove, seenQuiets[moveIndex], -bonus); + ctx.history.Update(board.sideToMove, seenQuiets[moveIndex], -bonus); } } @@ -358,7 +350,7 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { nodeType = PV; alpha = score; results.bestMove = currMove; - pvLine.SetMove(ply, currMove); + ctx.pvLine.SetMove(ply, currMove); } } @@ -370,14 +362,14 @@ SearchResults PVS(Board board, int depth, int alpha, int beta, int ply) { } } - if (searchStopped) return 0; + if (ctx.searchStopped) return 0; TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove); return results; } // Iterative deepening template -static SearchResults ID(Board &board, SearchParams params) { +static SearchResults ID(Board &board, SearchParams params, SearchContext& ctx) { int fullTime = board.sideToMove ? params.btime : params.wtime; int inc = board.sideToMove ? params.binc : params.winc; @@ -399,14 +391,14 @@ static SearchResults ID(Board &board, SearchParams params) { int elapsed = 0; - sw.Restart(); + ctx.sw.Restart(); for (int depth = 1; depth <= toDepth; depth++) { - timeToSearch = std::max((fullTime / 20) + (inc / 2), 4); - int softTime = timeToSearch * 0.65; + ctx.timeToSearch = std::max((fullTime / 20) + (inc / 2), 4); + int softTime = ctx.timeToSearch * 0.65; - SearchResults currentResults = PVS(board, depth, alpha, beta, ply); - elapsed = sw.GetElapsedMS(); + SearchResults currentResults = PVS(board, depth, alpha, beta, ply, ctx); + elapsed = ctx.sw.GetElapsedMS(); // If we fell outside the window, try again with full width if ((currentResults.score <= alpha) @@ -418,7 +410,7 @@ static SearchResults ID(Board &board, SearchParams params) { depth--; - if (searchStopped) break; + if (ctx.searchStopped) break; continue; } @@ -426,7 +418,7 @@ static SearchResults ID(Board &board, SearchParams params) { beta = currentResults.score + delta; delta = 50; - if (searchStopped) { + if (ctx.searchStopped) { break; } else { if (currentResults.bestMove) { @@ -438,21 +430,21 @@ static SearchResults ID(Board &board, SearchParams params) { std::cout << "depth " << depth; std::cout << " time " << elapsed; std::cout << " score cp " << UTILS::ConvertToWhiteRelative(board, safeResults.score); - std::cout << " nodes " << nodes << " nps " << int(nodes/sw.GetElapsedSec()); + std::cout << " nodes " << ctx.nodes << " nps " << int(ctx.nodes/ctx.sw.GetElapsedSec()); std::cout << " hashfull " << TT.GetUsedPercentage(); std::cout << " pv "; - pvLine.Print(0); + ctx.pvLine.Print(0); std::cout << std::endl; if constexpr (mode == normal) { - if (sw.GetElapsedMS() >= softTime) { - StopSearch(); + if (ctx.sw.GetElapsedMS() >= softTime) { + ctx.searchStopped = true; break; } } } else if constexpr (mode == datagen) { - if (nodes >= DATAGEN::SOFT_NODES) { - StopSearch(); + if (ctx.nodes >= DATAGEN::SOFT_NODES) { + ctx.searchStopped = true; break; } } @@ -463,18 +455,18 @@ static SearchResults ID(Board &board, SearchParams params) { } template -SearchResults SearchPosition(Board &board, SearchParams params) { - searchStopped = false; +SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx) { + ctx.searchStopped = false; if constexpr (mode != bench) { - nodes = 0; + ctx.nodes = 0; if constexpr (mode == nodesMode) { - nodesToGo = params.nodes; + ctx.nodesToGo = params.nodes; } } - pvLine.Clear(); + ctx.pvLine.Clear(); - SearchResults results = ID(board, params); + SearchResults results = ID(board, params, ctx); if constexpr (mode != normal) return results; @@ -485,20 +477,16 @@ SearchResults SearchPosition(Board &board, SearchParams params) { return results; } -void StopSearch() { - searchStopped = true; -} +template SearchResults PVS(Board, int, int, int, int, SearchContext& ctx); +template SearchResults PVS(Board, int, int, int, int, SearchContext& ctx); +template SearchResults PVS(Board, int, int, int, int, SearchContext& ctx); +template SearchResults PVS(Board, int, int, int, int, SearchContext& ctx); +template SearchResults PVS(Board, int, int, int, int, SearchContext& ctx); +template SearchResults PVS(Board, int, int, int, int, SearchContext& ctx); -template SearchResults PVS(Board, int, int, int, int); -template SearchResults PVS(Board, int, int, int, int); -template SearchResults PVS(Board, int, int, int, int); -template SearchResults PVS(Board, int, int, int, int); -template SearchResults PVS(Board, int, int, int, int); -template SearchResults PVS(Board, int, int, int, int); - -template SearchResults SearchPosition(Board &board, SearchParams params); -template SearchResults SearchPosition(Board &board, SearchParams params); -template SearchResults SearchPosition(Board &board, SearchParams params); -template SearchResults SearchPosition(Board &board, SearchParams params); +template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx); +template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx); +template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx); +template SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx); } diff --git a/source/search.h b/source/search.h index 4b31cdb..dd0ce78 100644 --- a/source/search.h +++ b/source/search.h @@ -4,6 +4,7 @@ #include #include "move.h" #include +#include "stopwatch.h" namespace SEARCH { @@ -19,16 +20,8 @@ constexpr int MAX_DEPTH = 64; constexpr int MAX_PLY = 128; constexpr int MAX_HISTORY = 16384; -extern U64 nodes; -extern bool benchStarted; - constexpr int inf = 100000; -inline bool searchStopped = false; - -// [id][ply] -inline int killerMoves[2][MAX_PLY]; - inline int lmrTable[MAX_DEPTH+1][MAX_MOVES]; void InitLMRTable(); @@ -75,8 +68,6 @@ public: } }; -inline History history; - class PVLine { private: int length[MAX_PLY] = {}; @@ -109,12 +100,35 @@ public: } }; +class SearchContext { +public: + U64 nodes = 0; + U64 nodesToGo = 0; + int timeToSearch = 0; + + bool doingNullMove = false; + bool searchStopped = false; + + PVLine pvLine; + History history; + + std::array, 2> killerMoves{}; + + Stopwatch sw; + + SearchContext(){ + pvLine.Clear(); + history.Clear(); + sw.Restart(); + killerMoves = {}; + } +}; + template -SearchResults PVS(Board board, int depth, int alpha, int beta, int ply); +SearchResults PVS(Board board, int depth, int alpha, int beta, int ply, SearchContext& ctx); template -SearchResults SearchPosition(Board &board, SearchParams params); -void StopSearch(); +SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx); bool IsDraw(Board &board); @@ -127,5 +141,5 @@ constexpr int moveScoreTable[6][6] = { 100, 200, 300, 400, 500, 600 }; -void ListScores(Board &board); +void ListScores(Board &board, SearchContext& ctx); } diff --git a/source/uci.cpp b/source/uci.cpp index 5055f65..01e131a 100644 --- a/source/uci.cpp +++ b/source/uci.cpp @@ -68,7 +68,7 @@ static int ReadParam(std::string param, std::string &command) { return 0; } -static void ParseGo(Board &board, std::string &command) { +static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext& ctx) { SearchParams params; params.wtime = ReadParam("wtime", command); @@ -84,10 +84,10 @@ static void ParseGo(Board &board, std::string &command) { } if (params.nodes) { - auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params); + auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params, std::ref(ctx)); worker.detach(); } else { - auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params); + auto worker = std::thread(SEARCH::SearchPosition, std::ref(board), params, std::ref(ctx)); worker.detach(); } } @@ -110,6 +110,8 @@ static void PrintEngineInfo() { void UCILoop(Board &board) { std::string input = ""; + SEARCH::SearchContext ctx; + // main loop while (true) { std::getline(std::cin, input); @@ -134,9 +136,10 @@ void UCILoop(Board &board) { // Clearing TT.Clear(); - std::memset(SEARCH::killerMoves, 0, sizeof(SEARCH::killerMoves)); - SEARCH::history.Clear(); + ctx.killerMoves = {}; + ctx.history.Clear(); + positionIndex = 0; continue; @@ -144,7 +147,7 @@ void UCILoop(Board &board) { // parse UCI "go" command if (input.find("go") != std::string::npos) { - ParseGo(board, input); + ParseGo(board, input, ctx); continue; } @@ -157,7 +160,7 @@ void UCILoop(Board &board) { // parse UCI "stop" command if (input.find("stop") != std::string::npos) { // stop the loop - SEARCH::StopSearch(); + ctx.searchStopped = true; continue; }