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