]> git.sesse.net Git - stockfish/blob - src/position.cpp
755e22d85a7c9317d2682f5838fda4b6bfd6a11c
[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-2014 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 <algorithm>
21 #include <cassert>
22 #include <cstring>
23 #include <iomanip>
24 #include <sstream>
25
26 #include "bitcount.h"
27 #include "movegen.h"
28 #include "notation.h"
29 #include "position.h"
30 #include "psqtab.h"
31 #include "rkiss.h"
32 #include "thread.h"
33 #include "tt.h"
34
35 using std::string;
36
37 static const string PieceToChar(" PNBRQK  pnbrqk");
38
39 CACHE_LINE_ALIGNMENT
40
41 Score psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
42 Value PieceValue[PHASE_NB][PIECE_NB] = {
43 { VALUE_ZERO, PawnValueMg, KnightValueMg, BishopValueMg, RookValueMg, QueenValueMg },
44 { VALUE_ZERO, PawnValueEg, KnightValueEg, BishopValueEg, RookValueEg, QueenValueEg } };
45
46 namespace Zobrist {
47
48   Key psq[COLOR_NB][PIECE_TYPE_NB][SQUARE_NB];
49   Key enpassant[FILE_NB];
50   Key castling[CASTLING_FLAG_NB];
51   Key side;
52   Key exclusion;
53 }
54
55 Key Position::exclusion_key() const { return st->key ^ Zobrist::exclusion;}
56
57 namespace {
58
59 // min_attacker() is a helper function used by see() to locate the least
60 // valuable attacker for the side to move, remove the attacker we just found
61 // from the bitboards and scan for new X-ray attacks behind it.
62
63 template<int Pt> FORCE_INLINE
64 PieceType min_attacker(const Bitboard* bb, const Square& to, const Bitboard& stmAttackers,
65                        Bitboard& occupied, Bitboard& attackers) {
66
67   Bitboard b = stmAttackers & bb[Pt];
68   if (!b)
69       return min_attacker<Pt+1>(bb, to, stmAttackers, occupied, attackers);
70
71   occupied ^= b & ~(b - 1);
72
73   if (Pt == PAWN || Pt == BISHOP || Pt == QUEEN)
74       attackers |= attacks_bb<BISHOP>(to, occupied) & (bb[BISHOP] | bb[QUEEN]);
75
76   if (Pt == ROOK || Pt == QUEEN)
77       attackers |= attacks_bb<ROOK>(to, occupied) & (bb[ROOK] | bb[QUEEN]);
78
79   attackers &= occupied; // After X-ray that may add already processed pieces
80   return (PieceType)Pt;
81 }
82
83 template<> FORCE_INLINE
84 PieceType min_attacker<KING>(const Bitboard*, const Square&, const Bitboard&, Bitboard&, Bitboard&) {
85   return KING; // No need to update bitboards: it is the last cycle
86 }
87
88 } // namespace
89
90
91 /// CheckInfo c'tor
92
93 CheckInfo::CheckInfo(const Position& pos) {
94
95   Color them = ~pos.side_to_move();
96   ksq = pos.king_square(them);
97
98   pinned = pos.pinned_pieces(pos.side_to_move());
99   dcCandidates = pos.discovered_check_candidates();
100
101   checkSq[PAWN]   = pos.attacks_from<PAWN>(ksq, them);
102   checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
103   checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
104   checkSq[ROOK]   = pos.attacks_from<ROOK>(ksq);
105   checkSq[QUEEN]  = checkSq[BISHOP] | checkSq[ROOK];
106   checkSq[KING]   = 0;
107 }
108
109
110 /// Position::init() initializes at startup the various arrays used to compute
111 /// hash keys and the piece square tables. The latter is a two-step operation:
112 /// Firstly, the white halves of the tables are copied from PSQT[] tables.
113 /// Secondly, the black halves of the tables are initialized by flipping and
114 /// changing the sign of the white scores.
115
116 void Position::init() {
117
118   RKISS rk;
119
120   for (Color c = WHITE; c <= BLACK; ++c)
121       for (PieceType pt = PAWN; pt <= KING; ++pt)
122           for (Square s = SQ_A1; s <= SQ_H8; ++s)
123               Zobrist::psq[c][pt][s] = rk.rand<Key>();
124
125   for (File f = FILE_A; f <= FILE_H; ++f)
126       Zobrist::enpassant[f] = rk.rand<Key>();
127
128   for (int cf = NO_CASTLING; cf <= ANY_CASTLING; ++cf)
129   {
130       Bitboard b = cf;
131       while (b)
132       {
133           Key k = Zobrist::castling[1ULL << pop_lsb(&b)];
134           Zobrist::castling[cf] ^= k ? k : rk.rand<Key>();
135       }
136   }
137
138   Zobrist::side = rk.rand<Key>();
139   Zobrist::exclusion  = rk.rand<Key>();
140
141   for (PieceType pt = PAWN; pt <= KING; ++pt)
142   {
143       PieceValue[MG][make_piece(BLACK, pt)] = PieceValue[MG][pt];
144       PieceValue[EG][make_piece(BLACK, pt)] = PieceValue[EG][pt];
145
146       Score v = make_score(PieceValue[MG][pt], PieceValue[EG][pt]);
147
148       for (Square s = SQ_A1; s <= SQ_H8; ++s)
149       {
150          psq[WHITE][pt][ s] =  (v + PSQT[pt][s]);
151          psq[BLACK][pt][~s] = -(v + PSQT[pt][s]);
152       }
153   }
154 }
155
156
157 /// Position::operator=() creates a copy of 'pos'. We want the new born Position
158 /// object to not depend on any external data so we detach state pointer from
159 /// the source one.
160
161 Position& Position::operator=(const Position& pos) {
162
163   std::memcpy(this, &pos, sizeof(Position));
164   startState = *st;
165   st = &startState;
166   nodes = 0;
167
168   assert(pos_is_ok());
169
170   return *this;
171 }
172
173
174 /// Position::set() initializes the position object with the given FEN string.
175 /// This function is not very robust - make sure that input FENs are correct,
176 /// this is assumed to be the responsibility of the GUI.
177
178 void Position::set(const string& fenStr, bool isChess960, Thread* th) {
179 /*
180    A FEN string defines a particular position using only the ASCII character set.
181
182    A FEN string contains six fields separated by a space. The fields are:
183
184    1) Piece placement (from white's perspective). Each rank is described, starting
185       with rank 8 and ending with rank 1. Within each rank, the contents of each
186       square are described from file A through file H. Following the Standard
187       Algebraic Notation (SAN), each piece is identified by a single letter taken
188       from the standard English names. White pieces are designated using upper-case
189       letters ("PNBRQK") whilst Black uses lowercase ("pnbrqk"). Blank squares are
190       noted using digits 1 through 8 (the number of blank squares), and "/"
191       separates ranks.
192
193    2) Active color. "w" means white moves next, "b" means black.
194
195    3) Castling availability. If neither side can castle, this is "-". Otherwise,
196       this has one or more letters: "K" (White can castle kingside), "Q" (White
197       can castle queenside), "k" (Black can castle kingside), and/or "q" (Black
198       can castle queenside).
199
200    4) En passant target square (in algebraic notation). If there's no en passant
201       target square, this is "-". If a pawn has just made a 2-square move, this
202       is the position "behind" the pawn. This is recorded regardless of whether
203       there is a pawn in position to make an en passant capture.
204
205    5) Halfmove clock. This is the number of halfmoves since the last pawn advance
206       or capture. This is used to determine if a draw can be claimed under the
207       fifty-move rule.
208
209    6) Fullmove number. The number of the full move. It starts at 1, and is
210       incremented after Black's move.
211 */
212
213   char col, row, token;
214   size_t idx;
215   Square sq = SQ_A8;
216   std::istringstream ss(fenStr);
217
218   clear();
219   ss >> std::noskipws;
220
221   // 1. Piece placement
222   while ((ss >> token) && !isspace(token))
223   {
224       if (isdigit(token))
225           sq += Square(token - '0'); // Advance the given number of files
226
227       else if (token == '/')
228           sq -= Square(16);
229
230       else if ((idx = PieceToChar.find(token)) != string::npos)
231       {
232           put_piece(sq, color_of(Piece(idx)), type_of(Piece(idx)));
233           ++sq;
234       }
235   }
236
237   // 2. Active color
238   ss >> token;
239   sideToMove = (token == 'w' ? WHITE : BLACK);
240   ss >> token;
241
242   // 3. Castling availability. Compatible with 3 standards: Normal FEN standard,
243   // Shredder-FEN that uses the letters of the columns on which the rooks began
244   // the game instead of KQkq and also X-FEN standard that, in case of Chess960,
245   // if an inner rook is associated with the castling right, the castling tag is
246   // replaced by the file letter of the involved rook, as for the Shredder-FEN.
247   while ((ss >> token) && !isspace(token))
248   {
249       Square rsq;
250       Color c = islower(token) ? BLACK : WHITE;
251
252       token = char(toupper(token));
253
254       if (token == 'K')
255           for (rsq = relative_square(c, SQ_H1); type_of(piece_on(rsq)) != ROOK; --rsq) {}
256
257       else if (token == 'Q')
258           for (rsq = relative_square(c, SQ_A1); type_of(piece_on(rsq)) != ROOK; ++rsq) {}
259
260       else if (token >= 'A' && token <= 'H')
261           rsq = File(token - 'A') | relative_rank(c, RANK_1);
262
263       else
264           continue;
265
266       set_castling_flag(c, rsq);
267   }
268
269   // 4. En passant square. Ignore if no pawn capture is possible
270   if (   ((ss >> col) && (col >= 'a' && col <= 'h'))
271       && ((ss >> row) && (row == '3' || row == '6')))
272   {
273       st->epSquare = File(col - 'a') | Rank(row - '1');
274
275       if (!(attackers_to(st->epSquare) & pieces(sideToMove, PAWN)))
276           st->epSquare = SQ_NONE;
277   }
278
279   // 5-6. Halfmove clock and fullmove number
280   ss >> std::skipws >> st->rule50 >> gamePly;
281
282   // Convert from fullmove starting from 1 to ply starting from 0,
283   // handle also common incorrect FEN with fullmove = 0.
284   gamePly = std::max(2 * (gamePly - 1), 0) + int(sideToMove == BLACK);
285
286   st->key = compute_key();
287   st->pawnKey = compute_pawn_key();
288   st->materialKey = compute_material_key();
289   st->psq = compute_psq_score();
290   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
291   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
292   st->checkersBB = attackers_to(king_square(sideToMove)) & pieces(~sideToMove);
293   chess960 = isChess960;
294   thisThread = th;
295
296   assert(pos_is_ok());
297 }
298
299
300 /// Position::set_castling_flag() is a helper function used to set castling
301 /// flags given the corresponding color and the rook starting square.
302
303 void Position::set_castling_flag(Color c, Square rfrom) {
304
305   Square kfrom = king_square(c);
306   CastlingSide cs = kfrom < rfrom ? KING_SIDE : QUEEN_SIDE;
307   CastlingFlag cf = make_castling_flag(c, cs);
308
309   st->castlingFlags |= cf;
310   castlingFlagsMask[kfrom] |= cf;
311   castlingFlagsMask[rfrom] |= cf;
312   castlingRookSquare[c][cs] = rfrom;
313
314   Square kto = relative_square(c, cs == KING_SIDE ? SQ_G1 : SQ_C1);
315   Square rto = relative_square(c, cs == KING_SIDE ? SQ_F1 : SQ_D1);
316
317   for (Square s = std::min(rfrom, rto); s <= std::max(rfrom, rto); ++s)
318       if (s != kfrom && s != rfrom)
319           castlingPath[c][cs] |= s;
320
321   for (Square s = std::min(kfrom, kto); s <= std::max(kfrom, kto); ++s)
322       if (s != kfrom && s != rfrom)
323           castlingPath[c][cs] |= s;
324 }
325
326
327 /// Position::fen() returns a FEN representation of the position. In case of
328 /// Chess960 the Shredder-FEN notation is used. This is mainly a debugging function.
329
330 const string Position::fen() const {
331
332   int emptyCnt;
333   std::ostringstream ss;
334
335   for (Rank rank = RANK_8; rank >= RANK_1; --rank)
336   {
337       for (File file = FILE_A; file <= FILE_H; ++file)
338       {
339           for (emptyCnt = 0; file <= FILE_H && empty(file | rank); ++file)
340               ++emptyCnt;
341
342           if (emptyCnt)
343               ss << emptyCnt;
344
345           if (file <= FILE_H)
346               ss << PieceToChar[piece_on(file | rank)];
347       }
348
349       if (rank > RANK_1)
350           ss << '/';
351   }
352
353   ss << (sideToMove == WHITE ? " w " : " b ");
354
355   if (can_castle(WHITE_OO))
356       ss << (chess960 ? file_to_char(file_of(castling_rook_square(WHITE,  KING_SIDE)), false) : 'K');
357
358   if (can_castle(WHITE_OOO))
359       ss << (chess960 ? file_to_char(file_of(castling_rook_square(WHITE, QUEEN_SIDE)), false) : 'Q');
360
361   if (can_castle(BLACK_OO))
362       ss << (chess960 ? file_to_char(file_of(castling_rook_square(BLACK,  KING_SIDE)),  true) : 'k');
363
364   if (can_castle(BLACK_OOO))
365       ss << (chess960 ? file_to_char(file_of(castling_rook_square(BLACK, QUEEN_SIDE)),  true) : 'q');
366
367   if (!can_castle(WHITE) && !can_castle(BLACK))
368       ss << '-';
369
370   ss << (ep_square() == SQ_NONE ? " - " : " " + square_to_string(ep_square()) + " ")
371      << st->rule50 << " " << 1 + (gamePly - int(sideToMove == BLACK)) / 2;
372
373   return ss.str();
374 }
375
376
377 /// Position::pretty() returns an ASCII representation of the position to be
378 /// printed to the standard output together with the move's san notation.
379
380 const string Position::pretty(Move move) const {
381
382   const string dottedLine =            "\n+---+---+---+---+---+---+---+---+";
383   const string twoRows =  dottedLine + "\n|   | . |   | . |   | . |   | . |"
384                         + dottedLine + "\n| . |   | . |   | . |   | . |   |";
385
386   string brd = twoRows + twoRows + twoRows + twoRows + dottedLine;
387
388   for (Bitboard b = pieces(); b; )
389   {
390       Square s = pop_lsb(&b);
391       brd[513 - 68 * rank_of(s) + 4 * file_of(s)] = PieceToChar[piece_on(s)];
392   }
393
394   std::ostringstream ss;
395
396   if (move)
397       ss << "\nMove: " << (sideToMove == BLACK ? ".." : "")
398          << move_to_san(*const_cast<Position*>(this), move);
399
400   ss << brd << "\nFen: " << fen() << "\nKey: " << std::hex << std::uppercase
401      << std::setfill('0') << std::setw(16) << st->key << "\nCheckers: ";
402
403   for (Bitboard b = checkers(); b; )
404       ss << square_to_string(pop_lsb(&b)) << " ";
405
406   ss << "\nLegal moves: ";
407   for (MoveList<LEGAL> it(*this); *it; ++it)
408       ss << move_to_san(*const_cast<Position*>(this), *it) << " ";
409
410   return ss.str();
411 }
412
413
414 /// Position:hidden_checkers() returns a bitboard of all pinned / discovered check
415 /// pieces, according to the call parameters. Pinned pieces protect our king and
416 /// discovered check pieces attack the enemy king.
417
418 Bitboard Position::hidden_checkers(Color c, Color kingColor) const {
419
420   Bitboard b, pinners, result = 0;
421   Square ksq = king_square(kingColor);
422
423   // Pinners are sliders that give check when a pinned piece is removed
424   pinners = (  (pieces(  ROOK, QUEEN) & PseudoAttacks[ROOK  ][ksq])
425              | (pieces(BISHOP, QUEEN) & PseudoAttacks[BISHOP][ksq])) & pieces(~kingColor);
426
427   while (pinners)
428   {
429       b = between_bb(ksq, pop_lsb(&pinners)) & pieces();
430
431       if (!more_than_one(b))
432           result |= b & pieces(c);
433   }
434   return result;
435 }
436
437
438 /// Position::attackers_to() computes a bitboard of all pieces which attack a
439 /// given square. Slider attacks use the occ bitboard to indicate occupancy.
440
441 Bitboard Position::attackers_to(Square s, Bitboard occ) const {
442
443   return  (attacks_from<PAWN>(s, BLACK) & pieces(WHITE, PAWN))
444         | (attacks_from<PAWN>(s, WHITE) & pieces(BLACK, PAWN))
445         | (attacks_from<KNIGHT>(s)      & pieces(KNIGHT))
446         | (attacks_bb<ROOK>(s, occ)     & pieces(ROOK, QUEEN))
447         | (attacks_bb<BISHOP>(s, occ)   & pieces(BISHOP, QUEEN))
448         | (attacks_from<KING>(s)        & pieces(KING));
449 }
450
451
452 /// Position::legal() tests whether a pseudo-legal move is legal
453
454 bool Position::legal(Move m, Bitboard pinned) const {
455
456   assert(is_ok(m));
457   assert(pinned == pinned_pieces(sideToMove));
458
459   Color us = sideToMove;
460   Square from = from_sq(m);
461
462   assert(color_of(moved_piece(m)) == us);
463   assert(piece_on(king_square(us)) == make_piece(us, KING));
464
465   // En passant captures are a tricky special case. Because they are rather
466   // uncommon, we do it simply by testing whether the king is attacked after
467   // the move is made.
468   if (type_of(m) == ENPASSANT)
469   {
470       Color them = ~us;
471       Square to = to_sq(m);
472       Square capsq = to + pawn_push(them);
473       Square ksq = king_square(us);
474       Bitboard b = (pieces() ^ from ^ capsq) | to;
475
476       assert(to == ep_square());
477       assert(moved_piece(m) == make_piece(us, PAWN));
478       assert(piece_on(capsq) == make_piece(them, PAWN));
479       assert(piece_on(to) == NO_PIECE);
480
481       return   !(attacks_bb<  ROOK>(ksq, b) & pieces(them, QUEEN, ROOK))
482             && !(attacks_bb<BISHOP>(ksq, b) & pieces(them, QUEEN, BISHOP));
483   }
484
485   // If the moving piece is a king, check whether the destination
486   // square is attacked by the opponent. Castling moves are checked
487   // for legality during move generation.
488   if (type_of(piece_on(from)) == KING)
489       return type_of(m) == CASTLING || !(attackers_to(to_sq(m)) & pieces(~us));
490
491   // A non-king move is legal if and only if it is not pinned or it
492   // is moving along the ray towards or away from the king.
493   return   !pinned
494         || !(pinned & from)
495         ||  aligned(from, to_sq(m), king_square(us));
496 }
497
498
499 /// Position::pseudo_legal() takes a random move and tests whether the move is
500 /// pseudo legal. It is used to validate moves from TT that can be corrupted
501 /// due to SMP concurrent access or hash position key aliasing.
502
503 bool Position::pseudo_legal(const Move m) const {
504
505   Color us = sideToMove;
506   Square from = from_sq(m);
507   Square to = to_sq(m);
508   Piece pc = moved_piece(m);
509
510   // Use a slower but simpler function for uncommon cases
511   if (type_of(m) != NORMAL)
512       return MoveList<LEGAL>(*this).contains(m);
513
514   // Is not a promotion, so promotion piece must be empty
515   if (promotion_type(m) - 2 != NO_PIECE_TYPE)
516       return false;
517
518   // If the 'from' square is not occupied by a piece belonging to the side to
519   // move, the move is obviously not legal.
520   if (pc == NO_PIECE || color_of(pc) != us)
521       return false;
522
523   // The destination square cannot be occupied by a friendly piece
524   if (pieces(us) & to)
525       return false;
526
527   // Handle the special case of a pawn move
528   if (type_of(pc) == PAWN)
529   {
530       // Move direction must be compatible with pawn color
531       int direction = to - from;
532       if ((us == WHITE) != (direction > 0))
533           return false;
534
535       // We have already handled promotion moves, so destination
536       // cannot be on the 8th/1st rank.
537       if (rank_of(to) == RANK_8 || rank_of(to) == RANK_1)
538           return false;
539
540       // Proceed according to the square delta between the origin and
541       // destination squares.
542       switch (direction)
543       {
544       case DELTA_NW:
545       case DELTA_NE:
546       case DELTA_SW:
547       case DELTA_SE:
548       // Capture. The destination square must be occupied by an enemy
549       // piece (en passant captures was handled earlier).
550       if (piece_on(to) == NO_PIECE || color_of(piece_on(to)) != ~us)
551           return false;
552
553       // From and to files must be one file apart, avoids a7h5
554       if (abs(file_of(from) - file_of(to)) != 1)
555           return false;
556       break;
557
558       case DELTA_N:
559       case DELTA_S:
560       // Pawn push. The destination square must be empty.
561       if (!empty(to))
562           return false;
563       break;
564
565       case DELTA_NN:
566       // Double white pawn push. The destination square must be on the fourth
567       // rank, and both the destination square and the square between the
568       // source and destination squares must be empty.
569       if (    rank_of(to) != RANK_4
570           || !empty(to)
571           || !empty(from + DELTA_N))
572           return false;
573       break;
574
575       case DELTA_SS:
576       // Double black pawn push. The destination square must be on the fifth
577       // rank, and both the destination square and the square between the
578       // source and destination squares must be empty.
579       if (    rank_of(to) != RANK_5
580           || !empty(to)
581           || !empty(from + DELTA_S))
582           return false;
583       break;
584
585       default:
586           return false;
587       }
588   }
589   else if (!(attacks_from(pc, from) & to))
590       return false;
591
592   // Evasions generator already takes care to avoid some kind of illegal moves
593   // and pl_move_is_legal() relies on this. We therefore have to take care that
594   // the same kind of moves are filtered out here.
595   if (checkers())
596   {
597       if (type_of(pc) != KING)
598       {
599           // Double check? In this case a king move is required
600           if (more_than_one(checkers()))
601               return false;
602
603           // Our move must be a blocking evasion or a capture of the checking piece
604           if (!((between_bb(lsb(checkers()), king_square(us)) | checkers()) & to))
605               return false;
606       }
607       // In case of king moves under check we have to remove king so as to catch
608       // invalid moves like b1a1 when opposite queen is on c1.
609       else if (attackers_to(to, pieces() ^ from) & pieces(~us))
610           return false;
611   }
612
613   return true;
614 }
615
616
617 /// Position::gives_check() tests whether a pseudo-legal move gives a check
618
619 bool Position::gives_check(Move m, const CheckInfo& ci) const {
620
621   assert(is_ok(m));
622   assert(ci.dcCandidates == discovered_check_candidates());
623   assert(color_of(moved_piece(m)) == sideToMove);
624
625   Square from = from_sq(m);
626   Square to = to_sq(m);
627   PieceType pt = type_of(piece_on(from));
628
629   // Is there a direct check?
630   if (ci.checkSq[pt] & to)
631       return true;
632
633   // Is there a discovered check?
634   if (   unlikely(ci.dcCandidates)
635       && (ci.dcCandidates & from)
636       && !aligned(from, to, king_square(~sideToMove)))
637       return true;
638
639   // Can we skip the ugly special cases?
640   if (type_of(m) == NORMAL)
641       return false;
642
643   Color us = sideToMove;
644   Square ksq = king_square(~us);
645
646   switch (type_of(m))
647   {
648   case PROMOTION:
649       return attacks_bb(Piece(promotion_type(m)), to, pieces() ^ from) & ksq;
650
651   // En passant capture with check? We have already handled the case
652   // of direct checks and ordinary discovered check, so the only case we
653   // need to handle is the unusual case of a discovered check through
654   // the captured pawn.
655   case ENPASSANT:
656   {
657       Square capsq = file_of(to) | rank_of(from);
658       Bitboard b = (pieces() ^ from ^ capsq) | to;
659
660       return  (attacks_bb<  ROOK>(ksq, b) & pieces(us, QUEEN, ROOK))
661             | (attacks_bb<BISHOP>(ksq, b) & pieces(us, QUEEN, BISHOP));
662   }
663   case CASTLING:
664   {
665       Square kfrom = from;
666       Square rfrom = to; // Castling is encoded as 'King captures the rook'
667       Square kto = relative_square(us, rfrom > kfrom ? SQ_G1 : SQ_C1);
668       Square rto = relative_square(us, rfrom > kfrom ? SQ_F1 : SQ_D1);
669
670       return   (PseudoAttacks[ROOK][rto] & ksq)
671             && (attacks_bb<ROOK>(rto, (pieces() ^ kfrom ^ rfrom) | rto | kto) & ksq);
672   }
673   default:
674       assert(false);
675       return false;
676   }
677 }
678
679
680 /// Position::do_move() makes a move, and saves all information necessary
681 /// to a StateInfo object. The move is assumed to be legal. Pseudo-legal
682 /// moves should be filtered out before this function is called.
683
684 void Position::do_move(Move m, StateInfo& newSt) {
685
686   CheckInfo ci(*this);
687   do_move(m, newSt, ci, gives_check(m, ci));
688 }
689
690 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
691
692   assert(is_ok(m));
693   assert(&newSt != st);
694
695   ++nodes;
696   Key k = st->key;
697
698   // Copy some fields of the old state to our new StateInfo object except the
699   // ones which are going to be recalculated from scratch anyway and then switch
700   // our state pointer to point to the new (ready to be updated) state.
701   std::memcpy(&newSt, st, StateCopySize64 * sizeof(uint64_t));
702
703   newSt.previous = st;
704   st = &newSt;
705
706   // Update side to move
707   k ^= Zobrist::side;
708
709   // Increment ply counters. In particular, rule50 will be reset to zero later on
710   // in case of a capture or a pawn move.
711   ++gamePly;
712   ++st->rule50;
713   ++st->pliesFromNull;
714
715   Color us = sideToMove;
716   Color them = ~us;
717   Square from = from_sq(m);
718   Square to = to_sq(m);
719   Piece pc = piece_on(from);
720   PieceType pt = type_of(pc);
721   PieceType captured = type_of(m) == ENPASSANT ? PAWN : type_of(piece_on(to));
722
723   assert(color_of(pc) == us);
724   assert(piece_on(to) == NO_PIECE || color_of(piece_on(to)) == them || type_of(m) == CASTLING);
725   assert(captured != KING);
726
727   if (type_of(m) == CASTLING)
728   {
729       assert(pc == make_piece(us, KING));
730
731       bool kingSide = to > from;
732       Square rfrom = to; // Castling is encoded as "king captures friendly rook"
733       Square rto = relative_square(us, kingSide ? SQ_F1 : SQ_D1);
734       to = relative_square(us, kingSide ? SQ_G1 : SQ_C1);
735       captured = NO_PIECE_TYPE;
736
737       do_castling(from, to, rfrom, rto);
738
739       st->psq += psq[us][ROOK][rto] - psq[us][ROOK][rfrom];
740       k ^= Zobrist::psq[us][ROOK][rfrom] ^ Zobrist::psq[us][ROOK][rto];
741   }
742
743   if (captured)
744   {
745       Square capsq = to;
746
747       // If the captured piece is a pawn, update pawn hash key, otherwise
748       // update non-pawn material.
749       if (captured == PAWN)
750       {
751           if (type_of(m) == ENPASSANT)
752           {
753               capsq += pawn_push(them);
754
755               assert(pt == PAWN);
756               assert(to == st->epSquare);
757               assert(relative_rank(us, to) == RANK_6);
758               assert(piece_on(to) == NO_PIECE);
759               assert(piece_on(capsq) == make_piece(them, PAWN));
760
761               board[capsq] = NO_PIECE;
762           }
763
764           st->pawnKey ^= Zobrist::psq[them][PAWN][capsq];
765       }
766       else
767           st->npMaterial[them] -= PieceValue[MG][captured];
768
769       // Update board and piece lists
770       remove_piece(capsq, them, captured);
771
772       // Update material hash key and prefetch access to materialTable
773       k ^= Zobrist::psq[them][captured][capsq];
774       st->materialKey ^= Zobrist::psq[them][captured][pieceCount[them][captured]];
775       prefetch((char*)thisThread->materialTable[st->materialKey]);
776
777       // Update incremental scores
778       st->psq -= psq[them][captured][capsq];
779
780       // Reset rule 50 counter
781       st->rule50 = 0;
782   }
783
784   // Update hash key
785   k ^= Zobrist::psq[us][pt][from] ^ Zobrist::psq[us][pt][to];
786
787   // Reset en passant square
788   if (st->epSquare != SQ_NONE)
789   {
790       k ^= Zobrist::enpassant[file_of(st->epSquare)];
791       st->epSquare = SQ_NONE;
792   }
793
794   // Update castling flags if needed
795   if (st->castlingFlags && (castlingFlagsMask[from] | castlingFlagsMask[to]))
796   {
797       int cf = castlingFlagsMask[from] | castlingFlagsMask[to];
798       k ^= Zobrist::castling[st->castlingFlags & cf];
799       st->castlingFlags &= ~cf;
800   }
801
802   // Prefetch TT access as soon as we know the new hash key
803   prefetch((char*)TT.first_entry(k));
804
805   // Move the piece. The tricky Chess960 castling is handled earlier
806   if (type_of(m) != CASTLING)
807       move_piece(from, to, us, pt);
808
809   // If the moving piece is a pawn do some special extra work
810   if (pt == PAWN)
811   {
812       // Set en-passant square if the moved pawn can be captured
813       if (   (int(to) ^ int(from)) == 16
814           && (attacks_from<PAWN>(from + pawn_push(us), us) & pieces(them, PAWN)))
815       {
816           st->epSquare = Square((from + to) / 2);
817           k ^= Zobrist::enpassant[file_of(st->epSquare)];
818       }
819
820       if (type_of(m) == PROMOTION)
821       {
822           PieceType promotion = promotion_type(m);
823
824           assert(relative_rank(us, to) == RANK_8);
825           assert(promotion >= KNIGHT && promotion <= QUEEN);
826
827           remove_piece(to, us, PAWN);
828           put_piece(to, us, promotion);
829
830           // Update hash keys
831           k ^= Zobrist::psq[us][PAWN][to] ^ Zobrist::psq[us][promotion][to];
832           st->pawnKey ^= Zobrist::psq[us][PAWN][to];
833           st->materialKey ^=  Zobrist::psq[us][promotion][pieceCount[us][promotion]-1]
834                             ^ Zobrist::psq[us][PAWN][pieceCount[us][PAWN]];
835
836           // Update incremental score
837           st->psq += psq[us][promotion][to] - psq[us][PAWN][to];
838
839           // Update material
840           st->npMaterial[us] += PieceValue[MG][promotion];
841       }
842
843       // Update pawn hash key and prefetch access to pawnsTable
844       st->pawnKey ^= Zobrist::psq[us][PAWN][from] ^ Zobrist::psq[us][PAWN][to];
845       prefetch((char*)thisThread->pawnsTable[st->pawnKey]);
846
847       // Reset rule 50 draw counter
848       st->rule50 = 0;
849   }
850
851   // Update incremental scores
852   st->psq += psq[us][pt][to] - psq[us][pt][from];
853
854   // Set capture piece
855   st->capturedType = captured;
856
857   // Update the key with the final value
858   st->key = k;
859
860   // Update checkers bitboard: piece must be already moved
861   st->checkersBB = 0;
862
863   if (moveIsCheck)
864   {
865       if (type_of(m) != NORMAL)
866           st->checkersBB = attackers_to(king_square(them)) & pieces(us);
867       else
868       {
869           // Direct checks
870           if (ci.checkSq[pt] & to)
871               st->checkersBB |= to;
872
873           // Discovered checks
874           if (ci.dcCandidates && (ci.dcCandidates & from))
875           {
876               if (pt != ROOK)
877                   st->checkersBB |= attacks_from<ROOK>(king_square(them)) & pieces(us, QUEEN, ROOK);
878
879               if (pt != BISHOP)
880                   st->checkersBB |= attacks_from<BISHOP>(king_square(them)) & pieces(us, QUEEN, BISHOP);
881           }
882       }
883   }
884
885   sideToMove = ~sideToMove;
886
887   assert(pos_is_ok());
888 }
889
890
891 /// Position::undo_move() unmakes a move. When it returns, the position should
892 /// be restored to exactly the same state as before the move was made.
893
894 void Position::undo_move(Move m) {
895
896   assert(is_ok(m));
897
898   sideToMove = ~sideToMove;
899
900   Color us = sideToMove;
901   Color them = ~us;
902   Square from = from_sq(m);
903   Square to = to_sq(m);
904   PieceType pt = type_of(piece_on(to));
905   PieceType captured = st->capturedType;
906
907   assert(empty(from) || type_of(m) == CASTLING);
908   assert(captured != KING);
909
910   if (type_of(m) == PROMOTION)
911   {
912       PieceType promotion = promotion_type(m);
913
914       assert(promotion == pt);
915       assert(relative_rank(us, to) == RANK_8);
916       assert(promotion >= KNIGHT && promotion <= QUEEN);
917
918       remove_piece(to, us, promotion);
919       put_piece(to, us, PAWN);
920       pt = PAWN;
921   }
922
923   if (type_of(m) == CASTLING)
924   {
925       bool kingSide = to > from;
926       Square rfrom = to; // Castling is encoded as "king captures friendly rook"
927       Square rto = relative_square(us, kingSide ? SQ_F1 : SQ_D1);
928       to = relative_square(us, kingSide ? SQ_G1 : SQ_C1);
929       captured = NO_PIECE_TYPE;
930       pt = KING;
931       do_castling(to, from, rto, rfrom);
932   }
933   else
934       move_piece(to, from, us, pt); // Put the piece back at the source square
935
936   if (captured)
937   {
938       Square capsq = to;
939
940       if (type_of(m) == ENPASSANT)
941       {
942           capsq -= pawn_push(us);
943
944           assert(pt == PAWN);
945           assert(to == st->previous->epSquare);
946           assert(relative_rank(us, to) == RANK_6);
947           assert(piece_on(capsq) == NO_PIECE);
948       }
949
950       put_piece(capsq, them, captured); // Restore the captured piece
951   }
952
953   // Finally point our state pointer back to the previous state
954   st = st->previous;
955   --gamePly;
956
957   assert(pos_is_ok());
958 }
959
960
961 /// Position::do_castling() is a helper used to do/undo a castling move. This
962 /// is a bit tricky, especially in Chess960.
963
964 void Position::do_castling(Square kfrom, Square kto, Square rfrom, Square rto) {
965
966   // Remove both pieces first since squares could overlap in Chess960
967   remove_piece(kfrom, sideToMove, KING);
968   remove_piece(rfrom, sideToMove, ROOK);
969   board[kfrom] = board[rfrom] = NO_PIECE; // Since remove_piece doesn't do it for us
970   put_piece(kto, sideToMove, KING);
971   put_piece(rto, sideToMove, ROOK);
972 }
973
974
975 /// Position::do(undo)_null_move() is used to do(undo) a "null move": It flips
976 /// the side to move without executing any move on the board.
977
978 void Position::do_null_move(StateInfo& newSt) {
979
980   assert(!checkers());
981
982   std::memcpy(&newSt, st, sizeof(StateInfo)); // Fully copy here
983
984   newSt.previous = st;
985   st = &newSt;
986
987   if (st->epSquare != SQ_NONE)
988   {
989       st->key ^= Zobrist::enpassant[file_of(st->epSquare)];
990       st->epSquare = SQ_NONE;
991   }
992
993   st->key ^= Zobrist::side;
994   prefetch((char*)TT.first_entry(st->key));
995
996   ++st->rule50;
997   st->pliesFromNull = 0;
998
999   sideToMove = ~sideToMove;
1000
1001   assert(pos_is_ok());
1002 }
1003
1004 void Position::undo_null_move() {
1005
1006   assert(!checkers());
1007
1008   st = st->previous;
1009   sideToMove = ~sideToMove;
1010 }
1011
1012
1013 /// Position::see() is a static exchange evaluator: It tries to estimate the
1014 /// material gain or loss resulting from a move.
1015
1016 int Position::see_sign(Move m) const {
1017
1018   assert(is_ok(m));
1019
1020   // Early return if SEE cannot be negative because captured piece value
1021   // is not less then capturing one. Note that king moves always return
1022   // here because king midgame value is set to 0.
1023   if (PieceValue[MG][moved_piece(m)] <= PieceValue[MG][piece_on(to_sq(m))])
1024       return 1;
1025
1026   return see(m);
1027 }
1028
1029 int Position::see(Move m) const {
1030
1031   Square from, to;
1032   Bitboard occupied, attackers, stmAttackers;
1033   int swapList[32], slIndex = 1;
1034   PieceType captured;
1035   Color stm;
1036
1037   assert(is_ok(m));
1038
1039   from = from_sq(m);
1040   to = to_sq(m);
1041   swapList[0] = PieceValue[MG][piece_on(to)];
1042   stm = color_of(piece_on(from));
1043   occupied = pieces() ^ from;
1044
1045   // Castling moves are implemented as king capturing the rook so cannot be
1046   // handled correctly. Simply return 0 that is always the correct value
1047   // unless in the rare case the rook ends up under attack.
1048   if (type_of(m) == CASTLING)
1049       return 0;
1050
1051   if (type_of(m) == ENPASSANT)
1052   {
1053       occupied ^= to - pawn_push(stm); // Remove the captured pawn
1054       swapList[0] = PieceValue[MG][PAWN];
1055   }
1056
1057   // Find all attackers to the destination square, with the moving piece
1058   // removed, but possibly an X-ray attacker added behind it.
1059   attackers = attackers_to(to, occupied) & occupied;
1060
1061   // If the opponent has no attackers we are finished
1062   stm = ~stm;
1063   stmAttackers = attackers & pieces(stm);
1064   if (!stmAttackers)
1065       return swapList[0];
1066
1067   // The destination square is defended, which makes things rather more
1068   // difficult to compute. We proceed by building up a "swap list" containing
1069   // the material gain or loss at each stop in a sequence of captures to the
1070   // destination square, where the sides alternately capture, and always
1071   // capture with the least valuable piece. After each capture, we look for
1072   // new X-ray attacks from behind the capturing piece.
1073   captured = type_of(piece_on(from));
1074
1075   do {
1076       assert(slIndex < 32);
1077
1078       // Add the new entry to the swap list
1079       swapList[slIndex] = -swapList[slIndex - 1] + PieceValue[MG][captured];
1080       ++slIndex;
1081
1082       // Locate and remove the next least valuable attacker
1083       captured = min_attacker<PAWN>(byTypeBB, to, stmAttackers, occupied, attackers);
1084       stm = ~stm;
1085       stmAttackers = attackers & pieces(stm);
1086
1087       // Stop before processing a king capture
1088       if (captured == KING && stmAttackers)
1089       {
1090           swapList[slIndex++] = QueenValueMg * 16;
1091           break;
1092       }
1093
1094   } while (stmAttackers);
1095
1096   // Having built the swap list, we negamax through it to find the best
1097   // achievable score from the point of view of the side to move.
1098   while (--slIndex)
1099       swapList[slIndex - 1] = std::min(-swapList[slIndex], swapList[slIndex - 1]);
1100
1101   return swapList[0];
1102 }
1103
1104
1105 /// Position::clear() erases the position object to a pristine state, with an
1106 /// empty board, white to move, and no castling rights.
1107
1108 void Position::clear() {
1109
1110   std::memset(this, 0, sizeof(Position));
1111   startState.epSquare = SQ_NONE;
1112   st = &startState;
1113
1114   for (int i = 0; i < PIECE_TYPE_NB; ++i)
1115       for (int j = 0; j < 16; ++j)
1116           pieceList[WHITE][i][j] = pieceList[BLACK][i][j] = SQ_NONE;
1117 }
1118
1119
1120 /// Position::compute_key() computes the hash key of the position. The hash
1121 /// key is usually updated incrementally as moves are made and unmade. The
1122 /// compute_key() function is only used when a new position is set up, and
1123 /// to verify the correctness of the hash key when running in debug mode.
1124
1125 Key Position::compute_key() const {
1126
1127   Key k = Zobrist::castling[st->castlingFlags];
1128
1129   for (Bitboard b = pieces(); b; )
1130   {
1131       Square s = pop_lsb(&b);
1132       k ^= Zobrist::psq[color_of(piece_on(s))][type_of(piece_on(s))][s];
1133   }
1134
1135   if (ep_square() != SQ_NONE)
1136       k ^= Zobrist::enpassant[file_of(ep_square())];
1137
1138   if (sideToMove == BLACK)
1139       k ^= Zobrist::side;
1140
1141   return k;
1142 }
1143
1144
1145 /// Position::compute_pawn_key() computes the hash key of the position. The
1146 /// hash key is usually updated incrementally as moves are made and unmade.
1147 /// The compute_pawn_key() function is only used when a new position is set
1148 /// up, and to verify the correctness of the pawn hash key when running in
1149 /// debug mode.
1150
1151 Key Position::compute_pawn_key() const {
1152
1153   Key k = 0;
1154
1155   for (Bitboard b = pieces(PAWN); b; )
1156   {
1157       Square s = pop_lsb(&b);
1158       k ^= Zobrist::psq[color_of(piece_on(s))][PAWN][s];
1159   }
1160
1161   return k;
1162 }
1163
1164
1165 /// Position::compute_material_key() computes the hash key of the position.
1166 /// The hash key is usually updated incrementally as moves are made and unmade.
1167 /// The compute_material_key() function is only used when a new position is set
1168 /// up, and to verify the correctness of the material hash key when running in
1169 /// debug mode.
1170
1171 Key Position::compute_material_key() const {
1172
1173   Key k = 0;
1174
1175   for (Color c = WHITE; c <= BLACK; ++c)
1176       for (PieceType pt = PAWN; pt <= QUEEN; ++pt)
1177           for (int cnt = 0; cnt < pieceCount[c][pt]; ++cnt)
1178               k ^= Zobrist::psq[c][pt][cnt];
1179
1180   return k;
1181 }
1182
1183
1184 /// Position::compute_psq_score() computes the incremental scores for the middlegame
1185 /// and the endgame. These functions are used to initialize the incremental scores
1186 /// when a new position is set up, and to verify that the scores are correctly
1187 /// updated by do_move and undo_move when the program is running in debug mode.
1188
1189 Score Position::compute_psq_score() const {
1190
1191   Score score = SCORE_ZERO;
1192
1193   for (Bitboard b = pieces(); b; )
1194   {
1195       Square s = pop_lsb(&b);
1196       Piece pc = piece_on(s);
1197       score += psq[color_of(pc)][type_of(pc)][s];
1198   }
1199
1200   return score;
1201 }
1202
1203
1204 /// Position::compute_non_pawn_material() computes the total non-pawn middlegame
1205 /// material value for the given side. Material values are updated incrementally
1206 /// during the search. This function is only used when initializing a new Position
1207 /// object.
1208
1209 Value Position::compute_non_pawn_material(Color c) const {
1210
1211   Value value = VALUE_ZERO;
1212
1213   for (PieceType pt = KNIGHT; pt <= QUEEN; ++pt)
1214       value += pieceCount[c][pt] * PieceValue[MG][pt];
1215
1216   return value;
1217 }
1218
1219
1220 /// Position::is_draw() tests whether the position is drawn by material, 50 moves
1221 /// rule or repetition. It does not detect stalemates.
1222
1223 bool Position::is_draw() const {
1224
1225   if (   !pieces(PAWN)
1226       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMg))
1227       return true;
1228
1229   if (st->rule50 > 99 && (!checkers() || MoveList<LEGAL>(*this).size()))
1230       return true;
1231
1232   StateInfo* stp = st;
1233   for (int i = 2, e = std::min(st->rule50, st->pliesFromNull); i <= e; i += 2)
1234   {
1235       stp = stp->previous->previous;
1236
1237       if (stp->key == st->key)
1238           return true; // Draw at first repetition
1239   }
1240
1241   return false;
1242 }
1243
1244
1245 /// Position::flip() flips position with the white and black sides reversed. This
1246 /// is only useful for debugging e.g. for finding evaluation symmetry bugs.
1247
1248 static char toggle_case(char c) {
1249   return char(islower(c) ? toupper(c) : tolower(c));
1250 }
1251
1252 void Position::flip() {
1253
1254   string f, token;
1255   std::stringstream ss(fen());
1256
1257   for (Rank rank = RANK_8; rank >= RANK_1; --rank) // Piece placement
1258   {
1259       std::getline(ss, token, rank > RANK_1 ? '/' : ' ');
1260       f.insert(0, token + (f.empty() ? " " : "/"));
1261   }
1262
1263   ss >> token; // Active color
1264   f += (token == "w" ? "B " : "W "); // Will be lowercased later
1265
1266   ss >> token; // Castling availability
1267   f += token + " ";
1268
1269   std::transform(f.begin(), f.end(), f.begin(), toggle_case);
1270
1271   ss >> token; // En passant square
1272   f += (token == "-" ? token : token.replace(1, 1, token[1] == '3' ? "6" : "3"));
1273
1274   std::getline(ss, token); // Half and full moves
1275   f += token;
1276
1277   set(f, is_chess960(), this_thread());
1278
1279   assert(pos_is_ok());
1280 }
1281
1282
1283 /// Position::pos_is_ok() performs some consistency checks for the position object.
1284 /// This is meant to be helpful when debugging.
1285
1286 bool Position::pos_is_ok(int* failedStep) const {
1287
1288   int dummy, *step = failedStep ? failedStep : &dummy;
1289
1290   // What features of the position should be verified?
1291   const bool all = false;
1292
1293   const bool debugBitboards       = all || false;
1294   const bool debugKingCount       = all || false;
1295   const bool debugKingCapture     = all || false;
1296   const bool debugCheckerCount    = all || false;
1297   const bool debugKey             = all || false;
1298   const bool debugMaterialKey     = all || false;
1299   const bool debugPawnKey         = all || false;
1300   const bool debugIncrementalEval = all || false;
1301   const bool debugNonPawnMaterial = all || false;
1302   const bool debugPieceCounts     = all || false;
1303   const bool debugPieceList       = all || false;
1304   const bool debugCastlingSquares = all || false;
1305
1306   *step = 1;
1307
1308   if (sideToMove != WHITE && sideToMove != BLACK)
1309       return false;
1310
1311   if ((*step)++, piece_on(king_square(WHITE)) != W_KING)
1312       return false;
1313
1314   if ((*step)++, piece_on(king_square(BLACK)) != B_KING)
1315       return false;
1316
1317   if ((*step)++, debugKingCount)
1318   {
1319       int kingCount[COLOR_NB] = {};
1320
1321       for (Square s = SQ_A1; s <= SQ_H8; ++s)
1322           if (type_of(piece_on(s)) == KING)
1323               ++kingCount[color_of(piece_on(s))];
1324
1325       if (kingCount[0] != 1 || kingCount[1] != 1)
1326           return false;
1327   }
1328
1329   if ((*step)++, debugKingCapture)
1330       if (attackers_to(king_square(~sideToMove)) & pieces(sideToMove))
1331           return false;
1332
1333   if ((*step)++, debugCheckerCount && popcount<Full>(st->checkersBB) > 2)
1334       return false;
1335
1336   if ((*step)++, debugBitboards)
1337   {
1338       // The intersection of the white and black pieces must be empty
1339       if (pieces(WHITE) & pieces(BLACK))
1340           return false;
1341
1342       // The union of the white and black pieces must be equal to all
1343       // occupied squares
1344       if ((pieces(WHITE) | pieces(BLACK)) != pieces())
1345           return false;
1346
1347       // Separate piece type bitboards must have empty intersections
1348       for (PieceType p1 = PAWN; p1 <= KING; ++p1)
1349           for (PieceType p2 = PAWN; p2 <= KING; ++p2)
1350               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1351                   return false;
1352   }
1353
1354   if ((*step)++, ep_square() != SQ_NONE && relative_rank(sideToMove, ep_square()) != RANK_6)
1355       return false;
1356
1357   if ((*step)++, debugKey && st->key != compute_key())
1358       return false;
1359
1360   if ((*step)++, debugPawnKey && st->pawnKey != compute_pawn_key())
1361       return false;
1362
1363   if ((*step)++, debugMaterialKey && st->materialKey != compute_material_key())
1364       return false;
1365
1366   if ((*step)++, debugIncrementalEval && st->psq != compute_psq_score())
1367       return false;
1368
1369   if ((*step)++, debugNonPawnMaterial)
1370       if (   st->npMaterial[WHITE] != compute_non_pawn_material(WHITE)
1371           || st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1372           return false;
1373
1374   if ((*step)++, debugPieceCounts)
1375       for (Color c = WHITE; c <= BLACK; ++c)
1376           for (PieceType pt = PAWN; pt <= KING; ++pt)
1377               if (pieceCount[c][pt] != popcount<Full>(pieces(c, pt)))
1378                   return false;
1379
1380   if ((*step)++, debugPieceList)
1381       for (Color c = WHITE; c <= BLACK; ++c)
1382           for (PieceType pt = PAWN; pt <= KING; ++pt)
1383               for (int i = 0; i < pieceCount[c][pt];  ++i)
1384                   if (   board[pieceList[c][pt][i]] != make_piece(c, pt)
1385                       || index[pieceList[c][pt][i]] != i)
1386                       return false;
1387
1388   if ((*step)++, debugCastlingSquares)
1389       for (Color c = WHITE; c <= BLACK; ++c)
1390           for (CastlingSide s = KING_SIDE; s <= QUEEN_SIDE; s = CastlingSide(s + 1))
1391           {
1392               CastlingFlag cf = make_castling_flag(c, s);
1393
1394               if (!can_castle(cf))
1395                   continue;
1396
1397               if (  (castlingFlagsMask[king_square(c)] & cf) != cf
1398                   || piece_on(castlingRookSquare[c][s]) != make_piece(c, ROOK)
1399                   || castlingFlagsMask[castlingRookSquare[c][s]] != cf)
1400                   return false;
1401           }
1402
1403   *step = 0;
1404   return true;
1405 }