]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Add syzygy support
[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   // Unary predicate used by std::partition to split positive values from remaining
53   // ones so as to sort the two sets separately, with the second sort delayed.
54   inline bool has_positive_value(const ExtMove& move) { return move.value > VALUE_ZERO; }
55
56   // Picks the best move in the range (begin, end) and moves it to the front.
57   // It's faster than sorting all the moves in advance when there are few
58   // moves e.g. possible captures.
59   inline ExtMove* pick_best(ExtMove* begin, ExtMove* end)
60   {
61       std::swap(*begin, *std::max_element(begin, end));
62       return begin;
63   }
64 } // namespace
65
66
67 /// Constructors of the MovePicker class. As arguments we pass information
68 /// to help it to return the (presumably) good moves first, to decide which
69 /// moves to return (in the quiescence search, for instance, we only want to
70 /// search captures, promotions and some checks) and how important good move
71 /// ordering is at the current node.
72
73 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
74                        Move* cm, Move* fm, Search::Stack* s) : pos(p), history(h), depth(d) {
75
76   assert(d > DEPTH_ZERO);
77
78   cur = end = moves;
79   endBadCaptures = moves + MAX_MOVES - 1;
80   countermoves = cm;
81   followupmoves = fm;
82   ss = s;
83
84   if (pos.checkers())
85       stage = EVASION;
86
87   else
88       stage = MAIN_SEARCH;
89
90   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
91   end += (ttMove != MOVE_NONE);
92 }
93
94 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const HistoryStats& h,
95                        Square s) : pos(p), history(h), cur(moves), end(moves) {
96
97   assert(d <= DEPTH_ZERO);
98
99   if (pos.checkers())
100       stage = EVASION;
101
102   else if (d > DEPTH_QS_NO_CHECKS)
103       stage = QSEARCH_0;
104
105   else if (d > DEPTH_QS_RECAPTURES)
106       stage = QSEARCH_1;
107
108   else
109   {
110       stage = RECAPTURE;
111       recaptureSquare = s;
112       ttm = MOVE_NONE;
113   }
114
115   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
116   end += (ttMove != MOVE_NONE);
117 }
118
119 MovePicker::MovePicker(const Position& p, Move ttm, const HistoryStats& h, PieceType pt)
120                        : pos(p), history(h), cur(moves), end(moves) {
121
122   assert(!pos.checkers());
123
124   stage = PROBCUT;
125
126   // In ProbCut we generate only captures that are better than the parent's
127   // captured piece.
128   captureThreshold = PieceValue[MG][pt];
129   ttMove = (ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE);
130
131   if (ttMove && (!pos.capture(ttMove) || pos.see(ttMove) <= captureThreshold))
132       ttMove = MOVE_NONE;
133
134   end += (ttMove != MOVE_NONE);
135 }
136
137
138 /// score() assign a numerical value to each move in a move list. The moves with
139 /// highest values will be picked first.
140 template<>
141 void MovePicker::score<CAPTURES>() {
142   // Winning and equal captures in the main search are ordered by MVV/LVA.
143   // Suprisingly, this appears to perform slightly better than SEE based
144   // move ordering. The reason is probably that in a position with a winning
145   // capture, capturing a more valuable (but sufficiently defended) piece
146   // first usually doesn't hurt. The opponent will have to recapture, and
147   // the hanging piece will still be hanging (except in the unusual cases
148   // where it is possible to recapture with the hanging piece). Exchanging
149   // big pieces before capturing a hanging piece probably helps to reduce
150   // the subtree size.
151   // In main search we want to push captures with negative SEE values to the
152   // badCaptures[] array, but instead of doing it now we delay until the move
153   // has been picked up in pick_move_from_list(). This way we save some SEE
154   // calls in case we get a cutoff.
155   Move m;
156
157   for (ExtMove* it = moves; it != end; ++it)
158   {
159       m = it->move;
160       it->value =  PieceValue[MG][pos.piece_on(to_sq(m))]
161                  - Value(type_of(pos.moved_piece(m)));
162
163       if (type_of(m) == ENPASSANT)
164           it->value += PieceValue[MG][PAWN];
165
166       else if (type_of(m) == PROMOTION)
167           it->value += PieceValue[MG][promotion_type(m)] - PieceValue[MG][PAWN];
168   }
169 }
170
171 template<>
172 void MovePicker::score<QUIETS>() {
173
174   Move m;
175
176   for (ExtMove* it = moves; it != end; ++it)
177   {
178       m = it->move;
179       it->value = history[pos.moved_piece(m)][to_sq(m)];
180   }
181 }
182
183 template<>
184 void MovePicker::score<EVASIONS>() {
185   // Try good captures ordered by MVV/LVA, then non-captures if destination square
186   // is not under attack, ordered by history value, then bad-captures and quiet
187   // moves with a negative SEE. This last group is ordered by the SEE value.
188   Move m;
189   Value see;
190
191   for (ExtMove* it = moves; it != end; ++it)
192   {
193       m = it->move;
194       if ((see = pos.see_sign(m)) < VALUE_ZERO)
195           it->value = see - HistoryStats::Max; // At the bottom
196
197       else if (pos.capture(m))
198           it->value =  PieceValue[MG][pos.piece_on(to_sq(m))]
199                      - Value(type_of(pos.moved_piece(m))) + HistoryStats::Max;
200       else
201           it->value = history[pos.moved_piece(m)][to_sq(m)];
202   }
203 }
204
205
206 /// generate_next_stage() generates, scores and sorts the next bunch of moves,
207 /// when there are no more moves to try for the current stage.
208
209 void MovePicker::generate_next_stage() {
210
211   cur = moves;
212
213   switch (++stage) {
214
215   case CAPTURES_S1: case CAPTURES_S3: case CAPTURES_S4: case CAPTURES_S5: case CAPTURES_S6:
216       end = generate<CAPTURES>(pos, moves);
217       score<CAPTURES>();
218       return;
219
220   case KILLERS_S1:
221       cur = killers;
222       end = cur + 2;
223
224       killers[0].move = ss->killers[0];
225       killers[1].move = ss->killers[1];
226       killers[2].move = killers[3].move = MOVE_NONE;
227       killers[4].move = killers[5].move = MOVE_NONE;
228
229       // Please note that following code is racy and could yield to rare (less
230       // than 1 out of a million) duplicated entries in SMP case. This is harmless.
231
232       // Be sure countermoves are different from killers
233       for (int i = 0; i < 2; ++i)
234           if (   countermoves[i] != (cur+0)->move
235               && countermoves[i] != (cur+1)->move)
236               (end++)->move = countermoves[i];
237
238       // Be sure followupmoves are different from killers and countermoves
239       for (int i = 0; i < 2; ++i)
240           if (   followupmoves[i] != (cur+0)->move
241               && followupmoves[i] != (cur+1)->move
242               && followupmoves[i] != (cur+2)->move
243               && followupmoves[i] != (cur+3)->move)
244               (end++)->move = followupmoves[i];
245       return;
246
247   case QUIETS_1_S1:
248       endQuiets = end = generate<QUIETS>(pos, moves);
249       score<QUIETS>();
250       end = std::partition(cur, end, has_positive_value);
251       insertion_sort(cur, end);
252       return;
253
254   case QUIETS_2_S1:
255       cur = end;
256       end = endQuiets;
257       if (depth >= 3 * ONE_PLY)
258           insertion_sort(cur, end);
259       return;
260
261   case BAD_CAPTURES_S1:
262       // Just pick them in reverse order to get MVV/LVA ordering
263       cur = moves + MAX_MOVES - 1;
264       end = endBadCaptures;
265       return;
266
267   case EVASIONS_S2:
268       end = generate<EVASIONS>(pos, moves);
269       if (end > moves + 1)
270           score<EVASIONS>();
271       return;
272
273   case QUIET_CHECKS_S3:
274       end = generate<QUIET_CHECKS>(pos, moves);
275       return;
276
277   case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT: case RECAPTURE:
278       stage = STOP;
279       /* Fall through */
280
281   case STOP:
282       end = cur + 1; // Avoid another next_phase() call
283       return;
284
285   default:
286       assert(false);
287   }
288 }
289
290
291 /// next_move() is the most important method of the MovePicker class. It returns
292 /// a new pseudo legal move every time it is called, until there are no more moves
293 /// left. It picks the move with the biggest value from a list of generated moves
294 /// taking care not to return the ttMove if it has already been searched.
295 template<>
296 Move MovePicker::next_move<false>() {
297
298   Move move;
299
300   while (true)
301   {
302       while (cur == end)
303           generate_next_stage();
304
305       switch (stage) {
306
307       case MAIN_SEARCH: case EVASION: case QSEARCH_0: case QSEARCH_1: case PROBCUT:
308           ++cur;
309           return ttMove;
310
311       case CAPTURES_S1:
312           move = pick_best(cur++, end)->move;
313           if (move != ttMove)
314           {
315               if (pos.see_sign(move) >= VALUE_ZERO)
316                   return move;
317
318               // Losing capture, move it to the tail of the array
319               (endBadCaptures--)->move = move;
320           }
321           break;
322
323       case KILLERS_S1:
324           move = (cur++)->move;
325           if (    move != MOVE_NONE
326               &&  move != ttMove
327               &&  pos.pseudo_legal(move)
328               && !pos.capture(move))
329               return move;
330           break;
331
332       case QUIETS_1_S1: case QUIETS_2_S1:
333           move = (cur++)->move;
334           if (   move != ttMove
335               && move != killers[0].move
336               && move != killers[1].move
337               && move != killers[2].move
338               && move != killers[3].move
339               && move != killers[4].move
340               && move != killers[5].move)
341               return move;
342           break;
343
344       case BAD_CAPTURES_S1:
345           return (cur--)->move;
346
347       case EVASIONS_S2: case CAPTURES_S3: case CAPTURES_S4:
348           move = pick_best(cur++, end)->move;
349           if (move != ttMove)
350               return move;
351           break;
352
353       case CAPTURES_S5:
354            move = pick_best(cur++, end)->move;
355            if (move != ttMove && pos.see(move) > captureThreshold)
356                return move;
357            break;
358
359       case CAPTURES_S6:
360           move = pick_best(cur++, end)->move;
361           if (to_sq(move) == recaptureSquare)
362               return move;
363           break;
364
365       case QUIET_CHECKS_S3:
366           move = (cur++)->move;
367           if (move != ttMove)
368               return move;
369           break;
370
371       case STOP:
372           return MOVE_NONE;
373
374       default:
375           assert(false);
376       }
377   }
378 }
379
380
381 /// Version of next_move() to use at split point nodes where the move is grabbed
382 /// from the split point's shared MovePicker object. This function is not thread
383 /// safe so must be lock protected by the caller.
384 template<>
385 Move MovePicker::next_move<true>() { return ss->splitPoint->movePicker->next_move<false>(); }