]> git.sesse.net Git - stockfish/blob - src/position.cpp
Greatly simplify castling rights handling
[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-2010 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 <cassert>
21 #include <cstring>
22 #include <fstream>
23 #include <iostream>
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 "ucioption.h"
34
35 using std::string;
36 using std::cout;
37 using std::endl;
38
39 Key Position::zobrist[2][8][64];
40 Key Position::zobEp[64];
41 Key Position::zobCastle[16];
42 Key Position::zobSideToMove;
43 Key Position::zobExclusion;
44
45 Score Position::PieceSquareTable[16][64];
46
47 // Material values arrays, indexed by Piece
48 const Value PieceValueMidgame[17] = {
49   VALUE_ZERO,
50   PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51   RookValueMidgame, QueenValueMidgame,
52   VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
53   PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54   RookValueMidgame, QueenValueMidgame
55 };
56
57 const Value PieceValueEndgame[17] = {
58   VALUE_ZERO,
59   PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60   RookValueEndgame, QueenValueEndgame,
61   VALUE_ZERO, VALUE_ZERO, VALUE_ZERO,
62   PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63   RookValueEndgame, QueenValueEndgame
64 };
65
66
67 namespace {
68
69   // Bonus for having the side to move (modified by Joona Kiiski)
70   const Score TempoValue = make_score(48, 22);
71
72   // To convert a Piece to and from a FEN char
73   const string PieceToChar(".PNBRQK  pnbrqk  ");
74 }
75
76
77 /// CheckInfo c'tor
78
79 CheckInfo::CheckInfo(const Position& pos) {
80
81   Color us = pos.side_to_move();
82   Color them = opposite_color(us);
83   Square ksq = pos.king_square(them);
84
85   dcCandidates = pos.discovered_check_candidates(us);
86   pinned = pos.pinned_pieces(us);
87
88   checkSq[PAWN]   = pos.attacks_from<PAWN>(ksq, them);
89   checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
90   checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
91   checkSq[ROOK]   = pos.attacks_from<ROOK>(ksq);
92   checkSq[QUEEN]  = checkSq[BISHOP] | checkSq[ROOK];
93   checkSq[KING]   = EmptyBoardBB;
94 }
95
96
97 /// Position c'tors. Here we always create a copy of the original position
98 /// or the FEN string, we want the new born Position object do not depend
99 /// on any external data so we detach state pointer from the source one.
100
101 Position::Position(const Position& pos, int th) {
102
103   memcpy(this, &pos, sizeof(Position));
104   detach(); // Always detach() in copy c'tor to avoid surprises
105   threadID = th;
106   nodes = 0;
107 }
108
109 Position::Position(const string& fen, bool isChess960, int th) {
110
111   from_fen(fen, isChess960);
112   threadID = th;
113 }
114
115
116 /// Position::detach() copies the content of the current state and castling
117 /// masks inside the position itself. This is needed when the st pointee could
118 /// become stale, as example because the caller is about to going out of scope.
119
120 void Position::detach() {
121
122   startState = *st;
123   st = &startState;
124   st->previous = NULL; // As a safe guard
125 }
126
127
128 /// Position::from_fen() initializes the position object with the given FEN
129 /// string. This function is not very robust - make sure that input FENs are
130 /// correct (this is assumed to be the responsibility of the GUI).
131
132 void Position::from_fen(const string& fen, bool isChess960) {
133 /*
134    A FEN string defines a particular position using only the ASCII character set.
135
136    A FEN string contains six fields. The separator between fields is a space. The fields are:
137
138    1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
139       with rank 1; within each rank, the contents of each square are described from file A through file H.
140       Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
141       from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
142       while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
143       of blank squares), and "/" separate ranks.
144
145    2) Active color. "w" means white moves next, "b" means black.
146
147    3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
148       letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
149       kingside), and/or "q" (Black can castle queenside).
150
151    4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
152       If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
153       regardless of whether there is a pawn in position to make an en passant capture.
154
155    5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
156       to determine if a draw can be claimed under the fifty-move rule.
157
158    6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
159 */
160
161   char token;
162   size_t p;
163   string ep;
164   Square sq = SQ_A8;
165   std::istringstream ss(fen);
166
167   clear();
168   ss >> std::skipws >> token >> std::noskipws;
169
170   // 1. Piece placement
171   while (!isspace(token))
172   {
173       if (token == '/')
174           sq -= Square(16); // Jump back of 2 rows
175
176       else if (isdigit(token))
177           sq += Square(token - '0'); // Skip the given number of files
178
179       else if ((p = PieceToChar.find(token)) != string::npos)
180       {
181           put_piece(Piece(p), sq);
182           sq++;
183       }
184
185       ss >> token;
186   }
187
188   // 2. Active color
189   ss >> std::skipws >> token;
190   sideToMove = (token == 'w' ? WHITE : BLACK);
191
192   // 3. Castling availability
193   ss >> token >> std::noskipws;
194   while (token != '-' && !isspace(token))
195   {
196       set_castling_rights(token);
197       ss >> token;
198   }
199
200   // 4. En passant square. Ignore if no pawn capture is possible
201   ss >> std::skipws >> ep;
202   if (ep.size() == 2)
203   {
204       st->epSquare = make_square(File(ep[0] - 'a'), Rank(ep[1] - '1'));
205
206       if (!(attackers_to(st->epSquare) & pieces(PAWN, sideToMove)))
207           st->epSquare = SQ_NONE;
208   }
209
210   // 5-6. Halfmove clock and fullmove number
211   ss >> st->rule50 >> fullMoves;
212
213   // Various initialisations
214   chess960 = isChess960;
215   find_checkers();
216
217   st->key = compute_key();
218   st->pawnKey = compute_pawn_key();
219   st->materialKey = compute_material_key();
220   st->value = compute_value();
221   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
222   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
223 }
224
225
226 /// Position::set_castle() is an helper function used to set
227 /// correct castling related flags.
228
229 void Position::set_castle(int f, Square ksq, Square rsq) {
230
231   st->castleRights |= f;
232   castleRightsMask[ksq] ^= f;
233   castleRightsMask[rsq] ^= f;
234   castleRookSquare[f] = rsq;
235 }
236
237
238 /// Position::set_castling_rights() sets castling parameters castling avaiability.
239 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
240 /// that uses the letters of the columns on which the rooks began the game instead
241 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
242 /// associated with the castling right, the traditional castling tag will be replaced
243 /// by the file letter of the involved rook as for the Shredder-FEN.
244
245 void Position::set_castling_rights(char token) {
246
247     Color c = islower(token) ? BLACK : WHITE;
248
249     Square sqA = relative_square(c, SQ_A1);
250     Square sqH = relative_square(c, SQ_H1);
251
252     Square rsq, ksq = king_square(c);
253
254     if (toupper(token) == 'K')
255     {
256         for (rsq = sqH; piece_on(rsq) != make_piece(c, ROOK); rsq--) {}
257         set_castle(WHITE_OO << c, ksq, rsq);
258     }
259     else if (toupper(token) == 'Q')
260     {
261         for (rsq = sqA; piece_on(rsq) != make_piece(c, ROOK); rsq++) {}
262         set_castle(WHITE_OOO << c, ksq, rsq);
263     }
264     else if (toupper(token) >= 'A' && toupper(token) <= 'H')
265     {
266         Square rsq = make_square(File(toupper(token) - 'A'), RANK_1);
267
268         if (square_file(rsq) < square_file(ksq))
269             set_castle(WHITE_OOO << c, ksq, rsq);
270         else
271             set_castle(WHITE_OO << c, ksq, rsq);
272     }
273 }
274
275
276 /// Position::to_fen() returns a FEN representation of the position. In case
277 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
278
279 const string Position::to_fen() const {
280
281   string fen;
282   Square sq;
283   char emptyCnt;
284
285   for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
286   {
287       emptyCnt = '0';
288
289       for (File file = FILE_A; file <= FILE_H; file++)
290       {
291           sq = make_square(file, rank);
292
293           if (square_is_occupied(sq))
294           {
295               if (emptyCnt != '0')
296               {
297                   fen += emptyCnt;
298                   emptyCnt = '0';
299               }
300               fen += PieceToChar[piece_on(sq)];
301           } else
302               emptyCnt++;
303       }
304
305       if (emptyCnt != '0')
306           fen += emptyCnt;
307   }
308
309   fen += (sideToMove == WHITE ? " w " : " b ");
310
311   if (st->castleRights != CASTLES_NONE)
312   {
313       if (can_castle(WHITE_OO))
314           fen += chess960 ? char(toupper(file_to_char(square_file(castle_rook_square(WHITE_OO))))) : 'K';
315
316       if (can_castle(WHITE_OOO))
317           fen += chess960 ? char(toupper(file_to_char(square_file(castle_rook_square(WHITE_OOO))))) : 'Q';
318
319       if (can_castle(BLACK_OO))
320           fen += chess960 ? file_to_char(square_file(castle_rook_square(BLACK_OO))) : 'k';
321
322       if (can_castle(BLACK_OOO))
323           fen += chess960 ? file_to_char(square_file(castle_rook_square(BLACK_OOO))) : 'q';
324   } else
325       fen += '-';
326
327   fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
328   return fen;
329 }
330
331
332 /// Position::print() prints an ASCII representation of the position to
333 /// the standard output. If a move is given then also the san is printed.
334
335 void Position::print(Move move) const {
336
337   const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
338
339   if (move)
340   {
341       Position p(*this, thread());
342       string dd = (piece_color(piece_on(move_from(move))) == BLACK ? ".." : "");
343       cout << "\nMove is: " << dd << move_to_san(p, move);
344   }
345
346   for (Rank rank = RANK_8; rank >= RANK_1; rank--)
347   {
348       cout << dottedLine << '|';
349       for (File file = FILE_A; file <= FILE_H; file++)
350       {
351           Square sq = make_square(file, rank);
352           Piece piece = piece_on(sq);
353
354           if (piece == PIECE_NONE && square_color(sq) == DARK)
355               piece = PIECE_NONE_DARK_SQ;
356
357           char c = (piece_color(piece_on(sq)) == BLACK ? '=' : ' ');
358           cout << c << PieceToChar[piece] << c << '|';
359       }
360   }
361   cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
362 }
363
364
365 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
366 /// king) pieces for the given color and for the given pinner type. Or, when
367 /// template parameter FindPinned is false, the pieces of the given color
368 /// candidate for a discovery check against the enemy king.
369 /// Bitboard checkersBB must be already updated when looking for pinners.
370
371 template<bool FindPinned>
372 Bitboard Position::hidden_checkers(Color c) const {
373
374   Bitboard result = EmptyBoardBB;
375   Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
376
377   // Pinned pieces protect our king, dicovery checks attack
378   // the enemy king.
379   Square ksq = king_square(FindPinned ? c : opposite_color(c));
380
381   // Pinners are sliders, not checkers, that give check when candidate pinned is removed
382   pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
383
384   if (FindPinned && pinners)
385       pinners &= ~st->checkersBB;
386
387   while (pinners)
388   {
389       Square s = pop_1st_bit(&pinners);
390       Bitboard b = squares_between(s, ksq) & occupied_squares();
391
392       assert(b);
393
394       if (  !(b & (b - 1)) // Only one bit set?
395           && (b & pieces_of_color(c))) // Is an our piece?
396           result |= b;
397   }
398   return result;
399 }
400
401
402 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
403 /// king) pieces for the given color. Note that checkersBB bitboard must
404 /// be already updated.
405
406 Bitboard Position::pinned_pieces(Color c) const {
407
408   return hidden_checkers<true>(c);
409 }
410
411
412 /// Position:discovered_check_candidates() returns a bitboard containing all
413 /// pieces for the given side which are candidates for giving a discovered
414 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
415 /// to be already updated.
416
417 Bitboard Position::discovered_check_candidates(Color c) const {
418
419   return hidden_checkers<false>(c);
420 }
421
422 /// Position::attackers_to() computes a bitboard containing all pieces which
423 /// attacks a given square.
424
425 Bitboard Position::attackers_to(Square s) const {
426
427   return  (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
428         | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
429         | (attacks_from<KNIGHT>(s)      & pieces(KNIGHT))
430         | (attacks_from<ROOK>(s)        & pieces(ROOK, QUEEN))
431         | (attacks_from<BISHOP>(s)      & pieces(BISHOP, QUEEN))
432         | (attacks_from<KING>(s)        & pieces(KING));
433 }
434
435 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
436
437   return  (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
438         | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
439         | (attacks_from<KNIGHT>(s)      & pieces(KNIGHT))
440         | (rook_attacks_bb(s, occ)      & pieces(ROOK, QUEEN))
441         | (bishop_attacks_bb(s, occ)    & pieces(BISHOP, QUEEN))
442         | (attacks_from<KING>(s)        & pieces(KING));
443 }
444
445 /// Position::attacks_from() computes a bitboard of all attacks
446 /// of a given piece put in a given square.
447
448 Bitboard Position::attacks_from(Piece p, Square s) const {
449
450   assert(square_is_ok(s));
451
452   switch (p)
453   {
454   case WB: case BB: return attacks_from<BISHOP>(s);
455   case WR: case BR: return attacks_from<ROOK>(s);
456   case WQ: case BQ: return attacks_from<QUEEN>(s);
457   default: return StepAttacksBB[p][s];
458   }
459 }
460
461 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
462
463   assert(square_is_ok(s));
464
465   switch (p)
466   {
467   case WB: case BB: return bishop_attacks_bb(s, occ);
468   case WR: case BR: return rook_attacks_bb(s, occ);
469   case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
470   default: return StepAttacksBB[p][s];
471   }
472 }
473
474
475 /// Position::move_attacks_square() tests whether a move from the current
476 /// position attacks a given square.
477
478 bool Position::move_attacks_square(Move m, Square s) const {
479
480   assert(move_is_ok(m));
481   assert(square_is_ok(s));
482
483   Bitboard occ, xray;
484   Square f = move_from(m), t = move_to(m);
485
486   assert(square_is_occupied(f));
487
488   if (bit_is_set(attacks_from(piece_on(f), t), s))
489       return true;
490
491   // Move the piece and scan for X-ray attacks behind it
492   occ = occupied_squares();
493   do_move_bb(&occ, make_move_bb(f, t));
494   xray = ( (rook_attacks_bb(s, occ)   & pieces(ROOK, QUEEN))
495           |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
496          & pieces_of_color(piece_color(piece_on(f)));
497
498   // If we have attacks we need to verify that are caused by our move
499   // and are not already existent ones.
500   return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
501 }
502
503
504 /// Position::find_checkers() computes the checkersBB bitboard, which
505 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
506 /// currently works by calling Position::attackers_to, which is probably
507 /// inefficient. Consider rewriting this function to use the last move
508 /// played, like in non-bitboard versions of Glaurung.
509
510 void Position::find_checkers() {
511
512   Color us = side_to_move();
513   st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
514 }
515
516
517 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
518
519 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
520
521   assert(is_ok());
522   assert(move_is_ok(m));
523   assert(pinned == pinned_pieces(side_to_move()));
524
525   Color us = side_to_move();
526   Square from = move_from(m);
527
528   assert(piece_color(piece_on(from)) == us);
529   assert(piece_on(king_square(us)) == make_piece(us, KING));
530
531   // En passant captures are a tricky special case. Because they are
532   // rather uncommon, we do it simply by testing whether the king is attacked
533   // after the move is made
534   if (move_is_ep(m))
535   {
536       Color them = opposite_color(us);
537       Square to = move_to(m);
538       Square capsq = make_square(square_file(to), square_rank(from));
539       Square ksq = king_square(us);
540       Bitboard b = occupied_squares();
541
542       assert(to == ep_square());
543       assert(piece_on(from) == make_piece(us, PAWN));
544       assert(piece_on(capsq) == make_piece(them, PAWN));
545       assert(piece_on(to) == PIECE_NONE);
546
547       clear_bit(&b, from);
548       clear_bit(&b, capsq);
549       set_bit(&b, to);
550
551       return   !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
552             && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
553   }
554
555   // If the moving piece is a king, check whether the destination
556   // square is attacked by the opponent. Castling moves are checked
557   // for legality during move generation.
558   if (piece_type(piece_on(from)) == KING)
559       return move_is_castle(m) || !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
560
561   // A non-king move is legal if and only if it is not pinned or it
562   // is moving along the ray towards or away from the king.
563   return   !pinned
564         || !bit_is_set(pinned, from)
565         ||  squares_aligned(from, move_to(m), king_square(us));
566 }
567
568
569 /// Position::move_is_pl_slow() takes a move and tests whether the move
570 /// is pseudo legal. This version is not very fast and should be used
571 /// only in non time-critical paths.
572
573 bool Position::move_is_pl_slow(const Move m) const {
574
575   MoveStack mlist[MAX_MOVES];
576   MoveStack *cur, *last;
577
578   last = in_check() ? generate<MV_EVASION>(*this, mlist)
579                     : generate<MV_NON_EVASION>(*this, mlist);
580
581   for (cur = mlist; cur != last; cur++)
582       if (cur->move == m)
583           return true;
584
585   return false;
586 }
587
588
589 /// Fast version of Position::move_is_pl() that takes a move and a bitboard
590 /// of pinned pieces as input, and tests whether the move is pseudo legal.
591
592 bool Position::move_is_pl(const Move m) const {
593
594   assert(is_ok());
595
596   Color us = sideToMove;
597   Color them = opposite_color(sideToMove);
598   Square from = move_from(m);
599   Square to = move_to(m);
600   Piece pc = piece_on(from);
601
602   // Use a slower but simpler function for uncommon cases
603   if (move_is_special(m))
604       return move_is_pl_slow(m);
605
606   // Is not a promotion, so promotion piece must be empty
607   if (promotion_piece_type(m) - 2 != PIECE_TYPE_NONE)
608       return false;
609
610   // If the from square is not occupied by a piece belonging to the side to
611   // move, the move is obviously not legal.
612   if (pc == PIECE_NONE || piece_color(pc) != us)
613       return false;
614
615   // The destination square cannot be occupied by a friendly piece
616   if (piece_color(piece_on(to)) == us)
617       return false;
618
619   // Handle the special case of a pawn move
620   if (piece_type(pc) == PAWN)
621   {
622       // Move direction must be compatible with pawn color
623       int direction = to - from;
624       if ((us == WHITE) != (direction > 0))
625           return false;
626
627       // We have already handled promotion moves, so destination
628       // cannot be on the 8/1th rank.
629       if (square_rank(to) == RANK_8 || square_rank(to) == RANK_1)
630           return false;
631
632       // Proceed according to the square delta between the origin and
633       // destination squares.
634       switch (direction)
635       {
636       case DELTA_NW:
637       case DELTA_NE:
638       case DELTA_SW:
639       case DELTA_SE:
640       // Capture. The destination square must be occupied by an enemy
641       // piece (en passant captures was handled earlier).
642       if (piece_color(piece_on(to)) != them)
643           return false;
644
645       // From and to files must be one file apart, avoids a7h5
646       if (abs(square_file(from) - square_file(to)) != 1)
647           return false;
648       break;
649
650       case DELTA_N:
651       case DELTA_S:
652       // Pawn push. The destination square must be empty.
653       if (!square_is_empty(to))
654           return false;
655       break;
656
657       case DELTA_NN:
658       // Double white pawn push. The destination square must be on the fourth
659       // rank, and both the destination square and the square between the
660       // source and destination squares must be empty.
661       if (   square_rank(to) != RANK_4
662           || !square_is_empty(to)
663           || !square_is_empty(from + DELTA_N))
664           return false;
665       break;
666
667       case DELTA_SS:
668       // Double black pawn push. The destination square must be on the fifth
669       // rank, and both the destination square and the square between the
670       // source and destination squares must be empty.
671       if (   square_rank(to) != RANK_5
672           || !square_is_empty(to)
673           || !square_is_empty(from + DELTA_S))
674           return false;
675       break;
676
677       default:
678           return false;
679       }
680   }
681   else if (!bit_is_set(attacks_from(pc, from), to))
682       return false;
683
684   if (in_check())
685   {
686       // In case of king moves under check we have to remove king so to catch
687       // as invalid moves like b1a1 when opposite queen is on c1.
688       if (piece_type(piece_on(from)) == KING)
689       {
690           Bitboard b = occupied_squares();
691           clear_bit(&b, from);
692           if (attackers_to(move_to(m), b) & pieces_of_color(opposite_color(us)))
693               return false;
694       }
695       else
696       {
697           Bitboard target = checkers();
698           Square checksq = pop_1st_bit(&target);
699
700           if (target) // double check ? In this case a king move is required
701               return false;
702
703           // Our move must be a blocking evasion or a capture of the checking piece
704           target = squares_between(checksq, king_square(us)) | checkers();
705           if (!bit_is_set(target, move_to(m)))
706               return false;
707       }
708   }
709
710   return true;
711 }
712
713
714 /// Position::move_gives_check() tests whether a pseudo-legal move is a check
715
716 bool Position::move_gives_check(Move m, const CheckInfo& ci) const {
717
718   assert(is_ok());
719   assert(move_is_ok(m));
720   assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
721   assert(piece_color(piece_on(move_from(m))) == side_to_move());
722
723   Square from = move_from(m);
724   Square to = move_to(m);
725   PieceType pt = piece_type(piece_on(from));
726
727   // Direct check ?
728   if (bit_is_set(ci.checkSq[pt], to))
729       return true;
730
731   // Discovery check ?
732   if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
733   {
734       // For pawn and king moves we need to verify also direction
735       if (  (pt != PAWN && pt != KING)
736           || !squares_aligned(from, to, king_square(opposite_color(side_to_move()))))
737           return true;
738   }
739
740   // Can we skip the ugly special cases ?
741   if (!move_is_special(m))
742       return false;
743
744   Color us = side_to_move();
745   Bitboard b = occupied_squares();
746   Square ksq = king_square(opposite_color(us));
747
748   // Promotion with check ?
749   if (move_is_promotion(m))
750   {
751       clear_bit(&b, from);
752
753       switch (promotion_piece_type(m))
754       {
755       case KNIGHT:
756           return bit_is_set(attacks_from<KNIGHT>(to), ksq);
757       case BISHOP:
758           return bit_is_set(bishop_attacks_bb(to, b), ksq);
759       case ROOK:
760           return bit_is_set(rook_attacks_bb(to, b), ksq);
761       case QUEEN:
762           return bit_is_set(queen_attacks_bb(to, b), ksq);
763       default:
764           assert(false);
765       }
766   }
767
768   // En passant capture with check ? We have already handled the case
769   // of direct checks and ordinary discovered check, the only case we
770   // need to handle is the unusual case of a discovered check through
771   // the captured pawn.
772   if (move_is_ep(m))
773   {
774       Square capsq = make_square(square_file(to), square_rank(from));
775       clear_bit(&b, from);
776       clear_bit(&b, capsq);
777       set_bit(&b, to);
778       return  (rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, us))
779             ||(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, us));
780   }
781
782   // Castling with check ?
783   if (move_is_castle(m))
784   {
785       Square kfrom, kto, rfrom, rto;
786       kfrom = from;
787       rfrom = to;
788
789       if (rfrom > kfrom)
790       {
791           kto = relative_square(us, SQ_G1);
792           rto = relative_square(us, SQ_F1);
793       } else {
794           kto = relative_square(us, SQ_C1);
795           rto = relative_square(us, SQ_D1);
796       }
797       clear_bit(&b, kfrom);
798       clear_bit(&b, rfrom);
799       set_bit(&b, rto);
800       set_bit(&b, kto);
801       return bit_is_set(rook_attacks_bb(rto, b), ksq);
802   }
803
804   return false;
805 }
806
807
808 /// Position::do_setup_move() makes a permanent move on the board. It should
809 /// be used when setting up a position on board. You can't undo the move.
810
811 void Position::do_setup_move(Move m) {
812
813   StateInfo newSt;
814
815   // Update the number of full moves after black's move
816   if (sideToMove == BLACK)
817       fullMoves++;
818
819   do_move(m, newSt);
820
821   // Reset "game ply" in case we made a non-reversible move.
822   // "game ply" is used for repetition detection.
823   if (st->rule50 == 0)
824       st->gamePly = 0;
825
826   // Our StateInfo newSt is about going out of scope so copy
827   // its content before it disappears.
828   detach();
829 }
830
831
832 /// Position::do_move() makes a move, and saves all information necessary
833 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
834 /// moves should be filtered out before this function is called.
835
836 void Position::do_move(Move m, StateInfo& newSt) {
837
838   CheckInfo ci(*this);
839   do_move(m, newSt, ci, move_gives_check(m, ci));
840 }
841
842 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
843
844   assert(is_ok());
845   assert(move_is_ok(m));
846   assert(&newSt != st);
847
848   nodes++;
849   Key key = st->key;
850
851   // Copy some fields of old state to our new StateInfo object except the
852   // ones which are recalculated from scratch anyway, then switch our state
853   // pointer to point to the new, ready to be updated, state.
854   struct ReducedStateInfo {
855     Key pawnKey, materialKey;
856     int castleRights, rule50, gamePly, pliesFromNull;
857     Square epSquare;
858     Score value;
859     Value npMaterial[2];
860   };
861
862   memcpy(&newSt, st, sizeof(ReducedStateInfo));
863
864   newSt.previous = st;
865   st = &newSt;
866
867   // Save the current key to the history[] array, in order to be able to
868   // detect repetition draws.
869   history[st->gamePly++] = key;
870
871   // Update side to move
872   key ^= zobSideToMove;
873
874   // Increment the 50 moves rule draw counter. Resetting it to zero in the
875   // case of non-reversible moves is taken care of later.
876   st->rule50++;
877   st->pliesFromNull++;
878
879   if (move_is_castle(m))
880   {
881       st->key = key;
882       do_castle_move(m);
883       return;
884   }
885
886   Color us = side_to_move();
887   Color them = opposite_color(us);
888   Square from = move_from(m);
889   Square to = move_to(m);
890   bool ep = move_is_ep(m);
891   bool pm = move_is_promotion(m);
892
893   Piece piece = piece_on(from);
894   PieceType pt = piece_type(piece);
895   PieceType capture = ep ? PAWN : piece_type(piece_on(to));
896
897   assert(piece_color(piece_on(from)) == us);
898   assert(piece_color(piece_on(to)) == them || square_is_empty(to));
899   assert(!(ep || pm) || piece == make_piece(us, PAWN));
900   assert(!pm || relative_rank(us, to) == RANK_8);
901
902   if (capture)
903       do_capture_move(key, capture, them, to, ep);
904
905   // Update hash key
906   key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
907
908   // Reset en passant square
909   if (st->epSquare != SQ_NONE)
910   {
911       key ^= zobEp[st->epSquare];
912       st->epSquare = SQ_NONE;
913   }
914
915   // Update castle rights if needed
916   if (    st->castleRights != CASTLES_NONE
917       && (castleRightsMask[from] & castleRightsMask[to]) != ALL_CASTLES)
918   {
919       key ^= zobCastle[st->castleRights];
920       st->castleRights &= castleRightsMask[from] & castleRightsMask[to];
921       key ^= zobCastle[st->castleRights];
922   }
923
924   // Prefetch TT access as soon as we know key is updated
925   prefetch((char*)TT.first_entry(key));
926
927   // Move the piece
928   Bitboard move_bb = make_move_bb(from, to);
929   do_move_bb(&(byColorBB[us]), move_bb);
930   do_move_bb(&(byTypeBB[pt]), move_bb);
931   do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
932
933   board[to] = board[from];
934   board[from] = PIECE_NONE;
935
936   // Update piece lists, note that index[from] is not updated and
937   // becomes stale. This works as long as index[] is accessed just
938   // by known occupied squares.
939   index[to] = index[from];
940   pieceList[us][pt][index[to]] = to;
941
942   // If the moving piece was a pawn do some special extra work
943   if (pt == PAWN)
944   {
945       // Reset rule 50 draw counter
946       st->rule50 = 0;
947
948       // Update pawn hash key and prefetch in L1/L2 cache
949       st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
950
951       // Set en passant square, only if moved pawn can be captured
952       if ((to ^ from) == 16)
953       {
954           if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
955           {
956               st->epSquare = Square((int(from) + int(to)) / 2);
957               key ^= zobEp[st->epSquare];
958           }
959       }
960
961       if (pm) // promotion ?
962       {
963           PieceType promotion = promotion_piece_type(m);
964
965           assert(promotion >= KNIGHT && promotion <= QUEEN);
966
967           // Insert promoted piece instead of pawn
968           clear_bit(&(byTypeBB[PAWN]), to);
969           set_bit(&(byTypeBB[promotion]), to);
970           board[to] = make_piece(us, promotion);
971
972           // Update piece counts
973           pieceCount[us][promotion]++;
974           pieceCount[us][PAWN]--;
975
976           // Update material key
977           st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
978           st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
979
980           // Update piece lists, move the last pawn at index[to] position
981           // and shrink the list. Add a new promotion piece to the list.
982           Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
983           index[lastPawnSquare] = index[to];
984           pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
985           pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
986           index[to] = pieceCount[us][promotion] - 1;
987           pieceList[us][promotion][index[to]] = to;
988
989           // Partially revert hash keys update
990           key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
991           st->pawnKey ^= zobrist[us][PAWN][to];
992
993           // Partially revert and update incremental scores
994           st->value -= pst(us, PAWN, to);
995           st->value += pst(us, promotion, to);
996
997           // Update material
998           st->npMaterial[us] += PieceValueMidgame[promotion];
999       }
1000   }
1001
1002   // Prefetch pawn and material hash tables
1003   Threads[threadID].pawnTable.prefetch(st->pawnKey);
1004   Threads[threadID].materialTable.prefetch(st->materialKey);
1005
1006   // Update incremental scores
1007   st->value += pst_delta(piece, from, to);
1008
1009   // Set capture piece
1010   st->capturedType = capture;
1011
1012   // Update the key with the final value
1013   st->key = key;
1014
1015   // Update checkers bitboard, piece must be already moved
1016   st->checkersBB = EmptyBoardBB;
1017
1018   if (moveIsCheck)
1019   {
1020       if (ep | pm)
1021           st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1022       else
1023       {
1024           // Direct checks
1025           if (bit_is_set(ci.checkSq[pt], to))
1026               st->checkersBB = SetMaskBB[to];
1027
1028           // Discovery checks
1029           if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
1030           {
1031               if (pt != ROOK)
1032                   st->checkersBB |= (attacks_from<ROOK>(king_square(them)) & pieces(ROOK, QUEEN, us));
1033
1034               if (pt != BISHOP)
1035                   st->checkersBB |= (attacks_from<BISHOP>(king_square(them)) & pieces(BISHOP, QUEEN, us));
1036           }
1037       }
1038   }
1039
1040   // Finish
1041   sideToMove = opposite_color(sideToMove);
1042   st->value += (sideToMove == WHITE ?  TempoValue : -TempoValue);
1043
1044   assert(is_ok());
1045 }
1046
1047
1048 /// Position::do_capture_move() is a private method used to update captured
1049 /// piece info. It is called from the main Position::do_move function.
1050
1051 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
1052
1053     assert(capture != KING);
1054
1055     Square capsq = to;
1056
1057     // If the captured piece was a pawn, update pawn hash key,
1058     // otherwise update non-pawn material.
1059     if (capture == PAWN)
1060     {
1061         if (ep) // en passant ?
1062         {
1063             capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1064
1065             assert(to == st->epSquare);
1066             assert(relative_rank(opposite_color(them), to) == RANK_6);
1067             assert(piece_on(to) == PIECE_NONE);
1068             assert(piece_on(capsq) == make_piece(them, PAWN));
1069
1070             board[capsq] = PIECE_NONE;
1071         }
1072         st->pawnKey ^= zobrist[them][PAWN][capsq];
1073     }
1074     else
1075         st->npMaterial[them] -= PieceValueMidgame[capture];
1076
1077     // Remove captured piece
1078     clear_bit(&(byColorBB[them]), capsq);
1079     clear_bit(&(byTypeBB[capture]), capsq);
1080     clear_bit(&(byTypeBB[0]), capsq);
1081
1082     // Update hash key
1083     key ^= zobrist[them][capture][capsq];
1084
1085     // Update incremental scores
1086     st->value -= pst(them, capture, capsq);
1087
1088     // Update piece count
1089     pieceCount[them][capture]--;
1090
1091     // Update material hash key
1092     st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1093
1094     // Update piece list, move the last piece at index[capsq] position
1095     //
1096     // WARNING: This is a not perfectly revresible operation. When we
1097     // will reinsert the captured piece in undo_move() we will put it
1098     // at the end of the list and not in its original place, it means
1099     // index[] and pieceList[] are not guaranteed to be invariant to a
1100     // do_move() + undo_move() sequence.
1101     Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1102     index[lastPieceSquare] = index[capsq];
1103     pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1104     pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1105
1106     // Reset rule 50 counter
1107     st->rule50 = 0;
1108 }
1109
1110
1111 /// Position::do_castle_move() is a private method used to make a castling
1112 /// move. It is called from the main Position::do_move function. Note that
1113 /// castling moves are encoded as "king captures friendly rook" moves, for
1114 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1115
1116 void Position::do_castle_move(Move m) {
1117
1118   assert(move_is_ok(m));
1119   assert(move_is_castle(m));
1120
1121   Color us = side_to_move();
1122   Color them = opposite_color(us);
1123
1124   // Reset capture field
1125   st->capturedType = PIECE_TYPE_NONE;
1126
1127   // Find source squares for king and rook
1128   Square kfrom = move_from(m);
1129   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1130   Square kto, rto;
1131
1132   assert(piece_on(kfrom) == make_piece(us, KING));
1133   assert(piece_on(rfrom) == make_piece(us, ROOK));
1134
1135   // Find destination squares for king and rook
1136   if (rfrom > kfrom) // O-O
1137   {
1138       kto = relative_square(us, SQ_G1);
1139       rto = relative_square(us, SQ_F1);
1140   } else { // O-O-O
1141       kto = relative_square(us, SQ_C1);
1142       rto = relative_square(us, SQ_D1);
1143   }
1144
1145   // Remove pieces from source squares:
1146   clear_bit(&(byColorBB[us]), kfrom);
1147   clear_bit(&(byTypeBB[KING]), kfrom);
1148   clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1149   clear_bit(&(byColorBB[us]), rfrom);
1150   clear_bit(&(byTypeBB[ROOK]), rfrom);
1151   clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1152
1153   // Put pieces on destination squares:
1154   set_bit(&(byColorBB[us]), kto);
1155   set_bit(&(byTypeBB[KING]), kto);
1156   set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1157   set_bit(&(byColorBB[us]), rto);
1158   set_bit(&(byTypeBB[ROOK]), rto);
1159   set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1160
1161   // Update board array
1162   Piece king = make_piece(us, KING);
1163   Piece rook = make_piece(us, ROOK);
1164   board[kfrom] = board[rfrom] = PIECE_NONE;
1165   board[kto] = king;
1166   board[rto] = rook;
1167
1168   // Update piece lists
1169   pieceList[us][KING][index[kfrom]] = kto;
1170   pieceList[us][ROOK][index[rfrom]] = rto;
1171   int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1172   index[kto] = index[kfrom];
1173   index[rto] = tmp;
1174
1175   // Update incremental scores
1176   st->value += pst_delta(king, kfrom, kto);
1177   st->value += pst_delta(rook, rfrom, rto);
1178
1179   // Update hash key
1180   st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1181   st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1182
1183   // Clear en passant square
1184   if (st->epSquare != SQ_NONE)
1185   {
1186       st->key ^= zobEp[st->epSquare];
1187       st->epSquare = SQ_NONE;
1188   }
1189
1190   // Update castling rights
1191   st->key ^= zobCastle[st->castleRights];
1192   st->castleRights &= castleRightsMask[kfrom];
1193   st->key ^= zobCastle[st->castleRights];
1194
1195   // Reset rule 50 counter
1196   st->rule50 = 0;
1197
1198   // Update checkers BB
1199   st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1200
1201   // Finish
1202   sideToMove = opposite_color(sideToMove);
1203   st->value += (sideToMove == WHITE ?  TempoValue : -TempoValue);
1204
1205   assert(is_ok());
1206 }
1207
1208
1209 /// Position::undo_move() unmakes a move. When it returns, the position should
1210 /// be restored to exactly the same state as before the move was made.
1211
1212 void Position::undo_move(Move m) {
1213
1214   assert(is_ok());
1215   assert(move_is_ok(m));
1216
1217   sideToMove = opposite_color(sideToMove);
1218
1219   if (move_is_castle(m))
1220   {
1221       undo_castle_move(m);
1222       return;
1223   }
1224
1225   Color us = side_to_move();
1226   Color them = opposite_color(us);
1227   Square from = move_from(m);
1228   Square to = move_to(m);
1229   bool ep = move_is_ep(m);
1230   bool pm = move_is_promotion(m);
1231
1232   PieceType pt = piece_type(piece_on(to));
1233
1234   assert(square_is_empty(from));
1235   assert(piece_color(piece_on(to)) == us);
1236   assert(!pm || relative_rank(us, to) == RANK_8);
1237   assert(!ep || to == st->previous->epSquare);
1238   assert(!ep || relative_rank(us, to) == RANK_6);
1239   assert(!ep || piece_on(to) == make_piece(us, PAWN));
1240
1241   if (pm) // promotion ?
1242   {
1243       PieceType promotion = promotion_piece_type(m);
1244       pt = PAWN;
1245
1246       assert(promotion >= KNIGHT && promotion <= QUEEN);
1247       assert(piece_on(to) == make_piece(us, promotion));
1248
1249       // Replace promoted piece with a pawn
1250       clear_bit(&(byTypeBB[promotion]), to);
1251       set_bit(&(byTypeBB[PAWN]), to);
1252
1253       // Update piece counts
1254       pieceCount[us][promotion]--;
1255       pieceCount[us][PAWN]++;
1256
1257       // Update piece list replacing promotion piece with a pawn
1258       Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1259       index[lastPromotionSquare] = index[to];
1260       pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1261       pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1262       index[to] = pieceCount[us][PAWN] - 1;
1263       pieceList[us][PAWN][index[to]] = to;
1264   }
1265
1266   // Put the piece back at the source square
1267   Bitboard move_bb = make_move_bb(to, from);
1268   do_move_bb(&(byColorBB[us]), move_bb);
1269   do_move_bb(&(byTypeBB[pt]), move_bb);
1270   do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1271
1272   board[from] = make_piece(us, pt);
1273   board[to] = PIECE_NONE;
1274
1275   // Update piece list
1276   index[from] = index[to];
1277   pieceList[us][pt][index[from]] = from;
1278
1279   if (st->capturedType)
1280   {
1281       Square capsq = to;
1282
1283       if (ep)
1284           capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1285
1286       assert(st->capturedType != KING);
1287       assert(!ep || square_is_empty(capsq));
1288
1289       // Restore the captured piece
1290       set_bit(&(byColorBB[them]), capsq);
1291       set_bit(&(byTypeBB[st->capturedType]), capsq);
1292       set_bit(&(byTypeBB[0]), capsq);
1293
1294       board[capsq] = make_piece(them, st->capturedType);
1295
1296       // Update piece count
1297       pieceCount[them][st->capturedType]++;
1298
1299       // Update piece list, add a new captured piece in capsq square
1300       index[capsq] = pieceCount[them][st->capturedType] - 1;
1301       pieceList[them][st->capturedType][index[capsq]] = capsq;
1302   }
1303
1304   // Finally point our state pointer back to the previous state
1305   st = st->previous;
1306
1307   assert(is_ok());
1308 }
1309
1310
1311 /// Position::undo_castle_move() is a private method used to unmake a castling
1312 /// move. It is called from the main Position::undo_move function. Note that
1313 /// castling moves are encoded as "king captures friendly rook" moves, for
1314 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1315
1316 void Position::undo_castle_move(Move m) {
1317
1318   assert(move_is_ok(m));
1319   assert(move_is_castle(m));
1320
1321   // When we have arrived here, some work has already been done by
1322   // Position::undo_move.  In particular, the side to move has been switched,
1323   // so the code below is correct.
1324   Color us = side_to_move();
1325
1326   // Find source squares for king and rook
1327   Square kfrom = move_from(m);
1328   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1329   Square kto, rto;
1330
1331   // Find destination squares for king and rook
1332   if (rfrom > kfrom) // O-O
1333   {
1334       kto = relative_square(us, SQ_G1);
1335       rto = relative_square(us, SQ_F1);
1336   } else { // O-O-O
1337       kto = relative_square(us, SQ_C1);
1338       rto = relative_square(us, SQ_D1);
1339   }
1340
1341   assert(piece_on(kto) == make_piece(us, KING));
1342   assert(piece_on(rto) == make_piece(us, ROOK));
1343
1344   // Remove pieces from destination squares:
1345   clear_bit(&(byColorBB[us]), kto);
1346   clear_bit(&(byTypeBB[KING]), kto);
1347   clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1348   clear_bit(&(byColorBB[us]), rto);
1349   clear_bit(&(byTypeBB[ROOK]), rto);
1350   clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1351
1352   // Put pieces on source squares:
1353   set_bit(&(byColorBB[us]), kfrom);
1354   set_bit(&(byTypeBB[KING]), kfrom);
1355   set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1356   set_bit(&(byColorBB[us]), rfrom);
1357   set_bit(&(byTypeBB[ROOK]), rfrom);
1358   set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1359
1360   // Update board
1361   board[rto] = board[kto] = PIECE_NONE;
1362   board[rfrom] = make_piece(us, ROOK);
1363   board[kfrom] = make_piece(us, KING);
1364
1365   // Update piece lists
1366   pieceList[us][KING][index[kto]] = kfrom;
1367   pieceList[us][ROOK][index[rto]] = rfrom;
1368   int tmp = index[rto];  // In Chess960 could be rto == kfrom
1369   index[kfrom] = index[kto];
1370   index[rfrom] = tmp;
1371
1372   // Finally point our state pointer back to the previous state
1373   st = st->previous;
1374
1375   assert(is_ok());
1376 }
1377
1378
1379 /// Position::do_null_move makes() a "null move": It switches the side to move
1380 /// and updates the hash key without executing any move on the board.
1381
1382 void Position::do_null_move(StateInfo& backupSt) {
1383
1384   assert(is_ok());
1385   assert(!in_check());
1386
1387   // Back up the information necessary to undo the null move to the supplied
1388   // StateInfo object.
1389   // Note that differently from normal case here backupSt is actually used as
1390   // a backup storage not as a new state to be used.
1391   backupSt.key      = st->key;
1392   backupSt.epSquare = st->epSquare;
1393   backupSt.value    = st->value;
1394   backupSt.previous = st->previous;
1395   backupSt.pliesFromNull = st->pliesFromNull;
1396   st->previous = &backupSt;
1397
1398   // Save the current key to the history[] array, in order to be able to
1399   // detect repetition draws.
1400   history[st->gamePly++] = st->key;
1401
1402   // Update the necessary information
1403   if (st->epSquare != SQ_NONE)
1404       st->key ^= zobEp[st->epSquare];
1405
1406   st->key ^= zobSideToMove;
1407   prefetch((char*)TT.first_entry(st->key));
1408
1409   sideToMove = opposite_color(sideToMove);
1410   st->epSquare = SQ_NONE;
1411   st->rule50++;
1412   st->pliesFromNull = 0;
1413   st->value += (sideToMove == WHITE) ?  TempoValue : -TempoValue;
1414 }
1415
1416
1417 /// Position::undo_null_move() unmakes a "null move".
1418
1419 void Position::undo_null_move() {
1420
1421   assert(is_ok());
1422   assert(!in_check());
1423
1424   // Restore information from the our backup StateInfo object
1425   StateInfo* backupSt = st->previous;
1426   st->key      = backupSt->key;
1427   st->epSquare = backupSt->epSquare;
1428   st->value    = backupSt->value;
1429   st->previous = backupSt->previous;
1430   st->pliesFromNull = backupSt->pliesFromNull;
1431
1432   // Update the necessary information
1433   sideToMove = opposite_color(sideToMove);
1434   st->rule50--;
1435   st->gamePly--;
1436 }
1437
1438
1439 /// Position::see() is a static exchange evaluator: It tries to estimate the
1440 /// material gain or loss resulting from a move. There are three versions of
1441 /// this function: One which takes a destination square as input, one takes a
1442 /// move, and one which takes a 'from' and a 'to' square. The function does
1443 /// not yet understand promotions captures.
1444
1445 int Position::see_sign(Move m) const {
1446
1447   assert(move_is_ok(m));
1448
1449   Square from = move_from(m);
1450   Square to = move_to(m);
1451
1452   // Early return if SEE cannot be negative because captured piece value
1453   // is not less then capturing one. Note that king moves always return
1454   // here because king midgame value is set to 0.
1455   if (piece_value_midgame(piece_on(to)) >= piece_value_midgame(piece_on(from)))
1456       return 1;
1457
1458   return see(m);
1459 }
1460
1461 int Position::see(Move m) const {
1462
1463   Square from, to;
1464   Bitboard occupied, attackers, stmAttackers, b;
1465   int swapList[32], slIndex = 1;
1466   PieceType capturedType, pt;
1467   Color stm;
1468
1469   assert(move_is_ok(m));
1470
1471   // As castle moves are implemented as capturing the rook, they have
1472   // SEE == RookValueMidgame most of the times (unless the rook is under
1473   // attack).
1474   if (move_is_castle(m))
1475       return 0;
1476
1477   from = move_from(m);
1478   to = move_to(m);
1479   capturedType = piece_type(piece_on(to));
1480   occupied = occupied_squares();
1481
1482   // Handle en passant moves
1483   if (st->epSquare == to && piece_type(piece_on(from)) == PAWN)
1484   {
1485       Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1486
1487       assert(capturedType == PIECE_TYPE_NONE);
1488       assert(piece_type(piece_on(capQq)) == PAWN);
1489
1490       // Remove the captured pawn
1491       clear_bit(&occupied, capQq);
1492       capturedType = PAWN;
1493   }
1494
1495   // Find all attackers to the destination square, with the moving piece
1496   // removed, but possibly an X-ray attacker added behind it.
1497   clear_bit(&occupied, from);
1498   attackers = attackers_to(to, occupied);
1499
1500   // If the opponent has no attackers we are finished
1501   stm = opposite_color(piece_color(piece_on(from)));
1502   stmAttackers = attackers & pieces_of_color(stm);
1503   if (!stmAttackers)
1504       return PieceValueMidgame[capturedType];
1505
1506   // The destination square is defended, which makes things rather more
1507   // difficult to compute. We proceed by building up a "swap list" containing
1508   // the material gain or loss at each stop in a sequence of captures to the
1509   // destination square, where the sides alternately capture, and always
1510   // capture with the least valuable piece. After each capture, we look for
1511   // new X-ray attacks from behind the capturing piece.
1512   swapList[0] = PieceValueMidgame[capturedType];
1513   capturedType = piece_type(piece_on(from));
1514
1515   do {
1516       // Locate the least valuable attacker for the side to move. The loop
1517       // below looks like it is potentially infinite, but it isn't. We know
1518       // that the side to move still has at least one attacker left.
1519       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1520           assert(pt < KING);
1521
1522       // Remove the attacker we just found from the 'occupied' bitboard,
1523       // and scan for new X-ray attacks behind the attacker.
1524       b = stmAttackers & pieces(pt);
1525       occupied ^= (b & (~b + 1));
1526       attackers |=  (rook_attacks_bb(to, occupied)   & pieces(ROOK, QUEEN))
1527                   | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1528
1529       attackers &= occupied; // Cut out pieces we've already done
1530
1531       // Add the new entry to the swap list
1532       assert(slIndex < 32);
1533       swapList[slIndex] = -swapList[slIndex - 1] + PieceValueMidgame[capturedType];
1534       slIndex++;
1535
1536       // Remember the value of the capturing piece, and change the side to
1537       // move before beginning the next iteration.
1538       capturedType = pt;
1539       stm = opposite_color(stm);
1540       stmAttackers = attackers & pieces_of_color(stm);
1541
1542       // Stop before processing a king capture
1543       if (capturedType == KING && stmAttackers)
1544       {
1545           assert(slIndex < 32);
1546           swapList[slIndex++] = QueenValueMidgame*10;
1547           break;
1548       }
1549   } while (stmAttackers);
1550
1551   // Having built the swap list, we negamax through it to find the best
1552   // achievable score from the point of view of the side to move.
1553   while (--slIndex)
1554       swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1555
1556   return swapList[0];
1557 }
1558
1559
1560 /// Position::clear() erases the position object to a pristine state, with an
1561 /// empty board, white to move, and no castling rights.
1562
1563 void Position::clear() {
1564
1565   st = &startState;
1566   memset(st, 0, sizeof(StateInfo));
1567   st->epSquare = SQ_NONE;
1568   fullMoves = 1;
1569   nodes = 0;
1570
1571   memset(byColorBB,  0, sizeof(Bitboard) * 2);
1572   memset(byTypeBB,   0, sizeof(Bitboard) * 8);
1573   memset(pieceCount, 0, sizeof(int) * 2 * 8);
1574   memset(index,      0, sizeof(int) * 64);
1575
1576   for (int i = 0; i < 64; i++)
1577       board[i] = PIECE_NONE;
1578
1579   for (int i = 0; i < 8; i++)
1580       for (int j = 0; j < 16; j++)
1581           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1582
1583   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1584       castleRightsMask[sq] = ALL_CASTLES;
1585
1586   sideToMove = WHITE;
1587 }
1588
1589
1590 /// Position::put_piece() puts a piece on the given square of the board,
1591 /// updating the board array, pieces list, bitboards, and piece counts.
1592
1593 void Position::put_piece(Piece p, Square s) {
1594
1595   Color c = piece_color(p);
1596   PieceType pt = piece_type(p);
1597
1598   board[s] = p;
1599   index[s] = pieceCount[c][pt]++;
1600   pieceList[c][pt][index[s]] = s;
1601
1602   set_bit(&(byTypeBB[pt]), s);
1603   set_bit(&(byColorBB[c]), s);
1604   set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1605 }
1606
1607
1608 /// Position::compute_key() computes the hash key of the position. The hash
1609 /// key is usually updated incrementally as moves are made and unmade, the
1610 /// compute_key() function is only used when a new position is set up, and
1611 /// to verify the correctness of the hash key when running in debug mode.
1612
1613 Key Position::compute_key() const {
1614
1615   Key result = zobCastle[st->castleRights];
1616
1617   for (Square s = SQ_A1; s <= SQ_H8; s++)
1618       if (square_is_occupied(s))
1619           result ^= zobrist[piece_color(piece_on(s))][piece_type(piece_on(s))][s];
1620
1621   if (ep_square() != SQ_NONE)
1622       result ^= zobEp[ep_square()];
1623
1624   if (side_to_move() == BLACK)
1625       result ^= zobSideToMove;
1626
1627   return result;
1628 }
1629
1630
1631 /// Position::compute_pawn_key() computes the hash key of the position. The
1632 /// hash key is usually updated incrementally as moves are made and unmade,
1633 /// the compute_pawn_key() function is only used when a new position is set
1634 /// up, and to verify the correctness of the pawn hash key when running in
1635 /// debug mode.
1636
1637 Key Position::compute_pawn_key() const {
1638
1639   Bitboard b;
1640   Key result = 0;
1641
1642   for (Color c = WHITE; c <= BLACK; c++)
1643   {
1644       b = pieces(PAWN, c);
1645       while (b)
1646           result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1647   }
1648   return result;
1649 }
1650
1651
1652 /// Position::compute_material_key() computes the hash key of the position.
1653 /// The hash key is usually updated incrementally as moves are made and unmade,
1654 /// the compute_material_key() function is only used when a new position is set
1655 /// up, and to verify the correctness of the material hash key when running in
1656 /// debug mode.
1657
1658 Key Position::compute_material_key() const {
1659
1660   int count;
1661   Key result = 0;
1662
1663   for (Color c = WHITE; c <= BLACK; c++)
1664       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1665       {
1666           count = piece_count(c, pt);
1667           for (int i = 0; i < count; i++)
1668               result ^= zobrist[c][pt][i];
1669       }
1670   return result;
1671 }
1672
1673
1674 /// Position::compute_value() compute the incremental scores for the middle
1675 /// game and the endgame. These functions are used to initialize the incremental
1676 /// scores when a new position is set up, and to verify that the scores are correctly
1677 /// updated by do_move and undo_move when the program is running in debug mode.
1678 Score Position::compute_value() const {
1679
1680   Bitboard b;
1681   Score result = SCORE_ZERO;
1682
1683   for (Color c = WHITE; c <= BLACK; c++)
1684       for (PieceType pt = PAWN; pt <= KING; pt++)
1685       {
1686           b = pieces(pt, c);
1687           while (b)
1688               result += pst(c, pt, pop_1st_bit(&b));
1689       }
1690
1691   result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1692   return result;
1693 }
1694
1695
1696 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1697 /// game material value for the given side. Material values are updated
1698 /// incrementally during the search, this function is only used while
1699 /// initializing a new Position object.
1700
1701 Value Position::compute_non_pawn_material(Color c) const {
1702
1703   Value result = VALUE_ZERO;
1704
1705   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1706       result += piece_count(c, pt) * PieceValueMidgame[pt];
1707
1708   return result;
1709 }
1710
1711
1712 /// Position::is_draw() tests whether the position is drawn by material,
1713 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1714 /// must be done by the search.
1715 template<bool SkipRepetition>
1716 bool Position::is_draw() const {
1717
1718   // Draw by material?
1719   if (   !pieces(PAWN)
1720       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1721       return true;
1722
1723   // Draw by the 50 moves rule?
1724   if (st->rule50 > 99 && !is_mate())
1725       return true;
1726
1727   // Draw by repetition?
1728   if (!SkipRepetition)
1729       for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1730           if (history[st->gamePly - i] == st->key)
1731               return true;
1732
1733   return false;
1734 }
1735
1736 // Explicit template instantiations
1737 template bool Position::is_draw<false>() const;
1738 template bool Position::is_draw<true>() const;
1739
1740
1741 /// Position::is_mate() returns true or false depending on whether the
1742 /// side to move is checkmated.
1743
1744 bool Position::is_mate() const {
1745
1746   MoveStack moves[MAX_MOVES];
1747   return in_check() && generate<MV_LEGAL>(*this, moves) == moves;
1748 }
1749
1750
1751 /// Position::init() is a static member function which initializes at
1752 /// startup the various arrays used to compute hash keys and the piece
1753 /// square tables. The latter is a two-step operation: First, the white
1754 /// halves of the tables are copied from the MgPST[][] and EgPST[][] arrays.
1755 /// Second, the black halves of the tables are initialized by mirroring
1756 /// and changing the sign of the corresponding white scores.
1757
1758 void Position::init() {
1759
1760   RKISS rk;
1761
1762   for (Color c = WHITE; c <= BLACK; c++)
1763       for (PieceType pt = PAWN; pt <= KING; pt++)
1764           for (Square s = SQ_A1; s <= SQ_H8; s++)
1765               zobrist[c][pt][s] = rk.rand<Key>();
1766
1767   for (Square s = SQ_A1; s <= SQ_H8; s++)
1768       zobEp[s] = rk.rand<Key>();
1769
1770   for (int i = 0; i < 16; i++)
1771       zobCastle[i] = rk.rand<Key>();
1772
1773   zobSideToMove = rk.rand<Key>();
1774   zobExclusion  = rk.rand<Key>();
1775
1776   for (Square s = SQ_A1; s <= SQ_H8; s++)
1777       for (Piece p = WP; p <= WK; p++)
1778           PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1779
1780   for (Square s = SQ_A1; s <= SQ_H8; s++)
1781       for (Piece p = BP; p <= BK; p++)
1782           PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1783 }
1784
1785
1786 /// Position::flip() flips position with the white and black sides reversed. This
1787 /// is only useful for debugging especially for finding evaluation symmetry bugs.
1788
1789 void Position::flip() {
1790
1791   assert(is_ok());
1792
1793   // Make a copy of current position before to start changing
1794   const Position pos(*this, threadID);
1795
1796   clear();
1797   threadID = pos.thread();
1798
1799   // Board
1800   for (Square s = SQ_A1; s <= SQ_H8; s++)
1801       if (!pos.square_is_empty(s))
1802           put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1803
1804   // Side to move
1805   sideToMove = opposite_color(pos.side_to_move());
1806
1807   // Castling rights
1808   if (pos.can_castle(WHITE_OO))
1809       set_castle(BLACK_OO,  king_square(BLACK), flip_square(pos.castle_rook_square(WHITE_OO)));
1810   if (pos.can_castle(WHITE_OOO))
1811       set_castle(BLACK_OOO, king_square(BLACK), flip_square(pos.castle_rook_square(WHITE_OOO)));
1812   if (pos.can_castle(BLACK_OO))
1813       set_castle(WHITE_OO,  king_square(WHITE), flip_square(pos.castle_rook_square(BLACK_OO)));
1814   if (pos.can_castle(BLACK_OOO))
1815       set_castle(WHITE_OOO, king_square(WHITE), flip_square(pos.castle_rook_square(BLACK_OOO)));
1816
1817   // En passant square
1818   if (pos.st->epSquare != SQ_NONE)
1819       st->epSquare = flip_square(pos.st->epSquare);
1820
1821   // Checkers
1822   find_checkers();
1823
1824   // Hash keys
1825   st->key = compute_key();
1826   st->pawnKey = compute_pawn_key();
1827   st->materialKey = compute_material_key();
1828
1829   // Incremental scores
1830   st->value = compute_value();
1831
1832   // Material
1833   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1834   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1835
1836   assert(is_ok());
1837 }
1838
1839
1840 /// Position::is_ok() performs some consitency checks for the position object.
1841 /// This is meant to be helpful when debugging.
1842
1843 bool Position::is_ok(int* failedStep) const {
1844
1845   // What features of the position should be verified?
1846   const bool debugAll = false;
1847
1848   const bool debugBitboards       = debugAll || false;
1849   const bool debugKingCount       = debugAll || false;
1850   const bool debugKingCapture     = debugAll || false;
1851   const bool debugCheckerCount    = debugAll || false;
1852   const bool debugKey             = debugAll || false;
1853   const bool debugMaterialKey     = debugAll || false;
1854   const bool debugPawnKey         = debugAll || false;
1855   const bool debugIncrementalEval = debugAll || false;
1856   const bool debugNonPawnMaterial = debugAll || false;
1857   const bool debugPieceCounts     = debugAll || false;
1858   const bool debugPieceList       = debugAll || false;
1859   const bool debugCastleSquares   = debugAll || false;
1860
1861   if (failedStep) *failedStep = 1;
1862
1863   // Side to move OK?
1864   if (side_to_move() != WHITE && side_to_move() != BLACK)
1865       return false;
1866
1867   // Are the king squares in the position correct?
1868   if (failedStep) (*failedStep)++;
1869   if (piece_on(king_square(WHITE)) != WK)
1870       return false;
1871
1872   if (failedStep) (*failedStep)++;
1873   if (piece_on(king_square(BLACK)) != BK)
1874       return false;
1875
1876   // Do both sides have exactly one king?
1877   if (failedStep) (*failedStep)++;
1878   if (debugKingCount)
1879   {
1880       int kingCount[2] = {0, 0};
1881       for (Square s = SQ_A1; s <= SQ_H8; s++)
1882           if (piece_type(piece_on(s)) == KING)
1883               kingCount[piece_color(piece_on(s))]++;
1884
1885       if (kingCount[0] != 1 || kingCount[1] != 1)
1886           return false;
1887   }
1888
1889   // Can the side to move capture the opponent's king?
1890   if (failedStep) (*failedStep)++;
1891   if (debugKingCapture)
1892   {
1893       Color us = side_to_move();
1894       Color them = opposite_color(us);
1895       Square ksq = king_square(them);
1896       if (attackers_to(ksq) & pieces_of_color(us))
1897           return false;
1898   }
1899
1900   // Is there more than 2 checkers?
1901   if (failedStep) (*failedStep)++;
1902   if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1903       return false;
1904
1905   // Bitboards OK?
1906   if (failedStep) (*failedStep)++;
1907   if (debugBitboards)
1908   {
1909       // The intersection of the white and black pieces must be empty
1910       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1911           return false;
1912
1913       // The union of the white and black pieces must be equal to all
1914       // occupied squares
1915       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1916           return false;
1917
1918       // Separate piece type bitboards must have empty intersections
1919       for (PieceType p1 = PAWN; p1 <= KING; p1++)
1920           for (PieceType p2 = PAWN; p2 <= KING; p2++)
1921               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1922                   return false;
1923   }
1924
1925   // En passant square OK?
1926   if (failedStep) (*failedStep)++;
1927   if (ep_square() != SQ_NONE)
1928   {
1929       // The en passant square must be on rank 6, from the point of view of the
1930       // side to move.
1931       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1932           return false;
1933   }
1934
1935   // Hash key OK?
1936   if (failedStep) (*failedStep)++;
1937   if (debugKey && st->key != compute_key())
1938       return false;
1939
1940   // Pawn hash key OK?
1941   if (failedStep) (*failedStep)++;
1942   if (debugPawnKey && st->pawnKey != compute_pawn_key())
1943       return false;
1944
1945   // Material hash key OK?
1946   if (failedStep) (*failedStep)++;
1947   if (debugMaterialKey && st->materialKey != compute_material_key())
1948       return false;
1949
1950   // Incremental eval OK?
1951   if (failedStep) (*failedStep)++;
1952   if (debugIncrementalEval && st->value != compute_value())
1953       return false;
1954
1955   // Non-pawn material OK?
1956   if (failedStep) (*failedStep)++;
1957   if (debugNonPawnMaterial)
1958   {
1959       if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1960           return false;
1961
1962       if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1963           return false;
1964   }
1965
1966   // Piece counts OK?
1967   if (failedStep) (*failedStep)++;
1968   if (debugPieceCounts)
1969       for (Color c = WHITE; c <= BLACK; c++)
1970           for (PieceType pt = PAWN; pt <= KING; pt++)
1971               if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1972                   return false;
1973
1974   if (failedStep) (*failedStep)++;
1975   if (debugPieceList)
1976       for (Color c = WHITE; c <= BLACK; c++)
1977           for (PieceType pt = PAWN; pt <= KING; pt++)
1978               for (int i = 0; i < pieceCount[c][pt]; i++)
1979               {
1980                   if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
1981                       return false;
1982
1983                   if (index[piece_list(c, pt, i)] != i)
1984                       return false;
1985               }
1986
1987   if (failedStep) (*failedStep)++;
1988   if (debugCastleSquares)
1989       for (CastleRight f = WHITE_OO; f <= BLACK_OOO; f = CastleRight(f << 1))
1990       {
1991           if (!can_castle(f))
1992               continue;
1993
1994           Piece rook = (f & (WHITE_OO | WHITE_OOO) ? WR : BR);
1995
1996           if (   castleRightsMask[castleRookSquare[f]] != (ALL_CASTLES ^ f)
1997               || piece_on(castleRookSquare[f]) != rook)
1998               return false;
1999       }
2000
2001   if (failedStep) *failedStep = 0;
2002   return true;
2003 }