]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
cab7c243cf3eb414aada89300f6f9456f7574bd7
[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-2009 Marco Costalba
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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26
27 #include "bitcount.h"
28 #include "movegen.h"
29
30 // Simple macro to wrap a very common while loop, no facny, no flexibility,
31 // hardcoded list name 'mlist' and from square 'from'.
32 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
33
34 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
35 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   enum CastlingSide {
44     KING_SIDE,
45     QUEEN_SIDE
46   };
47
48   enum MoveType {
49     CAPTURE,
50     NON_CAPTURE,
51     CHECK,
52     EVASION
53   };
54
55   // Functions
56   bool castling_is_check(const Position&, CastlingSide);
57
58   // Helper templates
59   template<CastlingSide Side>
60   MoveStack* generate_castle_moves(const Position&, MoveStack*);
61
62   template<Color Us, MoveType Type>
63   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard = EmptyBoardBB,
64                                  Square = SQ_NONE, Bitboard = EmptyBoardBB);
65
66   // Template generate_piece_moves (captures and non-captures) with specializations and overloads
67   template<PieceType>
68   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color, Bitboard);
69
70   template<>
71   MoveStack* generate_piece_moves<KING>(const Position&, MoveStack*, Color, Bitboard);
72
73   template<PieceType Piece, MoveType Type>
74   inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us) {
75
76     assert(Piece == PAWN);
77     assert(Type == CAPTURE || Type == NON_CAPTURE);
78
79     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m)
80                         : generate_pawn_moves<BLACK, Type>(p, m));
81   }
82
83   // Templates for non-capture checks generation
84
85   template<PieceType Piece>
86   MoveStack* generate_discovered_checks(const Position& pos, Square from, MoveStack* mlist);
87
88   template<PieceType>
89   MoveStack* generate_direct_checks(const Position&, MoveStack*, Color, Bitboard, Square);
90
91   template<>
92   inline MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
93
94     return (us == WHITE ? generate_pawn_moves<WHITE, CHECK>(p, m, dc, ksq)
95                         : generate_pawn_moves<BLACK, CHECK>(p, m, dc, ksq));
96   }
97
98   // Template generate_piece_evasions with specializations
99   template<PieceType>
100   MoveStack* generate_piece_evasions(const Position&, MoveStack*, Color, Bitboard, Bitboard);
101
102   template<>
103   inline MoveStack* generate_piece_evasions<PAWN>(const Position& p, MoveStack* m,
104                                                   Color us, Bitboard t, Bitboard pnd) {
105
106     return (us == WHITE ? generate_pawn_moves<WHITE, EVASION>(p, m, pnd, SQ_NONE, t)
107                         : generate_pawn_moves<BLACK, EVASION>(p, m, pnd, SQ_NONE, t));
108   }
109 }
110
111
112 ////
113 //// Functions
114 ////
115
116
117 /// generate_captures() generates all pseudo-legal captures and queen
118 /// promotions. Returns a pointer to the end of the move list.
119
120 MoveStack* generate_captures(const Position& pos, MoveStack* mlist) {
121
122   assert(pos.is_ok());
123   assert(!pos.is_check());
124
125   Color us = pos.side_to_move();
126   Bitboard target = pos.pieces_of_color(opposite_color(us));
127
128   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
129   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
130   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
131   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
132   mlist = generate_piece_moves<PAWN, CAPTURE>(pos, mlist, us);
133   return  generate_piece_moves<KING>(pos, mlist, us, target);
134 }
135
136
137 /// generate_noncaptures() generates all pseudo-legal non-captures and
138 /// underpromotions. Returns a pointer to the end of the move list.
139
140 MoveStack* generate_noncaptures(const Position& pos, MoveStack* mlist) {
141
142   assert(pos.is_ok());
143   assert(!pos.is_check());
144
145   Color us = pos.side_to_move();
146   Bitboard target = pos.empty_squares();
147
148   mlist = generate_piece_moves<PAWN, NON_CAPTURE>(pos, mlist, us);
149   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
150   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
151   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
152   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
153   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
154   mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
155   return  generate_castle_moves<QUEEN_SIDE>(pos, mlist);
156 }
157
158
159 /// generate_non_capture_checks() generates all pseudo-legal non-captures and
160 /// underpromotions that give check. Returns a pointer to the end of the move list.
161
162 MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist, Bitboard dc) {
163
164   assert(pos.is_ok());
165   assert(!pos.is_check());
166
167   Color us = pos.side_to_move();
168   Square ksq = pos.king_square(opposite_color(us));
169
170   assert(pos.piece_on(ksq) == piece_of_color_and_type(opposite_color(us), KING));
171
172   // Discovered non-capture checks
173   Bitboard b = dc;
174   while (b)
175   {
176      Square from = pop_1st_bit(&b);
177      switch (pos.type_of_piece_on(from))
178      {
179       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
180       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, from, mlist); break;
181       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, from, mlist); break;
182       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, from, mlist);   break;
183       case KING:   mlist = generate_discovered_checks<KING>(pos, from, mlist);   break;
184       default: assert(false); break;
185      }
186   }
187
188   // Direct non-capture checks
189   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
190   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
191   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
192   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
193   mlist = generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
194
195   // Castling moves that give check. Very rare but nice to have!
196   if (   pos.can_castle_queenside(us)
197       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_D)
198       && castling_is_check(pos, QUEEN_SIDE))
199       mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
200
201   if (   pos.can_castle_kingside(us)
202       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_F)
203       && castling_is_check(pos, KING_SIDE))
204       mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
205
206   return mlist;
207 }
208
209
210 /// generate_evasions() generates all check evasions when the side to move is
211 /// in check. Unlike the other move generation functions, this one generates
212 /// only legal moves. Returns a pointer to the end of the move list.
213
214 MoveStack* generate_evasions(const Position& pos, MoveStack* mlist, Bitboard pinned) {
215
216   assert(pos.is_ok());
217   assert(pos.is_check());
218
219   Square from, to;
220   Color us = pos.side_to_move();
221   Color them = opposite_color(us);
222   Square ksq = pos.king_square(us);
223   Bitboard sliderAttacks = EmptyBoardBB;
224   Bitboard checkers = pos.checkers();
225
226   assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
227
228   // The bitboard of occupied pieces without our king
229   Bitboard b_noKing = pos.occupied_squares();
230   clear_bit(&b_noKing, ksq);
231
232   // Find squares attacked by slider checkers, we will remove
233   // them from the king evasions set so to avoid a couple
234   // of cycles in the slow king evasions legality check loop
235   // and to be able to use attackers_to().
236   Bitboard b = checkers & pos.pieces(BISHOP, QUEEN);
237   while (b)
238   {
239       from = pop_1st_bit(&b);
240       sliderAttacks |= bishop_attacks_bb(from, b_noKing);
241   }
242
243   b = checkers & pos.pieces(ROOK, QUEEN);
244   while (b)
245   {
246       from = pop_1st_bit(&b);
247       sliderAttacks |= rook_attacks_bb(from, b_noKing);
248   }
249
250   // Generate evasions for king, capture and non capture moves
251   Bitboard enemy = pos.pieces_of_color(them);
252   Bitboard b1 = pos.attacks_from<KING>(ksq) & ~pos.pieces_of_color(us) & ~sliderAttacks;
253   while (b1)
254   {
255       // Note that we can use attackers_to() only because we have already
256       // removed from b1 the squares attacked by slider checkers.
257       to = pop_1st_bit(&b1);
258       if (!(pos.attackers_to(to) & enemy))
259           (*mlist++).move = make_move(ksq, to);
260   }
261
262   // Generate evasions for other pieces only if not double check. We use a
263   // simple bit twiddling hack here rather than calling count_1s in order to
264   // save some time (we know that pos.checkers() has at most two nonzero bits).
265   if (!(checkers & (checkers - 1))) // Only one bit set?
266   {
267       Square checksq = first_1(checkers);
268
269       assert(pos.color_of_piece_on(checksq) == them);
270
271       // Generate captures of the checking piece
272
273       // Pawn captures
274       b1 = pos.attacks_from<PAWN>(checksq, them) & pos.pieces(PAWN, us) & ~pinned;
275       while (b1)
276       {
277           from = pop_1st_bit(&b1);
278           if (relative_rank(us, checksq) == RANK_8)
279           {
280               (*mlist++).move = make_promotion_move(from, checksq, QUEEN);
281               (*mlist++).move = make_promotion_move(from, checksq, ROOK);
282               (*mlist++).move = make_promotion_move(from, checksq, BISHOP);
283               (*mlist++).move = make_promotion_move(from, checksq, KNIGHT);
284           } else
285               (*mlist++).move = make_move(from, checksq);
286       }
287
288       // Pieces captures
289       b1 = (  (pos.attacks_from<KNIGHT>(checksq) & pos.pieces(KNIGHT, us))
290             | (pos.attacks_from<BISHOP>(checksq) & pos.pieces(BISHOP, QUEEN, us))
291             | (pos.attacks_from<ROOK>(checksq)   & pos.pieces(ROOK, QUEEN, us)) ) & ~pinned;
292
293       while (b1)
294       {
295           from = pop_1st_bit(&b1);
296           (*mlist++).move = make_move(from, checksq);
297       }
298
299       // Blocking check evasions are possible only if the checking piece is a slider
300       if (sliderAttacks)
301       {
302           Bitboard blockSquares = squares_between(checksq, ksq);
303
304           assert((pos.occupied_squares() & blockSquares) == EmptyBoardBB);
305
306           if (blockSquares)
307           {
308               mlist = generate_piece_evasions<PAWN>(pos, mlist, us, blockSquares, pinned);
309               mlist = generate_piece_evasions<KNIGHT>(pos, mlist, us, blockSquares, pinned);
310               mlist = generate_piece_evasions<BISHOP>(pos, mlist, us, blockSquares, pinned);
311               mlist = generate_piece_evasions<ROOK>(pos, mlist, us, blockSquares, pinned);
312               mlist = generate_piece_evasions<QUEEN>(pos, mlist, us, blockSquares, pinned);
313           }
314       }
315
316       // Finally, the special case of en passant captures. An en passant
317       // capture can only be a check evasion if the check is not a discovered
318       // check. If pos.ep_square() is set, the last move made must have been
319       // a double pawn push. If, furthermore, the checking piece is a pawn,
320       // an en passant check evasion may be possible.
321       if (pos.ep_square() != SQ_NONE && (checkers & pos.pieces(PAWN, them)))
322       {
323           to = pos.ep_square();
324           b1 = pos.attacks_from<PAWN>(to, them) & pos.pieces(PAWN, us);
325
326           // The checking pawn cannot be a discovered (bishop) check candidate
327           // otherwise we were in check also before last double push move.
328           assert(!bit_is_set(pos.discovered_check_candidates(them), checksq));
329           assert(count_1s(b1) == 1 || count_1s(b1) == 2);
330
331           b1 &= ~pinned;
332           while (b1)
333           {
334               from = pop_1st_bit(&b1);
335               // Move is always legal because checking pawn is not a discovered
336               // check candidate and our capturing pawn has been already tested
337               // against pinned pieces.
338               (*mlist++).move = make_ep_move(from, to);
339           }
340       }
341   }
342   return mlist;
343 }
344
345
346 /// generate_moves() computes a complete list of legal or pseudo-legal moves in
347 /// the current position. This function is not very fast, and should be used
348 /// only in non time-critical paths.
349
350 MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal) {
351
352   assert(pos.is_ok());
353
354   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
355
356   if (pos.is_check())
357       return generate_evasions(pos, mlist, pinned);
358
359   // Generate pseudo-legal moves
360   MoveStack* last = generate_captures(pos, mlist);
361   last = generate_noncaptures(pos, last);
362   if (pseudoLegal)
363       return last;
364
365   // Remove illegal moves from the list
366   for (MoveStack* cur = mlist; cur != last; cur++)
367       if (!pos.pl_move_is_legal(cur->move, pinned))
368       {
369           cur->move = (--last)->move;
370           cur--;
371       }
372   return last;
373 }
374
375
376 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
377 /// move and tests whether the move is legal. This version is not very fast
378 /// and should be used only in non time-critical paths.
379
380 bool move_is_legal(const Position& pos, const Move m) {
381
382   MoveStack mlist[256];
383   MoveStack* last = generate_moves(pos, mlist, true);
384   for (MoveStack* cur = mlist; cur != last; cur++)
385       if (cur->move == m)
386           return pos.pl_move_is_legal(m);
387
388   return false;
389 }
390
391
392 /// Fast version of move_is_legal() that takes a position a move and a
393 /// bitboard of pinned pieces as input, and tests whether the move is legal.
394 /// This version must only be used when the side to move is not in check.
395
396 bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
397
398   assert(pos.is_ok());
399   assert(!pos.is_check());
400   assert(move_is_ok(m));
401   assert(pinned == pos.pinned_pieces(pos.side_to_move()));
402
403   // Use a slower but simpler function for uncommon cases
404   if (move_is_ep(m) || move_is_castle(m))
405       return move_is_legal(pos, m);
406
407   Color us = pos.side_to_move();
408   Color them = opposite_color(us);
409   Square from = move_from(m);
410   Square to = move_to(m);
411   Piece pc = pos.piece_on(from);
412
413   // If the from square is not occupied by a piece belonging to the side to
414   // move, the move is obviously not legal.
415   if (color_of_piece(pc) != us)
416       return false;
417
418   // The destination square cannot be occupied by a friendly piece
419   if (pos.color_of_piece_on(to) == us)
420       return false;
421
422   // Handle the special case of a pawn move
423   if (type_of_piece(pc) == PAWN)
424   {
425       // Move direction must be compatible with pawn color
426       int direction = to - from;
427       if ((us == WHITE) != (direction > 0))
428           return false;
429
430       // A pawn move is a promotion iff the destination square is
431       // on the 8/1th rank.
432       if ((  (square_rank(to) == RANK_8 && us == WHITE)
433            ||(square_rank(to) == RANK_1 && us != WHITE)) != bool(move_is_promotion(m)))
434           return false;
435
436       // Proceed according to the square delta between the origin and
437       // destination squares.
438       switch (direction)
439       {
440       case DELTA_NW:
441       case DELTA_NE:
442       case DELTA_SW:
443       case DELTA_SE:
444       // Capture. The destination square must be occupied by an enemy
445       // piece (en passant captures was handled earlier).
446           if (pos.color_of_piece_on(to) != them)
447               return false;
448           break;
449
450       case DELTA_N:
451       case DELTA_S:
452       // Pawn push. The destination square must be empty.
453           if (!pos.square_is_empty(to))
454               return false;
455           break;
456
457       case DELTA_NN:
458       // Double white pawn push. The destination square must be on the fourth
459       // rank, and both the destination square and the square between the
460       // source and destination squares must be empty.
461       if (   square_rank(to) != RANK_4
462           || !pos.square_is_empty(to)
463           || !pos.square_is_empty(from + DELTA_N))
464           return false;
465           break;
466
467       case DELTA_SS:
468       // Double black pawn push. The destination square must be on the fifth
469       // rank, and both the destination square and the square between the
470       // source and destination squares must be empty.
471           if (   square_rank(to) != RANK_5
472               || !pos.square_is_empty(to)
473               || !pos.square_is_empty(from + DELTA_S))
474               return false;
475           break;
476
477       default:
478           return false;
479       }
480       // The move is pseudo-legal, check if it is also legal
481       return pos.pl_move_is_legal(m, pinned);
482   }
483
484   // Luckly we can handle all the other pieces in one go
485   return (   bit_is_set(pos.attacks_from(pc, from), to)
486           && pos.pl_move_is_legal(m, pinned)
487           && !move_is_promotion(m));
488 }
489
490
491 namespace {
492
493   template<PieceType Piece>
494   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
495
496     Square from;
497     Bitboard b;
498     const Square* ptr = pos.piece_list_begin(us, Piece);
499
500     while ((from = *ptr++) != SQ_NONE)
501     {
502         b = pos.attacks_from<Piece>(from) & target;
503         SERIALIZE_MOVES(b);
504     }
505     return mlist;
506   }
507
508   template<>
509   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
510
511     Bitboard b;
512     Square from = pos.king_square(us);
513
514     b = pos.attacks_from<KING>(from) & target;
515     SERIALIZE_MOVES(b);
516     return mlist;
517   }
518
519   template<PieceType Piece>
520   MoveStack* generate_piece_evasions(const Position& pos, MoveStack* mlist,
521                                      Color us, Bitboard target, Bitboard pinned) {
522     Square from;
523     Bitboard b;
524     const Square* ptr = pos.piece_list_begin(us, Piece);
525
526     while ((from = *ptr++) != SQ_NONE)
527     {
528         if (pinned && bit_is_set(pinned, from))
529             continue;
530
531         b = pos.attacks_from<Piece>(from) & target;
532         SERIALIZE_MOVES(b);
533     }
534     return mlist;
535   }
536
537   template<Color Us, SquareDelta Direction>
538   inline Bitboard move_pawns(Bitboard p) {
539
540     if (Direction == DELTA_N)
541         return Us == WHITE ? p << 8 : p >> 8;
542     else if (Direction == DELTA_NE)
543         return Us == WHITE ? p << 9 : p >> 7;
544     else if (Direction == DELTA_NW)
545         return Us == WHITE ? p << 7 : p >> 9;
546     else
547         return p;
548   }
549
550   template<Color Us, SquareDelta Diagonal>
551   MoveStack* generate_pawn_diagonal_captures(MoveStack* mlist, Bitboard pawns, Bitboard enemyPieces, bool promotion) {
552
553     // Calculate our parametrized parameters at compile time
554     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
555     const Bitboard TFileABB = (Diagonal == DELTA_NE ? FileABB : FileHBB);
556     const SquareDelta TDELTA_NE = (Us == WHITE ? DELTA_NE : DELTA_SE);
557     const SquareDelta TDELTA_NW = (Us == WHITE ? DELTA_NW : DELTA_SW);
558     const SquareDelta TTDELTA_NE = (Diagonal == DELTA_NE ? TDELTA_NE : TDELTA_NW);
559
560     Square to;
561
562     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
563     Bitboard b1 = move_pawns<Us, Diagonal>(pawns) & ~TFileABB & enemyPieces;
564
565     // Capturing promotions
566     if (promotion)
567     {
568         Bitboard b2 = b1 & TRank8BB;
569         b1 &= ~TRank8BB;
570         while (b2)
571         {
572             to = pop_1st_bit(&b2);
573             (*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, QUEEN);
574         }
575     }
576
577     // Capturing non-promotions
578     SERIALIZE_MOVES_D(b1, -TTDELTA_NE);
579     return mlist;
580   }
581
582   template<Color Us, MoveType Type>
583   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard dcp,
584                                  Square ksq, Bitboard blockSquares) {
585
586     // Calculate our parametrized parameters at compile time
587     const Color Them = (Us == WHITE ? BLACK : WHITE);
588     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
589     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
590     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
591     const SquareDelta TDELTA_NE = (Us == WHITE ? DELTA_NE : DELTA_SE);
592     const SquareDelta TDELTA_NW = (Us == WHITE ? DELTA_NW : DELTA_SW);
593     const SquareDelta TDELTA_N = (Us == WHITE ? DELTA_N : DELTA_S);
594
595     Bitboard b1, b2, dcPawns1, dcPawns2;
596     Square to;
597     Bitboard pawns = (Type == EVASION ? pos.pieces(PAWN, Us) & ~dcp : pos.pieces(PAWN, Us));
598     bool possiblePromotion = pawns & TRank7BB;
599
600     if (Type == CAPTURE)
601     {
602         // Standard captures and capturing promotions in both directions
603         Bitboard enemyPieces = pos.pieces_of_color(opposite_color(Us));
604         mlist = generate_pawn_diagonal_captures<Us, DELTA_NE>(mlist, pawns, enemyPieces, possiblePromotion);
605         mlist = generate_pawn_diagonal_captures<Us, DELTA_NW>(mlist, pawns, enemyPieces, possiblePromotion);
606     }
607
608     if (possiblePromotion)
609     {
610         // When generating checks consider under-promotion moves (both captures
611         // and non captures) only if can give a discovery check. Note that dcp
612         // is dc bitboard or pinned bitboard when Type == EVASION.
613         Bitboard pp = (Type == CHECK ? pawns & dcp : pawns);
614
615         if (Type != EVASION && Type != CAPTURE)
616         {
617             Bitboard enemyPieces = pos.pieces_of_color(opposite_color(Us));
618
619             // Underpromotion captures in the a1-h8 (a8-h1 for black) direction
620             b1 = move_pawns<Us, DELTA_NE>(pp) & ~FileABB & enemyPieces & TRank8BB;
621             while (b1)
622             {
623                 to = pop_1st_bit(&b1);
624                 (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, ROOK);
625                 (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, BISHOP);
626                 (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, KNIGHT);
627             }
628
629             // Underpromotion captures in the h1-a8 (h8-a1 for black) direction
630             b1 = move_pawns<Us, DELTA_NW>(pp) & ~FileHBB & enemyPieces & TRank8BB;
631             while (b1)
632             {
633                 to = pop_1st_bit(&b1);
634                 (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, ROOK);
635                 (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, BISHOP);
636                 (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, KNIGHT);
637             }
638         }
639
640         // Underpromotion pawn pushes. Also queen promotions for evasions and captures.
641         b1 = move_pawns<Us, DELTA_N>(pp) & TRank8BB;
642         b1 &= (Type == EVASION ? blockSquares : pos.empty_squares());
643
644         while (b1)
645         {
646             to = pop_1st_bit(&b1);
647             if (Type == EVASION || Type == CAPTURE)
648                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
649
650             if (Type != CAPTURE)
651             {
652                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
653                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
654                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
655             }
656         }
657     }
658
659     if (Type != CAPTURE)
660     {
661         Bitboard emptySquares = pos.empty_squares();
662         dcPawns1 = dcPawns2 = EmptyBoardBB;
663         if (Type == CHECK && (pawns & dcp))
664         {
665             // Pawn moves which gives discovered check. This is possible only if the
666             // pawn is not on the same file as the enemy king, because we don't
667             // generate captures.
668             dcPawns1 = move_pawns<Us, DELTA_N>(pawns & dcp & ~file_bb(ksq)) & emptySquares & ~TRank8BB;
669             dcPawns2 = move_pawns<Us, DELTA_N>(dcPawns1 & TRank3BB) & emptySquares;
670         }
671
672         // Single pawn pushes
673         b1 = move_pawns<Us, DELTA_N>(pawns) & emptySquares & ~TRank8BB;
674         b2 = (Type == CHECK ? (b1 & pos.attacks_from<PAWN>(ksq, Them)) | dcPawns1 :
675              (Type == EVASION ? b1 & blockSquares : b1));
676         SERIALIZE_MOVES_D(b2, -TDELTA_N);
677
678         // Double pawn pushes
679         b1 = move_pawns<Us, DELTA_N>(b1 & TRank3BB) & emptySquares;
680         b2 = (Type == CHECK ? (b1 & pos.attacks_from<PAWN>(ksq, Them)) | dcPawns2 :
681              (Type == EVASION ? b1 & blockSquares : b1));
682         SERIALIZE_MOVES_D(b2, -TDELTA_N -TDELTA_N);
683     }
684     else if (pos.ep_square() != SQ_NONE) // En passant captures
685     {
686         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
687         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
688
689         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
690         assert(b1 != EmptyBoardBB);
691
692         while (b1)
693         {
694             to = pop_1st_bit(&b1);
695             (*mlist++).move = make_ep_move(to, pos.ep_square());
696         }
697     }
698     return mlist;
699   }
700
701   template<PieceType Piece>
702   MoveStack* generate_discovered_checks(const Position& pos, Square from, MoveStack* mlist) {
703
704     assert(Piece != QUEEN);
705
706     Bitboard b = pos.attacks_from<Piece>(from) & pos.empty_squares();
707     if (Piece == KING)
708     {
709         Square ksq = pos.king_square(opposite_color(pos.side_to_move()));
710         b &= ~QueenPseudoAttacks[ksq];
711     }
712     SERIALIZE_MOVES(b);
713     return mlist;
714   }
715
716   template<PieceType Piece>
717   MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
718                                    Bitboard dc, Square ksq) {
719     assert(Piece != KING);
720
721     Square from;
722     Bitboard checkSqs;
723     const Square* ptr = pos.piece_list_begin(us, Piece);
724
725     if ((from = *ptr++) == SQ_NONE)
726         return mlist;
727
728     checkSqs = pos.attacks_from<Piece>(ksq) & pos.empty_squares();
729
730     do
731     {
732         if (   (Piece == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
733             || (Piece == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
734             || (Piece == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
735             continue;
736
737         if (dc && bit_is_set(dc, from))
738             continue;
739
740         Bitboard bb = pos.attacks_from<Piece>(from) & checkSqs;
741         SERIALIZE_MOVES(bb);
742
743     } while ((from = *ptr++) != SQ_NONE);
744
745     return mlist;
746   }
747
748   template<CastlingSide Side>
749   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
750
751     Color us = pos.side_to_move();
752
753     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
754         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
755     {
756         Color them = opposite_color(us);
757         Square ksq = pos.king_square(us);
758
759         assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
760
761         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
762         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
763         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
764         Square s;
765         bool illegal = false;
766
767         assert(pos.piece_on(rsq) == piece_of_color_and_type(us, ROOK));
768
769         // It is a bit complicated to correctly handle Chess960
770         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
771             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
772                 ||(pos.attackers_to(s) & pos.pieces_of_color(them)))
773                 illegal = true;
774
775         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
776             if (s != ksq && s != rsq && pos.square_is_occupied(s))
777                 illegal = true;
778
779         if (   Side == QUEEN_SIDE
780             && square_file(rsq) == FILE_B
781             && (   pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, ROOK)
782                 || pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, QUEEN)))
783             illegal = true;
784
785         if (!illegal)
786             (*mlist++).move = make_castle_move(ksq, rsq);
787     }
788     return mlist;
789   }
790
791   bool castling_is_check(const Position& pos, CastlingSide side) {
792
793     // After castling opponent king is attacked by the castled rook?
794     File rookFile = (side == QUEEN_SIDE ? FILE_D : FILE_F);
795     Color us = pos.side_to_move();
796     Square ksq = pos.king_square(us);
797     Bitboard occ = pos.occupied_squares();
798
799     clear_bit(&occ, ksq); // Remove our king from the board
800     Square rsq = make_square(rookFile, square_rank(ksq));
801     return bit_is_set(rook_attacks_bb(rsq, occ), pos.king_square(opposite_color(us)));
802   }
803 }