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