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