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