]> git.sesse.net Git - stockfish/blob - src/position.cpp
Fixes FreeBSD compilation when using Clang
[stockfish] / src / position.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2021 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <algorithm>
20 #include <cassert>
21 #include <cstddef> // For offsetof()
22 #include <cstring> // For std::memset, std::memcmp
23 #include <iomanip>
24 #include <sstream>
25
26 #include "bitboard.h"
27 #include "misc.h"
28 #include "movegen.h"
29 #include "position.h"
30 #include "thread.h"
31 #include "tt.h"
32 #include "uci.h"
33 #include "syzygy/tbprobe.h"
34
35 using std::string;
36
37 namespace Zobrist {
38
39   Key psq[PIECE_NB][SQUARE_NB];
40   Key enpassant[FILE_NB];
41   Key castling[CASTLING_RIGHT_NB];
42   Key side, noPawns;
43 }
44
45 namespace {
46
47 const string PieceToChar(" PNBRQK  pnbrqk");
48
49 constexpr Piece Pieces[] = { W_PAWN, W_KNIGHT, W_BISHOP, W_ROOK, W_QUEEN, W_KING,
50                              B_PAWN, B_KNIGHT, B_BISHOP, B_ROOK, B_QUEEN, B_KING };
51 } // namespace
52
53
54 /// operator<<(Position) returns an ASCII representation of the position
55
56 std::ostream& operator<<(std::ostream& os, const Position& pos) {
57
58   os << "\n +---+---+---+---+---+---+---+---+\n";
59
60   for (Rank r = RANK_8; r >= RANK_1; --r)
61   {
62       for (File f = FILE_A; f <= FILE_H; ++f)
63           os << " | " << PieceToChar[pos.piece_on(make_square(f, r))];
64
65       os << " | " << (1 + r) << "\n +---+---+---+---+---+---+---+---+\n";
66   }
67
68   os << "   a   b   c   d   e   f   g   h\n"
69      << "\nFen: " << pos.fen() << "\nKey: " << std::hex << std::uppercase
70      << std::setfill('0') << std::setw(16) << pos.key()
71      << std::setfill(' ') << std::dec << "\nCheckers: ";
72
73   for (Bitboard b = pos.checkers(); b; )
74       os << UCI::square(pop_lsb(&b)) << " ";
75
76   if (    int(Tablebases::MaxCardinality) >= popcount(pos.pieces())
77       && !pos.can_castle(ANY_CASTLING))
78   {
79       StateInfo st;
80       ASSERT_ALIGNED(&st, Eval::NNUE::kCacheLineSize);
81
82       Position p;
83       p.set(pos.fen(), pos.is_chess960(), &st, pos.this_thread());
84       Tablebases::ProbeState s1, s2;
85       Tablebases::WDLScore wdl = Tablebases::probe_wdl(p, &s1);
86       int dtz = Tablebases::probe_dtz(p, &s2);
87       os << "\nTablebases WDL: " << std::setw(4) << wdl << " (" << s1 << ")"
88          << "\nTablebases DTZ: " << std::setw(4) << dtz << " (" << s2 << ")";
89   }
90
91   return os;
92 }
93
94
95 // Marcel van Kervinck's cuckoo algorithm for fast detection of "upcoming repetition"
96 // situations. Description of the algorithm in the following paper:
97 // https://marcelk.net/2013-04-06/paper/upcoming-rep-v2.pdf
98
99 // First and second hash functions for indexing the cuckoo tables
100 inline int H1(Key h) { return h & 0x1fff; }
101 inline int H2(Key h) { return (h >> 16) & 0x1fff; }
102
103 // Cuckoo tables with Zobrist hashes of valid reversible moves, and the moves themselves
104 Key cuckoo[8192];
105 Move cuckooMove[8192];
106
107
108 /// Position::init() initializes at startup the various arrays used to compute hash keys
109
110 void Position::init() {
111
112   PRNG rng(1070372);
113
114   for (Piece pc : Pieces)
115       for (Square s = SQ_A1; s <= SQ_H8; ++s)
116           Zobrist::psq[pc][s] = rng.rand<Key>();
117
118   for (File f = FILE_A; f <= FILE_H; ++f)
119       Zobrist::enpassant[f] = rng.rand<Key>();
120
121   for (int cr = NO_CASTLING; cr <= ANY_CASTLING; ++cr)
122       Zobrist::castling[cr] = rng.rand<Key>();
123
124   Zobrist::side = rng.rand<Key>();
125   Zobrist::noPawns = rng.rand<Key>();
126
127   // Prepare the cuckoo tables
128   std::memset(cuckoo, 0, sizeof(cuckoo));
129   std::memset(cuckooMove, 0, sizeof(cuckooMove));
130   int count = 0;
131   for (Piece pc : Pieces)
132       for (Square s1 = SQ_A1; s1 <= SQ_H8; ++s1)
133           for (Square s2 = Square(s1 + 1); s2 <= SQ_H8; ++s2)
134               if ((type_of(pc) != PAWN) && (attacks_bb(type_of(pc), s1, 0) & s2))
135               {
136                   Move move = make_move(s1, s2);
137                   Key key = Zobrist::psq[pc][s1] ^ Zobrist::psq[pc][s2] ^ Zobrist::side;
138                   int i = H1(key);
139                   while (true)
140                   {
141                       std::swap(cuckoo[i], key);
142                       std::swap(cuckooMove[i], move);
143                       if (move == MOVE_NONE) // Arrived at empty slot?
144                           break;
145                       i = (i == H1(key)) ? H2(key) : H1(key); // Push victim to alternative slot
146                   }
147                   count++;
148              }
149   assert(count == 3668);
150 }
151
152
153 /// Position::set() initializes the position object with the given FEN string.
154 /// This function is not very robust - make sure that input FENs are correct,
155 /// this is assumed to be the responsibility of the GUI.
156
157 Position& Position::set(const string& fenStr, bool isChess960, StateInfo* si, Thread* th) {
158 /*
159    A FEN string defines a particular position using only the ASCII character set.
160
161    A FEN string contains six fields separated by a space. The fields are:
162
163    1) Piece placement (from white's perspective). Each rank is described, starting
164       with rank 8 and ending with rank 1. Within each rank, the contents of each
165       square are described from file A through file H. Following the Standard
166       Algebraic Notation (SAN), each piece is identified by a single letter taken
167       from the standard English names. White pieces are designated using upper-case
168       letters ("PNBRQK") whilst Black uses lowercase ("pnbrqk"). Blank squares are
169       noted using digits 1 through 8 (the number of blank squares), and "/"
170       separates ranks.
171
172    2) Active color. "w" means white moves next, "b" means black.
173
174    3) Castling availability. If neither side can castle, this is "-". Otherwise,
175       this has one or more letters: "K" (White can castle kingside), "Q" (White
176       can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
177       can castle queenside).
178
179    4) En passant target square (in algebraic notation). If there's no en passant
180       target square, this is "-". If a pawn has just made a 2-square move, this
181       is the position "behind" the pawn. Following X-FEN standard, this is recorded only
182       if there is a pawn in position to make an en passant capture, and if there really
183       is a pawn that might have advanced two squares.
184
185    5) Halfmove clock. This is the number of halfmoves since the last pawn advance
186       or capture. This is used to determine if a draw can be claimed under the
187       fifty-move rule.
188
189    6) Fullmove number. The number of the full move. It starts at 1, and is
190       incremented after Black's move.
191 */
192
193   unsigned char col, row, token;
194   size_t idx;
195   Square sq = SQ_A8;
196   std::istringstream ss(fenStr);
197
198   std::memset(this, 0, sizeof(Position));
199   std::memset(si, 0, sizeof(StateInfo));
200   st = si;
201
202   ss >> std::noskipws;
203
204   // 1. Piece placement
205   while ((ss >> token) && !isspace(token))
206   {
207       if (isdigit(token))
208           sq += (token - '0') * EAST; // Advance the given number of files
209
210       else if (token == '/')
211           sq += 2 * SOUTH;
212
213       else if ((idx = PieceToChar.find(token)) != string::npos) {
214           put_piece(Piece(idx), sq);
215           ++sq;
216       }
217   }
218
219   // 2. Active color
220   ss >> token;
221   sideToMove = (token == 'w' ? WHITE : BLACK);
222   ss >> token;
223
224   // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
225   // Shredder-FEN that uses the letters of the columns on which the rooks began
226   // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
227   // if an inner rook is associated with the castling right, the castling tag is
228   // replaced by the file letter of the involved rook, as for the Shredder-FEN.
229   while ((ss >> token) && !isspace(token))
230   {
231       Square rsq;
232       Color c = islower(token) ? BLACK : WHITE;
233       Piece rook = make_piece(c, ROOK);
234
235       token = char(toupper(token));
236
237       if (token == 'K')
238           for (rsq = relative_square(c, SQ_H1); piece_on(rsq) != rook; --rsq) {}
239
240       else if (token == 'Q')
241           for (rsq = relative_square(c, SQ_A1); piece_on(rsq) != rook; ++rsq) {}
242
243       else if (token >= 'A' && token <= 'H')
244           rsq = make_square(File(token - 'A'), relative_rank(c, RANK_1));
245
246       else
247           continue;
248
249       set_castling_right(c, rsq);
250   }
251
252   set_state(st);
253
254   // 4. En passant square.
255   // Ignore if square is invalid or not on side to move relative rank 6.
256   bool enpassant = false;
257
258   if (   ((ss >> col) && (col >= 'a' && col <= 'h'))
259       && ((ss >> row) && (row == (sideToMove == WHITE ? '6' : '3'))))
260   {
261       st->epSquare = make_square(File(col - 'a'), Rank(row - '1'));
262
263       // En passant square will be considered only if
264       // a) side to move have a pawn threatening epSquare
265       // b) there is an enemy pawn in front of epSquare
266       // c) there is no piece on epSquare or behind epSquare
267       // d) enemy pawn didn't block a check of its own color by moving forward
268       enpassant = pawn_attacks_bb(~sideToMove, st->epSquare) & pieces(sideToMove, PAWN)
269                && (pieces(~sideToMove, PAWN) & (st->epSquare + pawn_push(~sideToMove)))
270                && !(pieces() & (st->epSquare | (st->epSquare + pawn_push(sideToMove))))
271                && (file_of(square<KING>(sideToMove)) == file_of(st->epSquare)
272                || !(blockers_for_king(sideToMove) & (st->epSquare + pawn_push(~sideToMove))));
273   }
274
275   // It's necessary for st->previous to be intialized in this way because legality check relies on its existence
276   if (enpassant) {
277       st->previous = new StateInfo();
278       remove_piece(st->epSquare - pawn_push(sideToMove));
279       st->previous->checkersBB = attackers_to(square<KING>(~sideToMove)) & pieces(sideToMove);
280       st->previous->blockersForKing[WHITE] = slider_blockers(pieces(BLACK), square<KING>(WHITE), st->previous->pinners[BLACK]);
281       st->previous->blockersForKing[BLACK] = slider_blockers(pieces(WHITE), square<KING>(BLACK), st->previous->pinners[WHITE]);
282       put_piece(make_piece(~sideToMove, PAWN), st->epSquare - pawn_push(sideToMove));
283   }
284   else
285       st->epSquare = SQ_NONE;
286
287   // 5-6. Halfmove clock and fullmove number
288   ss >> std::skipws >> st->rule50 >> gamePly;
289
290   // Convert from fullmove starting from 1 to gamePly starting from 0,
291   // handle also common incorrect FEN with fullmove = 0.
292   gamePly = std::max(2 * (gamePly - 1), 0) + (sideToMove == BLACK);
293
294   chess960 = isChess960;
295   thisThread = th;
296   st->accumulator.state[WHITE] = Eval::NNUE::INIT;
297   st->accumulator.state[BLACK] = Eval::NNUE::INIT;
298
299   assert(pos_is_ok());
300
301   return *this;
302 }
303
304
305 /// Position::set_castling_right() is a helper function used to set castling
306 /// rights given the corresponding color and the rook starting square.
307
308 void Position::set_castling_right(Color c, Square rfrom) {
309
310   Square kfrom = square<KING>(c);
311   CastlingRights cr = c & (kfrom < rfrom ? KING_SIDE: QUEEN_SIDE);
312
313   st->castlingRights |= cr;
314   castlingRightsMask[kfrom] |= cr;
315   castlingRightsMask[rfrom] |= cr;
316   castlingRookSquare[cr] = rfrom;
317
318   Square kto = relative_square(c, cr & KING_SIDE ? SQ_G1 : SQ_C1);
319   Square rto = relative_square(c, cr & KING_SIDE ? SQ_F1 : SQ_D1);
320
321   castlingPath[cr] =   (between_bb(rfrom, rto) | between_bb(kfrom, kto) | rto | kto)
322                     & ~(kfrom | rfrom);
323 }
324
325
326 /// Position::set_check_info() sets king attacks to detect if a move gives check
327
328 void Position::set_check_info(StateInfo* si) const {
329
330   si->blockersForKing[WHITE] = slider_blockers(pieces(BLACK), square<KING>(WHITE), si->pinners[BLACK]);
331   si->blockersForKing[BLACK] = slider_blockers(pieces(WHITE), square<KING>(BLACK), si->pinners[WHITE]);
332
333   Square ksq = square<KING>(~sideToMove);
334
335   si->checkSquares[PAWN]   = pawn_attacks_bb(~sideToMove, ksq);
336   si->checkSquares[KNIGHT] = attacks_bb<KNIGHT>(ksq);
337   si->checkSquares[BISHOP] = attacks_bb<BISHOP>(ksq, pieces());
338   si->checkSquares[ROOK]   = attacks_bb<ROOK>(ksq, pieces());
339   si->checkSquares[QUEEN]  = si->checkSquares[BISHOP] | si->checkSquares[ROOK];
340   si->checkSquares[KING]   = 0;
341 }
342
343
344 /// Position::set_state() computes the hash keys of the position, and other
345 /// data that once computed is updated incrementally as moves are made.
346 /// The function is only used when a new position is set up, and to verify
347 /// the correctness of the StateInfo data when running in debug mode.
348
349 void Position::set_state(StateInfo* si) const {
350
351   si->key = si->materialKey = 0;
352   si->pawnKey = Zobrist::noPawns;
353   si->nonPawnMaterial[WHITE] = si->nonPawnMaterial[BLACK] = VALUE_ZERO;
354   si->checkersBB = attackers_to(square<KING>(sideToMove)) & pieces(~sideToMove);
355
356   set_check_info(si);
357
358   for (Bitboard b = pieces(); b; )
359   {
360       Square s = pop_lsb(&b);
361       Piece pc = piece_on(s);
362       si->key ^= Zobrist::psq[pc][s];
363
364       if (type_of(pc) == PAWN)
365           si->pawnKey ^= Zobrist::psq[pc][s];
366
367       else if (type_of(pc) != KING)
368           si->nonPawnMaterial[color_of(pc)] += PieceValue[MG][pc];
369   }
370
371   if (si->epSquare != SQ_NONE)
372       si->key ^= Zobrist::enpassant[file_of(si->epSquare)];
373
374   if (sideToMove == BLACK)
375       si->key ^= Zobrist::side;
376
377   si->key ^= Zobrist::castling[si->castlingRights];
378
379   for (Piece pc : Pieces)
380       for (int cnt = 0; cnt < pieceCount[pc]; ++cnt)
381           si->materialKey ^= Zobrist::psq[pc][cnt];
382 }
383
384
385 /// Position::set() is an overload to initialize the position object with
386 /// the given endgame code string like "KBPKN". It is mainly a helper to
387 /// get the material key out of an endgame code.
388
389 Position& Position::set(const string& code, Color c, StateInfo* si) {
390
391   assert(code[0] == 'K');
392
393   string sides[] = { code.substr(code.find('K', 1)),      // Weak
394                      code.substr(0, std::min(code.find('v'), code.find('K', 1))) }; // Strong
395
396   assert(sides[0].length() > 0 && sides[0].length() < 8);
397   assert(sides[1].length() > 0 && sides[1].length() < 8);
398
399   std::transform(sides[c].begin(), sides[c].end(), sides[c].begin(), tolower);
400
401   string fenStr = "8/" + sides[0] + char(8 - sides[0].length() + '0') + "/8/8/8/8/"
402                        + sides[1] + char(8 - sides[1].length() + '0') + "/8 w - - 0 10";
403
404   return set(fenStr, false, si, nullptr);
405 }
406
407
408 /// Position::fen() returns a FEN representation of the position. In case of
409 /// Chess960 the Shredder-FEN notation is used. This is mainly a debugging function.
410
411 const string Position::fen() const {
412
413   int emptyCnt;
414   std::ostringstream ss;
415
416   for (Rank r = RANK_8; r >= RANK_1; --r)
417   {
418       for (File f = FILE_A; f <= FILE_H; ++f)
419       {
420           for (emptyCnt = 0; f <= FILE_H && empty(make_square(f, r)); ++f)
421               ++emptyCnt;
422
423           if (emptyCnt)
424               ss << emptyCnt;
425
426           if (f <= FILE_H)
427               ss << PieceToChar[piece_on(make_square(f, r))];
428       }
429
430       if (r > RANK_1)
431           ss << '/';
432   }
433
434   ss << (sideToMove == WHITE ? " w " : " b ");
435
436   if (can_castle(WHITE_OO))
437       ss << (chess960 ? char('A' + file_of(castling_rook_square(WHITE_OO ))) : 'K');
438
439   if (can_castle(WHITE_OOO))
440       ss << (chess960 ? char('A' + file_of(castling_rook_square(WHITE_OOO))) : 'Q');
441
442   if (can_castle(BLACK_OO))
443       ss << (chess960 ? char('a' + file_of(castling_rook_square(BLACK_OO ))) : 'k');
444
445   if (can_castle(BLACK_OOO))
446       ss << (chess960 ? char('a' + file_of(castling_rook_square(BLACK_OOO))) : 'q');
447
448   if (!can_castle(ANY_CASTLING))
449       ss << '-';
450
451   ss << (ep_square() == SQ_NONE ? " - " : " " + UCI::square(ep_square()) + " ")
452      << st->rule50 << " " << 1 + (gamePly - (sideToMove == BLACK)) / 2;
453
454   return ss.str();
455 }
456
457
458 /// Position::slider_blockers() returns a bitboard of all the pieces (both colors)
459 /// that are blocking attacks on the square 's' from 'sliders'. A piece blocks a
460 /// slider if removing that piece from the board would result in a position where
461 /// square 's' is attacked. For example, a king-attack blocking piece can be either
462 /// a pinned or a discovered check piece, according if its color is the opposite
463 /// or the same of the color of the slider.
464
465 Bitboard Position::slider_blockers(Bitboard sliders, Square s, Bitboard& pinners) const {
466
467   Bitboard blockers = 0;
468   pinners = 0;
469
470   // Snipers are sliders that attack 's' when a piece and other snipers are removed
471   Bitboard snipers = (  (attacks_bb<  ROOK>(s) & pieces(QUEEN, ROOK))
472                       | (attacks_bb<BISHOP>(s) & pieces(QUEEN, BISHOP))) & sliders;
473   Bitboard occupancy = pieces() ^ snipers;
474
475   while (snipers)
476   {
477     Square sniperSq = pop_lsb(&snipers);
478     Bitboard b = between_bb(s, sniperSq) & occupancy;
479
480     if (b && !more_than_one(b))
481     {
482         blockers |= b;
483         if (b & pieces(color_of(piece_on(s))))
484             pinners |= sniperSq;
485     }
486   }
487   return blockers;
488 }
489
490
491 /// Position::attackers_to() computes a bitboard of all pieces which attack a
492 /// given square. Slider attacks use the occupied bitboard to indicate occupancy.
493
494 Bitboard Position::attackers_to(Square s, Bitboard occupied) const {
495
496   return  (pawn_attacks_bb(BLACK, s)       & pieces(WHITE, PAWN))
497         | (pawn_attacks_bb(WHITE, s)       & pieces(BLACK, PAWN))
498         | (attacks_bb<KNIGHT>(s)           & pieces(KNIGHT))
499         | (attacks_bb<  ROOK>(s, occupied) & pieces(  ROOK, QUEEN))
500         | (attacks_bb<BISHOP>(s, occupied) & pieces(BISHOP, QUEEN))
501         | (attacks_bb<KING>(s)             & pieces(KING));
502 }
503
504
505 /// Position::legal() tests whether a pseudo-legal move is legal
506
507 bool Position::legal(Move m) const {
508
509   assert(is_ok(m));
510
511   Color us = sideToMove;
512   Square from = from_sq(m);
513   Square to = to_sq(m);
514
515   assert(color_of(moved_piece(m)) == us);
516   assert(piece_on(square<KING>(us)) == make_piece(us, KING));
517
518   // st->previous->blockersForKing consider capsq as empty.
519   // If pinned, it has to move along the king ray.
520   if (type_of(m) == EN_PASSANT)
521       return !(st->previous->blockersForKing[sideToMove] & from) ||
522                aligned(from, to, square<KING>(us));
523
524   // Castling moves generation does not check if the castling path is clear of
525   // enemy attacks, it is delayed at a later time: now!
526   if (type_of(m) == CASTLING)
527   {
528       // After castling, the rook and king final positions are the same in
529       // Chess960 as they would be in standard chess.
530       to = relative_square(us, to > from ? SQ_G1 : SQ_C1);
531       Direction step = to > from ? WEST : EAST;
532
533       for (Square s = to; s != from; s += step)
534           if (attackers_to(s) & pieces(~us))
535               return false;
536
537       // In case of Chess960, verify if the Rook blocks some checks
538       // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
539       return !chess960 || !(blockers_for_king(us) & to_sq(m));
540   }
541
542   // If the moving piece is a king, check whether the destination square is
543   // attacked by the opponent.
544   if (type_of(piece_on(from)) == KING)
545       return !(attackers_to(to) & pieces(~us));
546
547   // A non-king move is legal if and only if it is not pinned or it
548   // is moving along the ray towards or away from the king.
549   return   !(blockers_for_king(us) & from)
550         ||  aligned(from, to, square<KING>(us));
551 }
552
553
554 /// Position::pseudo_legal() takes a random move and tests whether the move is
555 /// pseudo legal. It is used to validate moves from TT that can be corrupted
556 /// due to SMP concurrent access or hash position key aliasing.
557
558 bool Position::pseudo_legal(const Move m) const {
559
560   Color us = sideToMove;
561   Square from = from_sq(m);
562   Square to = to_sq(m);
563   Piece pc = moved_piece(m);
564
565   // Use a slower but simpler function for uncommon cases
566   // yet we skip the legality check of MoveList<LEGAL>().
567   if (type_of(m) != NORMAL)
568       return checkers() ? MoveList<    EVASIONS>(*this).contains(m)
569                         : MoveList<NON_EVASIONS>(*this).contains(m);
570
571   // Is not a promotion, so promotion piece must be empty
572   if (promotion_type(m) - KNIGHT != NO_PIECE_TYPE)
573       return false;
574
575   // If the 'from' square is not occupied by a piece belonging to the side to
576   // move, the move is obviously not legal.
577   if (pc == NO_PIECE || color_of(pc) != us)
578       return false;
579
580   // The destination square cannot be occupied by a friendly piece
581   if (pieces(us) & to)
582       return false;
583
584   // Handle the special case of a pawn move
585   if (type_of(pc) == PAWN)
586   {
587       // We have already handled promotion moves, so destination
588       // cannot be on the 8th/1st rank.
589       if ((Rank8BB | Rank1BB) & to)
590           return false;
591
592       if (   !(pawn_attacks_bb(us, from) & pieces(~us) & to) // Not a capture
593           && !((from + pawn_push(us) == to) && empty(to))       // Not a single push
594           && !(   (from + 2 * pawn_push(us) == to)              // Not a double push
595                && (relative_rank(us, from) == RANK_2)
596                && empty(to)
597                && empty(to - pawn_push(us))))
598           return false;
599   }
600   else if (!(attacks_bb(type_of(pc), from, pieces()) & to))
601       return false;
602
603   // Evasions generator already takes care to avoid some kind of illegal moves
604   // and legal() relies on this. We therefore have to take care that the same
605   // kind of moves are filtered out here.
606   if (checkers())
607   {
608       if (type_of(pc) != KING)
609       {
610           // Double check? In this case a king move is required
611           if (more_than_one(checkers()))
612               return false;
613
614           // Our move must be a blocking evasion or a capture of the checking piece
615           if (!((between_bb(lsb(checkers()), square<KING>(us)) | checkers()) & to))
616               return false;
617       }
618       // In case of king moves under check we have to remove king so as to catch
619       // invalid moves like b1a1 when opposite queen is on c1.
620       else if (attackers_to(to, pieces() ^ from) & pieces(~us))
621           return false;
622   }
623
624   return true;
625 }
626
627
628 /// Position::gives_check() tests whether a pseudo-legal move gives a check
629
630 bool Position::gives_check(Move m) const {
631
632   assert(is_ok(m));
633   assert(color_of(moved_piece(m)) == sideToMove);
634
635   Square from = from_sq(m);
636   Square to = to_sq(m);
637
638   // Is there a direct check?
639   if (check_squares(type_of(piece_on(from))) & to)
640       return true;
641
642   // Is there a discovered check?
643   if (   (blockers_for_king(~sideToMove) & from)
644       && !aligned(from, to, square<KING>(~sideToMove)))
645       return true;
646
647   switch (type_of(m))
648   {
649   case NORMAL:
650       return false;
651
652   case PROMOTION:
653       return attacks_bb(promotion_type(m), to, pieces() ^ from) & square<KING>(~sideToMove);
654
655   // The double-pushed pawn blocked a check? En Passant will remove the blocker.
656   // The only discovery check that wasn't handle is through capsq and fromsq
657   // So the King must be in the same rank as fromsq to consider this possibility.
658   // st->previous->blockersForKing consider capsq as empty.
659   case EN_PASSANT:
660       return st->previous->checkersBB || (rank_of(square<KING>(~sideToMove)) == rank_of(from)
661           && st->previous->blockersForKing[~sideToMove] & from);
662
663   default: //CASTLING
664   {
665       // Castling is encoded as 'king captures the rook'
666       Square ksq = square<KING>(~sideToMove);
667       Square rto = relative_square(sideToMove, to > from ? SQ_F1 : SQ_D1);
668
669       return   (attacks_bb<ROOK>(rto) & ksq)
670             && (attacks_bb<ROOK>(rto, pieces() ^ from ^ to) & ksq);
671   }
672   }
673 }
674
675
676 /// Position::do_move() makes a move, and saves all information necessary
677 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
678 /// moves should be filtered out before this function is called.
679
680 void Position::do_move(Move m, StateInfo& newSt, bool givesCheck) {
681
682   assert(is_ok(m));
683   assert(&newSt != st);
684
685   thisThread->nodes.fetch_add(1, std::memory_order_relaxed);
686   Key k = st->key ^ Zobrist::side;
687
688   // Copy some fields of the old state to our new StateInfo object except the
689   // ones which are going to be recalculated from scratch anyway and then switch
690   // our state pointer to point to the new (ready to be updated) state.
691   std::memcpy(&newSt, st, offsetof(StateInfo, key));
692   newSt.previous = st;
693   st = &newSt;
694
695   // Increment ply counters. In particular, rule50 will be reset to zero later on
696   // in case of a capture or a pawn move.
697   ++gamePly;
698   ++st->rule50;
699   ++st->pliesFromNull;
700
701   // Used by NNUE
702   st->accumulator.state[WHITE] = Eval::NNUE::EMPTY;
703   st->accumulator.state[BLACK] = Eval::NNUE::EMPTY;
704   auto& dp = st->dirtyPiece;
705   dp.dirty_num = 1;
706
707   Color us = sideToMove;
708   Color them = ~us;
709   Square from = from_sq(m);
710   Square to = to_sq(m);
711   Piece pc = piece_on(from);
712   Piece captured = type_of(m) == EN_PASSANT ? make_piece(them, PAWN) : piece_on(to);
713
714   assert(color_of(pc) == us);
715   assert(captured == NO_PIECE || color_of(captured) == (type_of(m) != CASTLING ? them : us));
716   assert(type_of(captured) != KING);
717
718   if (type_of(m) == CASTLING)
719   {
720       assert(pc == make_piece(us, KING));
721       assert(captured == make_piece(us, ROOK));
722
723       Square rfrom, rto;
724       do_castling<true>(us, from, to, rfrom, rto);
725
726       k ^= Zobrist::psq[captured][rfrom] ^ Zobrist::psq[captured][rto];
727       captured = NO_PIECE;
728   }
729
730   if (captured)
731   {
732       Square capsq = to;
733
734       // If the captured piece is a pawn, update pawn hash key, otherwise
735       // update non-pawn material.
736       if (type_of(captured) == PAWN)
737       {
738           if (type_of(m) == EN_PASSANT)
739           {
740               capsq -= pawn_push(us);
741
742               assert(pc == make_piece(us, PAWN));
743               assert(to == st->epSquare);
744               assert(relative_rank(us, to) == RANK_6);
745               assert(piece_on(to) == NO_PIECE);
746               assert(piece_on(capsq) == make_piece(them, PAWN));
747           }
748
749           st->pawnKey ^= Zobrist::psq[captured][capsq];
750       }
751       else
752           st->nonPawnMaterial[them] -= PieceValue[MG][captured];
753
754       if (Eval::useNNUE)
755       {
756           dp.dirty_num = 2;  // 1 piece moved, 1 piece captured
757           dp.piece[1] = captured;
758           dp.from[1] = capsq;
759           dp.to[1] = SQ_NONE;
760       }
761
762       // Update board and piece lists
763       remove_piece(capsq);
764
765       if (type_of(m) == EN_PASSANT)
766           board[capsq] = NO_PIECE;
767
768       // Update material hash key and prefetch access to materialTable
769       k ^= Zobrist::psq[captured][capsq];
770       st->materialKey ^= Zobrist::psq[captured][pieceCount[captured]];
771       prefetch(thisThread->materialTable[st->materialKey]);
772
773       // Reset rule 50 counter
774       st->rule50 = 0;
775   }
776
777   // Update hash key
778   k ^= Zobrist::psq[pc][from] ^ Zobrist::psq[pc][to];
779
780   // Reset en passant square
781   if (st->epSquare != SQ_NONE)
782   {
783       k ^= Zobrist::enpassant[file_of(st->epSquare)];
784       st->epSquare = SQ_NONE;
785   }
786
787   // Update castling rights if needed
788   if (st->castlingRights && (castlingRightsMask[from] | castlingRightsMask[to]))
789   {
790       k ^= Zobrist::castling[st->castlingRights];
791       st->castlingRights &= ~(castlingRightsMask[from] | castlingRightsMask[to]);
792       k ^= Zobrist::castling[st->castlingRights];
793   }
794
795   // Move the piece. The tricky Chess960 castling is handled earlier
796   if (type_of(m) != CASTLING)
797   {
798       if (Eval::useNNUE)
799       {
800           dp.piece[0] = pc;
801           dp.from[0] = from;
802           dp.to[0] = to;
803       }
804
805       move_piece(from, to);
806   }
807
808   // If the moving piece is a pawn do some special extra work
809   if (type_of(pc) == PAWN)
810   {
811       // Set en passant square if the moved pawn can be captured
812       if (   (int(to) ^ int(from)) == 16
813           && (pawn_attacks_bb(us, to - pawn_push(us)) & pieces(them, PAWN)))
814       {
815           st->epSquare = to - pawn_push(us);
816           k ^= Zobrist::enpassant[file_of(st->epSquare)];
817       }
818
819       else if (type_of(m) == PROMOTION)
820       {
821           Piece promotion = make_piece(us, promotion_type(m));
822
823           assert(relative_rank(us, to) == RANK_8);
824           assert(type_of(promotion) >= KNIGHT && type_of(promotion) <= QUEEN);
825
826           remove_piece(to);
827           put_piece(promotion, to);
828
829           if (Eval::useNNUE)
830           {
831               // Promoting pawn to SQ_NONE, promoted piece from SQ_NONE
832               dp.to[0] = SQ_NONE;
833               dp.piece[dp.dirty_num] = promotion;
834               dp.from[dp.dirty_num] = SQ_NONE;
835               dp.to[dp.dirty_num] = to;
836               dp.dirty_num++;
837           }
838
839           // Update hash keys
840           k ^= Zobrist::psq[pc][to] ^ Zobrist::psq[promotion][to];
841           st->pawnKey ^= Zobrist::psq[pc][to];
842           st->materialKey ^=  Zobrist::psq[promotion][pieceCount[promotion]-1]
843                             ^ Zobrist::psq[pc][pieceCount[pc]];
844
845           // Update material
846           st->nonPawnMaterial[us] += PieceValue[MG][promotion];
847       }
848
849       // Update pawn hash key
850       st->pawnKey ^= Zobrist::psq[pc][from] ^ Zobrist::psq[pc][to];
851
852       // Reset rule 50 draw counter
853       st->rule50 = 0;
854   }
855
856   // Set capture piece
857   st->capturedPiece = captured;
858
859   // Update the key with the final value
860   st->key = k;
861
862   // Calculate checkers bitboard (if move gives check)
863   st->checkersBB = givesCheck ? attackers_to(square<KING>(them)) & pieces(us) : 0;
864
865   sideToMove = ~sideToMove;
866
867   // Update king attacks used for fast check detection
868   set_check_info(st);
869
870   // Calculate the repetition info. It is the ply distance from the previous
871   // occurrence of the same position, negative in the 3-fold case, or zero
872   // if the position was not repeated.
873   st->repetition = 0;
874   int end = std::min(st->rule50, st->pliesFromNull);
875   if (end >= 4)
876   {
877       StateInfo* stp = st->previous->previous;
878       for (int i = 4; i <= end; i += 2)
879       {
880           stp = stp->previous->previous;
881           if (stp->key == st->key)
882           {
883               st->repetition = stp->repetition ? -i : i;
884               break;
885           }
886       }
887   }
888
889   assert(pos_is_ok());
890 }
891
892
893 /// Position::undo_move() unmakes a move. When it returns, the position should
894 /// be restored to exactly the same state as before the move was made.
895
896 void Position::undo_move(Move m) {
897
898   assert(is_ok(m));
899
900   sideToMove = ~sideToMove;
901
902   Color us = sideToMove;
903   Square from = from_sq(m);
904   Square to = to_sq(m);
905   Piece pc = piece_on(to);
906
907   assert(empty(from) || type_of(m) == CASTLING);
908   assert(type_of(st->capturedPiece) != KING);
909
910   if (type_of(m) == PROMOTION)
911   {
912       assert(relative_rank(us, to) == RANK_8);
913       assert(type_of(pc) == promotion_type(m));
914       assert(type_of(pc) >= KNIGHT && type_of(pc) <= QUEEN);
915
916       remove_piece(to);
917       pc = make_piece(us, PAWN);
918       put_piece(pc, to);
919   }
920
921   if (type_of(m) == CASTLING)
922   {
923       Square rfrom, rto;
924       do_castling<false>(us, from, to, rfrom, rto);
925   }
926   else
927   {
928       move_piece(to, from); // Put the piece back at the source square
929
930       if (st->capturedPiece)
931       {
932           Square capsq = to;
933
934           if (type_of(m) == EN_PASSANT)
935           {
936               capsq -= pawn_push(us);
937
938               assert(type_of(pc) == PAWN);
939               assert(to == st->previous->epSquare);
940               assert(relative_rank(us, to) == RANK_6);
941               assert(piece_on(capsq) == NO_PIECE);
942               assert(st->capturedPiece == make_piece(~us, PAWN));
943           }
944
945           put_piece(st->capturedPiece, capsq); // Restore the captured piece
946       }
947   }
948
949   // Finally point our state pointer back to the previous state
950   st = st->previous;
951   --gamePly;
952
953   assert(pos_is_ok());
954 }
955
956
957 /// Position::do_castling() is a helper used to do/undo a castling move. This
958 /// is a bit tricky in Chess960 where from/to squares can overlap.
959 template<bool Do>
960 void Position::do_castling(Color us, Square from, Square& to, Square& rfrom, Square& rto) {
961
962   bool kingSide = to > from;
963   rfrom = to; // Castling is encoded as "king captures friendly rook"
964   rto = relative_square(us, kingSide ? SQ_F1 : SQ_D1);
965   to = relative_square(us, kingSide ? SQ_G1 : SQ_C1);
966
967   if (Do && Eval::useNNUE)
968   {
969       auto& dp = st->dirtyPiece;
970       dp.piece[0] = make_piece(us, KING);
971       dp.from[0] = from;
972       dp.to[0] = to;
973       dp.piece[1] = make_piece(us, ROOK);
974       dp.from[1] = rfrom;
975       dp.to[1] = rto;
976       dp.dirty_num = 2;
977   }
978
979   // Remove both pieces first since squares could overlap in Chess960
980   remove_piece(Do ? from : to);
981   remove_piece(Do ? rfrom : rto);
982   board[Do ? from : to] = board[Do ? rfrom : rto] = NO_PIECE; // Since remove_piece doesn't do this for us
983   put_piece(make_piece(us, KING), Do ? to : from);
984   put_piece(make_piece(us, ROOK), Do ? rto : rfrom);
985 }
986
987
988 /// Position::do(undo)_null_move() is used to do(undo) a "null move": it flips
989 /// the side to move without executing any move on the board.
990
991 void Position::do_null_move(StateInfo& newSt) {
992
993   assert(!checkers());
994   assert(&newSt != st);
995
996   std::memcpy(&newSt, st, offsetof(StateInfo, accumulator));
997
998   newSt.previous = st;
999   st = &newSt;
1000
1001   st->dirtyPiece.dirty_num = 0;
1002   st->dirtyPiece.piece[0] = NO_PIECE; // Avoid checks in UpdateAccumulator()
1003   st->accumulator.state[WHITE] = Eval::NNUE::EMPTY;
1004   st->accumulator.state[BLACK] = Eval::NNUE::EMPTY;
1005
1006   if (st->epSquare != SQ_NONE)
1007   {
1008       st->key ^= Zobrist::enpassant[file_of(st->epSquare)];
1009       st->epSquare = SQ_NONE;
1010   }
1011
1012   st->key ^= Zobrist::side;
1013   prefetch(TT.first_entry(key()));
1014
1015   ++st->rule50;
1016   st->pliesFromNull = 0;
1017
1018   sideToMove = ~sideToMove;
1019
1020   set_check_info(st);
1021
1022   st->repetition = 0;
1023
1024   assert(pos_is_ok());
1025 }
1026
1027 void Position::undo_null_move() {
1028
1029   assert(!checkers());
1030
1031   st = st->previous;
1032   sideToMove = ~sideToMove;
1033 }
1034
1035
1036 /// Position::key_after() computes the new hash key after the given move. Needed
1037 /// for speculative prefetch. It doesn't recognize special moves like castling,
1038 /// en passant and promotions.
1039
1040 Key Position::key_after(Move m) const {
1041
1042   Square from = from_sq(m);
1043   Square to = to_sq(m);
1044   Piece pc = piece_on(from);
1045   Piece captured = piece_on(to);
1046   Key k = st->key ^ Zobrist::side;
1047
1048   if (captured)
1049       k ^= Zobrist::psq[captured][to];
1050
1051   return k ^ Zobrist::psq[pc][to] ^ Zobrist::psq[pc][from];
1052 }
1053
1054
1055 /// Position::see_ge (Static Exchange Evaluation Greater or Equal) tests if the
1056 /// SEE value of move is greater or equal to the given threshold. We'll use an
1057 /// algorithm similar to alpha-beta pruning with a null window.
1058
1059 bool Position::see_ge(Move m, Value threshold) const {
1060
1061   assert(is_ok(m));
1062
1063   // Only deal with normal moves, assume others pass a simple SEE
1064   if (type_of(m) != NORMAL)
1065       return VALUE_ZERO >= threshold;
1066
1067   Square from = from_sq(m), to = to_sq(m);
1068
1069   int swap = PieceValue[MG][piece_on(to)] - threshold;
1070   if (swap < 0)
1071       return false;
1072
1073   swap = PieceValue[MG][piece_on(from)] - swap;
1074   if (swap <= 0)
1075       return true;
1076
1077   Bitboard occupied = pieces() ^ from ^ to;
1078   Color stm = color_of(piece_on(from));
1079   Bitboard attackers = attackers_to(to, occupied);
1080   Bitboard stmAttackers, bb;
1081   int res = 1;
1082
1083   while (true)
1084   {
1085       stm = ~stm;
1086       attackers &= occupied;
1087
1088       // If stm has no more attackers then give up: stm loses
1089       if (!(stmAttackers = attackers & pieces(stm)))
1090           break;
1091
1092       // Don't allow pinned pieces to attack (except the king) as long as
1093       // there are pinners on their original square.
1094       if (pinners(~stm) & occupied)
1095           stmAttackers &= ~blockers_for_king(stm);
1096
1097       if (!stmAttackers)
1098           break;
1099
1100       res ^= 1;
1101
1102       // Locate and remove the next least valuable attacker, and add to
1103       // the bitboard 'attackers' any X-ray attackers behind it.
1104       if ((bb = stmAttackers & pieces(PAWN)))
1105       {
1106           if ((swap = PawnValueMg - swap) < res)
1107               break;
1108
1109           occupied ^= lsb(bb);
1110           attackers |= attacks_bb<BISHOP>(to, occupied) & pieces(BISHOP, QUEEN);
1111       }
1112
1113       else if ((bb = stmAttackers & pieces(KNIGHT)))
1114       {
1115           if ((swap = KnightValueMg - swap) < res)
1116               break;
1117
1118           occupied ^= lsb(bb);
1119       }
1120
1121       else if ((bb = stmAttackers & pieces(BISHOP)))
1122       {
1123           if ((swap = BishopValueMg - swap) < res)
1124               break;
1125
1126           occupied ^= lsb(bb);
1127           attackers |= attacks_bb<BISHOP>(to, occupied) & pieces(BISHOP, QUEEN);
1128       }
1129
1130       else if ((bb = stmAttackers & pieces(ROOK)))
1131       {
1132           if ((swap = RookValueMg - swap) < res)
1133               break;
1134
1135           occupied ^= lsb(bb);
1136           attackers |= attacks_bb<ROOK>(to, occupied) & pieces(ROOK, QUEEN);
1137       }
1138
1139       else if ((bb = stmAttackers & pieces(QUEEN)))
1140       {
1141           if ((swap = QueenValueMg - swap) < res)
1142               break;
1143
1144           occupied ^= lsb(bb);
1145           attackers |=  (attacks_bb<BISHOP>(to, occupied) & pieces(BISHOP, QUEEN))
1146                       | (attacks_bb<ROOK  >(to, occupied) & pieces(ROOK  , QUEEN));
1147       }
1148
1149       else // KING
1150            // If we "capture" with the king but opponent still has attackers,
1151            // reverse the result.
1152           return (attackers & ~pieces(stm)) ? res ^ 1 : res;
1153   }
1154
1155   return bool(res);
1156 }
1157
1158
1159 /// Position::is_draw() tests whether the position is drawn by 50-move rule
1160 /// or by repetition. It does not detect stalemates.
1161
1162 bool Position::is_draw(int ply) const {
1163
1164   if (st->rule50 > 99 && (!checkers() || MoveList<LEGAL>(*this).size()))
1165       return true;
1166
1167   // Return a draw score if a position repeats once earlier but strictly
1168   // after the root, or repeats twice before or at the root.
1169   return st->repetition && st->repetition < ply;
1170 }
1171
1172
1173 // Position::has_repeated() tests whether there has been at least one repetition
1174 // of positions since the last capture or pawn move.
1175
1176 bool Position::has_repeated() const {
1177
1178     StateInfo* stc = st;
1179     int end = std::min(st->rule50, st->pliesFromNull);
1180     while (end-- >= 4)
1181     {
1182         if (stc->repetition)
1183             return true;
1184
1185         stc = stc->previous;
1186     }
1187     return false;
1188 }
1189
1190
1191 /// Position::has_game_cycle() tests if the position has a move which draws by repetition,
1192 /// or an earlier position has a move that directly reaches the current position.
1193
1194 bool Position::has_game_cycle(int ply) const {
1195
1196   int j;
1197
1198   int end = std::min(st->rule50, st->pliesFromNull);
1199
1200   if (end < 3)
1201     return false;
1202
1203   Key originalKey = st->key;
1204   StateInfo* stp = st->previous;
1205
1206   for (int i = 3; i <= end; i += 2)
1207   {
1208       stp = stp->previous->previous;
1209
1210       Key moveKey = originalKey ^ stp->key;
1211       if (   (j = H1(moveKey), cuckoo[j] == moveKey)
1212           || (j = H2(moveKey), cuckoo[j] == moveKey))
1213       {
1214           Move move = cuckooMove[j];
1215           Square s1 = from_sq(move);
1216           Square s2 = to_sq(move);
1217
1218           if (!(between_bb(s1, s2) & pieces()))
1219           {
1220               if (ply > i)
1221                   return true;
1222
1223               // For nodes before or at the root, check that the move is a
1224               // repetition rather than a move to the current position.
1225               // In the cuckoo table, both moves Rc1c5 and Rc5c1 are stored in
1226               // the same location, so we have to select which square to check.
1227               if (color_of(piece_on(empty(s1) ? s2 : s1)) != side_to_move())
1228                   continue;
1229
1230               // For repetitions before or at the root, require one more
1231               if (stp->repetition)
1232                   return true;
1233           }
1234       }
1235   }
1236   return false;
1237 }
1238
1239
1240 /// Position::flip() flips position with the white and black sides reversed. This
1241 /// is only useful for debugging e.g. for finding evaluation symmetry bugs.
1242
1243 void Position::flip() {
1244
1245   string f, token;
1246   std::stringstream ss(fen());
1247
1248   for (Rank r = RANK_8; r >= RANK_1; --r) // Piece placement
1249   {
1250       std::getline(ss, token, r > RANK_1 ? '/' : ' ');
1251       f.insert(0, token + (f.empty() ? " " : "/"));
1252   }
1253
1254   ss >> token; // Active color
1255   f += (token == "w" ? "B " : "W "); // Will be lowercased later
1256
1257   ss >> token; // Castling availability
1258   f += token + " ";
1259
1260   std::transform(f.begin(), f.end(), f.begin(),
1261                  [](char c) { return char(islower(c) ? toupper(c) : tolower(c)); });
1262
1263   ss >> token; // En passant square
1264   f += (token == "-" ? token : token.replace(1, 1, token[1] == '3' ? "6" : "3"));
1265
1266   std::getline(ss, token); // Half and full moves
1267   f += token;
1268
1269   set(f, is_chess960(), st, this_thread());
1270
1271   assert(pos_is_ok());
1272 }
1273
1274
1275 /// Position::pos_is_ok() performs some consistency checks for the
1276 /// position object and raises an asserts if something wrong is detected.
1277 /// This is meant to be helpful when debugging.
1278
1279 bool Position::pos_is_ok() const {
1280
1281   constexpr bool Fast = true; // Quick (default) or full check?
1282
1283   if (   (sideToMove != WHITE && sideToMove != BLACK)
1284       || piece_on(square<KING>(WHITE)) != W_KING
1285       || piece_on(square<KING>(BLACK)) != B_KING
1286       || (   ep_square() != SQ_NONE
1287           && relative_rank(sideToMove, ep_square()) != RANK_6))
1288       assert(0 && "pos_is_ok: Default");
1289
1290   if (Fast)
1291       return true;
1292
1293   if (   pieceCount[W_KING] != 1
1294       || pieceCount[B_KING] != 1
1295       || attackers_to(square<KING>(~sideToMove)) & pieces(sideToMove))
1296       assert(0 && "pos_is_ok: Kings");
1297
1298   if (   (pieces(PAWN) & (Rank1BB | Rank8BB))
1299       || pieceCount[W_PAWN] > 8
1300       || pieceCount[B_PAWN] > 8)
1301       assert(0 && "pos_is_ok: Pawns");
1302
1303   if (   (pieces(WHITE) & pieces(BLACK))
1304       || (pieces(WHITE) | pieces(BLACK)) != pieces()
1305       || popcount(pieces(WHITE)) > 16
1306       || popcount(pieces(BLACK)) > 16)
1307       assert(0 && "pos_is_ok: Bitboards");
1308
1309   for (PieceType p1 = PAWN; p1 <= KING; ++p1)
1310       for (PieceType p2 = PAWN; p2 <= KING; ++p2)
1311           if (p1 != p2 && (pieces(p1) & pieces(p2)))
1312               assert(0 && "pos_is_ok: Bitboards");
1313
1314   StateInfo si = *st;
1315   ASSERT_ALIGNED(&si, Eval::NNUE::kCacheLineSize);
1316
1317   set_state(&si);
1318   if (std::memcmp(&si, st, sizeof(StateInfo)))
1319       assert(0 && "pos_is_ok: State");
1320
1321   for (Piece pc : Pieces)
1322       if (   pieceCount[pc] != popcount(pieces(color_of(pc), type_of(pc)))
1323           || pieceCount[pc] != std::count(board, board + SQUARE_NB, pc))
1324           assert(0 && "pos_is_ok: Pieces");
1325
1326   for (Color c : { WHITE, BLACK })
1327       for (CastlingRights cr : {c & KING_SIDE, c & QUEEN_SIDE})
1328       {
1329           if (!can_castle(cr))
1330               continue;
1331
1332           if (   piece_on(castlingRookSquare[cr]) != make_piece(c, ROOK)
1333               || castlingRightsMask[castlingRookSquare[cr]] != cr
1334               || (castlingRightsMask[square<KING>(c)] & cr) != cr)
1335               assert(0 && "pos_is_ok: Castling");
1336       }
1337
1338   return true;
1339 }