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