]> git.sesse.net Git - stockfish/blob - src/position.h
Detach the state when copying a position
[stockfish] / src / position.h
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 #if !defined(POSITION_H_INCLUDED)
22 #define POSITION_H_INCLUDED
23
24 // Disable some silly and noisy warning from MSVC compiler
25 #if defined(_MSC_VER)
26
27 // Forcing value to bool 'true' or 'false' (performance warning)
28 #pragma warning(disable: 4800)
29
30 // Conditional expression is constant
31 #pragma warning(disable: 4127)
32
33
34 #endif
35
36 ////
37 //// Includes
38 ////
39
40 #include "bitboard.h"
41 #include "color.h"
42 #include "direction.h"
43 #include "move.h"
44 #include "piece.h"
45 #include "square.h"
46 #include "value.h"
47
48
49 ////
50 //// Constants
51 ////
52
53 /// FEN string for the initial position
54 const std::string StartPosition = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
55
56 /// Maximum number of plies per game (220 should be enough, because the
57 /// maximum search depth is 100, and during position setup we reset the
58 /// move counter for every non-reversible move).
59 const int MaxGameLength = 220;
60
61
62 ////
63 //// Types
64 ////
65
66 /// Castle rights, encoded as bit fields
67
68 enum CastleRights {
69   NO_CASTLES  = 0,
70   WHITE_OO    = 1,
71   BLACK_OO    = 2,
72   WHITE_OOO   = 4,
73   BLACK_OOO   = 8,
74   ALL_CASTLES = 15
75 };
76
77 /// Game phase
78 enum Phase {
79   PHASE_ENDGAME = 0,
80   PHASE_MIDGAME = 128
81 };
82
83
84 /// The StateInfo struct stores information we need to restore a Position
85 /// object to its previous state when we retract a move. Whenever a move
86 /// is made on the board (by calling Position::do_move), an StateInfo object
87 /// must be passed as a parameter.
88
89 struct StateInfo {
90   Key key, pawnKey, materialKey;
91   int castleRights, rule50;
92   Square epSquare;
93   Value mgValue, egValue;
94   Value npMaterial[2];
95
96   PieceType capture;
97   Bitboard checkersBB;
98   StateInfo* previous;
99 };
100
101
102 /// The position data structure. A position consists of the following data:
103 ///
104 ///    * For each piece type, a bitboard representing the squares occupied
105 ///      by pieces of that type.
106 ///    * For each color, a bitboard representing the squares occupied by
107 ///      pieces of that color.
108 ///    * A bitboard of all occupied squares.
109 ///    * A bitboard of all checking pieces.
110 ///    * A 64-entry array of pieces, indexed by the squares of the board.
111 ///    * The current side to move.
112 ///    * Information about the castling rights for both sides.
113 ///    * The initial files of the kings and both pairs of rooks. This is
114 ///      used to implement the Chess960 castling rules.
115 ///    * The en passant square (which is SQ_NONE if no en passant capture is
116 ///      possible).
117 ///    * The squares of the kings for both sides.
118 ///    * Hash keys for the position itself, the current pawn structure, and
119 ///      the current material situation.
120 ///    * Hash keys for all previous positions in the game for detecting
121 ///      repetition draws.
122 ///    * A counter for detecting 50 move rule draws.
123
124 class Position {
125
126   friend class MaterialInfo;
127   friend class EndgameFunctions;
128
129 public:
130   // Constructors
131   Position() {};
132   Position(const Position& pos);
133   Position(const std::string& fen);
134
135   // Text input/output
136   void from_fen(const std::string& fen);
137   const std::string to_fen() const;
138   void print(Move m = MOVE_NONE) const;
139
140   // Copying
141   void copy(const Position& pos);
142   void flipped_copy(const Position& pos);
143
144   // The piece on a given square
145   Piece piece_on(Square s) const;
146   PieceType type_of_piece_on(Square s) const;
147   Color color_of_piece_on(Square s) const;
148   bool square_is_empty(Square s) const;
149   bool square_is_occupied(Square s) const;
150   Value midgame_value_of_piece_on(Square s) const;
151   Value endgame_value_of_piece_on(Square s) const;
152
153   // Side to move
154   Color side_to_move() const;
155
156   // Bitboard representation of the position
157   Bitboard empty_squares() const;
158   Bitboard occupied_squares() const;
159   Bitboard pieces_of_color(Color c) const;
160   Bitboard pieces_of_type(PieceType pt) const;
161   Bitboard pieces_of_color_and_type(Color c, PieceType pt) const;
162   Bitboard pawns() const;
163   Bitboard knights() const;
164   Bitboard bishops() const;
165   Bitboard rooks() const;
166   Bitboard queens() const;
167   Bitboard kings() const;
168   Bitboard rooks_and_queens() const;
169   Bitboard bishops_and_queens() const;
170   Bitboard sliders() const;
171   Bitboard pawns(Color c) const;
172   Bitboard knights(Color c) const;
173   Bitboard bishops(Color c) const;
174   Bitboard rooks(Color c) const;
175   Bitboard queens(Color c) const;
176   Bitboard kings(Color c) const;
177   Bitboard rooks_and_queens(Color c) const;
178   Bitboard bishops_and_queens(Color c) const;
179   Bitboard sliders_of_color(Color c) const;
180
181   // Number of pieces of each color and type
182   int piece_count(Color c, PieceType pt) const;
183
184   // The en passant square
185   Square ep_square() const;
186
187   // Current king position for each color
188   Square king_square(Color c) const;
189
190   // Castling rights
191   bool can_castle_kingside(Color c) const;
192   bool can_castle_queenside(Color c) const;
193   bool can_castle(Color c) const;
194   Square initial_kr_square(Color c) const;
195   Square initial_qr_square(Color c) const;
196
197   // Attack bitboards
198   Bitboard sliding_attacks(Square s, Direction d) const;
199   Bitboard ray_attacks(Square s, SignedDirection d) const;
200   Bitboard pawn_attacks(Color c, Square s) const;
201
202   template<PieceType>
203   Bitboard piece_attacks(Square s) const;
204
205   // Bitboards for pinned pieces and discovered check candidates
206   Bitboard discovered_check_candidates(Color c) const;
207   Bitboard pinned_pieces(Color c, Bitboard& p) const;
208   Bitboard pinned_pieces(Color c) const;
209
210   // Checking pieces
211   Bitboard checkers() const;
212
213   // Piece lists
214   Square piece_list(Color c, PieceType pt, int index) const;
215
216   // Attack information for a given square
217   bool square_is_attacked(Square s, Color c) const;
218   Bitboard attacks_to(Square s) const;
219   Bitboard attacks_to(Square s, Color c) const;
220   bool is_check() const;
221   bool pawn_attacks_square(Color c, Square f, Square t) const;
222
223   template<PieceType>
224   Bitboard piece_attacks_square(Square f, Square t) const; // Dispatch at compile-time
225
226   bool piece_attacks_square(Piece p, Square f, Square t) const; // Dispatch at run-time
227
228   // Properties of moves
229   bool pl_move_is_legal(Move m) const;
230   bool pl_move_is_legal(Move m, Bitboard pinned) const;
231   bool move_is_check(Move m) const;
232   bool move_is_check(Move m, Bitboard dcCandidates) const;
233   bool move_is_capture(Move m) const;
234   bool move_is_deep_pawn_push(Move m) const;
235   bool move_is_pawn_push_to_7th(Move m) const;
236   bool move_is_passed_pawn_push(Move m) const;
237   bool move_was_passed_pawn_push(Move m) const;
238   bool move_attacks_square(Move m, Square s) const;
239
240   // Information about pawns
241   bool pawn_is_passed(Color c, Square s) const;
242   bool pawn_is_isolated(Color c, Square s) const;
243   bool pawn_is_doubled(Color c, Square s) const;
244
245   // Open and half-open files
246   bool file_is_open(File f) const;
247   bool file_is_half_open(Color c, File f) const;
248
249   // Weak squares
250   bool square_is_weak(Square s, Color c) const;
251
252   // Doing and undoing moves
253   void saveState();
254   void do_move(Move m, StateInfo& st);
255   void do_move(Move m, StateInfo& st, Bitboard dcCandidates);
256   void undo_move(Move m);
257   void do_null_move(StateInfo& st);
258   void undo_null_move();
259
260   // Static exchange evaluation
261   int see(Square from, Square to) const;
262   int see(Move m) const;
263   int see(Square to) const;
264
265   // Accessing hash keys
266   Key get_key() const;
267   Key get_pawn_key() const;
268   Key get_material_key() const;
269
270   // Incremental evaluation
271   Value mg_value() const;
272   Value eg_value() const;
273   Value non_pawn_material(Color c) const;
274   Phase game_phase() const;
275   Value mg_pst_delta(Move m) const;
276
277   // Game termination checks
278   bool is_mate() const;
279   bool is_draw() const;
280
281   // Check if one side threatens a mate in one
282   bool has_mate_threat(Color c);
283
284   // Number of plies since the last non-reversible move
285   int rule_50_counter() const;
286
287   // Other properties of the position
288   bool opposite_colored_bishops() const;
289   bool has_pawn_on_7th(Color c) const;
290
291   // Reset the gamePly variable to 0
292   void reset_game_ply();
293
294   // Position consistency check, for debugging
295   bool is_ok(int* failedStep = NULL) const;
296
297   // Static member functions:
298   static void init_zobrist();
299   static void init_piece_square_tables();
300
301 private:
302
303   // Initialization helper functions (used while setting up a position)
304   void clear();
305   void put_piece(Piece p, Square s);
306   void allow_oo(Color c);
307   void allow_ooo(Color c);
308
309   // Helper functions for doing and undoing moves
310   void do_capture_move(PieceType capture, Color them, Square to);
311   void do_castle_move(Move m);
312   void do_promotion_move(Move m);
313   void do_ep_move(Move m);
314   void undo_castle_move(Move m);
315   void undo_promotion_move(Move m);
316   void undo_ep_move(Move m);
317   void find_checkers();
318
319   template<PieceType Piece>
320   void update_checkers(Bitboard* pCheckersBB, Square ksq, Square from, Square to, Bitboard dcCandidates);
321
322   template<bool FindPinned>
323   Bitboard hidden_checkers(Color c) const;
324
325   // Computing hash keys from scratch (for initialization and debugging)
326   Key compute_key() const;
327   Key compute_pawn_key() const;
328   Key compute_material_key() const;
329
330   // Computing incremental evaluation scores and material counts
331   enum GamePhase {
332       MidGame,
333       EndGame
334   };
335   template<GamePhase> Value pst(Color c, PieceType pt, Square s) const;
336   template<GamePhase> Value compute_value() const;
337   Value compute_non_pawn_material(Color c) const;
338
339   // Bitboards
340   Bitboard byColorBB[2], byTypeBB[8];
341
342   // Board
343   Piece board[64];
344
345   // Piece counts
346   int pieceCount[2][8]; // [color][pieceType]
347
348   // Piece lists
349   Square pieceList[2][8][16]; // [color][pieceType][index]
350   int index[64];
351
352   // Other info
353   Square kingSquare[2];
354   Color sideToMove;
355   int gamePly;
356   Key history[MaxGameLength];
357   File initialKFile, initialKRFile, initialQRFile;
358   StateInfo startState;
359   StateInfo* st;
360
361   // Static variables
362   static int castleRightsMask[64];
363   static Key zobrist[2][8][64];
364   static Key zobEp[64];
365   static Key zobCastle[16];
366   static Key zobMaterial[2][8][16];
367   static Key zobSideToMove;
368   static Value MgPieceSquareTable[16][64];
369   static Value EgPieceSquareTable[16][64];
370 };
371
372
373 ////
374 //// Inline functions
375 ////
376
377 inline Piece Position::piece_on(Square s) const {
378   return board[s];
379 }
380
381 inline Color Position::color_of_piece_on(Square s) const {
382   return color_of_piece(piece_on(s));
383 }
384
385 inline PieceType Position::type_of_piece_on(Square s) const {
386   return type_of_piece(piece_on(s));
387 }
388
389 inline bool Position::square_is_empty(Square s) const {
390   return piece_on(s) == EMPTY;
391 }
392
393 inline bool Position::square_is_occupied(Square s) const {
394   return !square_is_empty(s);
395 }
396
397 inline Value Position::midgame_value_of_piece_on(Square s) const {
398   return piece_value_midgame(piece_on(s));
399 }
400
401 inline Value Position::endgame_value_of_piece_on(Square s) const {
402   return piece_value_endgame(piece_on(s));
403 }
404
405 inline Color Position::side_to_move() const {
406   return sideToMove;
407 }
408
409 inline Bitboard Position::occupied_squares() const {
410   return byTypeBB[0];
411 }
412
413 inline Bitboard Position::empty_squares() const {
414   return ~(occupied_squares());
415 }
416
417 inline Bitboard Position::pieces_of_color(Color c) const {
418   return byColorBB[c];
419 }
420
421 inline Bitboard Position::pieces_of_type(PieceType pt) const {
422   return byTypeBB[pt];
423 }
424
425 inline Bitboard Position::pieces_of_color_and_type(Color c, PieceType pt) const {
426   return pieces_of_color(c) & pieces_of_type(pt);
427 }
428
429 inline Bitboard Position::pawns() const {
430   return pieces_of_type(PAWN);
431 }
432
433 inline Bitboard Position::knights() const {
434   return pieces_of_type(KNIGHT);
435 }
436
437 inline Bitboard Position::bishops() const {
438   return pieces_of_type(BISHOP);
439 }
440
441 inline Bitboard Position::rooks() const {
442   return pieces_of_type(ROOK);
443 }
444
445 inline Bitboard Position::queens() const {
446   return pieces_of_type(QUEEN);
447 }
448
449 inline Bitboard Position::kings() const {
450   return pieces_of_type(KING);
451 }
452
453 inline Bitboard Position::rooks_and_queens() const {
454   return rooks() | queens();
455 }
456
457 inline Bitboard Position::bishops_and_queens() const {
458   return bishops() | queens();
459 }
460
461 inline Bitboard Position::sliders() const {
462   return bishops() | queens() | rooks();
463 }
464
465 inline Bitboard Position::pawns(Color c) const {
466   return pieces_of_color_and_type(c, PAWN);
467 }
468
469 inline Bitboard Position::knights(Color c) const {
470   return pieces_of_color_and_type(c, KNIGHT);
471 }
472
473 inline Bitboard Position::bishops(Color c) const {
474   return pieces_of_color_and_type(c, BISHOP);
475 }
476
477 inline Bitboard Position::rooks(Color c) const {
478   return pieces_of_color_and_type(c, ROOK);
479 }
480
481 inline Bitboard Position::queens(Color c) const {
482   return pieces_of_color_and_type(c, QUEEN);
483 }
484
485 inline Bitboard Position::kings(Color c) const {
486   return pieces_of_color_and_type(c, KING);
487 }
488
489 inline Bitboard Position::rooks_and_queens(Color c) const {
490   return rooks_and_queens() & pieces_of_color(c);
491 }
492
493 inline Bitboard Position::bishops_and_queens(Color c) const {
494   return bishops_and_queens() & pieces_of_color(c);
495 }
496
497 inline int Position::piece_count(Color c, PieceType pt) const {
498   return pieceCount[c][pt];
499 }
500
501 inline Square Position::piece_list(Color c, PieceType pt, int index) const {
502   return pieceList[c][pt][index];
503 }
504
505 inline Square Position::ep_square() const {
506   return st->epSquare;
507 }
508
509 inline Square Position::king_square(Color c) const {
510   return kingSquare[c];
511 }
512
513 inline bool Position::can_castle_kingside(Color side) const {
514   return st->castleRights & (1+int(side));
515 }
516
517 inline bool Position::can_castle_queenside(Color side) const {
518   return st->castleRights & (4+4*int(side));
519 }
520
521 inline bool Position::can_castle(Color side) const {
522   return can_castle_kingside(side) || can_castle_queenside(side);
523 }
524
525 inline Square Position::initial_kr_square(Color c) const {
526   return relative_square(c, make_square(initialKRFile, RANK_1));
527 }
528
529 inline Square Position::initial_qr_square(Color c) const {
530   return relative_square(c, make_square(initialQRFile, RANK_1));
531 }
532
533 inline Bitboard Position::pawn_attacks(Color c, Square s) const {
534   return StepAttackBB[piece_of_color_and_type(c, PAWN)][s];
535 }
536
537 template<PieceType Piece> // Knight and King
538 inline Bitboard Position::piece_attacks(Square s) const {
539   return StepAttackBB[Piece][s];
540 }
541
542 template<>
543 inline Bitboard Position::piece_attacks<PAWN>(Square s) const {
544   return StepAttackBB[piece_of_color_and_type(opposite_color(sideToMove), PAWN)][s];
545 }
546
547 template<>
548 inline Bitboard Position::piece_attacks<BISHOP>(Square s) const {
549   return bishop_attacks_bb(s, occupied_squares());
550 }
551
552 template<>
553 inline Bitboard Position::piece_attacks<ROOK>(Square s) const {
554   return rook_attacks_bb(s, occupied_squares());
555 }
556
557 template<>
558 inline Bitboard Position::piece_attacks<QUEEN>(Square s) const {
559   return piece_attacks<ROOK>(s) | piece_attacks<BISHOP>(s);
560 }
561
562 inline Bitboard Position::checkers() const {
563   return st->checkersBB;
564 }
565
566 inline bool Position::is_check() const {
567   return st->checkersBB != EmptyBoardBB;
568 }
569
570 inline bool Position::pawn_attacks_square(Color c, Square f, Square t) const {
571   return bit_is_set(pawn_attacks(c, f), t);
572 }
573
574 template<PieceType Piece>
575 Bitboard Position::piece_attacks_square(Square f, Square t) const {
576   return bit_is_set(piece_attacks<Piece>(f), t);
577 }
578
579 inline Bitboard Position::attacks_to(Square s, Color c) const {
580
581   return attacks_to(s) & pieces_of_color(c);
582 }
583
584 inline bool Position::square_is_attacked(Square s, Color c) const {
585
586   return attacks_to(s, c) != EmptyBoardBB;
587 }
588
589 inline bool Position::pawn_is_passed(Color c, Square s) const {
590   return !(pawns(opposite_color(c)) & passed_pawn_mask(c, s));
591 }
592
593 inline bool Position::pawn_is_isolated(Color c, Square s) const {
594   return !(pawns(c) & neighboring_files_bb(s));
595 }
596
597 inline bool Position::pawn_is_doubled(Color c, Square s) const {
598   return pawns(c) & squares_behind(c, s);
599 }
600
601 inline bool Position::file_is_open(File f) const {
602   return !(pawns() & file_bb(f));
603 }
604
605 inline bool Position::file_is_half_open(Color c, File f) const {
606   return !(pawns(c) & file_bb(f));
607 }
608
609 inline bool Position::square_is_weak(Square s, Color c) const {
610   return !(pawns(c) & outpost_mask(opposite_color(c), s));
611 }
612
613 inline Key Position::get_key() const {
614   return st->key;
615 }
616
617 inline Key Position::get_pawn_key() const {
618   return st->pawnKey;
619 }
620
621 inline Key Position::get_material_key() const {
622   return st->materialKey;
623 }
624
625 template<Position::GamePhase Phase>
626 inline Value Position::pst(Color c, PieceType pt, Square s) const {
627   return (Phase == MidGame ? MgPieceSquareTable[piece_of_color_and_type(c, pt)][s]
628                            : EgPieceSquareTable[piece_of_color_and_type(c, pt)][s]);
629 }
630
631 inline Value Position::mg_pst_delta(Move m) const {
632   return MgPieceSquareTable[piece_on(move_from(m))][move_to(m)]
633         -MgPieceSquareTable[piece_on(move_from(m))][move_from(m)];
634 }
635
636 inline Value Position::mg_value() const {
637   return st->mgValue;
638 }
639
640 inline Value Position::eg_value() const {
641   return st->egValue;
642 }
643
644 inline Value Position::non_pawn_material(Color c) const {
645   return st->npMaterial[c];
646 }
647
648 inline Phase Position::game_phase() const {
649
650   // Values modified by Joona Kiiski
651   static const Value MidgameLimit = Value(15713);
652   static const Value EndgameLimit = Value(4428);
653
654   Value npm = non_pawn_material(WHITE) + non_pawn_material(BLACK);
655
656   if (npm >= MidgameLimit)
657       return PHASE_MIDGAME;
658   else if(npm <= EndgameLimit)
659       return PHASE_ENDGAME;
660   else
661       return Phase(((npm - EndgameLimit) * 128) / (MidgameLimit - EndgameLimit));
662 }
663
664 inline bool Position::move_is_deep_pawn_push(Move m) const {
665
666   Color c = side_to_move();
667   return   piece_on(move_from(m)) == piece_of_color_and_type(c, PAWN)
668         && relative_rank(c, move_to(m)) > RANK_4;
669 }
670
671 inline bool Position::move_is_pawn_push_to_7th(Move m) const {
672
673   Color c = side_to_move();
674   return   piece_on(move_from(m)) == piece_of_color_and_type(c, PAWN)
675         && relative_rank(c, move_to(m)) == RANK_7;
676 }
677
678 inline bool Position::move_is_passed_pawn_push(Move m) const {
679
680   Color c = side_to_move();
681   return   piece_on(move_from(m)) == piece_of_color_and_type(c, PAWN)
682         && pawn_is_passed(c, move_to(m));
683 }
684
685 inline bool Position::move_was_passed_pawn_push(Move m) const {
686
687   Color c = opposite_color(side_to_move());
688   return   piece_on(move_to(m)) == piece_of_color_and_type(c, PAWN)
689         && pawn_is_passed(c, move_to(m));
690 }
691
692 inline int Position::rule_50_counter() const {
693
694   return st->rule50;
695 }
696
697 inline bool Position::opposite_colored_bishops() const {
698
699   return   piece_count(WHITE, BISHOP) == 1
700         && piece_count(BLACK, BISHOP) == 1
701         && square_color(piece_list(WHITE, BISHOP, 0)) != square_color(piece_list(BLACK, BISHOP, 0));
702 }
703
704 inline bool Position::has_pawn_on_7th(Color c) const {
705
706   return pawns(c) & relative_rank_bb(c, RANK_7);
707 }
708
709 inline bool Position::move_is_capture(Move m) const {
710
711   // Move must not be MOVE_NONE !
712
713   return (!square_is_empty(move_to(m)) && !move_is_castle(m)) || move_is_ep(m);
714 }
715
716 #endif // !defined(POSITION_H_INCLUDED)