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