]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
Remove special case of pawn move generatation
[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) Copyright (C) 2008 Marco Costalba
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19
20 ////
21 //// Includes
22 ////
23
24 #include <cassert>
25
26 #include "movegen.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 ////
33 //// Local definitions
34 ////
35
36 namespace {
37
38   enum CastlingSide {
39     KING_SIDE,
40     QUEEN_SIDE
41   };
42
43   static const bool CAPTURE = true;
44   static const bool NON_CAPTURE = false;
45
46   // Function
47   bool castling_is_check(const Position&, CastlingSide);
48
49   // Main templates
50   template<CastlingSide Side>
51   MoveStack* generate_castle_moves(const Position&, MoveStack*);
52
53   template<PieceType>
54   MoveStack* generate_piece_checks(const Position&, MoveStack*, Color us, Bitboard, Square);
55
56   // Helper templates
57   template<Color Us, Rank, Bitboard, SquareDelta>
58   MoveStack* do_generate_pawn_blocking_evasions(const Position& pos, Bitboard not_pinned,
59                                                 Bitboard blockSquares, MoveStack* mlist);
60
61   template<Color, Color, Bitboard, SquareDelta, SquareDelta, SquareDelta>
62   MoveStack* do_generate_pawn_captures(const Position& pos, MoveStack* mlist);
63
64   template<Color, Color, Bitboard, Bitboard, SquareDelta, SquareDelta, SquareDelta>
65   MoveStack* do_generate_pawn_noncaptures(const Position& pos, MoveStack* mlist);
66
67   // Template generate_pawn_checks() with specializations
68   template<Color, Color, Bitboard, Bitboard, SquareDelta>
69   MoveStack* do_generate_pawn_checks(const Position&, Bitboard, Square, MoveStack*);
70
71   template<Color>
72   inline MoveStack* generate_pawn_checks(const Position& p, MoveStack* m, Bitboard dc, Square ksq) {
73       return do_generate_pawn_checks<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_N>(p, dc, ksq, m);
74   }
75   template<>
76   inline MoveStack* generate_pawn_checks<BLACK>(const Position& p, MoveStack* m, Bitboard dc, Square ksq) {
77       return do_generate_pawn_checks<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_S>(p, dc, ksq, m);
78   }
79
80   // Template generate_piece_moves() with specializations
81   template<PieceType>
82   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color us, Bitboard);
83   template<>
84   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target);
85
86   template<PieceType Piece, bool Capture>
87   inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us) {
88
89       assert(Piece == PAWN);
90
91       if (Capture)
92           return (us == WHITE ? do_generate_pawn_captures<WHITE, BLACK, Rank8BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m)
93                               : do_generate_pawn_captures<BLACK, WHITE, Rank1BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m));
94       else
95           return (us == WHITE ? do_generate_pawn_noncaptures<WHITE, BLACK, Rank8BB, Rank3BB, DELTA_NE, DELTA_NW, DELTA_N>(p, m)
96                               : do_generate_pawn_noncaptures<BLACK, WHITE, Rank1BB, Rank6BB, DELTA_SE, DELTA_SW, DELTA_S>(p, m));
97   }
98
99   // Template generate_piece_blocking_evasions() with specializations
100   template<PieceType>
101   MoveStack* generate_piece_blocking_evasions(const Position&, MoveStack*, Color us, Bitboard, Bitboard);
102
103   template<>
104   MoveStack* generate_piece_blocking_evasions<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard np, Bitboard bs);
105 }
106
107
108 ////
109 //// Functions
110 ////
111
112
113 /// generate_captures generates() all pseudo-legal captures and queen
114 /// promotions.  The return value is the number of moves generated.
115
116 int generate_captures(const Position& pos, MoveStack* mlist) {
117
118   assert(pos.is_ok());
119   assert(!pos.is_check());
120
121   Color us = pos.side_to_move();
122   Bitboard target = pos.pieces_of_color(opposite_color(us));
123   MoveStack* mlist_start = mlist;
124
125   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
126   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
127   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
128   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
129   mlist = generate_piece_moves<PAWN, CAPTURE>(pos, mlist, us);
130   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
131   return int(mlist - mlist_start);
132 }
133
134
135 /// generate_noncaptures() generates all pseudo-legal non-captures and
136 /// underpromotions. The return value is the number of moves generated.
137
138 int generate_noncaptures(const Position& pos, MoveStack* mlist) {
139
140   assert(pos.is_ok());
141   assert(!pos.is_check());
142
143   Color us = pos.side_to_move();
144   Bitboard target = pos.empty_squares();
145   MoveStack* mlist_start = mlist;
146
147   mlist = generate_piece_moves<PAWN, NON_CAPTURE>(pos, mlist, us);
148   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
149   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
150   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
151   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
152   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
153   mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
154   mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
155   return int(mlist - mlist_start);
156 }
157
158
159 /// generate_checks() generates all pseudo-legal non-capturing, non-promoting
160 /// checks. It returns the number of generated moves.
161
162 int generate_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   MoveStack* mlist_start = mlist;
170
171   assert(pos.piece_on(ksq) == king_of_color(opposite_color(us)));
172
173   // Pawn moves
174   if (us == WHITE)
175      mlist = generate_pawn_checks<WHITE>(pos, mlist, dc, ksq);
176   else
177      mlist = generate_pawn_checks<BLACK>(pos, mlist, dc, ksq);
178
179   // Pieces moves
180   mlist = generate_piece_checks<KNIGHT>(pos, mlist, us, dc, ksq);
181   mlist = generate_piece_checks<BISHOP>(pos, mlist, us, dc, ksq);
182   mlist = generate_piece_checks<ROOK>(pos, mlist, us, dc, ksq);
183   mlist = generate_piece_checks<QUEEN>(pos, mlist, us, dc, ksq);
184   mlist = generate_piece_checks<KING>(pos, mlist, us, dc, ksq);
185
186   // Castling moves that give check. Very rare but nice to have!
187   if (   pos.can_castle_queenside(us)
188       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_D)
189       && castling_is_check(pos, QUEEN_SIDE))
190       mlist = generate_castle_moves<QUEEN_SIDE>(pos, mlist);
191
192   if (   pos.can_castle_kingside(us)
193       && (square_rank(ksq) == square_rank(pos.king_square(us)) || square_file(ksq) == FILE_F)
194       && castling_is_check(pos, KING_SIDE))
195       mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
196
197   return int(mlist - mlist_start);
198 }
199
200
201 /// generate_evasions() generates all check evasions when the side to move is
202 /// in check.  Unlike the other move generation functions, this one generates
203 /// only legal moves.  It returns the number of generated moves. This
204 /// function is very ugly, and needs cleaning up some time later.  FIXME
205
206 int generate_evasions(const Position& pos, MoveStack* mlist) {
207
208   assert(pos.is_ok());
209   assert(pos.is_check());
210
211   Square from, to;
212   Color us = pos.side_to_move();
213   Color them = opposite_color(us);
214   Square ksq = pos.king_square(us);
215   MoveStack* mlist_start = mlist;
216
217   assert(pos.piece_on(ksq) == king_of_color(us));
218
219   // The bitboard of occupied pieces without our king
220   Bitboard b2 = pos.occupied_squares();
221   clear_bit(&b2, ksq);
222
223   // Find squares attacked by slider checkers, we will
224   // remove them from king evasions set so to avoid a couple
225   // of cycles in the slow king evasions legality check loop.
226   Bitboard checkers = pos.checkers();
227   Bitboard checkersAttacks = EmptyBoardBB;
228   Bitboard b = checkers & (pos.queens() | pos.bishops());
229   while (b)
230   {
231       from = pop_1st_bit(&b);
232       checkersAttacks |= bishop_attacks_bb(from, b2);
233   }
234
235   b = checkers & (pos.queens() | pos.rooks());
236   while (b)
237   {
238       from = pop_1st_bit(&b);
239       checkersAttacks |= rook_attacks_bb(from, b2);
240   }
241
242   // Generate evasions for king
243   Bitboard b1 = pos.piece_attacks<KING>(ksq) & ~pos.pieces_of_color(us) & ~checkersAttacks;
244   while (b1)
245   {
246       to = pop_1st_bit(&b1);
247
248       // Make sure 'to' is not attacked by the other side. This is a bit ugly,
249       // because we can't use Position::square_is_attacked. Instead we use
250       // the low-level bishop_attacks_bb and rook_attacks_bb with the bitboard
251       // b2 (the occupied squares with the king removed) in order to test whether
252       // the king will remain in check on the destination square.
253       if (!(   (pos.piece_attacks<KNIGHT>(to) & pos.knights(them))
254             || (pos.pawn_attacks(us, to)      & pos.pawns(them))
255             || (bishop_attacks_bb(to, b2)     & pos.bishops_and_queens(them))
256             || (rook_attacks_bb(to, b2)       & pos.rooks_and_queens(them))
257             || (pos.piece_attacks<KING>(to)   & pos.kings(them))))
258           (*mlist++).move = make_move(ksq, to);
259   }
260
261   // Generate evasions for other pieces only if not double check. We use a
262   // simple bit twiddling hack here rather than calling count_1s in order to
263   // save some time (we know that pos.checkers() has at most two nonzero bits).
264   if (!(checkers & (checkers - 1))) // Only one bit set?
265   {
266       Square checksq = first_1(checkers);
267
268       assert(pos.color_of_piece_on(checksq) == them);
269
270       // Find pinned pieces
271       Bitboard not_pinned = ~pos.pinned_pieces(us);
272
273       // Generate captures of the checking piece
274
275       // Pawn captures
276       b1 = pos.pawn_attacks(them, checksq) & pos.pawns(us) & not_pinned;
277       while (b1)
278       {
279           from = pop_1st_bit(&b1);
280           if (relative_rank(us, checksq) == RANK_8)
281           {
282               (*mlist++).move = make_promotion_move(from, checksq, QUEEN);
283               (*mlist++).move = make_promotion_move(from, checksq, ROOK);
284               (*mlist++).move = make_promotion_move(from, checksq, BISHOP);
285               (*mlist++).move = make_promotion_move(from, checksq, KNIGHT);
286           } else
287               (*mlist++).move = make_move(from, checksq);
288       }
289
290       // Pieces captures
291       b1 = (  (pos.piece_attacks<KNIGHT>(checksq) & pos.knights(us))
292             | (pos.piece_attacks<BISHOP>(checksq) & pos.bishops_and_queens(us))
293             | (pos.piece_attacks<ROOK>(checksq)   & pos.rooks_and_queens(us)) ) & not_pinned;
294
295       while (b1)
296       {
297           from = pop_1st_bit(&b1);
298           (*mlist++).move = make_move(from, checksq);
299       }
300
301       // Blocking check evasions are possible only if the checking piece is
302       // a slider
303       if (checkers & pos.sliders())
304       {
305           Bitboard blockSquares = squares_between(checksq, ksq);
306
307           assert((pos.occupied_squares() & blockSquares) == EmptyBoardBB);
308
309           // Pieces moves
310           mlist = generate_piece_blocking_evasions<PAWN>(pos, mlist, us, not_pinned, blockSquares);
311           mlist = generate_piece_blocking_evasions<KNIGHT>(pos, mlist, us, not_pinned, blockSquares);
312           mlist = generate_piece_blocking_evasions<BISHOP>(pos, mlist, us, not_pinned, blockSquares);
313           mlist = generate_piece_blocking_evasions<ROOK>(pos, mlist, us, not_pinned, blockSquares);
314           mlist = generate_piece_blocking_evasions<QUEEN>(pos, mlist, us, not_pinned, blockSquares);
315     }
316
317     // Finally, the ugly special case of en passant captures. An en passant
318     // capture can only be a check evasion if the check is not a discovered
319     // check. If pos.ep_square() is set, the last move made must have been
320     // a double pawn push. If, furthermore, the checking piece is a pawn,
321     // an en passant check evasion may be possible.
322     if (pos.ep_square() != SQ_NONE && (checkers & pos.pawns(them)))
323     {
324         to = pos.ep_square();
325         b1 = pos.pawn_attacks(them, to) & pos.pawns(us);
326
327         assert(b1 != EmptyBoardBB);
328
329         b1 &= not_pinned;
330         while (b1)
331         {
332             from = pop_1st_bit(&b1);
333
334             // Before generating the move, we have to make sure it is legal.
335             // This is somewhat tricky, because the two disappearing pawns may
336             // cause new "discovered checks".  We test this by removing the
337             // two relevant bits from the occupied squares bitboard, and using
338             // the low-level bitboard functions for bishop and rook attacks.
339             b2 = pos.occupied_squares();
340             clear_bit(&b2, from);
341             clear_bit(&b2, checksq);
342             if (!(  (bishop_attacks_bb(ksq, b2) & pos.bishops_and_queens(them))
343                   ||(rook_attacks_bb(ksq, b2)   & pos.rooks_and_queens(them))))
344
345                  (*mlist++).move = make_ep_move(from, to);
346         }
347     }
348   }
349   return int(mlist - mlist_start);
350 }
351
352
353 /// generate_legal_moves() computes a complete list of legal moves in the
354 /// current position. This function is not very fast, and should be used
355 /// only in situations where performance is unimportant. It wouldn't be
356 /// very hard to write an efficient legal move generator, but for the moment
357 /// we don't need it.
358
359 int generate_legal_moves(const Position& pos, MoveStack* mlist) {
360
361   assert(pos.is_ok());
362
363   if (pos.is_check())
364       return generate_evasions(pos, mlist);
365
366   // Generate pseudo-legal moves
367   int n = generate_captures(pos, mlist);
368   n += generate_noncaptures(pos, mlist + n);
369
370   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
371
372   // Remove illegal moves from the list
373   for (int i = 0; i < n; i++)
374       if (!pos.pl_move_is_legal(mlist[i].move, pinned))
375           mlist[i--].move = mlist[--n].move;
376
377   return n;
378 }
379
380
381 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
382 /// move and a pinned pieces bitboard as input, and tests whether
383 /// the move is legal.  If the move is legal, the move itself is
384 /// returned. If not, the function returns false.  This function must
385 /// only be used when the side to move is not in check.
386
387 bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
388
389   assert(pos.is_ok());
390   assert(!pos.is_check());
391   assert(move_is_ok(m));
392   assert(pinned == pos.pinned_pieces(pos.side_to_move()));
393
394   Color us = pos.side_to_move();
395   Color them = opposite_color(us);
396   Square from = move_from(m);
397   Piece pc = pos.piece_on(from);
398
399   // If the from square is not occupied by a piece belonging to the side to
400   // move, the move is obviously not legal.
401   if (color_of_piece(pc) != us)
402       return false;
403
404   Square to = move_to(m);
405
406   // En passant moves
407   if (move_is_ep(m))
408   {
409       // The piece must be a pawn and destination square must be the
410       // en passant square.
411       if (   type_of_piece(pc) != PAWN
412           || to != pos.ep_square())
413           return false;
414
415       assert(pos.square_is_empty(to));
416       assert(pos.piece_on(to - pawn_push(us)) == pawn_of_color(them));
417
418       // The move is pseudo-legal, check if it is also legal
419       return pos.pl_move_is_legal(m, pinned);
420   }
421
422   // Castling moves
423   if (move_is_short_castle(m))
424   {
425       // The piece must be a king and side to move must still have
426       // the right to castle kingside.
427       if (   type_of_piece(pc) != KING
428           ||!pos.can_castle_kingside(us))
429           return false;
430
431       assert(from == pos.king_square(us));
432       assert(to == pos.initial_kr_square(us));
433       assert(pos.piece_on(to) == rook_of_color(us));
434
435       Square g1 = relative_square(us, SQ_G1);
436       Square f1 = relative_square(us, SQ_F1);
437       Square s;
438       bool illegal = false;
439
440       // Check if any of the squares between king and rook
441       // is occupied or under attack.
442       for (s = Min(from, g1); s <= Max(from, g1); s++)
443           if (  (s != from && s != to && !pos.square_is_empty(s))
444               || pos.square_is_attacked(s, them))
445               illegal = true;
446
447       // Check if any of the squares between king and rook
448       // is occupied.
449       for (s = Min(to, f1); s <= Max(to, f1); s++)
450           if (s != from && s != to && !pos.square_is_empty(s))
451               illegal = true;
452
453       return !illegal;
454   }
455
456   if (move_is_long_castle(m))
457   {
458       // The piece must be a king and side to move must still have
459       // the right to castle kingside.
460       if (   type_of_piece(pc) != KING
461           ||!pos.can_castle_queenside(us))
462           return false;
463
464       assert(from == pos.king_square(us));
465       assert(to == pos.initial_qr_square(us));
466       assert(pos.piece_on(to) == rook_of_color(us));
467
468       Square c1 = relative_square(us, SQ_C1);
469       Square d1 = relative_square(us, SQ_D1);
470       Square s;
471       bool illegal = false;
472
473       for (s = Min(from, c1); s <= Max(from, c1); s++)
474           if(  (s != from && s != to && !pos.square_is_empty(s))
475              || pos.square_is_attacked(s, them))
476               illegal = true;
477
478       for (s = Min(to, d1); s <= Max(to, d1); s++)
479           if(s != from && s != to && !pos.square_is_empty(s))
480               illegal = true;
481
482       if (   square_file(to) == FILE_B
483           && (   pos.piece_on(to + DELTA_W) == rook_of_color(them)
484               || pos.piece_on(to + DELTA_W) == queen_of_color(them)))
485           illegal = true;
486
487       return !illegal;
488   }
489
490   // Normal moves
491
492   // The destination square cannot be occupied by a friendly piece
493   if (pos.color_of_piece_on(to) == us)
494       return false;
495
496   // Proceed according to the type of the moving piece.
497   if (type_of_piece(pc) == PAWN)
498   {
499       // If the destination square is on the 8/1th rank, the move must
500       // be a promotion.
501       if (   (  (square_rank(to) == RANK_8 && us == WHITE)
502               ||(square_rank(to) == RANK_1 && us != WHITE))
503            && !move_promotion(m))
504           return false;
505
506       // Proceed according to the square delta between the source and
507       // destionation squares.
508       switch (to - from)
509       {
510       case DELTA_NW:
511       case DELTA_NE:
512       case DELTA_SW:
513       case DELTA_SE:
514       // Capture. The destination square must be occupied by an enemy
515       // piece (en passant captures was handled earlier).
516           if (pos.color_of_piece_on(to) != them)
517               return false;
518           break;
519
520       case DELTA_N:
521       case DELTA_S:
522       // Pawn push. The destination square must be empty.
523           if (!pos.square_is_empty(to))
524               return false;
525           break;
526
527       case DELTA_NN:
528       // Double white pawn push. The destination square must be on the fourth
529       // rank, and both the destination square and the square between the
530       // source and destination squares must be empty.
531       if (   square_rank(to) != RANK_4
532           || !pos.square_is_empty(to)
533           || !pos.square_is_empty(from + DELTA_N))
534           return false;
535           break;
536
537       case DELTA_SS:
538       // Double black pawn push. The destination square must be on the fifth
539       // rank, and both the destination square and the square between the
540       // source and destination squares must be empty.
541           if (   square_rank(to) != RANK_5
542               || !pos.square_is_empty(to)
543               || !pos.square_is_empty(from + DELTA_S))
544               return false;
545           break;
546
547       default:
548           return false;
549       }
550       // The move is pseudo-legal, check if it is also legal
551       return pos.pl_move_is_legal(m, pinned);
552   }
553
554   // Luckly we can handle all the other pieces in one go
555   return (   pos.piece_attacks_square(from, to)
556           && pos.pl_move_is_legal(m, pinned)
557           && !move_promotion(m));
558 }
559
560
561 namespace {
562
563   template<PieceType Piece>
564   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
565
566     Square from;
567     Bitboard b;
568
569     for (int i = 0, e = pos.piece_count(us, Piece); i < e; i++)
570     {
571         from = pos.piece_list(us, Piece, i);
572         b = pos.piece_attacks<Piece>(from) & target;
573         SERIALIZE_MOVES(b);
574     }
575     return mlist;
576   }
577
578   template<>
579   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
580
581     Bitboard b;
582     Square from = pos.king_square(us);
583
584     b = pos.piece_attacks<KING>(from) & target;
585     SERIALIZE_MOVES(b);
586     return mlist;
587   }
588
589   template<PieceType Piece>
590   MoveStack* generate_piece_blocking_evasions(const Position& pos, MoveStack* mlist, Color us,
591                                               Bitboard not_pinned, Bitboard blockSquares) {
592
593     Bitboard b = pos.pieces_of_color_and_type(us, Piece) & not_pinned;
594     while (b)
595     {
596         Square from = pop_1st_bit(&b);
597         Bitboard bb = pos.piece_attacks<Piece>(from) & blockSquares;
598         SERIALIZE_MOVES(bb);
599     }
600     return mlist;
601   }
602
603   template<>
604   MoveStack* generate_piece_blocking_evasions<PAWN>(const Position& p, MoveStack* m, Color us,
605                                                     Bitboard np, Bitboard bs) {
606     if (us == WHITE)
607         return do_generate_pawn_blocking_evasions<WHITE, RANK_8, Rank3BB, DELTA_N>(p, np, bs, m);
608     else
609         return do_generate_pawn_blocking_evasions<BLACK, RANK_1, Rank6BB, DELTA_S>(p, np, bs, m);
610   }
611
612   template<Color Us, Color Them, Bitboard TRank8BB, SquareDelta TDELTA_NE,
613            SquareDelta TDELTA_NW, SquareDelta TDELTA_N
614           >
615   MoveStack* do_generate_pawn_captures(const Position& pos, MoveStack* mlist) {
616
617     Square to;
618     Bitboard pawns = pos.pawns(Us);
619     Bitboard enemyPieces = pos.pieces_of_color(Them);
620
621     // Captures in the a1-h8 (a8-h1 for black) direction
622     Bitboard b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces;
623
624     // Capturing promotions
625     Bitboard b2 = b1 & TRank8BB;
626     while (b2)
627     {
628         to = pop_1st_bit(&b2);
629         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, QUEEN);
630     }
631
632     // Capturing non-promotions
633     b2 = b1 & ~TRank8BB;
634     while (b2)
635     {
636         to = pop_1st_bit(&b2);
637         (*mlist++).move = make_move(to - TDELTA_NE, to);
638     }
639
640     // Captures in the h1-a8 (h8-a1 for black) direction
641     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces;
642
643     // Capturing promotions
644     b2 = b1 & TRank8BB;
645     while (b2)
646     {
647         to = pop_1st_bit(&b2);
648         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, QUEEN);
649     }
650
651     // Capturing non-promotions
652     b2 = b1 & ~TRank8BB;
653     while (b2)
654     {
655         to = pop_1st_bit(&b2);
656         (*mlist++).move = make_move(to - TDELTA_NW, to);
657     }
658
659     // Non-capturing promotions
660     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & pos.empty_squares() & TRank8BB;
661     while (b1)
662     {
663         to = pop_1st_bit(&b1);
664         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
665     }
666
667     // En passant captures
668     if (pos.ep_square() != SQ_NONE)
669     {
670         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
671         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
672
673         b1 = pawns & pos.pawn_attacks(Them, pos.ep_square());
674         assert(b1 != EmptyBoardBB);
675
676         while (b1)
677         {
678             to = pop_1st_bit(&b1);
679             (*mlist++).move = make_ep_move(to, pos.ep_square());
680         }
681     }
682     return mlist;
683   }
684
685   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB,
686            SquareDelta TDELTA_NE, SquareDelta TDELTA_NW, SquareDelta TDELTA_N
687           >
688   MoveStack* do_generate_pawn_noncaptures(const Position& pos, MoveStack* mlist) {
689
690     Bitboard pawns = pos.pawns(Us);
691     Bitboard enemyPieces = pos.pieces_of_color(Them);
692     Bitboard emptySquares = pos.empty_squares();
693     Bitboard b1, b2;
694     Square to;
695
696     // Underpromotion captures in the a1-h8 (a8-h1 for black) direction
697     b1 = (Us == WHITE ? pawns << 9 : pawns >> 7) & ~FileABB & enemyPieces & TRank8BB;
698     while (b1)
699     {
700         to = pop_1st_bit(&b1);
701         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, ROOK);
702         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, BISHOP);
703         (*mlist++).move = make_promotion_move(to - TDELTA_NE, to, KNIGHT);
704     }
705
706     // Underpromotion captures in the h1-a8 (h8-a1 for black) direction
707     b1 = (Us == WHITE ? pawns << 7 : pawns >> 9) & ~FileHBB & enemyPieces & TRank8BB;
708     while (b1)
709     {
710         to = pop_1st_bit(&b1);
711         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, ROOK);
712         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, BISHOP);
713         (*mlist++).move = make_promotion_move(to - TDELTA_NW, to, KNIGHT);
714     }
715
716     // Single pawn pushes
717     b1 = (Us == WHITE ? pawns << 8 : pawns >> 8) & emptySquares;
718     b2 = b1 & TRank8BB;
719     while (b2)
720     {
721         to = pop_1st_bit(&b2);
722         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
723         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
724         (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
725     }
726     b2 = b1 & ~TRank8BB;
727     while (b2)
728     {
729         to = pop_1st_bit(&b2);
730         (*mlist++).move = make_move(to - TDELTA_N, to);
731     }
732
733     // Double pawn pushes
734     b2 = (Us == WHITE ? (b1 & TRank3BB) << 8 : (b1 & TRank3BB) >> 8) & emptySquares;
735     while (b2)
736     {
737         to = pop_1st_bit(&b2);
738         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
739     }
740     return mlist;
741   }
742
743
744   template<Color Us, Color Them, Bitboard TRank8BB, Bitboard TRank3BB, SquareDelta TDELTA_N>
745   MoveStack* do_generate_pawn_checks(const Position& pos, Bitboard dc, Square ksq, MoveStack* mlist)
746   {
747     // Find all friendly pawns not on the enemy king's file
748     Bitboard b1, b2, b3;
749     Bitboard empty = pos.empty_squares();
750
751     if (dc != EmptyBoardBB)
752     {
753         // Pawn moves which gives discovered check. This is possible only if the
754         // pawn is not on the same file as the enemy king, because we don't
755         // generate captures.
756         b1 = pos.pawns(Us) & ~file_bb(ksq);
757
758         // Discovered checks, single pawn pushes, no promotions
759         b2 = b3 = (Us == WHITE ? (b1 & dc) << 8 : (b1 & dc) >> 8) & empty & ~TRank8BB;
760         while (b3)
761         {
762             Square to = pop_1st_bit(&b3);
763             (*mlist++).move = make_move(to - TDELTA_N, to);
764         }
765
766         // Discovered checks, double pawn pushes
767         b3 = (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8) & empty;
768         while (b3)
769         {
770             Square to = pop_1st_bit(&b3);
771             (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
772         }
773     }
774
775     // Direct checks. These are possible only for pawns on neighboring files
776     // of the enemy king.
777     b1 = pos.pawns(Us) & neighboring_files_bb(ksq) & ~dc;
778
779     // Direct checks, single pawn pushes
780     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & empty;
781     b3 = b2 & pos.pawn_attacks(Them, ksq);
782     while (b3)
783     {
784         Square to = pop_1st_bit(&b3);
785         (*mlist++).move = make_move(to - TDELTA_N, to);
786     }
787
788     // Direct checks, double pawn pushes
789     b3 =  (Us == WHITE ? (b2 & TRank3BB) << 8 : (b2 & TRank3BB) >> 8)
790         & empty
791         & pos.pawn_attacks(Them, ksq);
792     while (b3)
793     {
794         Square to = pop_1st_bit(&b3);
795         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
796     }
797     return mlist;
798   }
799
800   template<PieceType Piece>
801   MoveStack* generate_piece_checks(const Position& pos, MoveStack* mlist, Color us,
802                                    Bitboard dc, Square ksq) {
803
804     Bitboard target = pos.pieces_of_color_and_type(us, Piece);
805
806     // Discovered checks
807     Bitboard b = target & dc;
808     while (b)
809     {
810         Square from = pop_1st_bit(&b);
811         Bitboard bb = pos.piece_attacks<Piece>(from) & pos.empty_squares();
812         if (Piece == KING)
813             bb &= ~QueenPseudoAttacks[ksq];
814
815         SERIALIZE_MOVES(bb);
816     }
817
818     // Direct checks
819     b = target & ~dc;
820     if (Piece == KING || !b)
821         return mlist;
822
823     Bitboard checkSqs = pos.piece_attacks<Piece>(ksq) & pos.empty_squares();
824     while (b)
825     {
826         Square from = pop_1st_bit(&b);
827         Bitboard bb = pos.piece_attacks<Piece>(from) & checkSqs;
828         SERIALIZE_MOVES(bb);
829     }
830     return mlist;
831   }
832
833   template<Color Us, Rank TRANK_8, Bitboard TRank3BB, SquareDelta TDELTA_N>
834   MoveStack* do_generate_pawn_blocking_evasions(const Position& pos, Bitboard not_pinned,
835                                                 Bitboard blockSquares, MoveStack* mlist) {
836     Square to;
837
838     // Find non-pinned pawns
839     Bitboard b1 = pos.pawns(Us) & not_pinned;
840
841     // Single pawn pushes. We don't have to AND with empty squares here,
842     // because the blocking squares will always be empty.
843     Bitboard b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & blockSquares;
844     while (b2)
845     {
846         to = pop_1st_bit(&b2);
847
848         assert(pos.piece_on(to) == EMPTY);
849
850         if (square_rank(to) == TRANK_8)
851         {
852             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
853             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
854             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
855             (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
856         } else
857             (*mlist++).move = make_move(to - TDELTA_N, to);
858     }
859
860     // Double pawn pushes
861     b2 = (Us == WHITE ? b1 << 8 : b1 >> 8) & pos.empty_squares() & TRank3BB;
862     b2 = (Us == WHITE ? b2 << 8 : b2 >> 8) & blockSquares;;
863     while (b2)
864     {
865         to = pop_1st_bit(&b2);
866
867         assert(pos.piece_on(to) == EMPTY);
868         assert(Us != WHITE || square_rank(to) == RANK_4);
869         assert(Us != BLACK || square_rank(to) == RANK_5);
870
871         (*mlist++).move = make_move(to - TDELTA_N - TDELTA_N, to);
872     }
873     return mlist;
874   }
875
876   template<CastlingSide Side>
877   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
878
879     Color us = pos.side_to_move();
880
881     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
882         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
883     {
884         Color them = opposite_color(us);
885         Square ksq = pos.king_square(us);
886
887         assert(pos.piece_on(ksq) == king_of_color(us));
888
889         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
890         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
891         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
892         Square s;
893         bool illegal = false;
894
895         assert(pos.piece_on(rsq) == rook_of_color(us));
896
897         // It is a bit complicated to correctly handle Chess960
898         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
899             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
900                 || pos.square_is_attacked(s, them))
901                 illegal = true;
902
903         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
904             if (s != ksq && s != rsq && pos.square_is_occupied(s))
905                 illegal = true;
906
907         if (   Side == QUEEN_SIDE
908             && square_file(rsq) == FILE_B
909             && (   pos.piece_on(relative_square(us, SQ_A1)) == rook_of_color(them)
910                 || pos.piece_on(relative_square(us, SQ_A1)) == queen_of_color(them)))
911             illegal = true;
912
913         if (!illegal)
914             (*mlist++).move = make_castle_move(ksq, rsq);
915     }
916     return mlist;
917   }
918
919   bool castling_is_check(const Position& pos, CastlingSide side) {
920
921     // After castling opponent king is attacked by the castled rook?
922     File rookFile = (side == QUEEN_SIDE ? FILE_D : FILE_F);
923     Color us = pos.side_to_move();
924     Square ksq = pos.king_square(us);
925     Bitboard occ = pos.occupied_squares();
926
927     clear_bit(&occ, ksq); // Remove our king from the board
928     Square rsq = make_square(rookFile, square_rank(ksq));
929     return bit_is_set(rook_attacks_bb(rsq, occ), pos.king_square(opposite_color(us)));
930   }
931 }