]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Simplify captures ordering
[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-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 #include <cassert>
21
22 #include "movegen.h"
23 #include "position.h"
24
25 /// Simple macro to wrap a very common while loop, no facny, no flexibility,
26 /// hardcoded names 'mlist' and 'from'.
27 #define SERIALIZE(b) while (b) (mlist++)->move = make_move(from, pop_lsb(&b))
28
29 /// Version used for pawns, where the 'from' square is given as a delta from the 'to' square
30 #define SERIALIZE_PAWNS(b, d) while (b) { Square to = pop_lsb(&b); \
31                                          (mlist++)->move = make_move(to - (d), to); }
32 namespace {
33
34   template<CastlingSide Side, bool Checks, bool Chess960>
35   ExtMove* generate_castle(const Position& pos, ExtMove* mlist, Color us) {
36
37     if (pos.castle_impeded(us, Side) || !pos.can_castle(make_castle_right(us, Side)))
38         return mlist;
39
40     // After castling, the rook and king final positions are the same in Chess960
41     // as they would be in standard chess.
42     Square kfrom = pos.king_square(us);
43     Square rfrom = pos.castle_rook_square(us, Side);
44     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
45     Bitboard enemies = pos.pieces(~us);
46
47     assert(!pos.checkers());
48
49     const int K = Chess960 ? kto > kfrom ? -1 : 1
50                            : Side == KING_SIDE ? -1 : 1;
51
52     for (Square s = kto; s != kfrom; s += (Square)K)
53         if (pos.attackers_to(s) & enemies)
54             return mlist;
55
56     // Because we generate only legal castling moves we need to verify that
57     // when moving the castling rook we do not discover some hidden checker.
58     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
59     if (Chess960 && (pos.attackers_to(kto, pos.pieces() ^ rfrom) & enemies))
60         return mlist;
61
62     (mlist++)->move = make<CASTLE>(kfrom, rfrom);
63
64     if (Checks && !pos.move_gives_check((mlist - 1)->move, CheckInfo(pos)))
65         mlist--;
66
67     return mlist;
68   }
69
70
71   template<GenType Type, Square Delta>
72   inline ExtMove* generate_promotions(ExtMove* mlist, Bitboard pawnsOn7,
73                                       Bitboard target, const CheckInfo* ci) {
74
75     Bitboard b = shift_bb<Delta>(pawnsOn7) & target;
76
77     while (b)
78     {
79         Square to = pop_lsb(&b);
80
81         if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
82             (mlist++)->move = make<PROMOTION>(to - Delta, to, QUEEN);
83
84         if (Type == QUIETS || Type == EVASIONS || Type == NON_EVASIONS)
85         {
86             (mlist++)->move = make<PROMOTION>(to - Delta, to, ROOK);
87             (mlist++)->move = make<PROMOTION>(to - Delta, to, BISHOP);
88             (mlist++)->move = make<PROMOTION>(to - Delta, to, KNIGHT);
89         }
90
91         // Knight-promotion is the only one that can give a direct check not
92         // already included in the queen-promotion.
93         if (Type == QUIET_CHECKS && (StepAttacksBB[W_KNIGHT][to] & ci->ksq))
94             (mlist++)->move = make<PROMOTION>(to - Delta, to, KNIGHT);
95         else
96             (void)ci; // Silence a warning under MSVC
97     }
98
99     return mlist;
100   }
101
102
103   template<Color Us, GenType Type>
104   ExtMove* generate_pawn_moves(const Position& pos, ExtMove* mlist,
105                                Bitboard target, const CheckInfo* ci) {
106
107     // Compute our parametrized parameters at compile time, named according to
108     // the point of view of white side.
109     const Color    Them     = (Us == WHITE ? BLACK    : WHITE);
110     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB  : Rank1BB);
111     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
112     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB  : Rank6BB);
113     const Square   Up       = (Us == WHITE ? DELTA_N  : DELTA_S);
114     const Square   Right    = (Us == WHITE ? DELTA_NE : DELTA_SW);
115     const Square   Left     = (Us == WHITE ? DELTA_NW : DELTA_SE);
116
117     Bitboard b1, b2, dc1, dc2, emptySquares;
118
119     Bitboard pawnsOn7    = pos.pieces(Us, PAWN) &  TRank7BB;
120     Bitboard pawnsNotOn7 = pos.pieces(Us, PAWN) & ~TRank7BB;
121
122     Bitboard enemies = (Type == EVASIONS ? pos.pieces(Them) & target:
123                         Type == CAPTURES ? target : pos.pieces(Them));
124
125     // Single and double pawn pushes, no promotions
126     if (Type != CAPTURES)
127     {
128         emptySquares = (Type == QUIETS || Type == QUIET_CHECKS ? target : ~pos.pieces());
129
130         b1 = shift_bb<Up>(pawnsNotOn7)   & emptySquares;
131         b2 = shift_bb<Up>(b1 & TRank3BB) & emptySquares;
132
133         if (Type == EVASIONS) // Consider only blocking squares
134         {
135             b1 &= target;
136             b2 &= target;
137         }
138
139         if (Type == QUIET_CHECKS)
140         {
141             b1 &= pos.attacks_from<PAWN>(ci->ksq, Them);
142             b2 &= pos.attacks_from<PAWN>(ci->ksq, Them);
143
144             // Add pawn pushes which give discovered check. This is possible only
145             // if the pawn is not on the same file as the enemy king, because we
146             // don't generate captures. Note that a possible discovery check
147             // promotion has been already generated among captures.
148             if (pawnsNotOn7 & ci->dcCandidates)
149             {
150                 dc1 = shift_bb<Up>(pawnsNotOn7 & ci->dcCandidates) & emptySquares & ~file_bb(ci->ksq);
151                 dc2 = shift_bb<Up>(dc1 & TRank3BB) & emptySquares;
152
153                 b1 |= dc1;
154                 b2 |= dc2;
155             }
156         }
157
158         SERIALIZE_PAWNS(b1, Up);
159         SERIALIZE_PAWNS(b2, Up + Up);
160     }
161
162     // Promotions and underpromotions
163     if (pawnsOn7 && (Type != EVASIONS || (target & TRank8BB)))
164     {
165         if (Type == CAPTURES)
166             emptySquares = ~pos.pieces();
167
168         if (Type == EVASIONS)
169             emptySquares &= target;
170
171         mlist = generate_promotions<Type, Right>(mlist, pawnsOn7, enemies, ci);
172         mlist = generate_promotions<Type, Left >(mlist, pawnsOn7, enemies, ci);
173         mlist = generate_promotions<Type, Up>(mlist, pawnsOn7, emptySquares, ci);
174     }
175
176     // Standard and en-passant captures
177     if (Type == CAPTURES || Type == EVASIONS || Type == NON_EVASIONS)
178     {
179         b1 = shift_bb<Right>(pawnsNotOn7) & enemies;
180         b2 = shift_bb<Left >(pawnsNotOn7) & enemies;
181
182         SERIALIZE_PAWNS(b1, Right);
183         SERIALIZE_PAWNS(b2, Left);
184
185         if (pos.ep_square() != SQ_NONE)
186         {
187             assert(rank_of(pos.ep_square()) == relative_rank(Us, RANK_6));
188
189             // An en passant capture can be an evasion only if the checking piece
190             // is the double pushed pawn and so is in the target. Otherwise this
191             // is a discovery check and we are forced to do otherwise.
192             if (Type == EVASIONS && !(target & (pos.ep_square() - Up)))
193                 return mlist;
194
195             b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
196
197             assert(b1);
198
199             while (b1)
200                 (mlist++)->move = make<ENPASSANT>(pop_lsb(&b1), pos.ep_square());
201         }
202     }
203
204     return mlist;
205   }
206
207
208   template<PieceType Pt, bool Checks> FORCE_INLINE
209   ExtMove* generate_moves(const Position& pos, ExtMove* mlist, Color us,
210                           Bitboard target, const CheckInfo* ci) {
211
212     assert(Pt != KING && Pt != PAWN);
213
214     const Square* pl = pos.list<Pt>(us);
215
216     for (Square from = *pl; from != SQ_NONE; from = *++pl)
217     {
218         if (Checks)
219         {
220             if (    (Pt == BISHOP || Pt == ROOK || Pt == QUEEN)
221                 && !(PseudoAttacks[Pt][from] & target & ci->checkSq[Pt]))
222                 continue;
223
224             if (ci->dcCandidates && (ci->dcCandidates & from))
225                 continue;
226         }
227
228         Bitboard b = pos.attacks_from<Pt>(from) & target;
229
230         if (Checks)
231             b &= ci->checkSq[Pt];
232
233         SERIALIZE(b);
234     }
235
236     return mlist;
237   }
238
239
240   template<GenType Type> FORCE_INLINE
241   ExtMove* generate_all(const Position& pos, ExtMove* mlist, Color us,
242                         Bitboard target, const CheckInfo* ci = NULL) {
243
244     const bool Checks = Type == QUIET_CHECKS;
245
246     mlist = (us == WHITE ? generate_pawn_moves<WHITE, Type>(pos, mlist, target, ci)
247                          : generate_pawn_moves<BLACK, Type>(pos, mlist, target, ci));
248
249     mlist = generate_moves<KNIGHT, Checks>(pos, mlist, us, target, ci);
250     mlist = generate_moves<BISHOP, Checks>(pos, mlist, us, target, ci);
251     mlist = generate_moves<ROOK,   Checks>(pos, mlist, us, target, ci);
252     mlist = generate_moves<QUEEN,  Checks>(pos, mlist, us, target, ci);
253
254     if (Type != QUIET_CHECKS && Type != EVASIONS)
255     {
256         Square from = pos.king_square(us);
257         Bitboard b = pos.attacks_from<KING>(from) & target;
258         SERIALIZE(b);
259     }
260
261     if (Type != CAPTURES && Type != EVASIONS && pos.can_castle(us))
262     {
263         if (pos.is_chess960())
264         {
265             mlist = generate_castle<KING_SIDE,  Checks, true>(pos, mlist, us);
266             mlist = generate_castle<QUEEN_SIDE, Checks, true>(pos, mlist, us);
267         }
268         else
269         {
270             mlist = generate_castle<KING_SIDE,  Checks, false>(pos, mlist, us);
271             mlist = generate_castle<QUEEN_SIDE, Checks, false>(pos, mlist, us);
272         }
273     }
274
275     return mlist;
276   }
277
278
279 } // namespace
280
281
282 /// generate<CAPTURES> generates all pseudo-legal captures and queen
283 /// promotions. Returns a pointer to the end of the move list.
284 ///
285 /// generate<QUIETS> generates all pseudo-legal non-captures and
286 /// underpromotions. Returns a pointer to the end of the move list.
287 ///
288 /// generate<NON_EVASIONS> generates all pseudo-legal captures and
289 /// non-captures. Returns a pointer to the end of the move list.
290
291 template<GenType Type>
292 ExtMove* generate(const Position& pos, ExtMove* mlist) {
293
294   assert(Type == CAPTURES || Type == QUIETS || Type == NON_EVASIONS);
295   assert(!pos.checkers());
296
297   Color us = pos.side_to_move();
298
299   Bitboard target = Type == CAPTURES     ?  pos.pieces(~us)
300                   : Type == QUIETS       ? ~pos.pieces()
301                   : Type == NON_EVASIONS ? ~pos.pieces(us) : 0;
302
303   return generate_all<Type>(pos, mlist, us, target);
304 }
305
306 // Explicit template instantiations
307 template ExtMove* generate<CAPTURES>(const Position&, ExtMove*);
308 template ExtMove* generate<QUIETS>(const Position&, ExtMove*);
309 template ExtMove* generate<NON_EVASIONS>(const Position&, ExtMove*);
310
311
312 /// generate<QUIET_CHECKS> generates all pseudo-legal non-captures and knight
313 /// underpromotions that give check. Returns a pointer to the end of the move list.
314 template<>
315 ExtMove* generate<QUIET_CHECKS>(const Position& pos, ExtMove* mlist) {
316
317   assert(!pos.checkers());
318
319   CheckInfo ci(pos);
320   Bitboard dc = ci.dcCandidates;
321
322   while (dc)
323   {
324      Square from = pop_lsb(&dc);
325      PieceType pt = type_of(pos.piece_on(from));
326
327      if (pt == PAWN)
328          continue; // Will be generated togheter with direct checks
329
330      Bitboard b = pos.attacks_from(Piece(pt), from) & ~pos.pieces();
331
332      if (pt == KING)
333          b &= ~PseudoAttacks[QUEEN][ci.ksq];
334
335      SERIALIZE(b);
336   }
337
338   return generate_all<QUIET_CHECKS>(pos, mlist, pos.side_to_move(), ~pos.pieces(), &ci);
339 }
340
341
342 /// generate<EVASIONS> generates all pseudo-legal check evasions when the side
343 /// to move is in check. Returns a pointer to the end of the move list.
344 template<>
345 ExtMove* generate<EVASIONS>(const Position& pos, ExtMove* mlist) {
346
347   assert(pos.checkers());
348
349   int checkersCnt = 0;
350   Color us = pos.side_to_move();
351   Square ksq = pos.king_square(us), from = ksq /* For SERIALIZE */, checksq;
352   Bitboard sliderAttacks = 0;
353   Bitboard b = pos.checkers();
354
355   assert(pos.checkers());
356
357   // Find squares attacked by slider checkers, we will remove them from the king
358   // evasions so to skip known illegal moves avoiding useless legality check later.
359   do
360   {
361       checkersCnt++;
362       checksq = pop_lsb(&b);
363
364       assert(color_of(pos.piece_on(checksq)) == ~us);
365
366       switch (type_of(pos.piece_on(checksq)))
367       {
368       case BISHOP: sliderAttacks |= PseudoAttacks[BISHOP][checksq]; break;
369       case ROOK:   sliderAttacks |= PseudoAttacks[ROOK][checksq];   break;
370       case QUEEN:
371           // If queen and king are far or not on a diagonal line we can safely
372           // remove all the squares attacked in the other direction becuase are
373           // not reachable by the king anyway.
374           if (between_bb(ksq, checksq) || !(PseudoAttacks[BISHOP][checksq] & ksq))
375               sliderAttacks |= PseudoAttacks[QUEEN][checksq];
376
377           // Otherwise we need to use real rook attacks to check if king is safe
378           // to move in the other direction. For example: king in B2, queen in A1
379           // a knight in B1, and we can safely move to C1.
380           else
381               sliderAttacks |= PseudoAttacks[BISHOP][checksq] | pos.attacks_from<ROOK>(checksq);
382
383       default:
384           break;
385       }
386   } while (b);
387
388   // Generate evasions for king, capture and non capture moves
389   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
390   SERIALIZE(b);
391
392   if (checkersCnt > 1)
393       return mlist; // Double check, only a king move can save the day
394
395   // Generate blocking evasions or captures of the checking piece
396   Bitboard target = between_bb(checksq, ksq) | checksq;
397
398   return generate_all<EVASIONS>(pos, mlist, us, target);
399 }
400
401
402 /// generate<LEGAL> generates all the legal moves in the given position
403
404 template<>
405 ExtMove* generate<LEGAL>(const Position& pos, ExtMove* mlist) {
406
407   ExtMove *end, *cur = mlist;
408   Bitboard pinned = pos.pinned_pieces();
409   Square ksq = pos.king_square(pos.side_to_move());
410
411   end = pos.checkers() ? generate<EVASIONS>(pos, mlist)
412                        : generate<NON_EVASIONS>(pos, mlist);
413   while (cur != end)
414       if (   (pinned || from_sq(cur->move) == ksq || type_of(cur->move) == ENPASSANT)
415           && !pos.pl_move_is_legal(cur->move, pinned))
416           cur->move = (--end)->move;
417       else
418           cur++;
419
420   return end;
421 }