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