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