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