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