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