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