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