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