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