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