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