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