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