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