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