]> git.sesse.net Git - stockfish/blob - src/position.h
Update copyright year
[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-2013 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #if !defined(POSITION_H_INCLUDED)
21 #define POSITION_H_INCLUDED
22
23 #include <cassert>
24 #include <cstddef>
25
26 #include "bitboard.h"
27 #include "types.h"
28
29
30 /// The checkInfo struct is initialized at c'tor time and keeps info used
31 /// to detect if a move gives check.
32 class Position;
33 struct Thread;
34
35 struct CheckInfo {
36
37   explicit CheckInfo(const Position&);
38
39   Bitboard dcCandidates;
40   Bitboard pinned;
41   Bitboard checkSq[PIECE_TYPE_NB];
42   Square ksq;
43 };
44
45
46 /// The StateInfo struct stores information we need to restore a Position
47 /// object to its previous state when we retract a move. Whenever a move
48 /// is made on the board (by calling Position::do_move), a StateInfo object
49 /// must be passed as a parameter.
50
51 struct StateInfo {
52   Key pawnKey, materialKey;
53   Value npMaterial[COLOR_NB];
54   int castleRights, rule50, pliesFromNull;
55   Score psqScore;
56   Square epSquare;
57
58   Key key;
59   Bitboard checkersBB;
60   PieceType capturedType;
61   StateInfo* previous;
62 };
63
64
65 /// When making a move the current StateInfo up to 'key' excluded is copied to
66 /// the new one. Here we calculate the quad words (64bits) needed to be copied.
67 const size_t StateCopySize64 = offsetof(StateInfo, key) / sizeof(uint64_t) + 1;
68
69
70 /// The position data structure. A position consists of the following data:
71 ///
72 ///    * For each piece type, a bitboard representing the squares occupied
73 ///      by pieces of that type.
74 ///    * For each color, a bitboard representing the squares occupied by
75 ///      pieces of that color.
76 ///    * A bitboard of all occupied squares.
77 ///    * A bitboard of all checking pieces.
78 ///    * A 64-entry array of pieces, indexed by the squares of the board.
79 ///    * The current side to move.
80 ///    * Information about the castling rights for both sides.
81 ///    * The initial files of the kings and both pairs of rooks. This is
82 ///      used to implement the Chess960 castling rules.
83 ///    * The en passant square (which is SQ_NONE if no en passant capture is
84 ///      possible).
85 ///    * The squares of the kings for both sides.
86 ///    * Hash keys for the position itself, the current pawn structure, and
87 ///      the current material situation.
88 ///    * Hash keys for all previous positions in the game for detecting
89 ///      repetition draws.
90 ///    * A counter for detecting 50 move rule draws.
91
92 class Position {
93 public:
94   Position() {}
95   Position(const Position& p, Thread* t) { *this = p; thisThread = t; }
96   Position(const std::string& f, bool c960, Thread* t) { set(f, c960, t); }
97   Position& operator=(const Position&);
98
99   // Text input/output
100   void set(const std::string& fen, bool isChess960, Thread* th);
101   const std::string fen() const;
102   const std::string pretty(Move m = MOVE_NONE) const;
103
104   // Position representation
105   Bitboard pieces() const;
106   Bitboard pieces(PieceType pt) const;
107   Bitboard pieces(PieceType pt1, PieceType pt2) const;
108   Bitboard pieces(Color c) const;
109   Bitboard pieces(Color c, PieceType pt) const;
110   Bitboard pieces(Color c, PieceType pt1, PieceType pt2) const;
111   Piece piece_on(Square s) const;
112   Square king_square(Color c) const;
113   Square ep_square() const;
114   bool is_empty(Square s) const;
115   const Square* piece_list(Color c, PieceType pt) const;
116   int piece_count(Color c, PieceType pt) const;
117
118   // Castling
119   int can_castle(CastleRight f) const;
120   int can_castle(Color c) const;
121   bool castle_impeded(Color c, CastlingSide s) const;
122   Square castle_rook_square(Color c, CastlingSide s) const;
123
124   // Checking
125   Bitboard checkers() const;
126   Bitboard discovered_check_candidates() const;
127   Bitboard pinned_pieces() const;
128
129   // Attacks to/from a given square
130   Bitboard attackers_to(Square s) const;
131   Bitboard attackers_to(Square s, Bitboard occ) const;
132   Bitboard attacks_from(Piece p, Square s) const;
133   static Bitboard attacks_from(Piece p, Square s, Bitboard occ);
134   template<PieceType> Bitboard attacks_from(Square s) const;
135   template<PieceType> Bitboard attacks_from(Square s, Color c) const;
136
137   // Properties of moves
138   bool move_gives_check(Move m, const CheckInfo& ci) const;
139   bool pl_move_is_legal(Move m, Bitboard pinned) const;
140   bool is_pseudo_legal(const Move m) const;
141   bool is_capture(Move m) const;
142   bool is_capture_or_promotion(Move m) const;
143   bool is_passed_pawn_push(Move m) const;
144   Piece piece_moved(Move m) const;
145   PieceType captured_piece_type() const;
146
147   // Piece specific
148   bool pawn_is_passed(Color c, Square s) const;
149   bool pawn_on_7th(Color c) const;
150   bool opposite_bishops() const;
151   bool bishop_pair(Color c) const;
152
153   // Doing and undoing moves
154   void do_move(Move m, StateInfo& st);
155   void do_move(Move m, StateInfo& st, const CheckInfo& ci, bool moveIsCheck);
156   void undo_move(Move m);
157   void do_null_move(StateInfo& st);
158   void undo_null_move();
159
160   // Static exchange evaluation
161   int see(Move m) const;
162   int see_sign(Move m) const;
163
164   // Accessing hash keys
165   Key key() const;
166   Key exclusion_key() const;
167   Key pawn_key() const;
168   Key material_key() const;
169
170   // Incremental piece-square evaluation
171   Score psq_score() const;
172   Score psq_delta(Piece p, Square from, Square to) const;
173   Value non_pawn_material(Color c) const;
174
175   // Other properties of the position
176   Color side_to_move() const;
177   int game_ply() const;
178   bool is_chess960() const;
179   Thread* this_thread() const;
180   int64_t nodes_searched() const;
181   void set_nodes_searched(int64_t n);
182   template<bool SkipRepetition> bool is_draw() const;
183
184   // Position consistency check, for debugging
185   bool pos_is_ok(int* failedStep = NULL) const;
186   void flip();
187
188 private:
189   // Initialization helpers (used while setting up a position)
190   void clear();
191   void put_piece(Piece p, Square s);
192   void set_castle_right(Color c, Square rfrom);
193
194   // Helper functions
195   void do_castle(Square kfrom, Square kto, Square rfrom, Square rto);
196   template<bool FindPinned> Bitboard hidden_checkers() const;
197
198   // Computing hash keys from scratch (for initialization and debugging)
199   Key compute_key() const;
200   Key compute_pawn_key() const;
201   Key compute_material_key() const;
202
203   // Computing incremental evaluation scores and material counts
204   Score compute_psq_score() const;
205   Value compute_non_pawn_material(Color c) const;
206
207   // Board and pieces
208   Piece board[SQUARE_NB];
209   Bitboard byTypeBB[PIECE_TYPE_NB];
210   Bitboard byColorBB[COLOR_NB];
211   int pieceCount[COLOR_NB][PIECE_TYPE_NB];
212   Square pieceList[COLOR_NB][PIECE_TYPE_NB][16];
213   int index[SQUARE_NB];
214
215   // Other info
216   int castleRightsMask[SQUARE_NB];
217   Square castleRookSquare[COLOR_NB][CASTLING_SIDE_NB];
218   Bitboard castlePath[COLOR_NB][CASTLING_SIDE_NB];
219   StateInfo startState;
220   int64_t nodes;
221   int gamePly;
222   Color sideToMove;
223   Thread* thisThread;
224   StateInfo* st;
225   int chess960;
226 };
227
228 inline int64_t Position::nodes_searched() const {
229   return nodes;
230 }
231
232 inline void Position::set_nodes_searched(int64_t n) {
233   nodes = n;
234 }
235
236 inline Piece Position::piece_on(Square s) const {
237   return board[s];
238 }
239
240 inline Piece Position::piece_moved(Move m) const {
241   return board[from_sq(m)];
242 }
243
244 inline bool Position::is_empty(Square s) const {
245   return board[s] == NO_PIECE;
246 }
247
248 inline Color Position::side_to_move() const {
249   return sideToMove;
250 }
251
252 inline Bitboard Position::pieces() const {
253   return byTypeBB[ALL_PIECES];
254 }
255
256 inline Bitboard Position::pieces(PieceType pt) const {
257   return byTypeBB[pt];
258 }
259
260 inline Bitboard Position::pieces(PieceType pt1, PieceType pt2) const {
261   return byTypeBB[pt1] | byTypeBB[pt2];
262 }
263
264 inline Bitboard Position::pieces(Color c) const {
265   return byColorBB[c];
266 }
267
268 inline Bitboard Position::pieces(Color c, PieceType pt) const {
269   return byColorBB[c] & byTypeBB[pt];
270 }
271
272 inline Bitboard Position::pieces(Color c, PieceType pt1, PieceType pt2) const {
273   return byColorBB[c] & (byTypeBB[pt1] | byTypeBB[pt2]);
274 }
275
276 inline int Position::piece_count(Color c, PieceType pt) const {
277   return pieceCount[c][pt];
278 }
279
280 inline const Square* Position::piece_list(Color c, PieceType pt) const {
281   return pieceList[c][pt];
282 }
283
284 inline Square Position::ep_square() const {
285   return st->epSquare;
286 }
287
288 inline Square Position::king_square(Color c) const {
289   return pieceList[c][KING][0];
290 }
291
292 inline int Position::can_castle(CastleRight f) const {
293   return st->castleRights & f;
294 }
295
296 inline int Position::can_castle(Color c) const {
297   return st->castleRights & ((WHITE_OO | WHITE_OOO) << (2 * c));
298 }
299
300 inline bool Position::castle_impeded(Color c, CastlingSide s) const {
301   return byTypeBB[ALL_PIECES] & castlePath[c][s];
302 }
303
304 inline Square Position::castle_rook_square(Color c, CastlingSide s) const {
305   return castleRookSquare[c][s];
306 }
307
308 template<PieceType Pt>
309 inline Bitboard Position::attacks_from(Square s) const {
310
311   return  Pt == BISHOP || Pt == ROOK ? attacks_bb<Pt>(s, pieces())
312         : Pt == QUEEN  ? attacks_from<ROOK>(s) | attacks_from<BISHOP>(s)
313         : StepAttacksBB[Pt][s];
314 }
315
316 template<>
317 inline Bitboard Position::attacks_from<PAWN>(Square s, Color c) const {
318   return StepAttacksBB[make_piece(c, PAWN)][s];
319 }
320
321 inline Bitboard Position::attacks_from(Piece p, Square s) const {
322   return attacks_from(p, s, byTypeBB[ALL_PIECES]);
323 }
324
325 inline Bitboard Position::attackers_to(Square s) const {
326   return attackers_to(s, byTypeBB[ALL_PIECES]);
327 }
328
329 inline Bitboard Position::checkers() const {
330   return st->checkersBB;
331 }
332
333 inline Bitboard Position::discovered_check_candidates() const {
334   return hidden_checkers<false>();
335 }
336
337 inline Bitboard Position::pinned_pieces() const {
338   return hidden_checkers<true>();
339 }
340
341 inline bool Position::pawn_is_passed(Color c, Square s) const {
342   return !(pieces(~c, PAWN) & passed_pawn_mask(c, s));
343 }
344
345 inline Key Position::key() const {
346   return st->key;
347 }
348
349 inline Key Position::exclusion_key() const {
350   return st->key ^ Zobrist::exclusion;
351 }
352
353 inline Key Position::pawn_key() const {
354   return st->pawnKey;
355 }
356
357 inline Key Position::material_key() const {
358   return st->materialKey;
359 }
360
361 inline Score Position::psq_delta(Piece p, Square from, Square to) const {
362   return pieceSquareTable[p][to] - pieceSquareTable[p][from];
363 }
364
365 inline Score Position::psq_score() const {
366   return st->psqScore;
367 }
368
369 inline Value Position::non_pawn_material(Color c) const {
370   return st->npMaterial[c];
371 }
372
373 inline bool Position::is_passed_pawn_push(Move m) const {
374
375   return   type_of(piece_moved(m)) == PAWN
376         && pawn_is_passed(sideToMove, to_sq(m));
377 }
378
379 inline int Position::game_ply() const {
380   return gamePly;
381 }
382
383 inline bool Position::opposite_bishops() const {
384
385   return   pieceCount[WHITE][BISHOP] == 1
386         && pieceCount[BLACK][BISHOP] == 1
387         && opposite_colors(pieceList[WHITE][BISHOP][0], pieceList[BLACK][BISHOP][0]);
388 }
389
390 inline bool Position::bishop_pair(Color c) const {
391
392   return   pieceCount[c][BISHOP] >= 2
393         && opposite_colors(pieceList[c][BISHOP][0], pieceList[c][BISHOP][1]);
394 }
395
396 inline bool Position::pawn_on_7th(Color c) const {
397   return pieces(c, PAWN) & rank_bb(relative_rank(c, RANK_7));
398 }
399
400 inline bool Position::is_chess960() const {
401   return chess960;
402 }
403
404 inline bool Position::is_capture_or_promotion(Move m) const {
405
406   assert(is_ok(m));
407   return type_of(m) ? type_of(m) != CASTLE : !is_empty(to_sq(m));
408 }
409
410 inline bool Position::is_capture(Move m) const {
411
412   // Note that castle is coded as "king captures the rook"
413   assert(is_ok(m));
414   return (!is_empty(to_sq(m)) && type_of(m) != CASTLE) || type_of(m) == ENPASSANT;
415 }
416
417 inline PieceType Position::captured_piece_type() const {
418   return st->capturedType;
419 }
420
421 inline Thread* Position::this_thread() const {
422   return thisThread;
423 }
424
425 #endif // !defined(POSITION_H_INCLUDED)