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