]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
d6cd4e230d66e89c23fec925d5e680a439e2acef
[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, CAPTURES_S1, KILLERS_S1, QUIETS_1_S1, QUIETS_2_S1, BAD_CAPTURES_S1,
30     EVASION,     EVASIONS_S2,
31     QSEARCH_0,   CAPTURES_S3, QUIET_CHECKS_S3,
32     QSEARCH_1,   CAPTURES_S4,
33     PROBCUT,     CAPTURES_S5,
34     RECAPTURE,   CAPTURES_S6,
35     STOP
36   };
37
38   // Our insertion sort, which is guaranteed (and also needed) to be stable
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   // Picks the best move in the range (begin, end) and moves it to the front.
53   // It's faster than sorting all the moves in advance when there are few
54   // moves e.g. possible captures.
55   inline ExtMove* pick_best(ExtMove* begin, ExtMove* end)
56   {
57       std::swap(*begin, *std::max_element(begin, end));
58       return begin;
59   }
60 } // namespace
61
62
63 /// Constructors of the MovePicker class. As arguments we pass information
64 /// to help it to return the (presumably) good moves first, to decide which
65 /// moves to return (in the quiescence search, for instance, we only want to
66 /// search captures, promotions and some checks) and how important good move
67 /// ordering is at the current node.
68
69 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
70                        Move* cm, Move* fm, Search::Stack* s) : pos(p), history(h), depth(d) {
71
72   assert(d > DEPTH_ZERO);
73
74   endBadCaptures = moves + MAX_MOVES - 1;
75   countermoves = cm;
76   followupmoves = fm;
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,
90                        Square s) : pos(p), history(h) {
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_0;
99
100   else if (d > DEPTH_QS_RECAPTURES)
101       stage = QSEARCH_1;
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, PieceType pt)
115                        : pos(p), history(h) {
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/LVA.
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 more 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                -  Value(type_of(pos.moved_piece(m)))
153                + (type_of(m) == ENPASSANT ? PieceValue[MG][PAWN] :
154                   type_of(m) == PROMOTION ? PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN]
155                                           : VALUE_ZERO);
156 }
157
158 template<>
159 void MovePicker::score<QUIETS>() {
160   for (auto& m : *this)
161       m.value = history[pos.moved_piece(m)][to_sq(m)];
162 }
163
164 template<>
165 void MovePicker::score<EVASIONS>() {
166   // Try good captures ordered by MVV/LVA, then non-captures if destination square
167   // is not under attack, ordered by history value, then bad-captures and quiet
168   // moves with a negative SEE. This last group is ordered by the SEE value.
169   Value see;
170
171   for (auto& m : *this)
172       if ((see = pos.see_sign(m)) < VALUE_ZERO)
173           m.value = see - HistoryStats::Max; // At the bottom
174
175       else if (pos.capture(m))
176           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
177                    - Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
178       else
179           m.value = history[pos.moved_piece(m)][to_sq(m)];
180 }
181
182
183 /// generate_next_stage() generates, scores and sorts the next bunch of moves,
184 /// when there are no more moves to try for the current stage.
185
186 void MovePicker::generate_next_stage() {
187
188   cur = moves;
189
190   switch (++stage) {
191
192   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
193       endMoves = generate<CAPTURES>(pos, moves);
194       score<CAPTURES>();
195       return;
196
197   case KILLERS_S1:
198       cur = killers;
199       endMoves = cur + 2;
200
201       killers[0].move = ss->killers[0];
202       killers[1].move = ss->killers[1];
203       killers[2].move = killers[3].move = MOVE_NONE;
204       killers[4].move = killers[5].move = MOVE_NONE;
205
206       // Please note that following code is racy and could yield to rare (less
207       // than 1 out of a million) duplicated entries in SMP case. This is harmless.
208
209       // Be sure countermoves are different from killers
210       for (int i = 0; i < 2; ++i)
211           if (   countermoves[i] != (cur+0)->move
212               && countermoves[i] != (cur+1)->move)
213               (endMoves++)->move = countermoves[i];
214
215       // Be sure followupmoves are different from killers and countermoves
216       for (int i = 0; i < 2; ++i)
217           if (   followupmoves[i] != (cur+0)->move
218               && followupmoves[i] != (cur+1)->move
219               && followupmoves[i] != (cur+2)->move
220               && followupmoves[i] != (cur+3)->move)
221               (endMoves++)->move = followupmoves[i];
222       return;
223
224   case QUIETS_1_S1:
225       endQuiets = endMoves = generate<QUIETS>(pos, moves);
226       score<QUIETS>();
227       endMoves = std::partition(cur, endMoves, [](const ExtMove& m) { return m.value > VALUE_ZERO; });
228       insertion_sort(cur, endMoves);
229       return;
230
231   case QUIETS_2_S1:
232       cur = endMoves;
233       endMoves = endQuiets;
234       if (depth >= 3 * ONE_PLY)
235           insertion_sort(cur, endMoves);
236       return;
237
238   case BAD_CAPTURES_S1:
239       // Just pick them in reverse order to get MVV/LVA ordering
240       cur = moves + MAX_MOVES - 1;
241       endMoves = endBadCaptures;
242       return;
243
244   case EVASIONS_S2:
245       endMoves = generate<EVASIONS>(pos, moves);
246       if (endMoves > moves + 1)
247           score<EVASIONS>();
248       return;
249
250   case QUIET_CHECKS_S3:
251       endMoves = generate<QUIET_CHECKS>(pos, moves);
252       return;
253
254   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
255       stage = STOP;
256       /* Fall through */
257
258   case STOP:
259       endMoves = cur + 1; // Avoid another next_phase() call
260       return;
261
262   default:
263       assert(false);
264   }
265 }
266
267
268 /// next_move() is the most important method of the MovePicker class. It returns
269 /// a new pseudo legal move every time it is called, until there are no more moves
270 /// left. It picks the move with the biggest value from a list of generated moves
271 /// taking care not to return the ttMove if it has already been searched.
272 template<>
273 Move MovePicker::next_move<false>() {
274
275   Move move;
276
277   while (true)
278   {
279       while (cur == endMoves)
280           generate_next_stage();
281
282       switch (stage) {
283
284       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
285           ++cur;
286           return ttMove;
287
288       case CAPTURES_S1:
289           move = pick_best(cur++, endMoves)->move;
290           if (move != ttMove)
291           {
292               if (pos.see_sign(move) >= VALUE_ZERO)
293                   return move;
294
295               // Losing capture, move it to the tail of the array
296               (endBadCaptures--)->move = move;
297           }
298           break;
299
300       case KILLERS_S1:
301           move = (cur++)->move;
302           if (    move != MOVE_NONE
303               &&  move != ttMove
304               &&  pos.pseudo_legal(move)
305               && !pos.capture(move))
306               return move;
307           break;
308
309       case QUIETS_1_S1: case QUIETS_2_S1:
310           move = (cur++)->move;
311           if (   move != ttMove
312               && move != killers[0].move
313               && move != killers[1].move
314               && move != killers[2].move
315               && move != killers[3].move
316               && move != killers[4].move
317               && move != killers[5].move)
318               return move;
319           break;
320
321       case BAD_CAPTURES_S1:
322           return (cur--)->move;
323
324       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
325           move = pick_best(cur++, endMoves)->move;
326           if (move != ttMove)
327               return move;
328           break;
329
330       case CAPTURES_S5:
331            move = pick_best(cur++, endMoves)->move;
332            if (move != ttMove && pos.see(move) > captureThreshold)
333                return move;
334            break;
335
336       case CAPTURES_S6:
337           move = pick_best(cur++, endMoves)->move;
338           if (to_sq(move) == recaptureSquare)
339               return move;
340           break;
341
342       case QUIET_CHECKS_S3:
343           move = (cur++)->move;
344           if (move != ttMove)
345               return move;
346           break;
347
348       case STOP:
349           return MOVE_NONE;
350
351       default:
352           assert(false);
353       }
354   }
355 }
356
357
358 /// Version of next_move() to use at split point nodes where the move is grabbed
359 /// from the split point's shared MovePicker object. This function is not thread
360 /// safe so must be lock protected by the caller.
361 template<>
362 Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }