]> git.sesse.net Git - stockfish/blob - src/movegen.cpp
da619d1c605e17de1199aa99de245403d60adb79
[stockfish] / src / movegen.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2009 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26
27 #include "bitcount.h"
28 #include "movegen.h"
29
30 // Simple macro to wrap a very common while loop, no facny, no flexibility,
31 // hardcoded list name 'mlist' and from square 'from'.
32 #define SERIALIZE_MOVES(b) while (b) (*mlist++).move = make_move(from, pop_1st_bit(&b))
33
34 // Version used for pawns, where the 'from' square is given as a delta from the 'to' square
35 #define SERIALIZE_MOVES_D(b, d) while (b) { to = pop_1st_bit(&b); (*mlist++).move = make_move(to + (d), to); }
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   enum CastlingSide {
44     KING_SIDE,
45     QUEEN_SIDE
46   };
47
48   enum MoveType {
49     CAPTURE,
50     NON_CAPTURE,
51     CHECK,
52     EVASION
53   };
54
55   // Helper templates
56   template<CastlingSide Side>
57   MoveStack* generate_castle_moves(const Position&, MoveStack*);
58
59   template<Color Us, MoveType Type>
60   MoveStack* generate_pawn_moves(const Position&, MoveStack*, Bitboard, Square);
61
62   // Template generate_piece_moves (captures and non-captures) with specializations and overloads
63   template<PieceType>
64   MoveStack* generate_piece_moves(const Position&, MoveStack*, Color, Bitboard);
65
66   template<>
67   MoveStack* generate_piece_moves<KING>(const Position&, MoveStack*, Color, Bitboard);
68
69   template<PieceType Piece, MoveType Type>
70   inline MoveStack* generate_piece_moves(const Position& p, MoveStack* m, Color us, Bitboard t) {
71
72     assert(Piece == PAWN);
73     assert(Type == CAPTURE || Type == NON_CAPTURE || Type == EVASION);
74
75     return (us == WHITE ? generate_pawn_moves<WHITE, Type>(p, m, t, SQ_NONE)
76                         : generate_pawn_moves<BLACK, Type>(p, m, t, SQ_NONE));
77   }
78
79   // Templates for non-capture checks generation
80
81   template<PieceType Piece>
82   MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from);
83
84   template<PieceType>
85   MoveStack* generate_direct_checks(const Position&, MoveStack*, Color, Bitboard, Square);
86
87   template<>
88   inline MoveStack* generate_direct_checks<PAWN>(const Position& p, MoveStack* m, Color us, Bitboard dc, Square ksq) {
89
90     return (us == WHITE ? generate_pawn_moves<WHITE, CHECK>(p, m, dc, ksq)
91                         : generate_pawn_moves<BLACK, CHECK>(p, m, dc, ksq));
92   }
93 }
94
95
96 ////
97 //// Functions
98 ////
99
100
101 /// generate_captures() generates all pseudo-legal captures and queen
102 /// promotions. Returns a pointer to the end of the move list.
103
104 MoveStack* generate_captures(const Position& pos, MoveStack* mlist) {
105
106   assert(pos.is_ok());
107   assert(!pos.is_check());
108
109   Color us = pos.side_to_move();
110   Bitboard target = pos.pieces_of_color(opposite_color(us));
111
112   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
113   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
114   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
115   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
116   mlist = generate_piece_moves<PAWN, CAPTURE>(pos, mlist, us, target);
117   return  generate_piece_moves<KING>(pos, mlist, us, target);
118 }
119
120
121 /// generate_noncaptures() generates all pseudo-legal non-captures and
122 /// underpromotions. Returns a pointer to the end of the move list.
123
124 MoveStack* generate_noncaptures(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.empty_squares();
131
132   mlist = generate_piece_moves<PAWN, NON_CAPTURE>(pos, mlist, us, target);
133   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
134   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
135   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
136   mlist = generate_piece_moves<QUEEN>(pos, mlist, us, target);
137   mlist = generate_piece_moves<KING>(pos, mlist, us, target);
138   mlist = generate_castle_moves<KING_SIDE>(pos, mlist);
139   return  generate_castle_moves<QUEEN_SIDE>(pos, mlist);
140 }
141
142
143 /// generate_non_capture_checks() generates all pseudo-legal non-captures and knight
144 /// underpromotions that give check. Returns a pointer to the end of the move list.
145
146 MoveStack* generate_non_capture_checks(const Position& pos, MoveStack* mlist) {
147
148   assert(pos.is_ok());
149   assert(!pos.is_check());
150
151   Color us = pos.side_to_move();
152   Square ksq = pos.king_square(opposite_color(us));
153   Bitboard dc = pos.discovered_check_candidates(us);
154
155   assert(pos.piece_on(ksq) == piece_of_color_and_type(opposite_color(us), KING));
156
157   // Discovered non-capture checks
158   Bitboard b = dc;
159   while (b)
160   {
161      Square from = pop_1st_bit(&b);
162      switch (pos.type_of_piece_on(from))
163      {
164       case PAWN:   /* Will be generated togheter with pawns direct checks */     break;
165       case KNIGHT: mlist = generate_discovered_checks<KNIGHT>(pos, mlist, from); break;
166       case BISHOP: mlist = generate_discovered_checks<BISHOP>(pos, mlist, from); break;
167       case ROOK:   mlist = generate_discovered_checks<ROOK>(pos, mlist, from);   break;
168       case KING:   mlist = generate_discovered_checks<KING>(pos, mlist, from);   break;
169       default: assert(false); break;
170      }
171   }
172
173   // Direct non-capture checks
174   mlist = generate_direct_checks<PAWN>(pos, mlist, us, dc, ksq);
175   mlist = generate_direct_checks<KNIGHT>(pos, mlist, us, dc, ksq);
176   mlist = generate_direct_checks<BISHOP>(pos, mlist, us, dc, ksq);
177   mlist = generate_direct_checks<ROOK>(pos, mlist, us, dc, ksq);
178   return  generate_direct_checks<QUEEN>(pos, mlist, us, dc, ksq);
179 }
180
181
182 /// generate_evasions() generates all pseudo-legal check evasions when
183 /// the side to move is in check. Returns a pointer to the end of the move list.
184
185 MoveStack* generate_evasions(const Position& pos, MoveStack* mlist) {
186
187   assert(pos.is_ok());
188   assert(pos.is_check());
189
190   Bitboard b;
191   Square from, checksq;
192   int checkersCnt = 0;
193   Color us = pos.side_to_move();
194   Square ksq = pos.king_square(us);
195   Bitboard checkers = pos.checkers();
196   Bitboard sliderAttacks = EmptyBoardBB;
197
198   assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
199   assert(checkers);
200
201   // Find squares attacked by slider checkers, we will remove
202   // them from the king evasions set so to early skip known
203   // illegal moves and avoid an useless legality check later.
204   b = checkers;
205   do
206   {
207       checkersCnt++;
208       checksq = pop_1st_bit(&b);
209
210       assert(pos.color_of_piece_on(checksq) == opposite_color(us));
211
212       switch (pos.type_of_piece_on(checksq))
213       {
214       case BISHOP: sliderAttacks |= BishopPseudoAttacks[checksq]; break;
215       case ROOK:   sliderAttacks |= RookPseudoAttacks[checksq];   break;
216       case QUEEN:
217           // In case of a queen remove also squares attacked in the other direction to
218           // avoid possible illegal moves when queen and king are on adjacent squares.
219           if (direction_is_straight(checksq, ksq))
220               sliderAttacks |= RookPseudoAttacks[checksq] | pos.attacks_from<BISHOP>(checksq);
221           else
222               sliderAttacks |= BishopPseudoAttacks[checksq] | pos.attacks_from<ROOK>(checksq);
223       default:
224           break;
225       }
226   } while (b);
227
228   // Generate evasions for king, capture and non capture moves
229   b = pos.attacks_from<KING>(ksq) & ~pos.pieces_of_color(us) & ~sliderAttacks;
230   from = ksq;
231   SERIALIZE_MOVES(b);
232
233   // Generate evasions for other pieces only if not double check
234   if (checkersCnt > 1)
235       return mlist;
236
237   // Find squares where a blocking evasion or a capture of the
238   // checker piece is possible.
239   Bitboard target = squares_between(checksq, ksq) | checkers;
240
241   mlist = generate_piece_moves<PAWN, EVASION>(pos, mlist, us, target);
242   mlist = generate_piece_moves<KNIGHT>(pos, mlist, us, target);
243   mlist = generate_piece_moves<BISHOP>(pos, mlist, us, target);
244   mlist = generate_piece_moves<ROOK>(pos, mlist, us, target);
245   return  generate_piece_moves<QUEEN>(pos, mlist, us, target);
246 }
247
248
249 /// generate_moves() computes a complete list of legal or pseudo-legal moves in
250 /// the current position. This function is not very fast, and should be used
251 /// only in non time-critical paths.
252
253 MoveStack* generate_moves(const Position& pos, MoveStack* mlist, bool pseudoLegal) {
254
255   assert(pos.is_ok());
256
257   MoveStack* last;
258   Bitboard pinned = pos.pinned_pieces(pos.side_to_move());
259
260   // Generate pseudo-legal moves
261   if (pos.is_check())
262       last = generate_evasions(pos, mlist);
263   else {
264       last = generate_captures(pos, mlist);
265       last = generate_noncaptures(pos, last);
266   }
267   if (pseudoLegal)
268       return last;
269
270   // Remove illegal moves from the list
271   for (MoveStack* cur = mlist; cur != last; cur++)
272       if (!pos.pl_move_is_legal(cur->move, pinned))
273       {
274           cur->move = (--last)->move;
275           cur--;
276       }
277   return last;
278 }
279
280
281 /// move_is_legal() takes a position and a (not necessarily pseudo-legal)
282 /// move and tests whether the move is legal. This version is not very fast
283 /// and should be used only in non time-critical paths.
284
285 bool move_is_legal(const Position& pos, const Move m) {
286
287   MoveStack mlist[256];
288   MoveStack* last = generate_moves(pos, mlist, true);
289   for (MoveStack* cur = mlist; cur != last; cur++)
290       if (cur->move == m)
291           return pos.pl_move_is_legal(m, pos.pinned_pieces(pos.side_to_move()));
292
293   return false;
294 }
295
296
297 /// Fast version of move_is_legal() that takes a position a move and a
298 /// bitboard of pinned pieces as input, and tests whether the move is legal.
299
300 bool move_is_legal(const Position& pos, const Move m, Bitboard pinned) {
301
302   assert(pos.is_ok());
303   assert(move_is_ok(m));
304   assert(pinned == pos.pinned_pieces(pos.side_to_move()));
305
306   // Use a slower but simpler function for uncommon cases
307   if (move_is_ep(m) || move_is_castle(m))
308       return move_is_legal(pos, m);
309
310   Color us = pos.side_to_move();
311   Color them = opposite_color(us);
312   Square from = move_from(m);
313   Square to = move_to(m);
314   Piece pc = pos.piece_on(from);
315
316   // If the from square is not occupied by a piece belonging to the side to
317   // move, the move is obviously not legal.
318   if (color_of_piece(pc) != us)
319       return false;
320
321   // The destination square cannot be occupied by a friendly piece
322   if (pos.color_of_piece_on(to) == us)
323       return false;
324
325   // Handle the special case of a pawn move
326   if (type_of_piece(pc) == PAWN)
327   {
328       // Move direction must be compatible with pawn color
329       int direction = to - from;
330       if ((us == WHITE) != (direction > 0))
331           return false;
332
333       // A pawn move is a promotion iff the destination square is
334       // on the 8/1th rank.
335       if ((  (square_rank(to) == RANK_8 && us == WHITE)
336            ||(square_rank(to) == RANK_1 && us != WHITE)) != bool(move_is_promotion(m)))
337           return false;
338
339       // Proceed according to the square delta between the origin and
340       // destination squares.
341       switch (direction)
342       {
343       case DELTA_NW:
344       case DELTA_NE:
345       case DELTA_SW:
346       case DELTA_SE:
347       // Capture. The destination square must be occupied by an enemy
348       // piece (en passant captures was handled earlier).
349           if (pos.color_of_piece_on(to) != them)
350               return false;
351           break;
352
353       case DELTA_N:
354       case DELTA_S:
355       // Pawn push. The destination square must be empty.
356           if (!pos.square_is_empty(to))
357               return false;
358           break;
359
360       case DELTA_NN:
361       // Double white pawn push. The destination square must be on the fourth
362       // rank, and both the destination square and the square between the
363       // source and destination squares must be empty.
364       if (   square_rank(to) != RANK_4
365           || !pos.square_is_empty(to)
366           || !pos.square_is_empty(from + DELTA_N))
367           return false;
368           break;
369
370       case DELTA_SS:
371       // Double black pawn push. The destination square must be on the fifth
372       // rank, and both the destination square and the square between the
373       // source and destination squares must be empty.
374           if (   square_rank(to) != RANK_5
375               || !pos.square_is_empty(to)
376               || !pos.square_is_empty(from + DELTA_S))
377               return false;
378           break;
379
380       default:
381           return false;
382       }
383       // The move is pseudo-legal, check if it is also legal
384       return pos.is_check() ? pos.pl_move_is_evasion(m, pinned) : pos.pl_move_is_legal(m, pinned);
385   }
386
387   // Luckly we can handle all the other pieces in one go
388   return    bit_is_set(pos.attacks_from(pc, from), to)
389         && (pos.is_check() ? pos.pl_move_is_evasion(m, pinned) : pos.pl_move_is_legal(m, pinned))
390         && !move_is_promotion(m);
391 }
392
393
394 namespace {
395
396   template<PieceType Piece>
397   MoveStack* generate_piece_moves(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
398
399     Square from;
400     Bitboard b;
401     const Square* ptr = pos.piece_list_begin(us, Piece);
402
403     while ((from = *ptr++) != SQ_NONE)
404     {
405         b = pos.attacks_from<Piece>(from) & target;
406         SERIALIZE_MOVES(b);
407     }
408     return mlist;
409   }
410
411   template<>
412   MoveStack* generate_piece_moves<KING>(const Position& pos, MoveStack* mlist, Color us, Bitboard target) {
413
414     Bitboard b;
415     Square from = pos.king_square(us);
416
417     b = pos.attacks_from<KING>(from) & target;
418     SERIALIZE_MOVES(b);
419     return mlist;
420   }
421
422   template<Color Us, SquareDelta Direction>
423   inline Bitboard move_pawns(Bitboard p) {
424
425     if (Direction == DELTA_N)
426         return Us == WHITE ? p << 8 : p >> 8;
427     else if (Direction == DELTA_NE)
428         return Us == WHITE ? p << 9 : p >> 7;
429     else if (Direction == DELTA_NW)
430         return Us == WHITE ? p << 7 : p >> 9;
431     else
432         return p;
433   }
434
435   template<Color Us, MoveType Type, SquareDelta Diagonal>
436   inline MoveStack* generate_pawn_captures(MoveStack* mlist, Bitboard pawns, Bitboard enemyPieces, bool possiblePromotion) {
437
438     // Calculate our parametrized parameters at compile time
439     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
440     const Bitboard TFileABB = (Diagonal == DELTA_NE ? FileABB : FileHBB);
441     const SquareDelta TDELTA_NE = (Us == WHITE ? DELTA_NE : DELTA_SE);
442     const SquareDelta TDELTA_NW = (Us == WHITE ? DELTA_NW : DELTA_SW);
443     const SquareDelta TTDELTA_NE = (Diagonal == DELTA_NE ? TDELTA_NE : TDELTA_NW);
444
445     Square to;
446
447     // Captures in the a1-h8 (a8-h1 for black) diagonal or in the h1-a8 (h8-a1 for black)
448     Bitboard b1 = move_pawns<Us, Diagonal>(pawns) & ~TFileABB & enemyPieces;
449
450     // Capturing promotions and under-promotions
451     if (possiblePromotion)
452     {
453         Bitboard b2 = b1 & TRank8BB;
454         b1 &= ~TRank8BB;
455         while (b2)
456         {
457             to = pop_1st_bit(&b2);
458
459             if (Type == CAPTURE || Type == EVASION)
460                 (*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, QUEEN);
461
462             if (Type == NON_CAPTURE || Type == EVASION)
463             {
464                 (*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, ROOK);
465                 (*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, BISHOP);
466                 (*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, KNIGHT);
467             }
468
469             // This is the only possible under promotion that can give a check
470             // not already included in the queen-promotion. It is not sure that
471             // the promoted knight will give check, but it doesn't worth to verify.
472             if (Type == CHECK)
473                 (*mlist++).move = make_promotion_move(to - TTDELTA_NE, to, KNIGHT);
474         }
475     }
476
477     // Serialize standard captures
478     if (Type == CAPTURE || Type == EVASION)
479         SERIALIZE_MOVES_D(b1, -TTDELTA_NE);
480
481     return mlist;
482   }
483
484   template<Color Us, MoveType Type>
485   MoveStack* generate_pawn_moves(const Position& pos, MoveStack* mlist, Bitboard target, Square ksq) {
486
487     // Calculate our parametrized parameters at compile time
488     const Color Them = (Us == WHITE ? BLACK : WHITE);
489     const Bitboard TRank8BB = (Us == WHITE ? Rank8BB : Rank1BB);
490     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB : Rank2BB);
491     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB : Rank6BB);
492     const SquareDelta TDELTA_N = (Us == WHITE ? DELTA_N : DELTA_S);
493
494     Square to;
495     Bitboard b1, b2, enemyPieces, emptySquares;
496     Bitboard pawns = pos.pieces(PAWN, Us);
497     bool possiblePromotion = pawns & TRank7BB;
498
499     // Standard captures and capturing promotions and underpromotions
500     if (Type == CAPTURE || Type == EVASION || possiblePromotion)
501     {
502         enemyPieces = (Type == CAPTURE ? target : pos.pieces_of_color(opposite_color(Us)));
503
504         if (Type == EVASION)
505             enemyPieces &= target; // Capture only the checker piece
506
507         mlist = generate_pawn_captures<Us, Type, DELTA_NE>(mlist, pawns, enemyPieces, possiblePromotion);
508         mlist = generate_pawn_captures<Us, Type, DELTA_NW>(mlist, pawns, enemyPieces, possiblePromotion);
509     }
510
511     // Non-capturing promotions and underpromotions
512     if (possiblePromotion)
513     {
514         b1 = move_pawns<Us, DELTA_N>(pawns) & TRank8BB & pos.empty_squares();
515
516         if (Type == EVASION)
517             b1 &= target; // Only blocking promotion pushes
518
519         while (b1)
520         {
521             to = pop_1st_bit(&b1);
522
523             if (Type == CAPTURE || Type == EVASION)
524                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, QUEEN);
525
526             if (Type == NON_CAPTURE || Type == EVASION)
527             {
528                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, ROOK);
529                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, BISHOP);
530                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
531             }
532
533             // This is the only possible under promotion that can give a check
534             // not already included in the queen-promotion.
535             if (Type == CHECK && bit_is_set(pos.attacks_from<KNIGHT>(to), pos.king_square(Them)))
536                 (*mlist++).move = make_promotion_move(to - TDELTA_N, to, KNIGHT);
537         }
538     }
539
540     // Standard pawn pushes and double pushes
541     if (Type != CAPTURE)
542     {
543         emptySquares = (Type == NON_CAPTURE ? target : pos.empty_squares());
544
545         // Single and double pawn pushes
546         b1 = move_pawns<Us, DELTA_N>(pawns) & emptySquares & ~TRank8BB;
547         b2 = move_pawns<Us, DELTA_N>(b1 & TRank3BB) & emptySquares;
548
549         // Filter out unwanted pushes according to the move type
550         if (Type == EVASION)
551         {
552             b1 &= target;
553             b2 &= target;
554         }
555         else if (Type == CHECK)
556         {
557             // Pawn moves which give direct cheks
558             b1 &= pos.attacks_from<PAWN>(ksq, Them);
559             b2 &= pos.attacks_from<PAWN>(ksq, Them);
560
561             // Pawn moves which gives discovered check. This is possible only if
562             // the pawn is not on the same file as the enemy king, because we
563             //  don't generate captures.
564             if (pawns & target) // For CHECK type target is dc bitboard
565             {
566                 Bitboard dc1 = move_pawns<Us, DELTA_N>(pawns & target & ~file_bb(ksq)) & emptySquares & ~TRank8BB;
567                 Bitboard dc2 = move_pawns<Us, DELTA_N>(dc1 & TRank3BB) & emptySquares;
568
569                 b1 |= dc1;
570                 b2 |= dc2;
571             }
572         }
573         SERIALIZE_MOVES_D(b1, -TDELTA_N);
574         SERIALIZE_MOVES_D(b2, -TDELTA_N -TDELTA_N);
575     }
576
577     // En passant captures
578     if ((Type == CAPTURE || Type == EVASION) && pos.ep_square() != SQ_NONE)
579     {
580         assert(Us != WHITE || square_rank(pos.ep_square()) == RANK_6);
581         assert(Us != BLACK || square_rank(pos.ep_square()) == RANK_3);
582
583         // An en passant capture can be an evasion only if the checking piece
584         // is the double pushed pawn and so is in the target. Otherwise this
585         // is a discovery check and we are forced to do otherwise.
586         if (Type == EVASION && !bit_is_set(target, pos.ep_square() - TDELTA_N))
587             return mlist;
588
589         b1 = pawns & pos.attacks_from<PAWN>(pos.ep_square(), Them);
590
591         assert(b1 != EmptyBoardBB);
592
593         while (b1)
594         {
595             to = pop_1st_bit(&b1);
596             (*mlist++).move = make_ep_move(to, pos.ep_square());
597         }
598     }
599     return mlist;
600   }
601
602   template<PieceType Piece>
603   MoveStack* generate_discovered_checks(const Position& pos, MoveStack* mlist, Square from) {
604
605     assert(Piece != QUEEN);
606
607     Bitboard b = pos.attacks_from<Piece>(from) & pos.empty_squares();
608     if (Piece == KING)
609     {
610         Square ksq = pos.king_square(opposite_color(pos.side_to_move()));
611         b &= ~QueenPseudoAttacks[ksq];
612     }
613     SERIALIZE_MOVES(b);
614     return mlist;
615   }
616
617   template<PieceType Piece>
618   MoveStack* generate_direct_checks(const Position& pos, MoveStack* mlist, Color us,
619                                    Bitboard dc, Square ksq) {
620     assert(Piece != KING);
621
622     Square from;
623     Bitboard checkSqs;
624     const Square* ptr = pos.piece_list_begin(us, Piece);
625
626     if ((from = *ptr++) == SQ_NONE)
627         return mlist;
628
629     checkSqs = pos.attacks_from<Piece>(ksq) & pos.empty_squares();
630
631     do
632     {
633         if (   (Piece == QUEEN  && !(QueenPseudoAttacks[from]  & checkSqs))
634             || (Piece == ROOK   && !(RookPseudoAttacks[from]   & checkSqs))
635             || (Piece == BISHOP && !(BishopPseudoAttacks[from] & checkSqs)))
636             continue;
637
638         if (dc && bit_is_set(dc, from))
639             continue;
640
641         Bitboard bb = pos.attacks_from<Piece>(from) & checkSqs;
642         SERIALIZE_MOVES(bb);
643
644     } while ((from = *ptr++) != SQ_NONE);
645
646     return mlist;
647   }
648
649   template<CastlingSide Side>
650   MoveStack* generate_castle_moves(const Position& pos, MoveStack* mlist) {
651
652     Color us = pos.side_to_move();
653
654     if (  (Side == KING_SIDE && pos.can_castle_kingside(us))
655         ||(Side == QUEEN_SIDE && pos.can_castle_queenside(us)))
656     {
657         Color them = opposite_color(us);
658         Square ksq = pos.king_square(us);
659
660         assert(pos.piece_on(ksq) == piece_of_color_and_type(us, KING));
661
662         Square rsq = (Side == KING_SIDE ? pos.initial_kr_square(us) : pos.initial_qr_square(us));
663         Square s1 = relative_square(us, Side == KING_SIDE ? SQ_G1 : SQ_C1);
664         Square s2 = relative_square(us, Side == KING_SIDE ? SQ_F1 : SQ_D1);
665         Square s;
666         bool illegal = false;
667
668         assert(pos.piece_on(rsq) == piece_of_color_and_type(us, ROOK));
669
670         // It is a bit complicated to correctly handle Chess960
671         for (s = Min(ksq, s1); s <= Max(ksq, s1); s++)
672             if (  (s != ksq && s != rsq && pos.square_is_occupied(s))
673                 ||(pos.attackers_to(s) & pos.pieces_of_color(them)))
674                 illegal = true;
675
676         for (s = Min(rsq, s2); s <= Max(rsq, s2); s++)
677             if (s != ksq && s != rsq && pos.square_is_occupied(s))
678                 illegal = true;
679
680         if (   Side == QUEEN_SIDE
681             && square_file(rsq) == FILE_B
682             && (   pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, ROOK)
683                 || pos.piece_on(relative_square(us, SQ_A1)) == piece_of_color_and_type(them, QUEEN)))
684             illegal = true;
685
686         if (!illegal)
687             (*mlist++).move = make_castle_move(ksq, rsq);
688     }
689     return mlist;
690   }
691 }