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