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