]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Last touches to movegen.cpp
[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-2012 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 <algorithm>
21 #include <cassert>
22
23 #include "movegen.h"
24 #include "position.h"
25
26 /// Simple macro to wrap a very common while loop, no facny, no flexibility,
27 /// hardcoded names 'mlist' and 'from'.
28 #define SERIALIZE(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
29
30 /// Version used for pawns, where the 'from' square is given as a delta from the 'to' square
31 #define SERIALIZE_PAWNS(b, d) while (b) { Square to = pop_1st_bit(&b); \
32                                          (*mlist++).move = make_move(to + (d), to); }
33 namespace {
34
35   enum CastlingSide { KING_SIDE, QUEEN_SIDE };
36
37   template<CastlingSide Side>
38   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist, Color us) {
39
40     const CastleRight CR[] = { Side ? WHITE_OOO : WHITE_OO,
41                                Side ? BLACK_OOO : BLACK_OO };
42
43     if (!pos.can_castle(CR[us]))
44         return mlist;
45
46     // After castling, the rook and king final positions are the same in Chess960
47     // as they would be in standard chess.
48     Square kfrom = pos.king_square(us);
49     Square rfrom = pos.castle_rook_square(CR[us]);
50     Square kto = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
51     Square rto = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
52     Bitboard enemies = pos.pieces(flip(us));
53
54     assert(!pos.in_check());
55     assert(pos.piece_on(kfrom) == make_piece(us, KING));
56     assert(pos.piece_on(rfrom) == make_piece(us, ROOK));
57
58     // Unimpeded rule: All the squares between the king's initial and final squares
59     // (including the final square), and all the squares between the rook's initial
60     // and final squares (including the final square), must be vacant except for
61     // the king and castling rook.
62     for (Square s = std::min(rfrom, rto), e = std::max(rfrom, rto); s <= e; s++)
63         if (s != kfrom && s != rfrom && !pos.square_is_empty(s))
64             return mlist;
65
66     for (Square s = std::min(kfrom, kto), e = std::max(kfrom, kto); s <= e; s++)
67         if (  (s != kfrom && s != rfrom && !pos.square_is_empty(s))
68             ||(pos.attackers_to(s) & enemies))
69             return mlist;
70
71     // Because we generate only legal castling moves we need to verify that
72     // when moving the castling rook we do not discover some hidden checker.
73     // For instance an enemy queen in SQ_A1 when castling rook is in SQ_B1.
74     if (pos.is_chess960())
75     {
76         Bitboard occ = pos.occupied_squares();
77         clear_bit(&occ, rfrom);
78         if (pos.attackers_to(kto, occ) & enemies)
79             return mlist;
80     }
81
82     (*mlist++).move = make_castle(kfrom, rfrom);
83
84     return mlist;
85   }
86
87
88   template<Square Delta>
89   inline Bitboard move_pawns(Bitboard p) {
90
91     return Delta == DELTA_N  ? p << 8 : Delta == DELTA_S  ? p >> 8 :
92            Delta == DELTA_NE ? p << 9 : Delta == DELTA_SE ? p >> 7 :
93            Delta == DELTA_NW ? p << 7 : Delta == DELTA_SW ? p >> 9 : p;
94   }
95
96
97   template<Square Delta>
98   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard target) {
99
100     const Bitboard TFileABB = (   Delta == DELTA_NE
101                                || Delta == DELTA_SE ? FileABB : FileHBB);
102
103     Bitboard b = move_pawns<Delta>(pawns) & target & ~TFileABB;
104     SERIALIZE_PAWNS(b, -Delta);
105     return mlist;
106   }
107
108
109   template<MoveType Type, Square Delta>
110   inline MoveStack* generate_promotions(MoveStack* mlist, Bitboard pawnsOn7, Bitboard target, Square ksq) {
111
112     const Bitboard TFileABB = (   Delta == DELTA_NE
113                                || Delta == DELTA_SE ? FileABB : FileHBB);
114
115     Bitboard b = move_pawns<Delta>(pawnsOn7) & target;
116
117     if (Delta != DELTA_N && Delta != DELTA_S)
118         b &= ~TFileABB;
119
120     while (b)
121     {
122         Square to = pop_1st_bit(&b);
123
124         if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
125             (*mlist++).move = make_promotion(to - Delta, to, QUEEN);
126
127         if (Type == MV_NON_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
128         {
129             (*mlist++).move = make_promotion(to - Delta, to, ROOK);
130             (*mlist++).move = make_promotion(to - Delta, to, BISHOP);
131             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
132         }
133
134         // Knight-promotion is the only one that can give a check (direct or
135         // discovered) not already included in the queen-promotion.
136         if (Type == MV_NON_CAPTURE_CHECK && bit_is_set(StepAttacksBB[W_KNIGHT][to], ksq))
137             (*mlist++).move = make_promotion(to - Delta, to, KNIGHT);
138         else
139             (void)ksq; // Silence a warning under MSVC
140     }
141     return mlist;
142   }
143
144
145   template<Color Us, MoveType Type>
146   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
147
148     // Calculate our parametrized parameters at compile time, named according to
149     // the point of view of white side.
150     const Color    Them     = (Us == WHITE ? BLACK    : WHITE);
151     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB  : Rank2BB);
152     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB  : Rank6BB);
153     const Square   UP       = (Us == WHITE ? DELTA_N  : DELTA_S);
154     const Square   RIGHT    = (Us == WHITE ? DELTA_NE : DELTA_SW);
155     const Square   LEFT     = (Us == WHITE ? DELTA_NW : DELTA_SE);
156
157     Bitboard b1, b2, dc1, dc2, emptySquares;
158
159     Bitboard pawnsOn7    = pos.pieces(PAWN, Us) &  TRank7BB;
160     Bitboard pawnsNotOn7 = pos.pieces(PAWN, Us) & ~TRank7BB;
161
162     Bitboard enemies = (Type == MV_EVASION ? pos.pieces(Them) & target:
163                         Type == MV_CAPTURE ? target : pos.pieces(Them));
164
165     // Single and double pawn pushes, no promotions
166     if (Type != MV_CAPTURE)
167     {
168         emptySquares = (Type == MV_NON_CAPTURE ? target : pos.empty_squares());
169
170         b1 = move_pawns<UP>(pawnsNotOn7)   & emptySquares;
171         b2 = move_pawns<UP>(b1 & TRank3BB) & emptySquares;
172
173         if (Type == MV_EVASION) // Consider only blocking squares
174         {
175             b1 &= target;
176             b2 &= target;
177         }
178
179         if (Type == MV_NON_CAPTURE_CHECK)
180         {
181             // Consider only direct checks
182             b1 &= pos.attacks_from<PAWN>(ksq, Them);
183             b2 &= pos.attacks_from<PAWN>(ksq, Them);
184
185             // Add pawn pushes which give discovered check. This is possible only
186             // if the pawn is not on the same file as the enemy king, because we
187             // don't generate captures. Note that a possible discovery check
188             // promotion has been already generated among captures.
189             if (pawnsNotOn7 & target) // Target is dc bitboard
190             {
191                 dc1 = move_pawns<UP>(pawnsNotOn7 & target) & emptySquares & ~file_bb(ksq);
192                 dc2 = move_pawns<UP>(dc1 & TRank3BB) & emptySquares;
193
194                 b1 |= dc1;
195                 b2 |= dc2;
196             }
197         }
198
199         SERIALIZE_PAWNS(b1, -UP);
200         SERIALIZE_PAWNS(b2, -UP -UP);
201     }
202
203     // Promotions and underpromotions
204     if (pawnsOn7)
205     {
206         if (Type == MV_CAPTURE)
207             emptySquares = pos.empty_squares();
208
209         if (Type == MV_EVASION)
210             emptySquares &= target;
211
212         mlist = generate_promotions<Type, RIGHT>(mlist, pawnsOn7, enemies, ksq);
213         mlist = generate_promotions<Type, LEFT>(mlist, pawnsOn7, enemies, ksq);
214         mlist = generate_promotions<Type, UP>(mlist, pawnsOn7, emptySquares, ksq);
215     }
216
217     // Standard and en-passant captures
218     if (Type == MV_CAPTURE || Type == MV_EVASION || Type == MV_NON_EVASION)
219     {
220         mlist = generate_pawn_captures<RIGHT>(mlist, pawnsNotOn7, enemies);
221         mlist = generate_pawn_captures<LEFT >(mlist, pawnsNotOn7, enemies);
222
223         if (pos.ep_square() != SQ_NONE)
224         {
225             assert(rank_of(pos.ep_square()) == (Us == WHITE ? RANK_6 : RANK_3));
226
227             // An en passant capture can be an evasion only if the checking piece
228             // is the double pushed pawn and so is in the target. Otherwise this
229             // is a discovery check and we are forced to do otherwise.
230             if (Type == MV_EVASION && !bit_is_set(target, pos.ep_square() - UP))
231                 return mlist;
232
233             b1 = pawnsNotOn7 & pos.attacks_from<PAWN>(pos.ep_square(), Them);
234
235             assert(b1);
236
237             while (b1)
238                 (*mlist++).move = make_enpassant(pop_1st_bit(&b1), pos.ep_square());
239         }
240     }
241
242     return mlist;
243   }
244
245
246   template<PieceType Pt>
247   inline MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
248                                            Bitboard dc, Square ksq) {
249     assert(Pt != KING && Pt != PAWN);
250
251     Bitboard checkSqs, b;
252     Square from;
253     const Square* pl = pos.piece_list(us, Pt);
254
255     if ((from = *pl++) == SQ_NONE)
256         return mlist;
257
258     checkSqs = pos.attacks_from<Pt>(ksq) & pos.empty_squares();
259
260     do
261     {
262         if (   (Pt == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
263             || (Pt == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
264             || (Pt == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
265             continue;
266
267         if (dc && bit_is_set(dc, from))
268             continue;
269
270         b = pos.attacks_from<Pt>(from) & checkSqs;
271         SERIALIZE(b);
272
273     } while ((from = *pl++) != SQ_NONE);
274
275     return mlist;
276   }
277
278
279   template<>
280   FORCE_INLINE MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
281
282     return us == WHITE ? generate_pawn_moves<WHITE, MV_NON_CAPTURE_CHECK>(p, m, dc, ksq)
283                        : generate_pawn_moves<BLACK, MV_NON_CAPTURE_CHECK>(p, m, dc, ksq);
284   }
285
286
287   template<PieceType Pt, MoveType Type>
288   FORCE_INLINE MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
289
290     assert(Pt == PAWN);
291     return us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
292                        : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE);
293   }
294
295
296   template<PieceType Pt>
297   FORCE_INLINE MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
298
299     Bitboard b;
300     Square from;
301     const Square* pl = pos.piece_list(us, Pt);
302
303     if (*pl != SQ_NONE)
304     {
305         do {
306             from = *pl;
307             b = pos.attacks_from<Pt>(from) & target;
308             SERIALIZE(b);
309         } while (*++pl != SQ_NONE);
310     }
311     return mlist;
312   }
313
314
315   template<>
316   FORCE_INLINE MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
317
318     Square from = pos.king_square(us);
319     Bitboard b = pos.attacks_from<KING>(from) & target;
320     SERIALIZE(b);
321     return mlist;
322   }
323
324 } // namespace
325
326
327 /// generate<MV_CAPTURE> generates all pseudo-legal captures and queen
328 /// promotions. Returns a pointer to the end of the move list.
329 ///
330 /// generate<MV_NON_CAPTURE> generates all pseudo-legal non-captures and
331 /// underpromotions. Returns a pointer to the end of the move list.
332 ///
333 /// generate<MV_NON_EVASION> generates all pseudo-legal captures and
334 /// non-captures. Returns a pointer to the end of the move list.
335
336 template<MoveType Type>
337 MoveStack* generate(const Position& pos, MoveStack* mlist) {
338
339   assert(Type == MV_CAPTURE || Type == MV_NON_CAPTURE || Type == MV_NON_EVASION);
340   assert(!pos.in_check());
341
342   Color us = pos.side_to_move();
343   Bitboard target;
344
345   if (Type == MV_CAPTURE)
346       target = pos.pieces(flip(us));
347
348   else if (Type == MV_NON_CAPTURE)
349       target = pos.empty_squares();
350
351   else if (Type == MV_NON_EVASION)
352       target = pos.pieces(flip(us)) | pos.empty_squares();
353
354   mlist = generate_piece_moves<PAWN, Type>(pos, mlist, us, target);
355   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
356   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
357   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
358   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
359   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
360
361   if (Type != MV_CAPTURE && pos.can_castle(us))
362   {
363       mlist = generate_castle_moves<KING_SIDE>(pos, mlist, us);
364       mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist, us);
365   }
366
367   return mlist;
368 }
369
370 // Explicit template instantiations
371 template MoveStack* generate<MV_CAPTURE>(const Position& pos, MoveStack* mlist);
372 template MoveStack* generate<MV_NON_CAPTURE>(const Position& pos, MoveStack* mlist);
373 template MoveStack* generate<MV_NON_EVASION>(const Position& pos, MoveStack* mlist);
374
375
376 /// generate<MV_NON_CAPTURE_CHECK> generates all pseudo-legal non-captures and knight
377 /// underpromotions that give check. Returns a pointer to the end of the move list.
378 template<>
379 MoveStack* generate<MV_NON_CAPTURE_CHECK>(const Position& pos, MoveStack* mlist) {
380
381   assert(!pos.in_check());
382
383   Bitboard b, dc;
384   Square from;
385   PieceType pt;
386   Color us = pos.side_to_move();
387   Square ksq = pos.king_square(flip(us));
388
389   assert(pos.piece_on(ksq) == make_piece(flip(us), KING));
390
391   b = dc = pos.discovered_check_candidates();
392
393   while (b)
394   {
395      from = pop_1st_bit(&b);
396      pt = type_of(pos.piece_on(from));
397
398      if (pt == PAWN)
399          continue; // Will be generated togheter with direct checks
400
401      b = pos.attacks_from(Piece(pt), from) & pos.empty_squares();
402
403      if (pt == KING)
404          b &= ~QueenPseudoAttacks[ksq];
405
406      SERIALIZE(b);
407   }
408
409   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
410   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
411   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
412   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
413   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
414 }
415
416
417 /// generate<MV_EVASION> generates all pseudo-legal check evasions when the side
418 /// to move is in check. Returns a pointer to the end of the move list.
419 template<>
420 MoveStack* generate<MV_EVASION>(const Position& pos, MoveStack* mlist) {
421
422   assert(pos.in_check());
423
424   Bitboard b, target;
425   Square from, checksq;
426   int checkersCnt = 0;
427   Color us = pos.side_to_move();
428   Square ksq = pos.king_square(us);
429   Bitboard checkers = pos.checkers();
430   Bitboard sliderAttacks = 0;
431
432   assert(pos.piece_on(ksq) == make_piece(us, KING));
433   assert(checkers);
434
435   // Find squares attacked by slider checkers, we will remove them from the king
436   // evasions set so to skip known illegal moves and avoid to do legality check later.
437   b = checkers;
438   do
439   {
440       checkersCnt++;
441       checksq = pop_1st_bit(&b);
442
443       assert(color_of(pos.piece_on(checksq)) == flip(us));
444
445       switch (type_of(pos.piece_on(checksq)))
446       {
447       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
448       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
449       case QUEEN:
450           // If queen and king are far we can safely remove all the squares attacked
451           // in the other direction becuase are not reachable by the king anyway.
452           if (squares_between(ksq, checksq) || (RookPseudoAttacks[checksq] & (1ULL << ksq)))
453               sliderAttacks |= QueenPseudoAttacks[checksq];
454
455           // Otherwise, if king and queen are adjacent and on a diagonal line, we need to
456           // use real rook attacks to check if king is safe to move in the other direction.
457           // For example: king in B2, queen in A1 a knight in B1, and we can safely move to C1.
458           else
459               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
460
461       default:
462           break;
463       }
464   } while (b);
465
466   // Generate evasions for king, capture and non capture moves
467   b = pos.attacks_from<KING>(ksq) & ~pos.pieces(us) & ~sliderAttacks;
468   from = ksq;
469   SERIALIZE(b);
470
471   // Generate evasions for other pieces only if not under a double check
472   if (checkersCnt > 1)
473       return mlist;
474
475   // Target for blocking evasions or captures of the checking piece
476   target = squares_between(checksq, ksq) | checkers;
477
478   mlist = generate_piece_moves<PAWN, MV_EVASION>(pos, mlist, us, target);
479   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
480   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
481   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
482   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
483 }
484
485
486 /// generate<MV_LEGAL> generates all the legal moves in the given position
487
488 template<>
489 MoveStack* generate<MV_LEGAL>(const Position& pos, MoveStack* mlist) {
490
491   MoveStack *last, *cur = mlist;
492   Bitboard pinned = pos.pinned_pieces();
493
494   last = pos.in_check() ? generate<MV_EVASION>(pos, mlist)
495                         : generate<MV_NON_EVASION>(pos, mlist);
496   while (cur != last)
497       if (!pos.pl_move_is_legal(cur->move, pinned))
498           cur->move = (--last)->move;
499       else
500           cur++;
501
502   return last;
503 }