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