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