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