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