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