]> git.sesse.net Git - stockfish/blob - src/position.cpp
b6c0a522e204edb3889e02d26036932d1e7da3d7
[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 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
762   assert(color_of_piece_on(from) == us);
763   assert(color_of_piece_on(to) == them || square_is_empty(to));
764   assert(!(ep || pm) || piece == piece_of_color_and_type(us, PAWN));
765   assert(!pm || relative_rank(us, to) == RANK_8);
766
767   st->capture = ep ? PAWN : type_of_piece_on(to);
768
769   if (st->capture)
770       do_capture_move(key, st->capture, them, to, ep);
771
772   // Update hash key
773   key ^= zobrist[us][pt][from] ^ zobrist[us][pt][to];
774
775   // Reset en passant square
776   if (st->epSquare != SQ_NONE)
777   {
778       key ^= zobEp[st->epSquare];
779       st->epSquare = SQ_NONE;
780   }
781
782   // Update castle rights, try to shortcut a common case
783   int cm = castleRightsMask[from] & castleRightsMask[to];
784   if (cm != ALL_CASTLES && ((cm & st->castleRights) != st->castleRights))
785   {
786       key ^= zobCastle[st->castleRights];
787       st->castleRights &= castleRightsMask[from];
788       st->castleRights &= castleRightsMask[to];
789       key ^= zobCastle[st->castleRights];
790   }
791
792   // Prefetch TT access as soon as we know key is updated
793   TT.prefetch(key);
794
795   // Move the piece
796   Bitboard move_bb = make_move_bb(from, to);
797   do_move_bb(&(byColorBB[us]), move_bb);
798   do_move_bb(&(byTypeBB[pt]), move_bb);
799   do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
800
801   board[to] = board[from];
802   board[from] = EMPTY;
803
804   // Update piece lists, note that index[from] is not updated and
805   // becomes stale. This works as long as index[] is accessed just
806   // by known occupied squares.
807   index[to] = index[from];
808   pieceList[us][pt][index[to]] = to;
809
810   // If the moving piece was a pawn do some special extra work
811   if (pt == PAWN)
812   {
813       // Reset rule 50 draw counter
814       st->rule50 = 0;
815
816       // Update pawn hash key
817       st->pawnKey ^= zobrist[us][PAWN][from] ^ zobrist[us][PAWN][to];
818
819       // Set en passant square, only if moved pawn can be captured
820       if (abs(int(to) - int(from)) == 16)
821       {
822           if (attacks_from<PAWN>(from + (us == WHITE ? DELTA_N : DELTA_S), us) & pieces(PAWN, them))
823           {
824               st->epSquare = Square((int(from) + int(to)) / 2);
825               key ^= zobEp[st->epSquare];
826           }
827       }
828   }
829
830   // Update incremental scores
831   st->value += pst_delta(piece, from, to);
832
833   if (pm) // promotion ?
834   {
835       PieceType promotion = move_promotion_piece(m);
836
837       assert(promotion >= KNIGHT && promotion <= QUEEN);
838
839       // Insert promoted piece instead of pawn
840       clear_bit(&(byTypeBB[PAWN]), to);
841       set_bit(&(byTypeBB[promotion]), to);
842       board[to] = piece_of_color_and_type(us, promotion);
843
844       // Update material key
845       st->materialKey ^= zobMaterial[us][PAWN][pieceCount[us][PAWN]];
846       st->materialKey ^= zobMaterial[us][promotion][pieceCount[us][promotion]+1];
847
848       // Update piece counts
849       pieceCount[us][PAWN]--;
850       pieceCount[us][promotion]++;
851
852       // Update piece lists, move the last pawn at index[to] position
853       // and shrink the list. Add a new promotion piece to the list.
854       Square lastPawnSquare = pieceList[us][PAWN][pieceCount[us][PAWN]];
855       index[lastPawnSquare] = index[to];
856       pieceList[us][PAWN][index[lastPawnSquare]] = lastPawnSquare;
857       pieceList[us][PAWN][pieceCount[us][PAWN]] = SQ_NONE;
858       index[to] = pieceCount[us][promotion] - 1;
859       pieceList[us][promotion][index[to]] = to;
860
861       // Partially revert hash keys update
862       key ^= zobrist[us][PAWN][to] ^ zobrist[us][promotion][to];
863       st->pawnKey ^= zobrist[us][PAWN][to];
864
865       // Partially revert and update incremental scores
866       st->value -= pst(us, PAWN, to);
867       st->value += pst(us, promotion, to);
868
869       // Update material
870       st->npMaterial[us] += piece_value_midgame(promotion);
871   }
872
873   // Update the key with the final value
874   st->key = key;
875
876   // Update checkers bitboard, piece must be already moved
877   if (ep | pm)
878       st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
879   else
880   {
881       st->checkersBB = EmptyBoardBB;
882       Square ksq = king_square(them);
883       switch (pt)
884       {
885       case PAWN:   update_checkers<PAWN>(&(st->checkersBB), ksq, from, to, dcCandidates);   break;
886       case KNIGHT: update_checkers<KNIGHT>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
887       case BISHOP: update_checkers<BISHOP>(&(st->checkersBB), ksq, from, to, dcCandidates); break;
888       case ROOK:   update_checkers<ROOK>(&(st->checkersBB), ksq, from, to, dcCandidates);   break;
889       case QUEEN:  update_checkers<QUEEN>(&(st->checkersBB), ksq, from, to, dcCandidates);  break;
890       case KING:   update_checkers<KING>(&(st->checkersBB), ksq, from, to, dcCandidates);   break;
891       default: assert(false); break;
892       }
893   }
894
895   // Finish
896   sideToMove = opposite_color(sideToMove);
897   st->value += (sideToMove == WHITE) ?  TempoValue : -TempoValue;
898
899   assert(is_ok());
900 }
901
902
903 /// Position::do_capture_move() is a private method used to update captured
904 /// piece info. It is called from the main Position::do_move function.
905
906 void Position::do_capture_move(Bitboard& key, PieceType capture, Color them, Square to, bool ep) {
907
908     assert(capture != KING);
909
910     Square capsq = to;
911
912     if (ep) // en passant ?
913     {
914         capsq = (them == BLACK)? (to - DELTA_N) : (to - DELTA_S);
915
916         assert(to == st->epSquare);
917         assert(relative_rank(opposite_color(them), to) == RANK_6);
918         assert(piece_on(to) == EMPTY);
919         assert(piece_on(capsq) == piece_of_color_and_type(them, PAWN));
920
921         board[capsq] = EMPTY;
922     }
923
924     // Remove captured piece
925     clear_bit(&(byColorBB[them]), capsq);
926     clear_bit(&(byTypeBB[capture]), capsq);
927     clear_bit(&(byTypeBB[0]), capsq);
928
929     // Update hash key
930     key ^= zobrist[them][capture][capsq];
931
932     // Update incremental scores
933     st->value -= pst(them, capture, capsq);
934
935     // If the captured piece was a pawn, update pawn hash key,
936     // otherwise update non-pawn material.
937     if (capture == PAWN)
938         st->pawnKey ^= zobrist[them][PAWN][capsq];
939     else
940         st->npMaterial[them] -= piece_value_midgame(capture);
941
942     // Update material hash key
943     st->materialKey ^= zobMaterial[them][capture][pieceCount[them][capture]];
944
945     // Update piece count
946     pieceCount[them][capture]--;
947
948     // Update piece list, move the last piece at index[capsq] position
949     //
950     // WARNING: This is a not perfectly revresible operation. When we
951     // will reinsert the captured piece in undo_move() we will put it
952     // at the end of the list and not in its original place, it means
953     // index[] and pieceList[] are not guaranteed to be invariant to a
954     // do_move() + undo_move() sequence.
955     Square lastPieceSquare = pieceList[them][capture][pieceCount[them][capture]];
956     index[lastPieceSquare] = index[capsq];
957     pieceList[them][capture][index[lastPieceSquare]] = lastPieceSquare;
958     pieceList[them][capture][pieceCount[them][capture]] = SQ_NONE;
959
960     // Reset rule 50 counter
961     st->rule50 = 0;
962 }
963
964
965 /// Position::do_castle_move() is a private method used to make a castling
966 /// move. It is called from the main Position::do_move function. Note that
967 /// castling moves are encoded as "king captures friendly rook" moves, for
968 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
969
970 void Position::do_castle_move(Move m) {
971
972   assert(move_is_ok(m));
973   assert(move_is_castle(m));
974
975   Color us = side_to_move();
976   Color them = opposite_color(us);
977
978   // Reset capture field
979   st->capture = NO_PIECE_TYPE;
980
981   // Find source squares for king and rook
982   Square kfrom = move_from(m);
983   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
984   Square kto, rto;
985
986   assert(piece_on(kfrom) == piece_of_color_and_type(us, KING));
987   assert(piece_on(rfrom) == piece_of_color_and_type(us, ROOK));
988
989   // Find destination squares for king and rook
990   if (rfrom > kfrom) // O-O
991   {
992       kto = relative_square(us, SQ_G1);
993       rto = relative_square(us, SQ_F1);
994   } else { // O-O-O
995       kto = relative_square(us, SQ_C1);
996       rto = relative_square(us, SQ_D1);
997   }
998
999   // Remove pieces from source squares:
1000   clear_bit(&(byColorBB[us]), kfrom);
1001   clear_bit(&(byTypeBB[KING]), kfrom);
1002   clear_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1003   clear_bit(&(byColorBB[us]), rfrom);
1004   clear_bit(&(byTypeBB[ROOK]), rfrom);
1005   clear_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1006
1007   // Put pieces on destination squares:
1008   set_bit(&(byColorBB[us]), kto);
1009   set_bit(&(byTypeBB[KING]), kto);
1010   set_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1011   set_bit(&(byColorBB[us]), rto);
1012   set_bit(&(byTypeBB[ROOK]), rto);
1013   set_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1014   
1015   // Update board array
1016   Piece king = piece_of_color_and_type(us, KING);
1017   Piece rook = piece_of_color_and_type(us, ROOK);
1018   board[kfrom] = board[rfrom] = EMPTY;
1019   board[kto] = king;
1020   board[rto] = rook;
1021
1022   // Update piece lists
1023   pieceList[us][KING][index[kfrom]] = kto;
1024   pieceList[us][ROOK][index[rfrom]] = rto;
1025   int tmp = index[rfrom]; // In Chess960 could be rto == kfrom
1026   index[kto] = index[kfrom];
1027   index[rto] = tmp;
1028
1029   // Update incremental scores
1030   st->value += pst_delta(king, kfrom, kto);
1031   st->value += pst_delta(rook, rfrom, rto);
1032
1033   // Update hash key
1034   st->key ^= zobrist[us][KING][kfrom] ^ zobrist[us][KING][kto];
1035   st->key ^= zobrist[us][ROOK][rfrom] ^ zobrist[us][ROOK][rto];
1036
1037   // Clear en passant square
1038   if (st->epSquare != SQ_NONE)
1039   {
1040       st->key ^= zobEp[st->epSquare];
1041       st->epSquare = SQ_NONE;
1042   }
1043
1044   // Update castling rights
1045   st->key ^= zobCastle[st->castleRights];
1046   st->castleRights &= castleRightsMask[kfrom];
1047   st->key ^= zobCastle[st->castleRights];
1048
1049   // Reset rule 50 counter
1050   st->rule50 = 0;
1051
1052   // Update checkers BB
1053   st->checkersBB = attackers_to(king_square(them)) & pieces_of_color(us);
1054
1055   // Finish
1056   sideToMove = opposite_color(sideToMove);
1057   st->value += (sideToMove == WHITE) ?  TempoValue : -TempoValue;
1058
1059   assert(is_ok());
1060 }
1061
1062
1063 /// Position::undo_move() unmakes a move. When it returns, the position should
1064 /// be restored to exactly the same state as before the move was made.
1065
1066 void Position::undo_move(Move m) {
1067
1068   assert(is_ok());
1069   assert(move_is_ok(m));
1070
1071   gamePly--;
1072   sideToMove = opposite_color(sideToMove);
1073
1074   if (move_is_castle(m))
1075   {
1076       undo_castle_move(m);
1077       return;
1078   }
1079
1080   Color us = side_to_move();
1081   Color them = opposite_color(us);
1082   Square from = move_from(m);
1083   Square to = move_to(m);
1084   bool ep = move_is_ep(m);
1085   bool pm = move_is_promotion(m);
1086
1087   PieceType pt = type_of_piece_on(to);
1088
1089   assert(square_is_empty(from));
1090   assert(color_of_piece_on(to) == us);
1091   assert(!pm || relative_rank(us, to) == RANK_8);
1092   assert(!ep || to == st->previous->epSquare);
1093   assert(!ep || relative_rank(us, to) == RANK_6);
1094   assert(!ep || piece_on(to) == piece_of_color_and_type(us, PAWN));
1095
1096   if (pm) // promotion ?
1097   {
1098       PieceType promotion = move_promotion_piece(m);
1099       pt = PAWN;
1100
1101       assert(promotion >= KNIGHT && promotion <= QUEEN);
1102       assert(piece_on(to) == piece_of_color_and_type(us, promotion));
1103
1104       // Replace promoted piece with a pawn
1105       clear_bit(&(byTypeBB[promotion]), to);
1106       set_bit(&(byTypeBB[PAWN]), to);
1107
1108       // Update piece counts
1109       pieceCount[us][promotion]--;
1110       pieceCount[us][PAWN]++;
1111
1112       // Update piece list replacing promotion piece with a pawn
1113       Square lastPromotionSquare = pieceList[us][promotion][pieceCount[us][promotion]];
1114       index[lastPromotionSquare] = index[to];
1115       pieceList[us][promotion][index[lastPromotionSquare]] = lastPromotionSquare;
1116       pieceList[us][promotion][pieceCount[us][promotion]] = SQ_NONE;
1117       index[to] = pieceCount[us][PAWN] - 1;
1118       pieceList[us][PAWN][index[to]] = to;
1119   }
1120
1121
1122   // Put the piece back at the source square
1123   Bitboard move_bb = make_move_bb(to, from);
1124   do_move_bb(&(byColorBB[us]), move_bb);
1125   do_move_bb(&(byTypeBB[pt]), move_bb);
1126   do_move_bb(&(byTypeBB[0]), move_bb); // HACK: byTypeBB[0] == occupied squares
1127
1128   board[from] = piece_of_color_and_type(us, pt);
1129   board[to] = EMPTY;
1130
1131   // Update piece list
1132   index[from] = index[to];
1133   pieceList[us][pt][index[from]] = from;
1134
1135   if (st->capture)
1136   {
1137       Square capsq = to;
1138
1139       if (ep)
1140           capsq = (us == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1141
1142       assert(st->capture != KING);
1143       assert(!ep || square_is_empty(capsq));
1144
1145       // Restore the captured piece
1146       set_bit(&(byColorBB[them]), capsq);
1147       set_bit(&(byTypeBB[st->capture]), capsq);
1148       set_bit(&(byTypeBB[0]), capsq);
1149
1150       board[capsq] = piece_of_color_and_type(them, st->capture);
1151
1152       // Update piece count
1153       pieceCount[them][st->capture]++;
1154
1155       // Update piece list, add a new captured piece in capsq square
1156       index[capsq] = pieceCount[them][st->capture] - 1;
1157       pieceList[them][st->capture][index[capsq]] = capsq;
1158   }
1159
1160   // Finally point our state pointer back to the previous state
1161   st = st->previous;
1162
1163   assert(is_ok());
1164 }
1165
1166
1167 /// Position::undo_castle_move() is a private method used to unmake a castling
1168 /// move. It is called from the main Position::undo_move function. Note that
1169 /// castling moves are encoded as "king captures friendly rook" moves, for
1170 /// instance white short castling in a non-Chess960 game is encoded as e1h1.
1171
1172 void Position::undo_castle_move(Move m) {
1173
1174   assert(move_is_ok(m));
1175   assert(move_is_castle(m));
1176
1177   // When we have arrived here, some work has already been done by
1178   // Position::undo_move.  In particular, the side to move has been switched,
1179   // so the code below is correct.
1180   Color us = side_to_move();
1181
1182   // Find source squares for king and rook
1183   Square kfrom = move_from(m);
1184   Square rfrom = move_to(m);  // HACK: See comment at beginning of function
1185   Square kto, rto;
1186
1187   // Find destination squares for king and rook
1188   if (rfrom > kfrom) // O-O
1189   {
1190       kto = relative_square(us, SQ_G1);
1191       rto = relative_square(us, SQ_F1);
1192   } else { // O-O-O
1193       kto = relative_square(us, SQ_C1);
1194       rto = relative_square(us, SQ_D1);
1195   }
1196
1197   assert(piece_on(kto) == piece_of_color_and_type(us, KING));
1198   assert(piece_on(rto) == piece_of_color_and_type(us, ROOK));
1199   
1200   // Remove pieces from destination squares:
1201   clear_bit(&(byColorBB[us]), kto);
1202   clear_bit(&(byTypeBB[KING]), kto);
1203   clear_bit(&(byTypeBB[0]), kto); // HACK: byTypeBB[0] == occupied squares
1204   clear_bit(&(byColorBB[us]), rto);
1205   clear_bit(&(byTypeBB[ROOK]), rto);
1206   clear_bit(&(byTypeBB[0]), rto); // HACK: byTypeBB[0] == occupied squares
1207  
1208   // Put pieces on source squares:
1209   set_bit(&(byColorBB[us]), kfrom);
1210   set_bit(&(byTypeBB[KING]), kfrom);
1211   set_bit(&(byTypeBB[0]), kfrom); // HACK: byTypeBB[0] == occupied squares
1212   set_bit(&(byColorBB[us]), rfrom);
1213   set_bit(&(byTypeBB[ROOK]), rfrom);
1214   set_bit(&(byTypeBB[0]), rfrom); // HACK: byTypeBB[0] == occupied squares
1215
1216   // Update board
1217   board[rto] = board[kto] = EMPTY;
1218   board[rfrom] = piece_of_color_and_type(us, ROOK);
1219   board[kfrom] = piece_of_color_and_type(us, KING);
1220
1221   // Update piece lists
1222   pieceList[us][KING][index[kto]] = kfrom;
1223   pieceList[us][ROOK][index[rto]] = rfrom;
1224   int tmp = index[rto];  // In Chess960 could be rto == kfrom
1225   index[kfrom] = index[kto];
1226   index[rfrom] = tmp;
1227
1228   // Finally point our state pointer back to the previous state
1229   st = st->previous;
1230
1231   assert(is_ok());
1232 }
1233
1234
1235 /// Position::do_null_move makes() a "null move": It switches the side to move
1236 /// and updates the hash key without executing any move on the board.
1237
1238 void Position::do_null_move(StateInfo& backupSt) {
1239
1240   assert(is_ok());
1241   assert(!is_check());
1242
1243   // Back up the information necessary to undo the null move to the supplied
1244   // StateInfo object.
1245   // Note that differently from normal case here backupSt is actually used as
1246   // a backup storage not as a new state to be used.
1247   backupSt.key      = st->key;
1248   backupSt.epSquare = st->epSquare;
1249   backupSt.value    = st->value;
1250   backupSt.previous = st->previous;
1251   backupSt.pliesFromNull = st->pliesFromNull;
1252   st->previous = &backupSt;
1253
1254   // Save the current key to the history[] array, in order to be able to
1255   // detect repetition draws.
1256   history[gamePly] = st->key;
1257
1258   // Update the necessary information
1259   if (st->epSquare != SQ_NONE)
1260       st->key ^= zobEp[st->epSquare];
1261
1262   st->key ^= zobSideToMove;
1263   TT.prefetch(st->key);
1264
1265   sideToMove = opposite_color(sideToMove);
1266   st->epSquare = SQ_NONE;
1267   st->rule50++;
1268   st->pliesFromNull = 0;
1269   st->value += (sideToMove == WHITE) ?  TempoValue : -TempoValue;
1270   gamePly++;
1271 }
1272
1273
1274 /// Position::undo_null_move() unmakes a "null move".
1275
1276 void Position::undo_null_move() {
1277
1278   assert(is_ok());
1279   assert(!is_check());
1280
1281   // Restore information from the our backup StateInfo object
1282   StateInfo* backupSt = st->previous;
1283   st->key      = backupSt->key;
1284   st->epSquare = backupSt->epSquare;
1285   st->value    = backupSt->value;
1286   st->previous = backupSt->previous;
1287   st->pliesFromNull = backupSt->pliesFromNull;
1288
1289   // Update the necessary information
1290   sideToMove = opposite_color(sideToMove);
1291   st->rule50--;
1292   gamePly--;
1293 }
1294
1295
1296 /// Position::see() is a static exchange evaluator: It tries to estimate the
1297 /// material gain or loss resulting from a move. There are three versions of
1298 /// this function: One which takes a destination square as input, one takes a
1299 /// move, and one which takes a 'from' and a 'to' square. The function does
1300 /// not yet understand promotions captures.
1301
1302 int Position::see(Square to) const {
1303
1304   assert(square_is_ok(to));
1305   return see(SQ_NONE, to);
1306 }
1307
1308 int Position::see(Move m) const {
1309
1310   assert(move_is_ok(m));
1311   return see(move_from(m), move_to(m));
1312 }
1313
1314 int Position::see_sign(Move m) const {
1315
1316   assert(move_is_ok(m));
1317
1318   Square from = move_from(m);
1319   Square to = move_to(m);
1320
1321   // Early return if SEE cannot be negative because capturing piece value
1322   // is not bigger then captured one.
1323   if (   midgame_value_of_piece_on(from) <= midgame_value_of_piece_on(to)
1324       && type_of_piece_on(from) != KING)
1325          return 1;
1326
1327   return see(from, to);
1328 }
1329
1330 int Position::see(Square from, Square to) const {
1331
1332   // Material values
1333   static const int seeValues[18] = {
1334     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1335        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1336     0, PawnValueMidgame, KnightValueMidgame, BishopValueMidgame,
1337        RookValueMidgame, QueenValueMidgame, QueenValueMidgame*10, 0,
1338     0, 0
1339   };
1340
1341   Bitboard attackers, stmAttackers, b;
1342
1343   assert(square_is_ok(from) || from == SQ_NONE);
1344   assert(square_is_ok(to));
1345
1346   // Initialize colors
1347   Color us = (from != SQ_NONE ? color_of_piece_on(from) : opposite_color(color_of_piece_on(to)));
1348   Color them = opposite_color(us);
1349
1350   // Initialize pieces
1351   Piece piece = piece_on(from);
1352   Piece capture = piece_on(to);
1353   Bitboard occ = occupied_squares();
1354
1355   // King cannot be recaptured
1356   if (type_of_piece(piece) == KING)
1357       return seeValues[capture];
1358
1359   // Handle en passant moves
1360   if (st->epSquare == to && type_of_piece_on(from) == PAWN)
1361   {
1362       assert(capture == EMPTY);
1363
1364       Square capQq = (side_to_move() == WHITE)? (to - DELTA_N) : (to - DELTA_S);
1365       capture = piece_on(capQq);
1366       assert(type_of_piece_on(capQq) == PAWN);
1367
1368       // Remove the captured pawn
1369       clear_bit(&occ, capQq);
1370   }
1371
1372   while (true)
1373   {
1374       // Find all attackers to the destination square, with the moving piece
1375       // removed, but possibly an X-ray attacker added behind it.
1376       clear_bit(&occ, from);
1377       attackers =  (rook_attacks_bb(to, occ)      & pieces(ROOK, QUEEN))
1378                  | (bishop_attacks_bb(to, occ)    & pieces(BISHOP, QUEEN))
1379                  | (attacks_from<KNIGHT>(to)      & pieces(KNIGHT))
1380                  | (attacks_from<KING>(to)        & pieces(KING))
1381                  | (attacks_from<PAWN>(to, WHITE) & pieces(PAWN, BLACK))
1382                  | (attacks_from<PAWN>(to, BLACK) & pieces(PAWN, WHITE));
1383
1384       if (from != SQ_NONE)
1385           break;
1386
1387       // If we don't have any attacker we are finished
1388       if ((attackers & pieces_of_color(us)) == EmptyBoardBB)
1389           return 0;
1390
1391       // Locate the least valuable attacker to the destination square
1392       // and use it to initialize from square.
1393       stmAttackers = attackers & pieces_of_color(us);
1394       PieceType pt;
1395       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1396           assert(pt < KING);
1397
1398       from = first_1(stmAttackers & pieces(pt));
1399       piece = piece_on(from);
1400   }
1401
1402   // If the opponent has no attackers we are finished
1403   stmAttackers = attackers & pieces_of_color(them);
1404   if (!stmAttackers)
1405       return seeValues[capture];
1406
1407   attackers &= occ; // Remove the moving piece
1408
1409   // The destination square is defended, which makes things rather more
1410   // difficult to compute. We proceed by building up a "swap list" containing
1411   // the material gain or loss at each stop in a sequence of captures to the
1412   // destination square, where the sides alternately capture, and always
1413   // capture with the least valuable piece. After each capture, we look for
1414   // new X-ray attacks from behind the capturing piece.
1415   int lastCapturingPieceValue = seeValues[piece];
1416   int swapList[32], n = 1;
1417   Color c = them;
1418   PieceType pt;
1419
1420   swapList[0] = seeValues[capture];
1421
1422   do {
1423       // Locate the least valuable attacker for the side to move. The loop
1424       // below looks like it is potentially infinite, but it isn't. We know
1425       // that the side to move still has at least one attacker left.
1426       for (pt = PAWN; !(stmAttackers & pieces(pt)); pt++)
1427           assert(pt < KING);
1428
1429       // Remove the attacker we just found from the 'attackers' bitboard,
1430       // and scan for new X-ray attacks behind the attacker.
1431       b = stmAttackers & pieces(pt);
1432       occ ^= (b & (~b + 1));
1433       attackers |=  (rook_attacks_bb(to, occ) &  pieces(ROOK, QUEEN))
1434                   | (bishop_attacks_bb(to, occ) & pieces(BISHOP, QUEEN));
1435
1436       attackers &= occ;
1437
1438       // Add the new entry to the swap list
1439       assert(n < 32);
1440       swapList[n] = -swapList[n - 1] + lastCapturingPieceValue;
1441       n++;
1442
1443       // Remember the value of the capturing piece, and change the side to move
1444       // before beginning the next iteration
1445       lastCapturingPieceValue = seeValues[pt];
1446       c = opposite_color(c);
1447       stmAttackers = attackers & pieces_of_color(c);
1448
1449       // Stop after a king capture
1450       if (pt == KING && stmAttackers)
1451       {
1452           assert(n < 32);
1453           swapList[n++] = QueenValueMidgame*10;
1454           break;
1455       }
1456   } while (stmAttackers);
1457
1458   // Having built the swap list, we negamax through it to find the best
1459   // achievable score from the point of view of the side to move
1460   while (--n)
1461       swapList[n-1] = Min(-swapList[n], swapList[n-1]);
1462
1463   return swapList[0];
1464 }
1465
1466
1467 /// Position::saveState() copies the content of the current state
1468 /// inside startState and makes st point to it. This is needed
1469 /// when the st pointee could become stale, as example because
1470 /// the caller is about to going out of scope.
1471
1472 void Position::saveState() {
1473
1474   startState = *st;
1475   st = &startState;
1476   st->previous = NULL; // as a safe guard
1477 }
1478
1479
1480 /// Position::clear() erases the position object to a pristine state, with an
1481 /// empty board, white to move, and no castling rights.
1482
1483 void Position::clear() {
1484
1485   st = &startState;
1486   memset(st, 0, sizeof(StateInfo));
1487   st->epSquare = SQ_NONE;
1488
1489   memset(byColorBB,  0, sizeof(Bitboard) * 2);
1490   memset(byTypeBB,   0, sizeof(Bitboard) * 8);
1491   memset(pieceCount, 0, sizeof(int) * 2 * 8);
1492   memset(index,      0, sizeof(int) * 64);
1493
1494   for (int i = 0; i < 64; i++)
1495       board[i] = EMPTY;
1496
1497   for (int i = 0; i < 8; i++)
1498       for (int j = 0; j < 16; j++)
1499           pieceList[0][i][j] = pieceList[1][i][j] = SQ_NONE;
1500
1501   sideToMove = WHITE;
1502   gamePly = 0;
1503   initialKFile = FILE_E;
1504   initialKRFile = FILE_H;
1505   initialQRFile = FILE_A;
1506 }
1507
1508
1509 /// Position::reset_game_ply() simply sets gamePly to 0. It is used from the
1510 /// UCI interface code, whenever a non-reversible move is made in a
1511 /// 'position fen <fen> moves m1 m2 ...' command.  This makes it possible
1512 /// for the program to handle games of arbitrary length, as long as the GUI
1513 /// handles draws by the 50 move rule correctly.
1514
1515 void Position::reset_game_ply() {
1516
1517   gamePly = 0;
1518 }
1519
1520
1521 /// Position::put_piece() puts a piece on the given square of the board,
1522 /// updating the board array, bitboards, and piece counts.
1523
1524 void Position::put_piece(Piece p, Square s) {
1525
1526   Color c = color_of_piece(p);
1527   PieceType pt = type_of_piece(p);
1528
1529   board[s] = p;
1530   index[s] = pieceCount[c][pt];
1531   pieceList[c][pt][index[s]] = s;
1532
1533   set_bit(&(byTypeBB[pt]), s);
1534   set_bit(&(byColorBB[c]), s);
1535   set_bit(&byTypeBB[0], s); // HACK: byTypeBB[0] contains all occupied squares.
1536
1537   pieceCount[c][pt]++;
1538 }
1539
1540
1541 /// Position::allow_oo() gives the given side the right to castle kingside.
1542 /// Used when setting castling rights during parsing of FEN strings.
1543
1544 void Position::allow_oo(Color c) {
1545
1546   st->castleRights |= (1 + int(c));
1547 }
1548
1549
1550 /// Position::allow_ooo() gives the given side the right to castle queenside.
1551 /// Used when setting castling rights during parsing of FEN strings.
1552
1553 void Position::allow_ooo(Color c) {
1554
1555   st->castleRights |= (4 + 4*int(c));
1556 }
1557
1558
1559 /// Position::compute_key() computes the hash key of the position. The hash
1560 /// key is usually updated incrementally as moves are made and unmade, the
1561 /// compute_key() function is only used when a new position is set up, and
1562 /// to verify the correctness of the hash key when running in debug mode.
1563
1564 Key Position::compute_key() const {
1565
1566   Key result = Key(0ULL);
1567
1568   for (Square s = SQ_A1; s <= SQ_H8; s++)
1569       if (square_is_occupied(s))
1570           result ^= zobrist[color_of_piece_on(s)][type_of_piece_on(s)][s];
1571
1572   if (ep_square() != SQ_NONE)
1573       result ^= zobEp[ep_square()];
1574
1575   result ^= zobCastle[st->castleRights];
1576   if (side_to_move() == BLACK)
1577       result ^= zobSideToMove;
1578
1579   return result;
1580 }
1581
1582
1583 /// Position::compute_pawn_key() computes the hash key of the position. The
1584 /// hash key is usually updated incrementally as moves are made and unmade,
1585 /// the compute_pawn_key() function is only used when a new position is set
1586 /// up, and to verify the correctness of the pawn hash key when running in
1587 /// debug mode.
1588
1589 Key Position::compute_pawn_key() const {
1590
1591   Key result = Key(0ULL);
1592   Bitboard b;
1593   Square s;
1594
1595   for (Color c = WHITE; c <= BLACK; c++)
1596   {
1597       b = pieces(PAWN, c);
1598       while(b)
1599       {
1600           s = pop_1st_bit(&b);
1601           result ^= zobrist[c][PAWN][s];
1602       }
1603   }
1604   return result;
1605 }
1606
1607
1608 /// Position::compute_material_key() computes the hash key of the position.
1609 /// The hash key is usually updated incrementally as moves are made and unmade,
1610 /// the compute_material_key() function is only used when a new position is set
1611 /// up, and to verify the correctness of the material hash key when running in
1612 /// debug mode.
1613
1614 Key Position::compute_material_key() const {
1615
1616   Key result = Key(0ULL);
1617   for (Color c = WHITE; c <= BLACK; c++)
1618       for (PieceType pt = PAWN; pt <= QUEEN; pt++)
1619       {
1620           int count = piece_count(c, pt);
1621           for (int i = 0; i <= count; i++)
1622               result ^= zobMaterial[c][pt][i];
1623       }
1624   return result;
1625 }
1626
1627
1628 /// Position::compute_value() compute the incremental scores for the middle
1629 /// game and the endgame. These functions are used to initialize the incremental
1630 /// scores when a new position is set up, and to verify that the scores are correctly
1631 /// updated by do_move and undo_move when the program is running in debug mode.
1632 Score Position::compute_value() const {
1633
1634   Score result(0, 0);
1635   Bitboard b;
1636   Square s;
1637
1638   for (Color c = WHITE; c <= BLACK; c++)
1639       for (PieceType pt = PAWN; pt <= KING; pt++)
1640       {
1641           b = pieces(pt, c);
1642           while(b)
1643           {
1644               s = pop_1st_bit(&b);
1645               assert(piece_on(s) == piece_of_color_and_type(c, pt));
1646               result += pst(c, pt, s);
1647           }
1648       }
1649
1650   result += (side_to_move() == WHITE)? TempoValue / 2 : -TempoValue / 2;
1651   return result;
1652 }
1653
1654
1655 /// Position::compute_non_pawn_material() computes the total non-pawn middle
1656 /// game material score for the given side. Material scores are updated
1657 /// incrementally during the search, this function is only used while
1658 /// initializing a new Position object.
1659
1660 Value Position::compute_non_pawn_material(Color c) const {
1661
1662   Value result = Value(0);
1663
1664   for (PieceType pt = KNIGHT; pt <= QUEEN; pt++)
1665   {
1666       Bitboard b = pieces(pt, c);
1667       while (b)
1668       {
1669           assert(piece_on(first_1(b)) == piece_of_color_and_type(c, pt));
1670           pop_1st_bit(&b);
1671           result += piece_value_midgame(pt);
1672       }
1673   }
1674   return result;
1675 }
1676
1677
1678 /// Position::is_draw() tests whether the position is drawn by material,
1679 /// repetition, or the 50 moves rule. It does not detect stalemates, this
1680 /// must be done by the search.
1681
1682 bool Position::is_draw() const {
1683
1684   // Draw by material?
1685   if (   !pieces(PAWN)
1686       && (non_pawn_material(WHITE) + non_pawn_material(BLACK) <= BishopValueMidgame))
1687       return true;
1688
1689   // Draw by the 50 moves rule?
1690   if (st->rule50 > 100 || (st->rule50 == 100 && !is_check()))
1691       return true;
1692
1693   // Draw by repetition?
1694   for (int i = 2; i < Min(Min(gamePly, st->rule50), st->pliesFromNull); i += 2)
1695       if (history[gamePly - i] == st->key)
1696           return true;
1697
1698   return false;
1699 }
1700
1701
1702 /// Position::is_mate() returns true or false depending on whether the
1703 /// side to move is checkmated.
1704
1705 bool Position::is_mate() const {
1706
1707   MoveStack moves[256];
1708   return is_check() && (generate_moves(*this, moves, false) == moves);
1709 }
1710
1711
1712 /// Position::has_mate_threat() tests whether a given color has a mate in one
1713 /// from the current position.
1714
1715 bool Position::has_mate_threat(Color c) {
1716
1717   StateInfo st1, st2;
1718   Color stm = side_to_move();
1719
1720   if (is_check())
1721       return false;
1722
1723   // If the input color is not equal to the side to move, do a null move
1724   if (c != stm)
1725       do_null_move(st1);
1726
1727   MoveStack mlist[120];
1728   bool result = false;
1729   Bitboard pinned = pinned_pieces(sideToMove);
1730
1731   // Generate pseudo-legal non-capture and capture check moves
1732   MoveStack* last = generate_non_capture_checks(*this, mlist);
1733   last = generate_captures(*this, last);
1734
1735   // Loop through the moves, and see if one of them is mate
1736   for (MoveStack* cur = mlist; cur != last; cur++)
1737   {
1738       Move move = cur->move;
1739       if (!pl_move_is_legal(move, pinned))
1740           continue;
1741
1742       do_move(move, st2);
1743       if (is_mate())
1744           result = true;
1745
1746       undo_move(move);
1747   }
1748
1749   // Undo null move, if necessary
1750   if (c != stm)
1751       undo_null_move();
1752
1753   return result;
1754 }
1755
1756
1757 /// Position::init_zobrist() is a static member function which initializes the
1758 /// various arrays used to compute hash keys.
1759
1760 void Position::init_zobrist() {
1761
1762   for (int i = 0; i < 2; i++)
1763       for (int j = 0; j < 8; j++)
1764           for (int k = 0; k < 64; k++)
1765               zobrist[i][j][k] = Key(genrand_int64());
1766
1767   for (int i = 0; i < 64; i++)
1768       zobEp[i] = Key(genrand_int64());
1769
1770   for (int i = 0; i < 16; i++)
1771       zobCastle[i] = genrand_int64();
1772
1773   zobSideToMove = genrand_int64();
1774
1775   for (int i = 0; i < 2; i++)
1776       for (int j = 0; j < 8; j++)
1777           for (int k = 0; k < 16; k++)
1778               zobMaterial[i][j][k] = (k > 0)? Key(genrand_int64()) : Key(0LL);
1779
1780   for (int i = 0; i < 16; i++)
1781       zobMaterial[0][KING][i] = zobMaterial[1][KING][i] = Key(0ULL);
1782 }
1783
1784
1785 /// Position::init_piece_square_tables() initializes the piece square tables.
1786 /// This is a two-step operation:  First, the white halves of the tables are
1787 /// copied from the MgPST[][] and EgPST[][] arrays, with a small random number
1788 /// added to each entry if the "Randomness" UCI parameter is non-zero.
1789 /// Second, the black halves of the tables are initialized by mirroring
1790 /// and changing the sign of the corresponding white scores.
1791
1792 void Position::init_piece_square_tables() {
1793
1794   int r = get_option_value_int("Randomness"), i;
1795   for (Square s = SQ_A1; s <= SQ_H8; s++)
1796       for (Piece p = WP; p <= WK; p++)
1797       {
1798           i = (r == 0)? 0 : (genrand_int32() % (r*2) - r);
1799           PieceSquareTable[p][s] = Score(MgPST[p][s] + i, EgPST[p][s] + i);
1800       }
1801
1802   for (Square s = SQ_A1; s <= SQ_H8; s++)
1803       for (Piece p = BP; p <= BK; p++)
1804           PieceSquareTable[p][s] = -PieceSquareTable[p-8][flip_square(s)];
1805 }
1806
1807
1808 /// Position::flipped_copy() makes a copy of the input position, but with
1809 /// the white and black sides reversed. This is only useful for debugging,
1810 /// especially for finding evaluation symmetry bugs.
1811
1812 void Position::flipped_copy(const Position& pos) {
1813
1814   assert(pos.is_ok());
1815
1816   clear();
1817
1818   // Board
1819   for (Square s = SQ_A1; s <= SQ_H8; s++)
1820       if (!pos.square_is_empty(s))
1821           put_piece(Piece(int(pos.piece_on(s)) ^ 8), flip_square(s));
1822
1823   // Side to move
1824   sideToMove = opposite_color(pos.side_to_move());
1825
1826   // Castling rights
1827   if (pos.can_castle_kingside(WHITE))  allow_oo(BLACK);
1828   if (pos.can_castle_queenside(WHITE)) allow_ooo(BLACK);
1829   if (pos.can_castle_kingside(BLACK))  allow_oo(WHITE);
1830   if (pos.can_castle_queenside(BLACK)) allow_ooo(WHITE);
1831
1832   initialKFile  = pos.initialKFile;
1833   initialKRFile = pos.initialKRFile;
1834   initialQRFile = pos.initialQRFile;
1835
1836   for (Square sq = SQ_A1; sq <= SQ_H8; sq++)
1837       castleRightsMask[sq] = ALL_CASTLES;
1838
1839   castleRightsMask[make_square(initialKFile,  RANK_1)] ^= (WHITE_OO | WHITE_OOO);
1840   castleRightsMask[make_square(initialKFile,  RANK_8)] ^= (BLACK_OO | BLACK_OOO);
1841   castleRightsMask[make_square(initialKRFile, RANK_1)] ^=  WHITE_OO;
1842   castleRightsMask[make_square(initialKRFile, RANK_8)] ^=  BLACK_OO;
1843   castleRightsMask[make_square(initialQRFile, RANK_1)] ^=  WHITE_OOO;
1844   castleRightsMask[make_square(initialQRFile, RANK_8)] ^=  BLACK_OOO;
1845
1846   // En passant square
1847   if (pos.st->epSquare != SQ_NONE)
1848       st->epSquare = flip_square(pos.st->epSquare);
1849
1850   // Checkers
1851   find_checkers();
1852
1853   // Hash keys
1854   st->key = compute_key();
1855   st->pawnKey = compute_pawn_key();
1856   st->materialKey = compute_material_key();
1857
1858   // Incremental scores
1859   st->value = compute_value();
1860
1861   // Material
1862   st->npMaterial[WHITE] = compute_non_pawn_material(WHITE);
1863   st->npMaterial[BLACK] = compute_non_pawn_material(BLACK);
1864
1865   assert(is_ok());
1866 }
1867
1868
1869 /// Position::is_ok() performs some consitency checks for the position object.
1870 /// This is meant to be helpful when debugging.
1871
1872 bool Position::is_ok(int* failedStep) const {
1873
1874   // What features of the position should be verified?
1875   static const bool debugBitboards = false;
1876   static const bool debugKingCount = false;
1877   static const bool debugKingCapture = false;
1878   static const bool debugCheckerCount = false;
1879   static const bool debugKey = false;
1880   static const bool debugMaterialKey = false;
1881   static const bool debugPawnKey = false;
1882   static const bool debugIncrementalEval = false;
1883   static const bool debugNonPawnMaterial = false;
1884   static const bool debugPieceCounts = false;
1885   static const bool debugPieceList = false;
1886
1887   if (failedStep) *failedStep = 1;
1888
1889   // Side to move OK?
1890   if (!color_is_ok(side_to_move()))
1891       return false;
1892
1893   // Are the king squares in the position correct?
1894   if (failedStep) (*failedStep)++;
1895   if (piece_on(king_square(WHITE)) != WK)
1896       return false;
1897
1898   if (failedStep) (*failedStep)++;
1899   if (piece_on(king_square(BLACK)) != BK)
1900       return false;
1901
1902   // Castle files OK?
1903   if (failedStep) (*failedStep)++;
1904   if (!file_is_ok(initialKRFile))
1905       return false;
1906
1907   if (!file_is_ok(initialQRFile))
1908       return false;
1909
1910   // Do both sides have exactly one king?
1911   if (failedStep) (*failedStep)++;
1912   if (debugKingCount)
1913   {
1914       int kingCount[2] = {0, 0};
1915       for (Square s = SQ_A1; s <= SQ_H8; s++)
1916           if (type_of_piece_on(s) == KING)
1917               kingCount[color_of_piece_on(s)]++;
1918
1919       if (kingCount[0] != 1 || kingCount[1] != 1)
1920           return false;
1921   }
1922
1923   // Can the side to move capture the opponent's king?
1924   if (failedStep) (*failedStep)++;
1925   if (debugKingCapture)
1926   {
1927       Color us = side_to_move();
1928       Color them = opposite_color(us);
1929       Square ksq = king_square(them);
1930       if (attackers_to(ksq) & pieces_of_color(us))
1931           return false;
1932   }
1933
1934   // Is there more than 2 checkers?
1935   if (failedStep) (*failedStep)++;
1936   if (debugCheckerCount && count_1s(st->checkersBB) > 2)
1937       return false;
1938
1939   // Bitboards OK?
1940   if (failedStep) (*failedStep)++;
1941   if (debugBitboards)
1942   {
1943       // The intersection of the white and black pieces must be empty
1944       if ((pieces_of_color(WHITE) & pieces_of_color(BLACK)) != EmptyBoardBB)
1945           return false;
1946
1947       // The union of the white and black pieces must be equal to all
1948       // occupied squares
1949       if ((pieces_of_color(WHITE) | pieces_of_color(BLACK)) != occupied_squares())
1950           return false;
1951
1952       // Separate piece type bitboards must have empty intersections
1953       for (PieceType p1 = PAWN; p1 <= KING; p1++)
1954           for (PieceType p2 = PAWN; p2 <= KING; p2++)
1955               if (p1 != p2 && (pieces(p1) & pieces(p2)))
1956                   return false;
1957   }
1958
1959   // En passant square OK?
1960   if (failedStep) (*failedStep)++;
1961   if (ep_square() != SQ_NONE)
1962   {
1963       // The en passant square must be on rank 6, from the point of view of the
1964       // side to move.
1965       if (relative_rank(side_to_move(), ep_square()) != RANK_6)
1966           return false;
1967   }
1968
1969   // Hash key OK?
1970   if (failedStep) (*failedStep)++;
1971   if (debugKey && st->key != compute_key())
1972       return false;
1973
1974   // Pawn hash key OK?
1975   if (failedStep) (*failedStep)++;
1976   if (debugPawnKey && st->pawnKey != compute_pawn_key())
1977       return false;
1978
1979   // Material hash key OK?
1980   if (failedStep) (*failedStep)++;
1981   if (debugMaterialKey && st->materialKey != compute_material_key())
1982       return false;
1983
1984   // Incremental eval OK?
1985   if (failedStep) (*failedStep)++;
1986   if (debugIncrementalEval && st->value != compute_value())
1987       return false;
1988
1989   // Non-pawn material OK?
1990   if (failedStep) (*failedStep)++;
1991   if (debugNonPawnMaterial)
1992   {
1993       if (st->npMaterial[WHITE] != compute_non_pawn_material(WHITE))
1994           return false;
1995
1996       if (st->npMaterial[BLACK] != compute_non_pawn_material(BLACK))
1997           return false;
1998   }
1999
2000   // Piece counts OK?
2001   if (failedStep) (*failedStep)++;
2002   if (debugPieceCounts)
2003       for (Color c = WHITE; c <= BLACK; c++)
2004           for (PieceType pt = PAWN; pt <= KING; pt++)
2005               if (pieceCount[c][pt] != count_1s(pieces(pt, c)))
2006                   return false;
2007
2008   if (failedStep) (*failedStep)++;
2009   if (debugPieceList)
2010   {
2011       for(Color c = WHITE; c <= BLACK; c++)
2012           for(PieceType pt = PAWN; pt <= KING; pt++)
2013               for(int i = 0; i < pieceCount[c][pt]; i++)
2014               {
2015                   if (piece_on(piece_list(c, pt, i)) != piece_of_color_and_type(c, pt))
2016                       return false;
2017
2018                   if (index[piece_list(c, pt, i)] != i)
2019                       return false;
2020               }
2021   }
2022   if (failedStep) *failedStep = 0;
2023   return true;
2024 }