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