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