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