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