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