]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Remove intermediate re-search in LMR
[stockfish] / src / movepick.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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
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
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cassert>
22
23 #include "movepick.h"
24 #include "thread.h"
25
26 namespace {
27
28   enum Stages {
29     MAIN_SEARCH, GOOD_CAPTURES, KILLERS, GOOD_QUIETS, BAD_QUIETS, BAD_CAPTURES,
30     EVASION, ALL_EVASIONS,
31     QSEARCH_WITH_CHECKS, QCAPTURES_1, CHECKS,
32     QSEARCH_WITHOUT_CHECKS, QCAPTURES_2,
33     PROBCUT, PROBCUT_CAPTURES,
34     RECAPTURE, RECAPTURES,
35     STOP
36   };
37
38   // Our insertion sort, which is guaranteed to be stable, as it should be
39   void insertion_sort(ExtMove* begin, ExtMove* end)
40   {
41     ExtMove tmp, *p, *q;
42
43     for (p = begin + 1; p < end; ++p)
44     {
45         tmp = *p;
46         for (q = p; q != begin && *(q-1) < tmp; --q)
47             *q = *(q-1);
48         *q = tmp;
49     }
50   }
51
52   // pick_best() finds the best move in the range (begin, end) and moves it to
53   // the front. It's faster than sorting all the moves in advance when there
54   // are few moves e.g. the possible captures.
55   Move pick_best(ExtMove* begin, ExtMove* end)
56   {
57       std::swap(*begin, *std::max_element(begin, end));
58       return *begin;
59   }
60
61 } // namespace
62
63
64 /// Constructors of the MovePicker class. As arguments we pass information
65 /// to help it to return the (presumably) good moves first, to decide which
66 /// moves to return (in the quiescence search, for instance, we only want to
67 /// search captures, promotions and some checks) and how important good move
68 /// ordering is at the current node.
69
70 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h, const CounterMovesHistoryStats& cmh,
71                        Move cm, Search::Stack* s) : pos(p), history(h), counterMovesHistory(cmh), depth(d) {
72
73   assert(d > DEPTH_ZERO);
74
75   endBadCaptures = moves + MAX_MOVES - 1;
76   countermove = cm;
77   ss = s;
78
79   if (pos.checkers())
80       stage = EVASION;
81
82   else
83       stage = MAIN_SEARCH;
84
85   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
86   endMoves += (ttMove != MOVE_NONE);
87 }
88
89 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h, const CounterMovesHistoryStats& cmh,
90                        Square s) : pos(p), history(h), counterMovesHistory(cmh) {
91
92   assert(d <= DEPTH_ZERO);
93
94   if (pos.checkers())
95       stage = EVASION;
96
97   else if (d > DEPTH_QS_NO_CHECKS)
98       stage = QSEARCH_WITH_CHECKS;
99
100   else if (d > DEPTH_QS_RECAPTURES)
101       stage = QSEARCH_WITHOUT_CHECKS;
102
103   else
104   {
105       stage = RECAPTURE;
106       recaptureSquare = s;
107       ttm = MOVE_NONE;
108   }
109
110   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
111   endMoves += (ttMove != MOVE_NONE);
112 }
113
114 MovePicker::MovePicker(const Position& p, Move ttm, const HistoryStats& h, const CounterMovesHistoryStats& cmh, PieceType pt)
115                        : pos(p), history(h), counterMovesHistory(cmh) {
116
117   assert(!pos.checkers());
118
119   stage = PROBCUT;
120
121   // In ProbCut we generate only captures that are better than the parent's
122   // captured piece.
123   captureThreshold = PieceValue[MG][pt];
124   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
125
126   if (ttMove && (!pos.capture(ttMove) || pos.see(ttMove) <= captureThreshold))
127       ttMove = MOVE_NONE;
128
129   endMoves += (ttMove != MOVE_NONE);
130 }
131
132
133 /// score() assign a numerical value to each move in a move list. The moves with
134 /// highest values will be picked first.
135 template<>
136 void MovePicker::score<CAPTURES>() {
137   // Winning and equal captures in the main search are ordered by MVV.
138   // Suprisingly, this appears to perform slightly better than SEE based
139   // move ordering. The reason is probably that in a position with a winning
140   // capture, capturing a valuable (but sufficiently defended) piece
141   // first usually doesn't hurt. The opponent will have to recapture, and
142   // the hanging piece will still be hanging (except in the unusual cases
143   // where it is possible to recapture with the hanging piece). Exchanging
144   // big pieces before capturing a hanging piece probably helps to reduce
145   // the subtree size.
146   // In main search we want to push captures with negative SEE values to the
147   // badCaptures[] array, but instead of doing it now we delay until the move
148   // has been picked up in pick_move_from_list(). This way we save some SEE
149   // calls in case we get a cutoff.
150   for (auto& m : *this)
151       m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
152                - 200 * relative_rank(pos.side_to_move(), to_sq(m));
153 }
154
155 template<>
156 void MovePicker::score<QUIETS>() {
157
158   Square prevSq = to_sq((ss-1)->currentMove);
159   const HistoryStats& cmh = counterMovesHistory[pos.piece_on(prevSq)][prevSq];
160
161   for (auto& m : *this)
162       m.value =  history[pos.moved_piece(m)][to_sq(m)]
163                + cmh[pos.moved_piece(m)][to_sq(m)] * 3;
164 }
165
166 template<>
167 void MovePicker::score<EVASIONS>() {
168   // Try good captures ordered by MVV/LVA, then non-captures if destination square
169   // is not under attack, ordered by history value, then bad-captures and quiet
170   // moves with a negative SEE. This last group is ordered by the SEE value.
171   Value see;
172
173   for (auto& m : *this)
174       if ((see = pos.see_sign(m)) < VALUE_ZERO)
175           m.value = see - HistoryStats::Max; // At the bottom
176
177       else if (pos.capture(m))
178           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
179                    - Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
180       else
181           m.value = history[pos.moved_piece(m)][to_sq(m)];
182 }
183
184
185 /// generate_next_stage() generates, scores and sorts the next bunch of moves,
186 /// when there are no more moves to try for the current stage.
187
188 void MovePicker::generate_next_stage() {
189
190   cur = moves;
191
192   switch (++stage) {
193
194   case GOOD_CAPTURES: case QCAPTURES_1: case QCAPTURES_2:
195   case PROBCUT_CAPTURES: case RECAPTURES:
196       endMoves = generate<CAPTURES>(pos, moves);
197       score<CAPTURES>();
198       break;
199
200   case KILLERS:
201       cur = killers;
202       endMoves = cur + 2;
203
204       killers[0] = ss->killers[0];
205       killers[1] = ss->killers[1];
206       killers[2].move = MOVE_NONE;
207
208       // Be sure countermoves are different from killers
209       if (   countermove != killers[0]
210           && countermove != killers[1])
211           *endMoves++ = countermove;
212       break;
213
214   case GOOD_QUIETS:
215       endQuiets = endMoves = generate<QUIETS>(pos, moves);
216       score<QUIETS>();
217       endMoves = std::partition(cur, endMoves, [](const ExtMove& m) { return m.value > VALUE_ZERO; });
218       insertion_sort(cur, endMoves);
219       break;
220
221   case BAD_QUIETS:
222       cur = endMoves;
223       endMoves = endQuiets;
224       if (depth >= 3 * ONE_PLY)
225           insertion_sort(cur, endMoves);
226       break;
227
228   case BAD_CAPTURES:
229       // Just pick them in reverse order to get MVV/LVA ordering
230       cur = moves + MAX_MOVES - 1;
231       endMoves = endBadCaptures;
232       break;
233
234   case ALL_EVASIONS:
235       endMoves = generate<EVASIONS>(pos, moves);
236       if (endMoves - moves > 1)
237           score<EVASIONS>();
238       break;
239
240   case CHECKS:
241       endMoves = generate<QUIET_CHECKS>(pos, moves);
242       break;
243
244   case EVASION: case QSEARCH_WITH_CHECKS: case QSEARCH_WITHOUT_CHECKS:
245   case PROBCUT: case RECAPTURE:
246       stage = STOP;
247       /* Fall through */
248
249   case STOP:
250       endMoves = cur + 1; // Avoid another generate_next_stage() call
251       break;
252
253   default:
254       assert(false);
255   }
256 }
257
258
259 /// next_move() is the most important method of the MovePicker class. It returns
260 /// a new pseudo legal move every time it is called, until there are no more moves
261 /// left. It picks the move with the biggest value from a list of generated moves
262 /// taking care not to return the ttMove if it has already been searched.
263 template<>
264 Move MovePicker::next_move<false>() {
265
266   Move move;
267
268   while (true)
269   {
270       while (cur == endMoves)
271           generate_next_stage();
272
273       switch (stage) {
274
275       case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
276       case QSEARCH_WITHOUT_CHECKS: case PROBCUT:
277           ++cur;
278           return ttMove;
279
280       case GOOD_CAPTURES:
281           move = pick_best(cur++, endMoves);
282           if (move != ttMove)
283           {
284               if (pos.see_sign(move) >= VALUE_ZERO)
285                   return move;
286
287               // Losing capture, move it to the tail of the array
288               *endBadCaptures-- = move;
289           }
290           break;
291
292       case KILLERS:
293           move = *cur++;
294           if (    move != MOVE_NONE
295               &&  move != ttMove
296               &&  pos.pseudo_legal(move)
297               && !pos.capture(move))
298               return move;
299           break;
300
301       case GOOD_QUIETS: case BAD_QUIETS:
302           move = *cur++;
303           if (   move != ttMove
304               && move != killers[0]
305               && move != killers[1]
306               && move != killers[2])
307               return move;
308           break;
309
310       case BAD_CAPTURES:
311           return *cur--;
312
313       case ALL_EVASIONS: case QCAPTURES_1: case QCAPTURES_2:
314           move = pick_best(cur++, endMoves);
315           if (move != ttMove)
316               return move;
317           break;
318
319       case PROBCUT_CAPTURES:
320            move = pick_best(cur++, endMoves);
321            if (move != ttMove && pos.see(move) > captureThreshold)
322                return move;
323            break;
324
325       case RECAPTURES:
326           move = pick_best(cur++, endMoves);
327           if (to_sq(move) == recaptureSquare)
328               return move;
329           break;
330
331       case CHECKS:
332           move = *cur++;
333           if (move != ttMove)
334               return move;
335           break;
336
337       case STOP:
338           return MOVE_NONE;
339
340       default:
341           assert(false);
342       }
343   }
344 }
345
346
347 /// Version of next_move() to use at split point nodes where the move is grabbed
348 /// from the split point's shared MovePicker object. This function is not thread
349 /// safe so must be lock protected by the caller.
350 template<>
351 Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }