]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
3a69f8ab998885e18277b25960bf90e31cd5ed0b
[stockfish] / src / movegen.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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include "movegen.h"
24 #include "position.h"
25
26 namespace {
27
28   template<CastlingRight Cr, bool Checks, bool Chess960>
29   ExtMove* generate_castling(const Position& pos, ExtMove* moveList, Color us) {
30
31     static const bool KingSide = (Cr == WHITE_OO || Cr == BLACK_OO);
32
33     if (pos.castling_impeded(Cr) || !pos.can_castle(Cr))
34         return moveList;
35
36     // After castling, the rook and king final positions are the same in Chess960
37     // as they would be in standard chess.
38     Square kfrom = pos.square<KING>(us);
39     Square rfrom = pos.castling_rook_square(Cr);
40     Square kto = relative_square(us, KingSide ? SQ_G1 : SQ_C1);
41     Bitboard enemies = pos.pieces(~us);
42
43     assert(!pos.checkers());
44
45     const Square K = Chess960 ? kto > kfrom ? DELTA_W : DELTA_E
46                               : KingSide    ? DELTA_W : DELTA_E;
47
48     for (Square s = kto; s != kfrom; s += K)
49         if (pos.attackers_to(s) & enemies)
50             return moveList;
51
52     // Because we generate only legal castling moves we need to verify that
53     // when moving the castling rook we do not discover some hidden checker.
54     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
55     if (Chess960 && (attacks_bb<ROOK>(kto, pos.pieces() ^ rfrom) & pos.pieces(~us, ROOK, QUEEN)))
56         return moveList;
57
58     Move m = make<CASTLING>(kfrom, rfrom);
59
60     if (Checks && !pos.gives_check(m))
61         return moveList;
62
63     *moveList++ = m;
64     return moveList;
65   }
66
67
68   template<GenType Type, Square Delta>
69   ExtMove* make_promotions(ExtMove* moveList, Square to, Square ksq) {
70
71     if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
72         *moveList++ = make<PROMOTION>(to - Delta, to, QUEEN);
73
74     if (Type == QUIETS || Type == EVASIONS || Type == NON_EVASIONS)
75     {
76         *moveList++ = make<PROMOTION>(to - Delta, to, ROOK);
77         *moveList++ = make<PROMOTION>(to - Delta, to, BISHOP);
78         *moveList++ = make<PROMOTION>(to - Delta, to, KNIGHT);
79     }
80
81     // Knight promotion is the only promotion that can give a direct check
82     // that's not already included in the queen promotion.
83     if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ksq))
84         *moveList++ = make<PROMOTION>(to - Delta, to, KNIGHT);
85
86     return moveList;
87   }
88
89
90   template<Color Us, GenType Type>
91   ExtMove* generate_pawn_moves(const Position& pos, ExtMove* moveList, Bitboard target) {
92
93     // Compute our parametrized parameters at compile time, named according to
94     // the point of view of white side.
95     const Color    Them     = (Us == WHITE ? BLACK    : WHITE);
96     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB  : Rank1BB);
97     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
98     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB  : Rank6BB);
99     const Square   Up       = (Us == WHITE ? DELTA_N  : DELTA_S);
100     const Square   Right    = (Us == WHITE ? DELTA_NE : DELTA_SW);
101     const Square   Left     = (Us == WHITE ? DELTA_NW : DELTA_SE);
102
103     Bitboard emptySquares;
104
105     Bitboard pawnsOn7    = pos.pieces(Us, PAWN) &  TRank7BB;
106     Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
107
108     Bitboard enemies = (Type == EVASIONS ? pos.pieces(Them) & target:
109                         Type == CAPTURES ? target : pos.pieces(Them));
110
111     // Single and double pawn pushes, no promotions
112     if (Type != CAPTURES)
113     {
114         emptySquares = (Type == QUIETS || Type == QUIET_CHECKS ? target : ~pos.pieces());
115
116         Bitboard b1 = shift_bb<Up>(pawnsNotOn7)   & emptySquares;
117         Bitboard b2 = shift_bb<Up>(b1 & TRank3BB) & emptySquares;
118
119         if (Type == EVASIONS) // Consider only blocking squares
120         {
121             b1 &= target;
122             b2 &= target;
123         }
124
125         if (Type == QUIET_CHECKS)
126         {
127             Square ksq = pos.square<KING>(Them);
128
129             b1 &= pos.attacks_from<PAWN>(ksq, Them);
130             b2 &= pos.attacks_from<PAWN>(ksq, Them);
131
132             // Add pawn pushes which give discovered check. This is possible only
133             // if the pawn is not on the same file as the enemy king, because we
134             // don't generate captures. Note that a possible discovery check
135             // promotion has been already generated amongst the captures.
136             Bitboard dcCandidates = pos.discovered_check_candidates();
137             if (pawnsNotOn7 & dcCandidates)
138             {
139                 Bitboard dc1 = shift_bb<Up>(pawnsNotOn7 & dcCandidates) & emptySquares & ~file_bb(ksq);
140                 Bitboard dc2 = shift_bb<Up>(dc1 & TRank3BB) & emptySquares;
141
142                 b1 |= dc1;
143                 b2 |= dc2;
144             }
145         }
146
147         while (b1)
148         {
149             Square to = pop_lsb(&b1);
150             *moveList++ = make_move(to - Up, to);
151         }
152
153         while (b2)
154         {
155             Square to = pop_lsb(&b2);
156             *moveList++ = make_move(to - Up - Up, to);
157         }
158     }
159
160     // Promotions and underpromotions
161     if (pawnsOn7 && (Type != EVASIONS || (target & TRank8BB)))
162     {
163         if (Type == CAPTURES)
164             emptySquares = ~pos.pieces();
165
166         if (Type == EVASIONS)
167             emptySquares &= target;
168
169         Bitboard b1 = shift_bb<Right>(pawnsOn7) & enemies;
170         Bitboard b2 = shift_bb<Left >(pawnsOn7) & enemies;
171         Bitboard b3 = shift_bb<Up   >(pawnsOn7) & emptySquares;
172
173         Square ksq = pos.square<KING>(Them);
174
175         while (b1)
176             moveList = make_promotions<Type, Right>(moveList, pop_lsb(&b1), ksq);
177
178         while (b2)
179             moveList = make_promotions<Type, Left >(moveList, pop_lsb(&b2), ksq);
180
181         while (b3)
182             moveList = make_promotions<Type, Up   >(moveList, pop_lsb(&b3), ksq);
183     }
184
185     // Standard and en-passant captures
186     if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
187     {
188         Bitboard b1 = shift_bb<Right>(pawnsNotOn7) & enemies;
189         Bitboard b2 = shift_bb<Left >(pawnsNotOn7) & enemies;
190
191         while (b1)
192         {
193             Square to = pop_lsb(&b1);
194             *moveList++ = make_move(to - Right, to);
195         }
196
197         while (b2)
198         {
199             Square to = pop_lsb(&b2);
200             *moveList++ = make_move(to - Left, to);
201         }
202
203         if (pos.ep_square() != SQ_NONE)
204         {
205             assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
206
207             // An en passant capture can be an evasion only if the checking piece
208             // is the double pushed pawn and so is in the target. Otherwise this
209             // is a discovery check and we are forced to do otherwise.
210             if (Type == EVASIONS && !(target & (pos.ep_square() - Up)))
211                 return moveList;
212
213             b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
214
215             assert(b1);
216
217             while (b1)
218                 *moveList++ = make<ENPASSANT>(pop_lsb(&b1), pos.ep_square());
219         }
220     }
221
222     return moveList;
223   }
224
225
226   template<PieceType Pt, bool Checks>
227   ExtMove* generate_moves(const Position& pos, ExtMove* moveList, Color us,
228                           Bitboard target) {
229
230     assert(Pt != KING && Pt != PAWN);
231
232     const Square* pl = pos.squares<Pt>(us);
233
234     for (Square from = *pl; from != SQ_NONE; from = *++pl)
235     {
236         if (Checks)
237         {
238             if (    (Pt == BISHOP || Pt == ROOK || Pt == QUEEN)
239                 && !(PseudoAttacks[Pt][from] & target & pos.check_info().checkSquares[Pt]))
240                 continue;
241
242             if (pos.discovered_check_candidates() & from)
243                 continue;
244         }
245
246         Bitboard b = pos.attacks_from<Pt>(from) & target;
247
248         if (Checks)
249             b &= pos.check_info().checkSquares[Pt];
250
251         while (b)
252             *moveList++ = make_move(from, pop_lsb(&b));
253     }
254
255     return moveList;
256   }
257
258
259   template<Color Us, GenType Type>
260   ExtMove* generate_all(const Position& pos, ExtMove* moveList, Bitboard target) {
261
262     const bool Checks = Type == QUIET_CHECKS;
263
264     moveList = generate_pawn_moves<Us, Type>(pos, moveList, target);
265     moveList = generate_moves<KNIGHT, Checks>(pos, moveList, Us, target);
266     moveList = generate_moves<BISHOP, Checks>(pos, moveList, Us, target);
267     moveList = generate_moves<  ROOK, Checks>(pos, moveList, Us, target);
268     moveList = generate_moves< QUEEN, Checks>(pos, moveList, Us, target);
269
270     if (Type != QUIET_CHECKS && Type != EVASIONS)
271     {
272         Square ksq = pos.square<KING>(Us);
273         Bitboard b = pos.attacks_from<KING>(ksq) & target;
274         while (b)
275             *moveList++ = make_move(ksq, pop_lsb(&b));
276     }
277
278     if (Type != CAPTURES && Type != EVASIONS && pos.can_castle(Us))
279     {
280         if (pos.is_chess960())
281         {
282             moveList = generate_castling<MakeCastling<Us,  KING_SIDE>::right, Checks, true>(pos, moveList, Us);
283             moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, true>(pos, moveList, Us);
284         }
285         else
286         {
287             moveList = generate_castling<MakeCastling<Us,  KING_SIDE>::right, Checks, false>(pos, moveList, Us);
288             moveList = generate_castling<MakeCastling<Us, QUEEN_SIDE>::right, Checks, false>(pos, moveList, Us);
289         }
290     }
291
292     return moveList;
293   }
294
295 } // namespace
296
297
298 /// generate<CAPTURES> generates all pseudo-legal captures and queen
299 /// promotions. Returns a pointer to the end of the move list.
300 ///
301 /// generate<QUIETS> generates all pseudo-legal non-captures and
302 /// underpromotions. Returns a pointer to the end of the move list.
303 ///
304 /// generate<NON_EVASIONS> generates all pseudo-legal captures and
305 /// non-captures. Returns a pointer to the end of the move list.
306
307 template<GenType Type>
308 ExtMove* generate(const Position& pos, ExtMove* moveList) {
309
310   assert(Type == CAPTURES || Type == QUIETS || Type == NON_EVASIONS);
311   assert(!pos.checkers());
312
313   Color us = pos.side_to_move();
314
315   Bitboard target =  Type == CAPTURES     ?  pos.pieces(~us)
316                    : Type == QUIETS       ? ~pos.pieces()
317                    : Type == NON_EVASIONS ? ~pos.pieces(us) : 0;
318
319   return us == WHITE ? generate_all<WHITE, Type>(pos, moveList, target)
320                      : generate_all<BLACK, Type>(pos, moveList, target);
321 }
322
323 // Explicit template instantiations
324 template ExtMove* generate<CAPTURES>(const Position&, ExtMove*);
325 template ExtMove* generate<QUIETS>(const Position&, ExtMove*);
326 template ExtMove* generate<NON_EVASIONS>(const Position&, ExtMove*);
327
328
329 /// generate<QUIET_CHECKS> generates all pseudo-legal non-captures and knight
330 /// underpromotions that give check. Returns a pointer to the end of the move list.
331 template<>
332 ExtMove* generate<QUIET_CHECKS>(const Position& pos, ExtMove* moveList) {
333
334   assert(!pos.checkers());
335
336   Color us = pos.side_to_move();
337   Bitboard dc = pos.discovered_check_candidates();
338
339   while (dc)
340   {
341      Square from = pop_lsb(&dc);
342      PieceType pt = type_of(pos.piece_on(from));
343
344      if (pt == PAWN)
345          continue; // Will be generated together with direct checks
346
347      Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();
348
349      if (pt == KING)
350          b &= ~PseudoAttacks[QUEEN][pos.square<KING>(~us)];
351
352      while (b)
353          *moveList++ = make_move(from, pop_lsb(&b));
354   }
355
356   return us == WHITE ? generate_all<WHITE, QUIET_CHECKS>(pos, moveList, ~pos.pieces())
357                      : generate_all<BLACK, QUIET_CHECKS>(pos, moveList, ~pos.pieces());
358 }
359
360
361 /// generate<EVASIONS> generates all pseudo-legal check evasions when the side
362 /// to move is in check. Returns a pointer to the end of the move list.
363 template<>
364 ExtMove* generate<EVASIONS>(const Position& pos, ExtMove* moveList) {
365
366   assert(pos.checkers());
367
368   Color us = pos.side_to_move();
369   Square ksq = pos.square<KING>(us);
370   Bitboard sliderAttacks = 0;
371   Bitboard sliders = pos.checkers() & ~pos.pieces(KNIGHT, PAWN);
372
373   // Find all the squares attacked by slider checkers. We will remove them from
374   // the king evasions in order to skip known illegal moves, which avoids any
375   // useless legality checks later on.
376   while (sliders)
377   {
378       Square checksq = pop_lsb(&sliders);
379       sliderAttacks |= LineBB[checksq][ksq] ^ checksq;
380   }
381
382   // Generate evasions for king, capture and non capture moves
383   Bitboard b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
384   while (b)
385       *moveList++ = make_move(ksq, pop_lsb(&b));
386
387   if (more_than_one(pos.checkers()))
388       return moveList; // Double check, only a king move can save the day
389
390   // Generate blocking evasions or captures of the checking piece
391   Square checksq = lsb(pos.checkers());
392   Bitboard target = between_bb(checksq, ksq) | checksq;
393
394   return us == WHITE ? generate_all<WHITE, EVASIONS>(pos, moveList, target)
395                      : generate_all<BLACK, EVASIONS>(pos, moveList, target);
396 }
397
398
399 /// generate<LEGAL> generates all the legal moves in the given position
400
401 template<>
402 ExtMove* generate<LEGAL>(const Position& pos, ExtMove* moveList) {
403
404   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
405   Square ksq = pos.square<KING>(pos.side_to_move());
406   ExtMove* cur = moveList;
407
408   moveList = pos.checkers() ? generate<EVASIONS    >(pos, moveList)
409                             : generate<NON_EVASIONS>(pos, moveList);
410   while (cur != moveList)
411       if (   (pinned || from_sq(*cur) == ksq || type_of(*cur) == ENPASSANT)
412           && !pos.legal(*cur))
413           *cur = (--moveList)->move;
414       else
415           ++cur;
416
417   return moveList;
418 }