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