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