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