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