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