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