]> git.sesse.net Git - stockfish/blob - src/position.cpp
Fix some warnings and a compile error with icc
[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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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 #include <cassert>
21 #include <cstring>
22 #include <fstream>
23 #include <map>
24 #include <iostream>
25 #include <sstream>
26
27 #include "bitcount.h"
28 #include "movegen.h"
29 #include "position.h"
30 #include "psqtab.h"
31 #include "rkiss.h"
32 #include "tt.h"
33 #include "ucioption.h"
34
35 using std::string;
36 using std::cout;
37 using std::endl;
38
39 Key Position::zobrist[2][8][64];
40 Key Position::zobEp[64];
41 Key Position::zobCastle[16];
42 Key Position::zobSideToMove;
43 Key Position::zobExclusion;
44
45 Score Position::PieceSquareTable[16][64];
46
47 // Material values arrays, indexed by Piece
48 const Value Position::PieceValueMidgame[17] = {
49   VALUE_ZERO,
50   PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
51   RookValueMidgame, QueenValueMidgame, VALUE_ZERO,
52   VALUE_ZERO, VALUE_ZERO,
53   PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
54   RookValueMidgame, QueenValueMidgame
55 };
56
57 const Value Position::PieceValueEndgame[17] = {
58   VALUE_ZERO,
59   PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
60   RookValueEndgame, QueenValueEndgame, VALUE_ZERO,
61   VALUE_ZERO, VALUE_ZERO,
62   PawnValueEndgame, KnightValueEndgame, BishopValueEndgame,
63   RookValueEndgame, QueenValueEndgame
64 };
65
66 // Material values array used by SEE, indexed by PieceType
67 const Value Position::seeValues[] = {
68     VALUE_ZERO,
69     PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
70     RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10
71 };
72
73
74 namespace {
75
76   // Bonus for having the side to move (modified by Joona Kiiski)
77   const Score TempoValue = make_score(48, 22);
78
79   struct PieceLetters : public std::map<char, Piece> {
80
81     PieceLetters() {
82
83       operator[]('K') = WK; operator[]('k') = BK;
84       operator[]('Q') = WQ; operator[]('q') = BQ;
85       operator[]('R') = WR; operator[]('r') = BR;
86       operator[]('B') = WB; operator[]('b') = BB;
87       operator[]('N') = WN; operator[]('n') = BN;
88       operator[]('P') = WP; operator[]('p') = BP;
89       operator[](' ') = PIECE_NONE;
90       operator[]('.') = PIECE_NONE_DARK_SQ;
91     }
92
93     char from_piece(Piece p) const {
94
95       std::map<char, Piece>::const_iterator it;
96       for (it = begin(); it != end(); ++it)
97           if (it->second == p)
98               return it->first;
99
100       assert(false);
101       return 0;
102     }
103   };
104
105   PieceLetters pieceLetters;
106 }
107
108
109 /// CheckInfo c'tor
110
111 CheckInfo::CheckInfo(const Position& pos) {
112
113   Color us = pos.side_to_move();
114   Color them = opposite_color(us);
115
116   ksq = pos.king_square(them);
117   dcCandidates = pos.discovered_check_candidates(us);
118
119   checkSq[PAWN] = pos.attacks_from<PAWN>(ksq, them);
120   checkSq[KNIGHT] = pos.attacks_from<KNIGHT>(ksq);
121   checkSq[BISHOP] = pos.attacks_from<BISHOP>(ksq);
122   checkSq[ROOK] = pos.attacks_from<ROOK>(ksq);
123   checkSq[QUEEN] = checkSq[BISHOP] | checkSq[ROOK];
124   checkSq[KING] = EmptyBoardBB;
125 }
126
127
128 /// Position c'tors. Here we always create a copy of the original position
129 /// or the FEN string, we want the new born Position object do not depend
130 /// on any external data so we detach state pointer from the source one.
131
132 Position::Position(const Position& pos, int th) {
133
134   memcpy(this, &pos, sizeof(Position));
135   detach(); // Always detach() in copy c'tor to avoid surprises
136   threadID = th;
137   nodes = 0;
138 }
139
140 Position::Position(const string& fen, bool isChess960, int th) {
141
142   from_fen(fen, isChess960);
143   threadID = th;
144 }
145
146
147 /// Position::detach() copies the content of the current state and castling
148 /// masks inside the position itself. This is needed when the st pointee could
149 /// become stale, as example because the caller is about to going out of scope.
150
151 void Position::detach() {
152
153   startState = *st;
154   st = &startState;
155   st->previous = NULL; // as a safe guard
156 }
157
158
159 /// Position::from_fen() initializes the position object with the given FEN
160 /// string. This function is not very robust - make sure that input FENs are
161 /// correct (this is assumed to be the responsibility of the GUI).
162
163 void Position::from_fen(const string& fen, bool isChess960) {
164 /*
165    A FEN string defines a particular position using only the ASCII character set.
166
167    A FEN string contains six fields. The separator between fields is a space. The fields are:
168
169    1) Piece placement (from white's perspective). Each rank is described, starting with rank 8 and ending
170       with rank 1; within each rank, the contents of each square are described from file A through file H.
171       Following the Standard Algebraic Notation (SAN), each piece is identified by a single letter taken
172       from the standard English names. White pieces are designated using upper-case letters ("PNBRQK")
173       while Black take lowercase ("pnbrqk"). Blank squares are noted using digits 1 through 8 (the number
174       of blank squares), and "/" separate ranks.
175
176    2) Active color. "w" means white moves next, "b" means black.
177
178    3) Castling availability. If neither side can castle, this is "-". Otherwise, this has one or more
179       letters: "K" (White can castle kingside), "Q" (White can castle queenside), "k" (Black can castle
180       kingside), and/or "q" (Black can castle queenside).
181
182    4) En passant target square in algebraic notation. If there's no en passant target square, this is "-".
183       If a pawn has just made a 2-square move, this is the position "behind" the pawn. This is recorded
184       regardless of whether there is a pawn in position to make an en passant capture.
185
186    5) Halfmove clock: This is the number of halfmoves since the last pawn advance or capture. This is used
187       to determine if a draw can be claimed under the fifty-move rule.
188
189    6) Fullmove number: The number of the full move. It starts at 1, and is incremented after Black's move.
190 */
191
192   char token;
193   int hmc, fmn;
194   std::istringstream ss(fen);
195   Square sq = SQ_A8;
196
197   clear();
198
199   // 1. Piece placement field
200   while (ss.get(token) && token != ' ')
201   {
202       if (pieceLetters.find(token) != pieceLetters.end())
203       {
204           put_piece(pieceLetters[token], sq);
205           sq++;
206       }
207       else if (isdigit(token))
208           sq += Square(token - '0'); // Skip the given number of files
209       else if (token == '/')
210           sq -= SQ_A3; // Jump back of 2 rows
211       else
212           goto incorrect_fen;
213   }
214
215   // 2. Active color
216   if (!ss.get(token) || (token != 'w' && token != 'b'))
217       goto incorrect_fen;
218
219   sideToMove = (token == 'w' ? WHITE : BLACK);
220
221   if (!ss.get(token) || token != ' ')
222       goto incorrect_fen;
223
224   // 3. Castling availability
225   while (ss.get(token) && token != ' ')
226       if (!set_castling_rights(token))
227           goto incorrect_fen;
228
229   // 4. En passant square
230   char col, row;
231   if (   (ss.get(col) && (col >= 'a' && col <= 'h'))
232       && (ss.get(row) && (row == '3' || row == '6')))
233   {
234       st->epSquare = make_square(file_from_char(col), rank_from_char(row));
235
236       // Ignore if no capture is possible
237       Color them = opposite_color(sideToMove);
238       if (!(attacks_from<PAWN>(st->epSquare, them) & pieces(PAWN, sideToMove)))
239           st->epSquare = SQ_NONE;
240   }
241
242   // 5. Halfmove clock
243   if (ss >> hmc)
244       st->rule50 = hmc;
245
246   // 6. Fullmove number
247   if (ss >> fmn)
248       startPosPlyCounter = (fmn - 1) * 2 + int(sideToMove == BLACK);
249
250   // Various initialisations
251   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= WHITE_OO | WHITE_OOO;
252   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= BLACK_OO | BLACK_OOO;
253   castleRightsMask[make_square(initialKRFile, RANK_1)] ^= WHITE_OO;
254   castleRightsMask[make_square(initialKRFile, RANK_8)] ^= BLACK_OO;
255   castleRightsMask[make_square(initialQRFile, RANK_1)] ^= WHITE_OOO;
256   castleRightsMask[make_square(initialQRFile, RANK_8)] ^= BLACK_OOO;
257
258   chess960 = isChess960;
259   find_checkers();
260
261   st->key = compute_key();
262   st->pawnKey = compute_pawn_key();
263   st->materialKey = compute_material_key();
264   st->value = compute_value();
265   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
266   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
267   return;
268
269 incorrect_fen:
270   cout << "Error in FEN string: " << fen << endl;
271 }
272
273
274 /// Position::set_castling_rights() sets castling parameters castling avaiability.
275 /// This function is compatible with 3 standards: Normal FEN standard, Shredder-FEN
276 /// that uses the letters of the columns on which the rooks began the game instead
277 /// of KQkq and also X-FEN standard that, in case of Chess960, if an inner Rook is
278 /// associated with the castling right, the traditional castling tag will be replaced
279 /// by the file letter of the involved rook as for the Shredder-FEN.
280
281 bool Position::set_castling_rights(char token) {
282
283     Color c = token >= 'a' ? BLACK : WHITE;
284     Square sqA = (c == WHITE ? SQ_A1 : SQ_A8);
285     Square sqH = (c == WHITE ? SQ_H1 : SQ_H8);
286     Piece rook = (c == WHITE ? WR : BR);
287
288     initialKFile = square_file(king_square(c));
289     token = char(toupper(token));
290
291     if (token == 'K')
292     {
293         for (Square sq = sqH; sq >= sqA; sq--)
294             if (piece_on(sq) == rook)
295             {
296                 do_allow_oo(c);
297                 initialKRFile = square_file(sq);
298                 break;
299             }
300     }
301     else if (token == 'Q')
302     {
303         for (Square sq = sqA; sq <= sqH; sq++)
304             if (piece_on(sq) == rook)
305             {
306                 do_allow_ooo(c);
307                 initialQRFile = square_file(sq);
308                 break;
309             }
310     }
311     else if (token >= 'A' && token <= 'H')
312     {
313         File rookFile = File(token - 'A') + FILE_A;
314         if (rookFile < initialKFile)
315         {
316             do_allow_ooo(c);
317             initialQRFile = rookFile;
318         }
319         else
320         {
321             do_allow_oo(c);
322             initialKRFile = rookFile;
323         }
324     }
325     else
326         return token == '-';
327
328   return true;
329 }
330
331
332 /// Position::to_fen() returns a FEN representation of the position. In case
333 /// of Chess960 the Shredder-FEN notation is used. Mainly a debugging function.
334
335 const string Position::to_fen() const {
336
337   string fen;
338   Square sq;
339   char emptyCnt = '0';
340
341   for (Rank rank = RANK_8; rank >= RANK_1; rank--, fen += '/')
342   {
343       for (File file = FILE_A; file <= FILE_H; file++)
344       {
345           sq = make_square(file, rank);
346
347           if (square_is_occupied(sq))
348           {
349               if (emptyCnt != '0')
350               {
351                   fen += emptyCnt;
352                   emptyCnt = '0';
353               }
354               fen += pieceLetters.from_piece(piece_on(sq));
355           } else
356               emptyCnt++;
357       }
358
359       if (emptyCnt != '0')
360       {
361           fen += emptyCnt;
362           emptyCnt = '0';
363       }
364   }
365
366   fen += (sideToMove == WHITE ? " w " : " b ");
367
368   if (st->castleRights != CASTLES_NONE)
369   {
370       if (can_castle_kingside(WHITE))
371           fen += chess960 ? char(toupper(file_to_char(initialKRFile))) : 'K';
372
373       if (can_castle_queenside(WHITE))
374           fen += chess960 ? char(toupper(file_to_char(initialQRFile))) : 'Q';
375
376       if (can_castle_kingside(BLACK))
377           fen += chess960 ? file_to_char(initialKRFile) : 'k';
378
379       if (can_castle_queenside(BLACK))
380           fen += chess960 ? file_to_char(initialQRFile) : 'q';
381   } else
382       fen += '-';
383
384   fen += (ep_square() == SQ_NONE ? " -" : " " + square_to_string(ep_square()));
385   return fen;
386 }
387
388
389 /// Position::print() prints an ASCII representation of the position to
390 /// the standard output. If a move is given then also the san is printed.
391
392 void Position::print(Move move) const {
393
394   const char* dottedLine = "\n+---+---+---+---+---+---+---+---+\n";
395
396   if (move)
397   {
398       Position p(*this, thread());
399       string dd = (color_of_piece_on(move_from(move)) == BLACK ? ".." : "");
400       cout << "\nMove is: " << dd << move_to_san(p, move);
401   }
402
403   for (Rank rank = RANK_8; rank >= RANK_1; rank--)
404   {
405       cout << dottedLine << '|';
406       for (File file = FILE_A; file <= FILE_H; file++)
407       {
408           Square sq = make_square(file, rank);
409           Piece piece = piece_on(sq);
410
411           if (piece == PIECE_NONE && square_color(sq) == DARK)
412               piece = PIECE_NONE_DARK_SQ;
413
414           char c = (color_of_piece_on(sq) == BLACK ? '=' : ' ');
415           cout << c << pieceLetters.from_piece(piece) << c << '|';
416       }
417   }
418   cout << dottedLine << "Fen is: " << to_fen() << "\nKey is: " << st->key << endl;
419 }
420
421
422 /// Position:hidden_checkers<>() returns a bitboard of all pinned (against the
423 /// king) pieces for the given color and for the given pinner type. Or, when
424 /// template parameter FindPinned is false, the pieces of the given color
425 /// candidate for a discovery check against the enemy king.
426 /// Bitboard checkersBB must be already updated when looking for pinners.
427
428 template<bool FindPinned>
429 Bitboard Position::hidden_checkers(Color c) const {
430
431   Bitboard result = EmptyBoardBB;
432   Bitboard pinners = pieces_of_color(FindPinned ? opposite_color(c) : c);
433
434   // Pinned pieces protect our king, dicovery checks attack
435   // the enemy king.
436   Square ksq = king_square(FindPinned ? c : opposite_color(c));
437
438   // Pinners are sliders, not checkers, that give check when candidate pinned is removed
439   pinners &= (pieces(ROOK, QUEEN) & RookPseudoAttacks[ksq]) | (pieces(BISHOP, QUEEN) & BishopPseudoAttacks[ksq]);
440
441   if (FindPinned && pinners)
442       pinners &= ~st->checkersBB;
443
444   while (pinners)
445   {
446       Square s = pop_1st_bit(&pinners);
447       Bitboard b = squares_between(s, ksq) & occupied_squares();
448
449       assert(b);
450
451       if (  !(b & (b - 1)) // Only one bit set?
452           && (b & pieces_of_color(c))) // Is an our piece?
453           result |= b;
454   }
455   return result;
456 }
457
458
459 /// Position:pinned_pieces() returns a bitboard of all pinned (against the
460 /// king) pieces for the given color. Note that checkersBB bitboard must
461 /// be already updated.
462
463 Bitboard Position::pinned_pieces(Color c) const {
464
465   return hidden_checkers<true>(c);
466 }
467
468
469 /// Position:discovered_check_candidates() returns a bitboard containing all
470 /// pieces for the given side which are candidates for giving a discovered
471 /// check. Contrary to pinned_pieces() here there is no need of checkersBB
472 /// to be already updated.
473
474 Bitboard Position::discovered_check_candidates(Color c) const {
475
476   return hidden_checkers<false>(c);
477 }
478
479 /// Position::attackers_to() computes a bitboard containing all pieces which
480 /// attacks a given square.
481
482 Bitboard Position::attackers_to(Square s) const {
483
484   return  (attacks_from<PAWN>(s, BLACK) & pieces(PAWN, WHITE))
485         | (attacks_from<PAWN>(s, WHITE) & pieces(PAWN, BLACK))
486         | (attacks_from<KNIGHT>(s)      & pieces(KNIGHT))
487         | (attacks_from<ROOK>(s)        & pieces(ROOK, QUEEN))
488         | (attacks_from<BISHOP>(s)      & pieces(BISHOP, QUEEN))
489         | (attacks_from<KING>(s)        & pieces(KING));
490 }
491
492 /// Position::attacks_from() computes a bitboard of all attacks
493 /// of a given piece put in a given square.
494
495 Bitboard Position::attacks_from(Piece p, Square s) const {
496
497   assert(square_is_ok(s));
498
499   switch (p)
500   {
501   case WB: case BB: return attacks_from<BISHOP>(s);
502   case WR: case BR: return attacks_from<ROOK>(s);
503   case WQ: case BQ: return attacks_from<QUEEN>(s);
504   default: return StepAttacksBB[p][s];
505   }
506 }
507
508 Bitboard Position::attacks_from(Piece p, Square s, Bitboard occ) {
509
510   assert(square_is_ok(s));
511
512   switch (p)
513   {
514   case WB: case BB: return bishop_attacks_bb(s, occ);
515   case WR: case BR: return rook_attacks_bb(s, occ);
516   case WQ: case BQ: return bishop_attacks_bb(s, occ) | rook_attacks_bb(s, occ);
517   default: return StepAttacksBB[p][s];
518   }
519 }
520
521
522 /// Position::move_attacks_square() tests whether a move from the current
523 /// position attacks a given square.
524
525 bool Position::move_attacks_square(Move m, Square s) const {
526
527   assert(move_is_ok(m));
528   assert(square_is_ok(s));
529
530   Bitboard occ, xray;
531   Square f = move_from(m), t = move_to(m);
532
533   assert(square_is_occupied(f));
534
535   if (bit_is_set(attacks_from(piece_on(f), t), s))
536       return true;
537
538   // Move the piece and scan for X-ray attacks behind it
539   occ = occupied_squares();
540   do_move_bb(&occ, make_move_bb(f, t));
541   xray = ( (rook_attacks_bb(s, occ)   & pieces(ROOK, QUEEN))
542           |(bishop_attacks_bb(s, occ) & pieces(BISHOP, QUEEN)))
543          & pieces_of_color(color_of_piece_on(f));
544
545   // If we have attacks we need to verify that are caused by our move
546   // and are not already existent ones.
547   return xray && (xray ^ (xray & attacks_from<QUEEN>(s)));
548 }
549
550
551 /// Position::find_checkers() computes the checkersBB bitboard, which
552 /// contains a nonzero bit for each checking piece (0, 1 or 2). It
553 /// currently works by calling Position::attackers_to, which is probably
554 /// inefficient. Consider rewriting this function to use the last move
555 /// played, like in non-bitboard versions of Glaurung.
556
557 void Position::find_checkers() {
558
559   Color us = side_to_move();
560   st->checkersBB = attackers_to(king_square(us)) & pieces_of_color(opposite_color(us));
561 }
562
563
564 /// Position::pl_move_is_legal() tests whether a pseudo-legal move is legal
565
566 bool Position::pl_move_is_legal(Move m, Bitboard pinned) const {
567
568   assert(is_ok());
569   assert(move_is_ok(m));
570   assert(pinned == pinned_pieces(side_to_move()));
571
572   // Castling moves are checked for legality during move generation.
573   if (move_is_castle(m))
574       return true;
575
576   // En passant captures are a tricky special case. Because they are
577   // rather uncommon, we do it simply by testing whether the king is attacked
578   // after the move is made
579   if (move_is_ep(m))
580   {
581       Color us = side_to_move();
582       Color them = opposite_color(us);
583       Square from = move_from(m);
584       Square to = move_to(m);
585       Square capsq = make_square(square_file(to), square_rank(from));
586       Square ksq = king_square(us);
587       Bitboard b = occupied_squares();
588
589       assert(to == ep_square());
590       assert(piece_on(from) == make_piece(us, PAWN));
591       assert(piece_on(capsq) == make_piece(them, PAWN));
592       assert(piece_on(to) == PIECE_NONE);
593
594       clear_bit(&b, from);
595       clear_bit(&b, capsq);
596       set_bit(&b, to);
597
598       return   !(rook_attacks_bb(ksq, b) & pieces(ROOK, QUEEN, them))
599             && !(bishop_attacks_bb(ksq, b) & pieces(BISHOP, QUEEN, them));
600   }
601
602   Color us = side_to_move();
603   Square from = move_from(m);
604
605   assert(color_of_piece_on(from) == us);
606   assert(piece_on(king_square(us)) == make_piece(us, KING));
607
608   // If the moving piece is a king, check whether the destination
609   // square is attacked by the opponent.
610   if (type_of_piece_on(from) == KING)
611       return !(attackers_to(move_to(m)) & pieces_of_color(opposite_color(us)));
612
613   // A non-king move is legal if and only if it is not pinned or it
614   // is moving along the ray towards or away from the king.
615   return   !pinned
616         || !bit_is_set(pinned, from)
617         ||  squares_aligned(from, move_to(m), king_square(us));
618 }
619
620
621 /// Position::pl_move_is_evasion() tests whether a pseudo-legal move is a legal evasion
622
623 bool Position::pl_move_is_evasion(Move m, Bitboard pinned) const
624 {
625   assert(is_check());
626
627   Color us = side_to_move();
628   Square from = move_from(m);
629   Square to = move_to(m);
630
631   // King moves and en-passant captures are verified in pl_move_is_legal()
632   if (type_of_piece_on(from) == KING || move_is_ep(m))
633       return pl_move_is_legal(m, pinned);
634
635   Bitboard target = checkers();
636   Square checksq = pop_1st_bit(&target);
637
638   if (target) // double check ?
639       return false;
640
641   // Our move must be a blocking evasion or a capture of the checking piece
642   target = squares_between(checksq, king_square(us)) | checkers();
643   return bit_is_set(target, to) && pl_move_is_legal(m, pinned);
644 }
645
646
647 /// Position::move_is_check() tests whether a pseudo-legal move is a check
648
649 bool Position::move_is_check(Move m) const {
650
651   return move_is_check(m, CheckInfo(*this));
652 }
653
654 bool Position::move_is_check(Move m, const CheckInfo& ci) const {
655
656   assert(is_ok());
657   assert(move_is_ok(m));
658   assert(ci.dcCandidates == discovered_check_candidates(side_to_move()));
659   assert(color_of_piece_on(move_from(m)) == side_to_move());
660   assert(piece_on(ci.ksq) == make_piece(opposite_color(side_to_move()), KING));
661
662   Square from = move_from(m);
663   Square to = move_to(m);
664   PieceType pt = type_of_piece_on(from);
665
666   // Direct check ?
667   if (bit_is_set(ci.checkSq[pt], to))
668       return true;
669
670   // Discovery check ?
671   if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
672   {
673       // For pawn and king moves we need to verify also direction
674       if (  (pt != PAWN && pt != KING)
675           || !squares_aligned(from, to, ci.ksq))
676           return true;
677   }
678
679   // Can we skip the ugly special cases ?
680   if (!move_is_special(m))
681       return false;
682
683   Color us = side_to_move();
684   Bitboard b = occupied_squares();
685
686   // Promotion with check ?
687   if (move_is_promotion(m))
688   {
689       clear_bit(&b, from);
690
691       switch (move_promotion_piece(m))
692       {
693       case KNIGHT:
694           return bit_is_set(attacks_from<KNIGHT>(to), ci.ksq);
695       case BISHOP:
696           return bit_is_set(bishop_attacks_bb(to, b), ci.ksq);
697       case ROOK:
698           return bit_is_set(rook_attacks_bb(to, b), ci.ksq);
699       case QUEEN:
700           return bit_is_set(queen_attacks_bb(to, b), ci.ksq);
701       default:
702           assert(false);
703       }
704   }
705
706   // En passant capture with check ? We have already handled the case
707   // of direct checks and ordinary discovered check, the only case we
708   // need to handle is the unusual case of a discovered check through
709   // the captured pawn.
710   if (move_is_ep(m))
711   {
712       Square capsq = make_square(square_file(to), square_rank(from));
713       clear_bit(&b, from);
714       clear_bit(&b, capsq);
715       set_bit(&b, to);
716       return  (rook_attacks_bb(ci.ksq, b) & pieces(ROOK, QUEEN, us))
717             ||(bishop_attacks_bb(ci.ksq, b) & pieces(BISHOP, QUEEN, us));
718   }
719
720   // Castling with check ?
721   if (move_is_castle(m))
722   {
723       Square kfrom, kto, rfrom, rto;
724       kfrom = from;
725       rfrom = to;
726
727       if (rfrom > kfrom)
728       {
729           kto = relative_square(us, SQ_G1);
730           rto = relative_square(us, SQ_F1);
731       } else {
732           kto = relative_square(us, SQ_C1);
733           rto = relative_square(us, SQ_D1);
734       }
735       clear_bit(&b, kfrom);
736       clear_bit(&b, rfrom);
737       set_bit(&b, rto);
738       set_bit(&b, kto);
739       return bit_is_set(rook_attacks_bb(rto, b), ci.ksq);
740   }
741
742   return false;
743 }
744
745
746 /// Position::do_setup_move() makes a permanent move on the board.
747 /// It should be used when setting up a position on board.
748 /// You can't undo the move.
749
750 void Position::do_setup_move(Move m) {
751
752   StateInfo newSt;
753
754   do_move(m, newSt);
755
756   // Reset "game ply" in case we made a non-reversible move.
757   // "game ply" is used for repetition detection.
758   if (st->rule50 == 0)
759       st->gamePly = 0;
760
761   // Update the number of plies played from the starting position
762   startPosPlyCounter++;
763
764   // Our StateInfo newSt is about going out of scope so copy
765   // its content inside pos before it disappears.
766   detach();
767 }
768
769 /// Position::do_move() makes a move, and saves all information necessary
770 /// to a StateInfo object. The move is assumed to be legal.
771 /// Pseudo-legal moves should be filtered out before this function is called.
772
773 void Position::do_move(Move m, StateInfo& newSt) {
774
775   CheckInfo ci(*this);
776   do_move(m, newSt, ci, move_is_check(m, ci));
777 }
778
779 void Position::do_move(Move m, StateInfo& newSt, const CheckInfo& ci, bool moveIsCheck) {
780
781   assert(is_ok());
782   assert(move_is_ok(m));
783   assert(&newSt != st);
784
785   nodes++;
786   Key key = st->key;
787
788   // Copy some fields of old state to our new StateInfo object except the
789   // ones which are recalculated from scratch anyway, then switch our state
790   // pointer to point to the new, ready to be updated, state.
791   struct ReducedStateInfo {
792     Key pawnKey, materialKey;
793     int castleRights, rule50, gamePly, pliesFromNull;
794     Square epSquare;
795     Score value;
796     Value npMaterial[2];
797   };
798
799   memcpy(&newSt, st, sizeof(ReducedStateInfo));
800
801   newSt.previous = st;
802   st = &newSt;
803
804   // Save the current key to the history[] array, in order to be able to
805   // detect repetition draws.
806   history[st->gamePly++] = key;
807
808   // Update side to move
809   key ^= zobSideToMove;
810
811   // Increment the 50 moves rule draw counter. Resetting it to zero in the
812   // case of non-reversible moves is taken care of later.
813   st->rule50++;
814   st->pliesFromNull++;
815
816   if (move_is_castle(m))
817   {
818       st->key = key;
819       do_castle_move(m);
820       return;
821   }
822
823   Color us = side_to_move();
824   Color them = opposite_color(us);
825   Square from = move_from(m);
826   Square to = move_to(m);
827   bool ep = move_is_ep(m);
828   bool pm = move_is_promotion(m);
829
830   Piece piece = piece_on(from);
831   PieceType pt = type_of_piece(piece);
832   PieceType capture = ep ? PAWN : type_of_piece_on(to);
833
834   assert(color_of_piece_on(from) == us);
835   assert(color_of_piece_on(to) == them || square_is_empty(to));
836   assert(!(ep || pm) || piece == make_piece(us, PAWN));
837   assert(!pm || relative_rank(us, to) == RANK_8);
838
839   if (capture)
840       do_capture_move(key, capture, them, to, ep);
841
842   // Update hash key
843   key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
844
845   // Reset en passant square
846   if (st->epSquare != SQ_NONE)
847   {
848       key ^= zobEp[st->epSquare];
849       st->epSquare = SQ_NONE;
850   }
851
852   // Update castle rights, try to shortcut a common case
853   int cm = castleRightsMask[from] & castleRightsMask[to];
854   if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
855   {
856       key ^= zobCastle[st->castleRights];
857       st->castleRights &= castleRightsMask[from];
858       st->castleRights &= castleRightsMask[to];
859       key ^= zobCastle[st->castleRights];
860   }
861
862   // Prefetch TT access as soon as we know key is updated
863   prefetch((char*)TT.first_entry(key));
864
865   // Move the piece
866   Bitboard move_bb = make_move_bb(from, to);
867   do_move_bb(&(byColorBB[us]), move_bb);
868   do_move_bb(&(byTypeBB[pt]), move_bb);
869   do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
870
871   board[to] = board[from];
872   board[from] = PIECE_NONE;
873
874   // Update piece lists, note that index[from] is not updated and
875   // becomes stale. This works as long as index[] is accessed just
876   // by known occupied squares.
877   index[to] = index[from];
878   pieceList[us][pt][index[to]] = to;
879
880   // If the moving piece was a pawn do some special extra work
881   if (pt == PAWN)
882   {
883       // Reset rule 50 draw counter
884       st->rule50 = 0;
885
886       // Update pawn hash key and prefetch in L1/L2 cache
887       st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
888
889       // Set en passant square, only if moved pawn can be captured
890       if ((to ^ from) == 16)
891       {
892           if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
893           {
894               st->epSquare = Square((int(from) + int(to)) / 2);
895               key ^= zobEp[st->epSquare];
896           }
897       }
898
899       if (pm) // promotion ?
900       {
901           PieceType promotion = move_promotion_piece(m);
902
903           assert(promotion >= KNIGHT && promotion <= QUEEN);
904
905           // Insert promoted piece instead of pawn
906           clear_bit(&(byTypeBB[PAWN]), to);
907           set_bit(&(byTypeBB[promotion]), to);
908           board[to] = make_piece(us, promotion);
909
910           // Update piece counts
911           pieceCount[us][promotion]++;
912           pieceCount[us][PAWN]--;
913
914           // Update material key
915           st->materialKey ^= zobrist[us][PAWN][pieceCount[us][PAWN]];
916           st->materialKey ^= zobrist[us][promotion][pieceCount[us][promotion]-1];
917
918           // Update piece lists, move the last pawn at index[to] position
919           // and shrink the list. Add a new promotion piece to the list.
920           Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
921           index[lastPawnSquare] = index[to];
922           pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
923           pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
924           index[to] = pieceCount[us][promotion] - 1;
925           pieceList[us][promotion][index[to]] = to;
926
927           // Partially revert hash keys update
928           key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
929           st->pawnKey ^= zobrist[us][PAWN][to];
930
931           // Partially revert and update incremental scores
932           st->value -= pst(us, PAWN, to);
933           st->value += pst(us, promotion, to);
934
935           // Update material
936           st->npMaterial[us] += PieceValueMidgame[promotion];
937       }
938   }
939
940   // Prefetch pawn and material hash tables
941   prefetchTables(st->pawnKey, st->materialKey, threadID);
942
943   // Update incremental scores
944   st->value += pst_delta(piece, from, to);
945
946   // Set capture piece
947   st->capturedType = capture;
948
949   // Update the key with the final value
950   st->key = key;
951
952   // Update checkers bitboard, piece must be already moved
953   st->checkersBB = EmptyBoardBB;
954
955   if (moveIsCheck)
956   {
957       if (ep | pm)
958           st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
959       else
960       {
961           // Direct checks
962           if (bit_is_set(ci.checkSq[pt], to))
963               st->checkersBB = SetMaskBB[to];
964
965           // Discovery checks
966           if (ci.dcCandidates && bit_is_set(ci.dcCandidates, from))
967           {
968               if (pt != ROOK)
969                   st->checkersBB |= (attacks_from<ROOK>(ci.ksq) & pieces(ROOK, QUEEN, us));
970
971               if (pt != BISHOP)
972                   st->checkersBB |= (attacks_from<BISHOP>(ci.ksq) & pieces(BISHOP, QUEEN, us));
973           }
974       }
975   }
976
977   // Finish
978   sideToMove = opposite_color(sideToMove);
979   st->value += (sideToMove == WHITE ?  TempoValue : -TempoValue);
980
981   assert(is_ok());
982 }
983
984
985 /// Position::do_capture_move() is a private method used to update captured
986 /// piece info. It is called from the main Position::do_move function.
987
988 void Position::do_capture_move(Key& key, PieceType capture, Color them, Square to, bool ep) {
989
990     assert(capture != KING);
991
992     Square capsq = to;
993
994     // If the captured piece was a pawn, update pawn hash key,
995     // otherwise update non-pawn material.
996     if (capture == PAWN)
997     {
998         if (ep) // en passant ?
999         {
1000             capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
1001
1002             assert(to == st->epSquare);
1003             assert(relative_rank(opposite_color(them), to) == RANK_6);
1004             assert(piece_on(to) == PIECE_NONE);
1005             assert(piece_on(capsq) == make_piece(them, PAWN));
1006
1007             board[capsq] = PIECE_NONE;
1008         }
1009         st->pawnKey ^= zobrist[them][PAWN][capsq];
1010     }
1011     else
1012         st->npMaterial[them] -= PieceValueMidgame[capture];
1013
1014     // Remove captured piece
1015     clear_bit(&(byColorBB[them]), capsq);
1016     clear_bit(&(byTypeBB[capture]), capsq);
1017     clear_bit(&(byTypeBB[0]), capsq);
1018
1019     // Update hash key
1020     key ^= zobrist[them][capture][capsq];
1021
1022     // Update incremental scores
1023     st->value -= pst(them, capture, capsq);
1024
1025     // Update piece count
1026     pieceCount[them][capture]--;
1027
1028     // Update material hash key
1029     st->materialKey ^= zobrist[them][capture][pieceCount[them][capture]];
1030
1031     // Update piece list, move the last piece at index[capsq] position
1032     //
1033     // WARNING: This is a not perfectly revresible operation. When we
1034     // will reinsert the captured piece in undo_move() we will put it
1035     // at the end of the list and not in its original place, it means
1036     // index[] and pieceList[] are not guaranteed to be invariant to a
1037     // do_move() + undo_move() sequence.
1038     Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
1039     index[lastPieceSquare] = index[capsq];
1040     pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
1041     pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
1042
1043     // Reset rule 50 counter
1044     st->rule50 = 0;
1045 }
1046
1047
1048 /// Position::do_castle_move() is a private method used to make a castling
1049 /// move. It is called from the main Position::do_move function. Note that
1050 /// castling moves are encoded as "king captures friendly rook" moves, for
1051 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1052
1053 void Position::do_castle_move(Move m) {
1054
1055   assert(move_is_ok(m));
1056   assert(move_is_castle(m));
1057
1058   Color us = side_to_move();
1059   Color them = opposite_color(us);
1060
1061   // Reset capture field
1062   st->capturedType = PIECE_TYPE_NONE;
1063
1064   // Find source squares for king and rook
1065   Square kfrom = move_from(m);
1066   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1067   Square kto, rto;
1068
1069   assert(piece_on(kfrom) == make_piece(us, KING));
1070   assert(piece_on(rfrom) == make_piece(us, ROOK));
1071
1072   // Find destination squares for king and rook
1073   if (rfrom > kfrom) // O-O
1074   {
1075       kto = relative_square(us, SQ_G1);
1076       rto = relative_square(us, SQ_F1);
1077   } else { // O-O-O
1078       kto = relative_square(us, SQ_C1);
1079       rto = relative_square(us, SQ_D1);
1080   }
1081
1082   // Remove pieces from source squares:
1083   clear_bit(&(byColorBB[us]), kfrom);
1084   clear_bit(&(byTypeBB[KING]), kfrom);
1085   clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1086   clear_bit(&(byColorBB[us]), rfrom);
1087   clear_bit(&(byTypeBB[ROOK]), rfrom);
1088   clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1089
1090   // Put pieces on destination squares:
1091   set_bit(&(byColorBB[us]), kto);
1092   set_bit(&(byTypeBB[KING]), kto);
1093   set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1094   set_bit(&(byColorBB[us]), rto);
1095   set_bit(&(byTypeBB[ROOK]), rto);
1096   set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1097
1098   // Update board array
1099   Piece king = make_piece(us, KING);
1100   Piece rook = make_piece(us, ROOK);
1101   board[kfrom] = board[rfrom] = PIECE_NONE;
1102   board[kto] = king;
1103   board[rto] = rook;
1104
1105   // Update piece lists
1106   pieceList[us][KING][index[kfrom]] = kto;
1107   pieceList[us][ROOK][index[rfrom]] = rto;
1108   int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1109   index[kto] = index[kfrom];
1110   index[rto] = tmp;
1111
1112   // Update incremental scores
1113   st->value += pst_delta(king, kfrom, kto);
1114   st->value += pst_delta(rook, rfrom, rto);
1115
1116   // Update hash key
1117   st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1118   st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1119
1120   // Clear en passant square
1121   if (st->epSquare != SQ_NONE)
1122   {
1123       st->key ^= zobEp[st->epSquare];
1124       st->epSquare = SQ_NONE;
1125   }
1126
1127   // Update castling rights
1128   st->key ^= zobCastle[st->castleRights];
1129   st->castleRights &= castleRightsMask[kfrom];
1130   st->key ^= zobCastle[st->castleRights];
1131
1132   // Reset rule 50 counter
1133   st->rule50 = 0;
1134
1135   // Update checkers BB
1136   st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1137
1138   // Finish
1139   sideToMove = opposite_color(sideToMove);
1140   st->value += (sideToMove == WHITE ?  TempoValue : -TempoValue);
1141
1142   assert(is_ok());
1143 }
1144
1145
1146 /// Position::undo_move() unmakes a move. When it returns, the position should
1147 /// be restored to exactly the same state as before the move was made.
1148
1149 void Position::undo_move(Move m) {
1150
1151   assert(is_ok());
1152   assert(move_is_ok(m));
1153
1154   sideToMove = opposite_color(sideToMove);
1155
1156   if (move_is_castle(m))
1157   {
1158       undo_castle_move(m);
1159       return;
1160   }
1161
1162   Color us = side_to_move();
1163   Color them = opposite_color(us);
1164   Square from = move_from(m);
1165   Square to = move_to(m);
1166   bool ep = move_is_ep(m);
1167   bool pm = move_is_promotion(m);
1168
1169   PieceType pt = type_of_piece_on(to);
1170
1171   assert(square_is_empty(from));
1172   assert(color_of_piece_on(to) == us);
1173   assert(!pm || relative_rank(us, to) == RANK_8);
1174   assert(!ep || to == st->previous->epSquare);
1175   assert(!ep || relative_rank(us, to) == RANK_6);
1176   assert(!ep || piece_on(to) == make_piece(us, PAWN));
1177
1178   if (pm) // promotion ?
1179   {
1180       PieceType promotion = move_promotion_piece(m);
1181       pt = PAWN;
1182
1183       assert(promotion >= KNIGHT && promotion <= QUEEN);
1184       assert(piece_on(to) == make_piece(us, promotion));
1185
1186       // Replace promoted piece with a pawn
1187       clear_bit(&(byTypeBB[promotion]), to);
1188       set_bit(&(byTypeBB[PAWN]), to);
1189
1190       // Update piece counts
1191       pieceCount[us][promotion]--;
1192       pieceCount[us][PAWN]++;
1193
1194       // Update piece list replacing promotion piece with a pawn
1195       Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1196       index[lastPromotionSquare] = index[to];
1197       pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1198       pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1199       index[to] = pieceCount[us][PAWN] - 1;
1200       pieceList[us][PAWN][index[to]] = to;
1201   }
1202
1203   // Put the piece back at the source square
1204   Bitboard move_bb = make_move_bb(to, from);
1205   do_move_bb(&(byColorBB[us]), move_bb);
1206   do_move_bb(&(byTypeBB[pt]), move_bb);
1207   do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1208
1209   board[from] = make_piece(us, pt);
1210   board[to] = PIECE_NONE;
1211
1212   // Update piece list
1213   index[from] = index[to];
1214   pieceList[us][pt][index[from]] = from;
1215
1216   if (st->capturedType)
1217   {
1218       Square capsq = to;
1219
1220       if (ep)
1221           capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1222
1223       assert(st->capturedType != KING);
1224       assert(!ep || square_is_empty(capsq));
1225
1226       // Restore the captured piece
1227       set_bit(&(byColorBB[them]), capsq);
1228       set_bit(&(byTypeBB[st->capturedType]), capsq);
1229       set_bit(&(byTypeBB[0]), capsq);
1230
1231       board[capsq] = make_piece(them, st->capturedType);
1232
1233       // Update piece count
1234       pieceCount[them][st->capturedType]++;
1235
1236       // Update piece list, add a new captured piece in capsq square
1237       index[capsq] = pieceCount[them][st->capturedType] - 1;
1238       pieceList[them][st->capturedType][index[capsq]] = capsq;
1239   }
1240
1241   // Finally point our state pointer back to the previous state
1242   st = st->previous;
1243
1244   assert(is_ok());
1245 }
1246
1247
1248 /// Position::undo_castle_move() is a private method used to unmake a castling
1249 /// move. It is called from the main Position::undo_move function. Note that
1250 /// castling moves are encoded as "king captures friendly rook" moves, for
1251 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1252
1253 void Position::undo_castle_move(Move m) {
1254
1255   assert(move_is_ok(m));
1256   assert(move_is_castle(m));
1257
1258   // When we have arrived here, some work has already been done by
1259   // Position::undo_move.  In particular, the side to move has been switched,
1260   // so the code below is correct.
1261   Color us = side_to_move();
1262
1263   // Find source squares for king and rook
1264   Square kfrom = move_from(m);
1265   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1266   Square kto, rto;
1267
1268   // Find destination squares for king and rook
1269   if (rfrom > kfrom) // O-O
1270   {
1271       kto = relative_square(us, SQ_G1);
1272       rto = relative_square(us, SQ_F1);
1273   } else { // O-O-O
1274       kto = relative_square(us, SQ_C1);
1275       rto = relative_square(us, SQ_D1);
1276   }
1277
1278   assert(piece_on(kto) == make_piece(us, KING));
1279   assert(piece_on(rto) == make_piece(us, ROOK));
1280
1281   // Remove pieces from destination squares:
1282   clear_bit(&(byColorBB[us]), kto);
1283   clear_bit(&(byTypeBB[KING]), kto);
1284   clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1285   clear_bit(&(byColorBB[us]), rto);
1286   clear_bit(&(byTypeBB[ROOK]), rto);
1287   clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1288
1289   // Put pieces on source squares:
1290   set_bit(&(byColorBB[us]), kfrom);
1291   set_bit(&(byTypeBB[KING]), kfrom);
1292   set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1293   set_bit(&(byColorBB[us]), rfrom);
1294   set_bit(&(byTypeBB[ROOK]), rfrom);
1295   set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1296
1297   // Update board
1298   board[rto] = board[kto] = PIECE_NONE;
1299   board[rfrom] = make_piece(us, ROOK);
1300   board[kfrom] = make_piece(us, KING);
1301
1302   // Update piece lists
1303   pieceList[us][KING][index[kto]] = kfrom;
1304   pieceList[us][ROOK][index[rto]] = rfrom;
1305   int tmp = index[rto];  // In Chess960 could be rto == kfrom
1306   index[kfrom] = index[kto];
1307   index[rfrom] = tmp;
1308
1309   // Finally point our state pointer back to the previous state
1310   st = st->previous;
1311
1312   assert(is_ok());
1313 }
1314
1315
1316 /// Position::do_null_move makes() a "null move": It switches the side to move
1317 /// and updates the hash key without executing any move on the board.
1318
1319 void Position::do_null_move(StateInfo& backupSt) {
1320
1321   assert(is_ok());
1322   assert(!is_check());
1323
1324   // Back up the information necessary to undo the null move to the supplied
1325   // StateInfo object.
1326   // Note that differently from normal case here backupSt is actually used as
1327   // a backup storage not as a new state to be used.
1328   backupSt.key      = st->key;
1329   backupSt.epSquare = st->epSquare;
1330   backupSt.value    = st->value;
1331   backupSt.previous = st->previous;
1332   backupSt.pliesFromNull = st->pliesFromNull;
1333   st->previous = &backupSt;
1334
1335   // Save the current key to the history[] array, in order to be able to
1336   // detect repetition draws.
1337   history[st->gamePly++] = st->key;
1338
1339   // Update the necessary information
1340   if (st->epSquare != SQ_NONE)
1341       st->key ^= zobEp[st->epSquare];
1342
1343   st->key ^= zobSideToMove;
1344   prefetch((char*)TT.first_entry(st->key));
1345
1346   sideToMove = opposite_color(sideToMove);
1347   st->epSquare = SQ_NONE;
1348   st->rule50++;
1349   st->pliesFromNull = 0;
1350   st->value += (sideToMove == WHITE) ?  TempoValue : -TempoValue;
1351 }
1352
1353
1354 /// Position::undo_null_move() unmakes a "null move".
1355
1356 void Position::undo_null_move() {
1357
1358   assert(is_ok());
1359   assert(!is_check());
1360
1361   // Restore information from the our backup StateInfo object
1362   StateInfo* backupSt = st->previous;
1363   st->key      = backupSt->key;
1364   st->epSquare = backupSt->epSquare;
1365   st->value    = backupSt->value;
1366   st->previous = backupSt->previous;
1367   st->pliesFromNull = backupSt->pliesFromNull;
1368
1369   // Update the necessary information
1370   sideToMove = opposite_color(sideToMove);
1371   st->rule50--;
1372   st->gamePly--;
1373 }
1374
1375
1376 /// Position::see() is a static exchange evaluator: It tries to estimate the
1377 /// material gain or loss resulting from a move. There are three versions of
1378 /// this function: One which takes a destination square as input, one takes a
1379 /// move, and one which takes a 'from' and a 'to' square. The function does
1380 /// not yet understand promotions captures.
1381
1382 int Position::see(Move m) const {
1383
1384   assert(move_is_ok(m));
1385   return see(move_from(m), move_to(m));
1386 }
1387
1388 int Position::see_sign(Move m) const {
1389
1390   assert(move_is_ok(m));
1391
1392   Square from = move_from(m);
1393   Square to = move_to(m);
1394
1395   // Early return if SEE cannot be negative because captured piece value
1396   // is not less then capturing one. Note that king moves always return
1397   // here because king midgame value is set to 0.
1398   if (midgame_value_of_piece_on(to) >= midgame_value_of_piece_on(from))
1399       return 1;
1400
1401   return see(from, to);
1402 }
1403
1404 int Position::see(Square from, Square to) const {
1405
1406   Bitboard occupied, attackers, stmAttackers, b;
1407   int swapList[32], slIndex = 1;
1408   PieceType capturedType, pt;
1409   Color stm;
1410
1411   assert(square_is_ok(from));
1412   assert(square_is_ok(to));
1413
1414   capturedType = type_of_piece_on(to);
1415
1416   // King cannot be recaptured
1417   if (capturedType == KING)
1418       return seeValues[capturedType];
1419
1420   occupied = occupied_squares();
1421
1422   // Handle en passant moves
1423   if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1424   {
1425       Square capQq = (side_to_move() == WHITE ? to - DELTA_N : to - DELTA_S);
1426
1427       assert(capturedType == PIECE_TYPE_NONE);
1428       assert(type_of_piece_on(capQq) == PAWN);
1429
1430       // Remove the captured pawn
1431       clear_bit(&occupied, capQq);
1432       capturedType = PAWN;
1433   }
1434
1435   // Find all attackers to the destination square, with the moving piece
1436   // removed, but possibly an X-ray attacker added behind it.
1437   clear_bit(&occupied, from);
1438   attackers =  (rook_attacks_bb(to, occupied)  & pieces(ROOK, QUEEN))
1439              | (bishop_attacks_bb(to, occupied)& pieces(BISHOP, QUEEN))
1440              | (attacks_from<KNIGHT>(to)       & pieces(KNIGHT))
1441              | (attacks_from<KING>(to)         & pieces(KING))
1442              | (attacks_from<PAWN>(to, WHITE)  & pieces(PAWN, BLACK))
1443              | (attacks_from<PAWN>(to, BLACK)  & pieces(PAWN, WHITE));
1444
1445   // If the opponent has no attackers we are finished
1446   stm = opposite_color(color_of_piece_on(from));
1447   stmAttackers = attackers & pieces_of_color(stm);
1448   if (!stmAttackers)
1449       return seeValues[capturedType];
1450
1451   // The destination square is defended, which makes things rather more
1452   // difficult to compute. We proceed by building up a "swap list" containing
1453   // the material gain or loss at each stop in a sequence of captures to the
1454   // destination square, where the sides alternately capture, and always
1455   // capture with the least valuable piece. After each capture, we look for
1456   // new X-ray attacks from behind the capturing piece.
1457   swapList[0] = seeValues[capturedType];
1458   capturedType = type_of_piece_on(from);
1459
1460   do {
1461       // Locate the least valuable attacker for the side to move. The loop
1462       // below looks like it is potentially infinite, but it isn't. We know
1463       // that the side to move still has at least one attacker left.
1464       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1465           assert(pt < KING);
1466
1467       // Remove the attacker we just found from the 'occupied' bitboard,
1468       // and scan for new X-ray attacks behind the attacker.
1469       b = stmAttackers & pieces(pt);
1470       occupied ^= (b & (~b + 1));
1471       attackers |=  (rook_attacks_bb(to, occupied)   & pieces(ROOK, QUEEN))
1472                   | (bishop_attacks_bb(to, occupied) & pieces(BISHOP, QUEEN));
1473
1474       attackers &= occupied; // Cut out pieces we've already done
1475
1476       // Add the new entry to the swap list
1477       assert(slIndex < 32);
1478       swapList[slIndex] = -swapList[slIndex - 1] + seeValues[capturedType];
1479       slIndex++;
1480
1481       // Remember the value of the capturing piece, and change the side to
1482       // move before beginning the next iteration.
1483       capturedType = pt;
1484       stm = opposite_color(stm);
1485       stmAttackers = attackers & pieces_of_color(stm);
1486
1487       // Stop before processing a king capture
1488       if (capturedType == KING && stmAttackers)
1489       {
1490           assert(slIndex < 32);
1491           swapList[slIndex++] = QueenValueMidgame*10;
1492           break;
1493       }
1494   } while (stmAttackers);
1495
1496   // Having built the swap list, we negamax through it to find the best
1497   // achievable score from the point of view of the side to move.
1498   while (--slIndex)
1499       swapList[slIndex-1] = Min(-swapList[slIndex], swapList[slIndex-1]);
1500
1501   return swapList[0];
1502 }
1503
1504
1505 /// Position::clear() erases the position object to a pristine state, with an
1506 /// empty board, white to move, and no castling rights.
1507
1508 void Position::clear() {
1509
1510   st = &startState;
1511   memset(st, 0, sizeof(StateInfo));
1512   st->epSquare = SQ_NONE;
1513   startPosPlyCounter = 0;
1514   nodes = 0;
1515
1516   memset(byColorBB,  0, sizeof(Bitboard) * 2);
1517   memset(byTypeBB,   0, sizeof(Bitboard) * 8);
1518   memset(pieceCount, 0, sizeof(int) * 2 * 8);
1519   memset(index,      0, sizeof(int) * 64);
1520
1521   for (int i = 0; i < 64; i++)
1522       board[i] = PIECE_NONE;
1523
1524   for (int i = 0; i < 8; i++)
1525       for (int j = 0; j < 16; j++)
1526           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1527
1528   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1529       castleRightsMask[sq] = ALL_CASTLES;
1530
1531   sideToMove = WHITE;
1532   initialKFile = FILE_E;
1533   initialKRFile = FILE_H;
1534   initialQRFile = FILE_A;
1535 }
1536
1537
1538 /// Position::put_piece() puts a piece on the given square of the board,
1539 /// updating the board array, pieces list, bitboards, and piece counts.
1540
1541 void Position::put_piece(Piece p, Square s) {
1542
1543   Color c = color_of_piece(p);
1544   PieceType pt = type_of_piece(p);
1545
1546   board[s] = p;
1547   index[s] = pieceCount[c][pt]++;
1548   pieceList[c][pt][index[s]] = s;
1549
1550   set_bit(&(byTypeBB[pt]), s);
1551   set_bit(&(byColorBB[c]), s);
1552   set_bit(&(byTypeBB[0]), s); // HACK: byTypeBB[0] contains all occupied squares.
1553 }
1554
1555
1556 /// Position::compute_key() computes the hash key of the position. The hash
1557 /// key is usually updated incrementally as moves are made and unmade, the
1558 /// compute_key() function is only used when a new position is set up, and
1559 /// to verify the correctness of the hash key when running in debug mode.
1560
1561 Key Position::compute_key() const {
1562
1563   Key result = zobCastle[st->castleRights];
1564
1565   for (Square s = SQ_A1; s <= SQ_H8; s++)
1566       if (square_is_occupied(s))
1567           result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1568
1569   if (ep_square() != SQ_NONE)
1570       result ^= zobEp[ep_square()];
1571
1572   if (side_to_move() == BLACK)
1573       result ^= zobSideToMove;
1574
1575   return result;
1576 }
1577
1578
1579 /// Position::compute_pawn_key() computes the hash key of the position. The
1580 /// hash key is usually updated incrementally as moves are made and unmade,
1581 /// the compute_pawn_key() function is only used when a new position is set
1582 /// up, and to verify the correctness of the pawn hash key when running in
1583 /// debug mode.
1584
1585 Key Position::compute_pawn_key() const {
1586
1587   Bitboard b;
1588   Key result = 0;
1589
1590   for (Color c = WHITE; c <= BLACK; c++)
1591   {
1592       b = pieces(PAWN, c);
1593       while (b)
1594           result ^= zobrist[c][PAWN][pop_1st_bit(&b)];
1595   }
1596   return result;
1597 }
1598
1599
1600 /// Position::compute_material_key() computes the hash key of the position.
1601 /// The hash key is usually updated incrementally as moves are made and unmade,
1602 /// the compute_material_key() function is only used when a new position is set
1603 /// up, and to verify the correctness of the material hash key when running in
1604 /// debug mode.
1605
1606 Key Position::compute_material_key() const {
1607
1608   int count;
1609   Key result = 0;
1610
1611   for (Color c = WHITE; c <= BLACK; c++)
1612       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1613       {
1614           count = piece_count(c, pt);
1615           for (int i = 0; i < count; i++)
1616               result ^= zobrist[c][pt][i];
1617       }
1618   return result;
1619 }
1620
1621
1622 /// Position::compute_value() compute the incremental scores for the middle
1623 /// game and the endgame. These functions are used to initialize the incremental
1624 /// scores when a new position is set up, and to verify that the scores are correctly
1625 /// updated by do_move and undo_move when the program is running in debug mode.
1626 Score Position::compute_value() const {
1627
1628   Bitboard b;
1629   Score result = SCORE_ZERO;
1630
1631   for (Color c = WHITE; c <= BLACK; c++)
1632       for (PieceType pt = PAWN; pt <= KING; pt++)
1633       {
1634           b = pieces(pt, c);
1635           while (b)
1636               result += pst(c, pt, pop_1st_bit(&b));
1637       }
1638
1639   result += (side_to_move() == WHITE ? TempoValue / 2 : -TempoValue / 2);
1640   return result;
1641 }
1642
1643
1644 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1645 /// game material value for the given side. Material values are updated
1646 /// incrementally during the search, this function is only used while
1647 /// initializing a new Position object.
1648
1649 Value Position::compute_non_pawn_material(Color c) const {
1650
1651   Value result = VALUE_ZERO;
1652
1653   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1654       result += piece_count(c, pt) * PieceValueMidgame[pt];
1655
1656   return result;
1657 }
1658
1659
1660 /// Position::is_draw() tests whether the position is drawn by material,
1661 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1662 /// must be done by the search.
1663
1664 bool Position::is_draw() const {
1665
1666   // Draw by material?
1667   if (   !pieces(PAWN)
1668       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1669       return true;
1670
1671   // Draw by the 50 moves rule?
1672   if (st->rule50 > 99 && !is_mate())
1673       return true;
1674
1675   // Draw by repetition?
1676   for (int i = 4, e = Min(Min(st->gamePly, st->rule50), st->pliesFromNull); i <= e; i += 2)
1677       if (history[st->gamePly - i] == st->key)
1678           return true;
1679
1680   return false;
1681 }
1682
1683
1684 /// Position::is_mate() returns true or false depending on whether the
1685 /// side to move is checkmated.
1686
1687 bool Position::is_mate() const {
1688
1689   MoveStack moves[MOVES_MAX];
1690   return is_check() && generate<MV_LEGAL>(*this, moves) == moves;
1691 }
1692
1693
1694 /// Position::init_zobrist() is a static member function which initializes at
1695 /// startup the various arrays used to compute hash keys.
1696
1697 void Position::init_zobrist() {
1698
1699   int i,j, k;
1700   RKISS rk;
1701
1702   for (i = 0; i < 2; i++) for (j = 0; j < 8; j++) for (k = 0; k < 64; k++)
1703       zobrist[i][j][k] = rk.rand<Key>();
1704
1705   for (i = 0; i < 64; i++)
1706       zobEp[i] = rk.rand<Key>();
1707
1708   for (i = 0; i < 16; i++)
1709       zobCastle[i] = rk.rand<Key>();
1710
1711   zobSideToMove = rk.rand<Key>();
1712   zobExclusion  = rk.rand<Key>();
1713 }
1714
1715
1716 /// Position::init_piece_square_tables() initializes the piece square tables.
1717 /// This is a two-step operation: First, the white halves of the tables are
1718 /// copied from the MgPST[][] and EgPST[][] arrays. Second, the black halves
1719 /// of the tables are initialized by mirroring and changing the sign of the
1720 /// corresponding white scores.
1721
1722 void Position::init_piece_square_tables() {
1723
1724   for (Square s = SQ_A1; s <= SQ_H8; s++)
1725       for (Piece p = WP; p <= WK; p++)
1726           PieceSquareTable[p][s] = make_score(MgPST[p][s], EgPST[p][s]);
1727
1728   for (Square s = SQ_A1; s <= SQ_H8; s++)
1729       for (Piece p = BP; p <= BK; p++)
1730           PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1731 }
1732
1733
1734 /// Position::flipped_copy() makes a copy of the input position, but with
1735 /// the white and black sides reversed. This is only useful for debugging,
1736 /// especially for finding evaluation symmetry bugs.
1737
1738 void Position::flipped_copy(const Position& pos) {
1739
1740   assert(pos.is_ok());
1741
1742   clear();
1743   threadID = pos.thread();
1744
1745   // Board
1746   for (Square s = SQ_A1; s <= SQ_H8; s++)
1747       if (!pos.square_is_empty(s))
1748           put_piece(Piece(pos.piece_on(s) ^ 8), flip_square(s));
1749
1750   // Side to move
1751   sideToMove = opposite_color(pos.side_to_move());
1752
1753   // Castling rights
1754   if (pos.can_castle_kingside(WHITE))  do_allow_oo(BLACK);
1755   if (pos.can_castle_queenside(WHITE)) do_allow_ooo(BLACK);
1756   if (pos.can_castle_kingside(BLACK))  do_allow_oo(WHITE);
1757   if (pos.can_castle_queenside(BLACK)) do_allow_ooo(WHITE);
1758
1759   initialKFile  = pos.initialKFile;
1760   initialKRFile = pos.initialKRFile;
1761   initialQRFile = pos.initialQRFile;
1762
1763   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1764   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1765   castleRightsMask[make_square(initialKRFile, RANK_1)] ^=  WHITE_OO;
1766   castleRightsMask[make_square(initialKRFile, RANK_8)] ^=  BLACK_OO;
1767   castleRightsMask[make_square(initialQRFile, RANK_1)] ^=  WHITE_OOO;
1768   castleRightsMask[make_square(initialQRFile, RANK_8)] ^=  BLACK_OOO;
1769
1770   // En passant square
1771   if (pos.st->epSquare != SQ_NONE)
1772       st->epSquare = flip_square(pos.st->epSquare);
1773
1774   // Checkers
1775   find_checkers();
1776
1777   // Hash keys
1778   st->key = compute_key();
1779   st->pawnKey = compute_pawn_key();
1780   st->materialKey = compute_material_key();
1781
1782   // Incremental scores
1783   st->value = compute_value();
1784
1785   // Material
1786   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1787   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1788
1789   assert(is_ok());
1790 }
1791
1792
1793 /// Position::is_ok() performs some consitency checks for the position object.
1794 /// This is meant to be helpful when debugging.
1795
1796 bool Position::is_ok(int* failedStep) const {
1797
1798   // What features of the position should be verified?
1799   const bool debugAll = false;
1800
1801   const bool debugBitboards       = debugAll || false;
1802   const bool debugKingCount       = debugAll || false;
1803   const bool debugKingCapture     = debugAll || false;
1804   const bool debugCheckerCount    = debugAll || false;
1805   const bool debugKey             = debugAll || false;
1806   const bool debugMaterialKey     = debugAll || false;
1807   const bool debugPawnKey         = debugAll || false;
1808   const bool debugIncrementalEval = debugAll || false;
1809   const bool debugNonPawnMaterial = debugAll || false;
1810   const bool debugPieceCounts     = debugAll || false;
1811   const bool debugPieceList       = debugAll || false;
1812   const bool debugCastleSquares   = debugAll || false;
1813
1814   if (failedStep) *failedStep = 1;
1815
1816   // Side to move OK?
1817   if (!color_is_ok(side_to_move()))
1818       return false;
1819
1820   // Are the king squares in the position correct?
1821   if (failedStep) (*failedStep)++;
1822   if (piece_on(king_square(WHITE)) != WK)
1823       return false;
1824
1825   if (failedStep) (*failedStep)++;
1826   if (piece_on(king_square(BLACK)) != BK)
1827       return false;
1828
1829   // Castle files OK?
1830   if (failedStep) (*failedStep)++;
1831   if (!file_is_ok(initialKRFile))
1832       return false;
1833
1834   if (!file_is_ok(initialQRFile))
1835       return false;
1836
1837   // Do both sides have exactly one king?
1838   if (failedStep) (*failedStep)++;
1839   if (debugKingCount)
1840   {
1841       int kingCount[2] = {0, 0};
1842       for (Square s = SQ_A1; s <= SQ_H8; s++)
1843           if (type_of_piece_on(s) == KING)
1844               kingCount[color_of_piece_on(s)]++;
1845
1846       if (kingCount[0] != 1 || kingCount[1] != 1)
1847           return false;
1848   }
1849
1850   // Can the side to move capture the opponent's king?
1851   if (failedStep) (*failedStep)++;
1852   if (debugKingCapture)
1853   {
1854       Color us = side_to_move();
1855       Color them = opposite_color(us);
1856       Square ksq = king_square(them);
1857       if (attackers_to(ksq) & pieces_of_color(us))
1858           return false;
1859   }
1860
1861   // Is there more than 2 checkers?
1862   if (failedStep) (*failedStep)++;
1863   if (debugCheckerCount && count_1s<CNT32>(st->checkersBB) > 2)
1864       return false;
1865
1866   // Bitboards OK?
1867   if (failedStep) (*failedStep)++;
1868   if (debugBitboards)
1869   {
1870       // The intersection of the white and black pieces must be empty
1871       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1872           return false;
1873
1874       // The union of the white and black pieces must be equal to all
1875       // occupied squares
1876       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1877           return false;
1878
1879       // Separate piece type bitboards must have empty intersections
1880       for (PieceType p1 = PAWN; p1 <= KING; p1++)
1881           for (PieceType p2 = PAWN; p2 <= KING; p2++)
1882               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1883                   return false;
1884   }
1885
1886   // En passant square OK?
1887   if (failedStep) (*failedStep)++;
1888   if (ep_square() != SQ_NONE)
1889   {
1890       // The en passant square must be on rank 6, from the point of view of the
1891       // side to move.
1892       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1893           return false;
1894   }
1895
1896   // Hash key OK?
1897   if (failedStep) (*failedStep)++;
1898   if (debugKey && st->key != compute_key())
1899       return false;
1900
1901   // Pawn hash key OK?
1902   if (failedStep) (*failedStep)++;
1903   if (debugPawnKey && st->pawnKey != compute_pawn_key())
1904       return false;
1905
1906   // Material hash key OK?
1907   if (failedStep) (*failedStep)++;
1908   if (debugMaterialKey && st->materialKey != compute_material_key())
1909       return false;
1910
1911   // Incremental eval OK?
1912   if (failedStep) (*failedStep)++;
1913   if (debugIncrementalEval && st->value != compute_value())
1914       return false;
1915
1916   // Non-pawn material OK?
1917   if (failedStep) (*failedStep)++;
1918   if (debugNonPawnMaterial)
1919   {
1920       if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1921           return false;
1922
1923       if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1924           return false;
1925   }
1926
1927   // Piece counts OK?
1928   if (failedStep) (*failedStep)++;
1929   if (debugPieceCounts)
1930       for (Color c = WHITE; c <= BLACK; c++)
1931           for (PieceType pt = PAWN; pt <= KING; pt++)
1932               if (pieceCount[c][pt] != count_1s<CNT32>(pieces(pt, c)))
1933                   return false;
1934
1935   if (failedStep) (*failedStep)++;
1936   if (debugPieceList)
1937       for (Color c = WHITE; c <= BLACK; c++)
1938           for (PieceType pt = PAWN; pt <= KING; pt++)
1939               for (int i = 0; i < pieceCount[c][pt]; i++)
1940               {
1941                   if (piece_on(piece_list(c, pt, i)) != make_piece(c, pt))
1942                       return false;
1943
1944                   if (index[piece_list(c, pt, i)] != i)
1945                       return false;
1946               }
1947
1948   if (failedStep) (*failedStep)++;
1949   if (debugCastleSquares)
1950   {
1951       for (Color c = WHITE; c <= BLACK; c++)
1952       {
1953           if (can_castle_kingside(c) && piece_on(initial_kr_square(c)) != make_piece(c, ROOK))
1954               return false;
1955
1956           if (can_castle_queenside(c) && piece_on(initial_qr_square(c)) != make_piece(c, ROOK))
1957               return false;
1958       }
1959       if (castleRightsMask[initial_kr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OO))
1960           return false;
1961       if (castleRightsMask[initial_qr_square(WHITE)] != (ALL_CASTLES ^ WHITE_OOO))
1962           return false;
1963       if (castleRightsMask[initial_kr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OO))
1964           return false;
1965       if (castleRightsMask[initial_qr_square(BLACK)] != (ALL_CASTLES ^ BLACK_OOO))
1966           return false;
1967   }
1968
1969   if (failedStep) *failedStep = 0;
1970   return true;
1971 }