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