]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
In movepicker increase priority for moves that evade a capture
[stockfish] / src / movepick.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2022 The Stockfish developers (see AUTHORS file)
4
5   Stockfish is free software: you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published by
7   the Free Software Foundation, either version 3 of the License, or
8   (at your option) any later version.
9
10   Stockfish is distributed in the hope that it will be useful,
11   but WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   GNU General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 #include <cassert>
20
21 #include "movepick.h"
22
23 namespace Stockfish {
24
25 namespace {
26
27   enum Stages {
28     MAIN_TT, CAPTURE_INIT, GOOD_CAPTURE, REFUTATION, QUIET_INIT, QUIET, BAD_CAPTURE,
29     EVASION_TT, EVASION_INIT, EVASION,
30     PROBCUT_TT, PROBCUT_INIT, PROBCUT,
31     QSEARCH_TT, QCAPTURE_INIT, QCAPTURE, QCHECK_INIT, QCHECK
32   };
33
34   // partial_insertion_sort() sorts moves in descending order up to and including
35   // a given limit. The order of moves smaller than the limit is left unspecified.
36   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
37
38     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
39         if (p->value >= limit)
40         {
41             ExtMove tmp = *p, *q;
42             *p = *++sortedEnd;
43             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
44                 *q = *(q - 1);
45             *q = tmp;
46         }
47   }
48
49 } // namespace
50
51
52 /// Constructors of the MovePicker class. As arguments we pass information
53 /// to help it to return the (presumably) good moves first, to decide which
54 /// moves to return (in the quiescence search, for instance, we only want to
55 /// search captures, promotions, and some checks) and how important good move
56 /// ordering is at the current node.
57
58 /// MovePicker constructor for the main search
59 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
60                                                              const CapturePieceToHistory* cph,
61                                                              const PieceToHistory** ch,
62                                                              Move cm,
63                                                              const Move* killers)
64            : pos(p), mainHistory(mh), captureHistory(cph), continuationHistory(ch),
65              ttMove(ttm), refutations{{killers[0], 0}, {killers[1], 0}, {cm, 0}}, depth(d)
66 {
67   assert(d > 0);
68
69   stage = (pos.checkers() ? EVASION_TT : MAIN_TT) +
70           !(ttm && pos.pseudo_legal(ttm));
71 }
72
73 /// MovePicker constructor for quiescence search
74 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
75                                                              const CapturePieceToHistory* cph,
76                                                              const PieceToHistory** ch,
77                                                              Square rs)
78            : pos(p), mainHistory(mh), captureHistory(cph), continuationHistory(ch), ttMove(ttm), recaptureSquare(rs), depth(d)
79 {
80   assert(d <= 0);
81
82   stage = (pos.checkers() ? EVASION_TT : QSEARCH_TT) +
83           !(   ttm
84             && (pos.checkers() || depth > DEPTH_QS_RECAPTURES || to_sq(ttm) == recaptureSquare)
85             && pos.pseudo_legal(ttm));
86 }
87
88 /// MovePicker constructor for ProbCut: we generate captures with SEE greater
89 /// than or equal to the given threshold.
90 MovePicker::MovePicker(const Position& p, Move ttm, Value th, Depth d, const CapturePieceToHistory* cph)
91            : pos(p), captureHistory(cph), ttMove(ttm), threshold(th), depth(d)
92 {
93   assert(!pos.checkers());
94
95   stage = PROBCUT_TT + !(ttm && pos.capture(ttm)
96                              && pos.pseudo_legal(ttm)
97                              && pos.see_ge(ttm, threshold));
98 }
99
100 //squares threatened by pawn attacks
101 template <Color Us>
102 Bitboard threatsByPawn (const Position& pos)
103 {
104     return pawn_attacks_bb<Us>(pos.pieces(Us, PAWN));
105 }
106
107 //squares threatened by minor attacks
108 template <Color Us>
109 Bitboard threatsByMinor (const Position& pos)
110 {
111     Bitboard our = pos.pieces(Us, KNIGHT, BISHOP);
112     Bitboard threats = 0;
113     while (our)
114     {
115         Square s = pop_lsb(our);
116         if (type_of(pos.piece_on(s)) == KNIGHT)
117             threats |= attacks_bb<KNIGHT>(s, pos.pieces());
118         else
119             threats |= attacks_bb<BISHOP>(s, pos.pieces());
120     }
121     return threats;
122 }
123
124 //squares threatened by rook attacks
125 template <Color Us>
126 Bitboard threatsByRook (const Position& pos)
127 {
128     Bitboard our = pos.pieces(Us, ROOK);
129     Bitboard threats = 0;
130     while (our)
131     {
132         Square s = pop_lsb(our);
133         threats |= attacks_bb<ROOK>(s, pos.pieces());
134     }
135     return threats;
136 }
137
138 /// MovePicker::score() assigns a numerical value to each move in a list, used
139 /// for sorting. Captures are ordered by Most Valuable Victim (MVV), preferring
140 /// captures with a good history. Quiets moves are ordered using the histories.
141 template<GenType Type>
142 void MovePicker::score() {
143
144   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
145
146   Bitboard threatened, threatenedByPawn, threatenedByMinor, threatenedByRook;
147   if constexpr (Type == QUIETS)
148   {
149       // squares threatened by pawns
150       threatenedByPawn   = pos.side_to_move() == WHITE ? threatsByPawn<BLACK>(pos)  : threatsByPawn<WHITE>(pos);
151       // squares threatened by minors or pawns
152       threatenedByMinor  = pos.side_to_move() == WHITE ? threatsByMinor<BLACK>(pos) : threatsByMinor<WHITE>(pos);
153       threatenedByMinor |= threatenedByPawn;
154       // squares threatened by rooks, minors or pawns
155       threatenedByRook   = pos.side_to_move() == WHITE ? threatsByRook<BLACK>(pos)  : threatsByRook<WHITE>(pos);
156       threatenedByRook  |= threatenedByMinor;
157
158       // pieces threatened by pieces of lesser material value
159       threatened = pos.side_to_move() == WHITE ? ((pos.pieces(WHITE, QUEEN) & threatenedByRook) |
160                                                   (pos.pieces(WHITE, ROOK) & threatenedByMinor) |
161                                                   (pos.pieces(WHITE, KNIGHT, BISHOP) & threatenedByPawn))
162                                                : ((pos.pieces(BLACK, QUEEN) & threatenedByRook) |
163                                                   (pos.pieces(BLACK, ROOK) & threatenedByMinor) |
164                                                   (pos.pieces(BLACK, KNIGHT, BISHOP) & threatenedByPawn));
165   }
166   else
167   {
168       // Silence unused variable warning
169       (void) threatened;
170       (void) threatenedByPawn;
171       (void) threatenedByMinor;
172       (void) threatenedByRook;
173   }
174
175   for (auto& m : *this)
176       if constexpr (Type == CAPTURES)
177           m.value =  6 * int(PieceValue[MG][pos.piece_on(to_sq(m))])
178                    +     (*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))];
179
180       else if constexpr (Type == QUIETS)
181           m.value =      (*mainHistory)[pos.side_to_move()][from_to(m)]
182                    + 2 * (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
183                    +     (*continuationHistory[1])[pos.moved_piece(m)][to_sq(m)]
184                    +     (*continuationHistory[3])[pos.moved_piece(m)][to_sq(m)]
185                    +     (*continuationHistory[5])[pos.moved_piece(m)][to_sq(m)]
186                    +     (threatened & from_sq(m) ?
187                            (type_of(pos.piece_on(from_sq(m))) == QUEEN && !(to_sq(m) & threatenedByRook)  ? 50000
188                           : type_of(pos.piece_on(from_sq(m))) == ROOK  && !(to_sq(m) & threatenedByMinor) ? 25000
189                           :                                               !(to_sq(m) & threatenedByPawn)  ? 15000
190                           :                                                                                 0)
191                           :                                                                                 0);
192
193       else // Type == EVASIONS
194       {
195           if (pos.capture(m))
196               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
197                        - Value(type_of(pos.moved_piece(m)));
198           else
199               m.value =      (*mainHistory)[pos.side_to_move()][from_to(m)]
200                        + 2 * (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
201                        - (1 << 28);
202       }
203 }
204
205 /// MovePicker::select() returns the next move satisfying a predicate function.
206 /// It never returns the TT move.
207 template<MovePicker::PickType T, typename Pred>
208 Move MovePicker::select(Pred filter) {
209
210   while (cur < endMoves)
211   {
212       if (T == Best)
213           std::swap(*cur, *std::max_element(cur, endMoves));
214
215       if (*cur != ttMove && filter())
216           return *cur++;
217
218       cur++;
219   }
220   return MOVE_NONE;
221 }
222
223 /// MovePicker::next_move() is the most important method of the MovePicker class. It
224 /// returns a new pseudo-legal move every time it is called until there are no more
225 /// moves left, picking the move with the highest score from a list of generated moves.
226 Move MovePicker::next_move(bool skipQuiets) {
227
228 top:
229   switch (stage) {
230
231   case MAIN_TT:
232   case EVASION_TT:
233   case QSEARCH_TT:
234   case PROBCUT_TT:
235       ++stage;
236       return ttMove;
237
238   case CAPTURE_INIT:
239   case PROBCUT_INIT:
240   case QCAPTURE_INIT:
241       cur = endBadCaptures = moves;
242       endMoves = generate<CAPTURES>(pos, cur);
243
244       score<CAPTURES>();
245       partial_insertion_sort(cur, endMoves, -3000 * depth);
246       ++stage;
247       goto top;
248
249   case GOOD_CAPTURE:
250       if (select<Next>([&](){
251                        return pos.see_ge(*cur, Value(-69 * cur->value / 1024)) ?
252                               // Move losing capture to endBadCaptures to be tried later
253                               true : (*endBadCaptures++ = *cur, false); }))
254           return *(cur - 1);
255
256       // Prepare the pointers to loop over the refutations array
257       cur = std::begin(refutations);
258       endMoves = std::end(refutations);
259
260       // If the countermove is the same as a killer, skip it
261       if (   refutations[0].move == refutations[2].move
262           || refutations[1].move == refutations[2].move)
263           --endMoves;
264
265       ++stage;
266       [[fallthrough]];
267
268   case REFUTATION:
269       if (select<Next>([&](){ return    *cur != MOVE_NONE
270                                     && !pos.capture(*cur)
271                                     &&  pos.pseudo_legal(*cur); }))
272           return *(cur - 1);
273       ++stage;
274       [[fallthrough]];
275
276   case QUIET_INIT:
277       if (!skipQuiets)
278       {
279           cur = endBadCaptures;
280           endMoves = generate<QUIETS>(pos, cur);
281
282           score<QUIETS>();
283           partial_insertion_sort(cur, endMoves, -3000 * depth);
284       }
285
286       ++stage;
287       [[fallthrough]];
288
289   case QUIET:
290       if (   !skipQuiets
291           && select<Next>([&](){return   *cur != refutations[0].move
292                                       && *cur != refutations[1].move
293                                       && *cur != refutations[2].move;}))
294           return *(cur - 1);
295
296       // Prepare the pointers to loop over the bad captures
297       cur = moves;
298       endMoves = endBadCaptures;
299
300       ++stage;
301       [[fallthrough]];
302
303   case BAD_CAPTURE:
304       return select<Next>([](){ return true; });
305
306   case EVASION_INIT:
307       cur = moves;
308       endMoves = generate<EVASIONS>(pos, cur);
309
310       score<EVASIONS>();
311       ++stage;
312       [[fallthrough]];
313
314   case EVASION:
315       return select<Best>([](){ return true; });
316
317   case PROBCUT:
318       return select<Next>([&](){ return pos.see_ge(*cur, threshold); });
319
320   case QCAPTURE:
321       if (select<Next>([&](){ return   depth > DEPTH_QS_RECAPTURES
322                                     || to_sq(*cur) == recaptureSquare; }))
323           return *(cur - 1);
324
325       // If we did not find any move and we do not try checks, we have finished
326       if (depth != DEPTH_QS_CHECKS)
327           return MOVE_NONE;
328
329       ++stage;
330       [[fallthrough]];
331
332   case QCHECK_INIT:
333       cur = moves;
334       endMoves = generate<QUIET_CHECKS>(pos, cur);
335
336       ++stage;
337       [[fallthrough]];
338
339   case QCHECK:
340       return select<Next>([](){ return true; });
341   }
342
343   assert(false);
344   return MOVE_NONE; // Silence warning
345 }
346
347 } // namespace Stockfish