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