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