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