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