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