]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Fix last search info carried over to mate position
[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   Copyright (C) 2015-2016 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
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,
71                        const CounterMoveStats& cmh, const CounterMoveStats& fmh,
72                        Move cm, Search::Stack* s)
73            : pos(p), history(h), counterMoveHistory(&cmh),
74              followupMoveHistory(&fmh), ss(s), countermove(cm), depth(d) {
75
76   assert(d > DEPTH_ZERO);
77
78   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
79   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
80   endMoves += (ttMove != MOVE_NONE);
81 }
82
83 MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
84                        const HistoryStats& h, Square s)
85            : pos(p), history(h) {
86
87   assert(d <= DEPTH_ZERO);
88
89   if (pos.checkers())
90       stage = EVASION;
91
92   else if (d > DEPTH_QS_NO_CHECKS)
93       stage = QSEARCH_WITH_CHECKS;
94
95   else if (d > DEPTH_QS_RECAPTURES)
96       stage = QSEARCH_WITHOUT_CHECKS;
97
98   else
99   {
100       stage = RECAPTURE;
101       recaptureSquare = s;
102       ttm = MOVE_NONE;
103   }
104
105   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
106   endMoves += (ttMove != MOVE_NONE);
107 }
108
109 MovePicker::MovePicker(const Position& p, Move ttm, const HistoryStats& h, Value th)
110            : pos(p), history(h), threshold(th) {
111
112   assert(!pos.checkers());
113
114   stage = PROBCUT;
115
116   // In ProbCut we generate captures with SEE higher than the given threshold
117   ttMove =   ttm
118           && pos.pseudo_legal(ttm)
119           && pos.capture(ttm)
120           && pos.see(ttm) > threshold ? ttm : MOVE_NONE;
121
122   endMoves += (ttMove != MOVE_NONE);
123 }
124
125
126 /// score() assigns a numerical value to each move in a move list. The moves with
127 /// highest values will be picked first.
128 template<>
129 void MovePicker::score<CAPTURES>() {
130   // Winning and equal captures in the main search are ordered by MVV, preferring
131   // captures near our home rank. Surprisingly, this appears to perform slightly
132   // better than SEE-based move ordering: exchanging big pieces before capturing
133   // a hanging piece probably helps to reduce the subtree size.
134   // In the main search we want to push captures with negative SEE values to the
135   // badCaptures[] array, but instead of doing it now we delay until the move
136   // has been picked up, saving some SEE calls in case we get a cutoff.
137   for (auto& m : *this)
138       m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
139                - Value(200 * relative_rank(pos.side_to_move(), to_sq(m)));
140 }
141
142 template<>
143 void MovePicker::score<QUIETS>() {
144
145   for (auto& m : *this)
146       m.value =  history[pos.moved_piece(m)][to_sq(m)]
147                + (*counterMoveHistory )[pos.moved_piece(m)][to_sq(m)]
148                + (*followupMoveHistory)[pos.moved_piece(m)][to_sq(m)];
149 }
150
151 template<>
152 void MovePicker::score<EVASIONS>() {
153   // Try winning and equal captures ordered by MVV/LVA, then non-captures ordered
154   // by history value, then bad captures and quiet moves with a negative SEE ordered
155   // by SEE value.
156   Value see;
157
158   for (auto& m : *this)
159       if ((see = pos.see_sign(m)) < VALUE_ZERO)
160           m.value = see - HistoryStats::Max; // At the bottom
161
162       else if (pos.capture(m))
163           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
164                    - Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
165       else
166           m.value = history[pos.moved_piece(m)][to_sq(m)];
167 }
168
169
170 /// generate_next_stage() generates, scores, and sorts the next bunch of moves
171 /// when there are no more moves to try for the current stage.
172
173 void MovePicker::generate_next_stage() {
174
175   assert(stage != STOP);
176
177   cur = moves;
178
179   switch (++stage) {
180
181   case GOOD_CAPTURES: case QCAPTURES_1: case QCAPTURES_2:
182   case PROBCUT_CAPTURES: case RECAPTURES:
183       endMoves = generate<CAPTURES>(pos, moves);
184       score<CAPTURES>();
185       break;
186
187   case KILLERS:
188       killers[0] = ss->killers[0];
189       killers[1] = ss->killers[1];
190       killers[2] = countermove;
191       cur = killers;
192       endMoves = cur + 2 + (countermove != killers[0] && countermove != killers[1]);
193       break;
194
195   case GOOD_QUIETS:
196       endQuiets = endMoves = generate<QUIETS>(pos, moves);
197       score<QUIETS>();
198       endMoves = std::partition(cur, endMoves, [](const ExtMove& m) { return m.value > VALUE_ZERO; });
199       insertion_sort(cur, endMoves);
200       break;
201
202   case BAD_QUIETS:
203       cur = endMoves;
204       endMoves = endQuiets;
205       if (depth >= 3 * ONE_PLY)
206           insertion_sort(cur, endMoves);
207       break;
208
209   case BAD_CAPTURES:
210       // Just pick them in reverse order to get correct ordering
211       cur = moves + MAX_MOVES - 1;
212       endMoves = endBadCaptures;
213       break;
214
215   case ALL_EVASIONS:
216       endMoves = generate<EVASIONS>(pos, moves);
217       if (endMoves - moves > 1)
218           score<EVASIONS>();
219       break;
220
221   case CHECKS:
222       endMoves = generate<QUIET_CHECKS>(pos, moves);
223       break;
224
225   case EVASION: case QSEARCH_WITH_CHECKS: case QSEARCH_WITHOUT_CHECKS:
226   case PROBCUT: case RECAPTURE: case STOP:
227       stage = STOP;
228       break;
229
230   default:
231       assert(false);
232   }
233 }
234
235
236 /// next_move() is the most important method of the MovePicker class. It returns
237 /// a new pseudo legal move every time it is called, until there are no more moves
238 /// left. It picks the move with the biggest value from a list of generated moves
239 /// taking care not to return the ttMove if it has already been searched.
240
241 Move MovePicker::next_move() {
242
243   Move move;
244
245   while (true)
246   {
247       while (cur == endMoves && stage != STOP)
248           generate_next_stage();
249
250       switch (stage) {
251
252       case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
253       case QSEARCH_WITHOUT_CHECKS: case PROBCUT:
254           ++cur;
255           return ttMove;
256
257       case GOOD_CAPTURES:
258           move = pick_best(cur++, endMoves);
259           if (move != ttMove)
260           {
261               if (pos.see_sign(move) >= VALUE_ZERO)
262                   return move;
263
264               // Losing capture, move it to the tail of the array
265               *endBadCaptures-- = move;
266           }
267           break;
268
269       case KILLERS:
270           move = *cur++;
271           if (    move != MOVE_NONE
272               &&  move != ttMove
273               &&  pos.pseudo_legal(move)
274               && !pos.capture(move))
275               return move;
276           break;
277
278       case GOOD_QUIETS: case BAD_QUIETS:
279           move = *cur++;
280           if (   move != ttMove
281               && move != killers[0]
282               && move != killers[1]
283               && move != killers[2])
284               return move;
285           break;
286
287       case BAD_CAPTURES:
288           return *cur--;
289
290       case ALL_EVASIONS: case QCAPTURES_1: case QCAPTURES_2:
291           move = pick_best(cur++, endMoves);
292           if (move != ttMove)
293               return move;
294           break;
295
296       case PROBCUT_CAPTURES:
297            move = pick_best(cur++, endMoves);
298            if (move != ttMove && pos.see(move) > threshold)
299                return move;
300            break;
301
302       case RECAPTURES:
303           move = pick_best(cur++, endMoves);
304           if (to_sq(move) == recaptureSquare)
305               return move;
306           break;
307
308       case CHECKS:
309           move = *cur++;
310           if (move != ttMove)
311               return move;
312           break;
313
314       case STOP:
315           return MOVE_NONE;
316
317       default:
318           assert(false);
319       }
320   }
321 }