]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
9611315c3a5aedc8c0e55f4d2d5fa23fa4ca3cd0
[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_INIT, GOOD_CAPTURES, KILLERS, KILLERS_2,
30     QUIET_INIT, QUIET, BAD_CAPTURES,
31     EVASION, ALL_EVASIONS,
32     QSEARCH_WITH_CHECKS, QCAPTURES_CHECKS_INIT, QCAPTURES_CHECKS, CHECKS,
33     QSEARCH_WITHOUT_CHECKS, QCAPTURES_NO_CHECKS, REMAINING,
34     RECAPTURE, RECAPTURES,
35     PROBCUT, PROBCUT_INIT, PROBCUT_CAPTURES
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, Search::Stack* s)
71            : pos(p), ss(s), depth(d) {
72
73   assert(d > DEPTH_ZERO);
74
75   Square prevSq = to_sq((ss-1)->currentMove);
76   countermove = pos.this_thread()->counterMoves[pos.piece_on(prevSq)][prevSq];
77
78   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
79   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
80   stage += (ttMove == MOVE_NONE);
81 }
82
83 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, Square s)
84            : pos(p) {
85
86   assert(d <= DEPTH_ZERO);
87
88   if (pos.checkers())
89       stage = EVASION;
90
91   else if (d > DEPTH_QS_NO_CHECKS)
92       stage = QSEARCH_WITH_CHECKS;
93
94   else if (d > DEPTH_QS_RECAPTURES)
95       stage = QSEARCH_WITHOUT_CHECKS;
96
97   else
98   {
99       stage = RECAPTURE;
100       recaptureSquare = s;
101       return;
102   }
103
104   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
105   stage += (ttMove == MOVE_NONE);
106 }
107
108 MovePicker::MovePicker(const Position& p, Move ttm, Value th)
109            : pos(p), threshold(th) {
110
111   assert(!pos.checkers());
112
113   stage = PROBCUT;
114
115   // In ProbCut we generate captures with SEE higher than the given threshold
116   ttMove =   ttm
117           && pos.pseudo_legal(ttm)
118           && pos.capture(ttm)
119           && pos.see(ttm) > threshold ? ttm : MOVE_NONE;
120
121   stage += (ttMove == MOVE_NONE);
122 }
123
124
125 /// score() assigns a numerical value to each move in a move list. The moves with
126 /// highest values will be picked first.
127 template<>
128 void MovePicker::score<CAPTURES>() {
129   // Winning and equal captures in the main search are ordered by MVV, preferring
130   // captures near our home rank. Surprisingly, this appears to perform slightly
131   // better than SEE-based move ordering: exchanging big pieces before capturing
132   // a hanging piece probably helps to reduce the subtree size.
133   // In the main search we want to push captures with negative SEE values to the
134   // badCaptures[] array, but instead of doing it now we delay until the move
135   // has been picked up, saving some SEE calls in case we get a cutoff.
136   for (auto& m : *this)
137       m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
138                - Value(200 * relative_rank(pos.side_to_move(), to_sq(m)));
139 }
140
141 template<>
142 void MovePicker::score<QUIETS>() {
143
144   const HistoryStats& history = pos.this_thread()->history;
145   const FromToStats& fromTo = pos.this_thread()->fromTo;
146
147   const CounterMoveStats* cm = (ss-1)->counterMoves;
148   const CounterMoveStats* fm = (ss-2)->counterMoves;
149   const CounterMoveStats* f2 = (ss-4)->counterMoves;
150
151   Color c = pos.side_to_move();
152
153   for (auto& m : *this)
154       m.value =      history[pos.moved_piece(m)][to_sq(m)]
155                + (cm ? (*cm)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
156                + (fm ? (*fm)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
157                + (f2 ? (*f2)[pos.moved_piece(m)][to_sq(m)] : VALUE_ZERO)
158                + fromTo.get(c, m);
159 }
160
161 template<>
162 void MovePicker::score<EVASIONS>() {
163   // Try winning and equal captures ordered by MVV/LVA, then non-captures ordered
164   // by history value, then bad captures and quiet moves with a negative SEE ordered
165   // by SEE value.
166   const HistoryStats& history = pos.this_thread()->history;
167   const FromToStats& fromTo = pos.this_thread()->fromTo;
168   Color c = pos.side_to_move();
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)] + fromTo.get(c, m);
180 }
181
182 int MovePicker::see_sign() const
183 {
184   return  stage == GOOD_CAPTURES ?  1
185         : stage == BAD_CAPTURES  ? -1 : 0;
186 }
187
188 /// next_move() is the most important method of the MovePicker class. It returns
189 /// a new pseudo legal move every time it is called, until there are no more moves
190 /// left. It picks the move with the biggest value from a list of generated moves
191 /// taking care not to return the ttMove if it has already been searched.
192
193 Move MovePicker::next_move() {
194
195   Move move;
196
197   switch (stage) {
198
199   case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
200   case QSEARCH_WITHOUT_CHECKS: case PROBCUT:
201       ++stage;
202       return ttMove;
203
204   case GOOD_CAPTURES_INIT:
205       endBadCaptures = cur = moves;
206       endMoves = generate<CAPTURES>(pos, cur);
207       score<CAPTURES>();
208       ++stage;
209
210   case GOOD_CAPTURES:
211       while (cur < endMoves)
212       {
213           move = pick_best(cur++, endMoves);
214           if (move != ttMove)
215           {
216               if (pos.see_sign(move) >= VALUE_ZERO)
217                   return move;
218
219               // Losing capture, move it to the beginning of the array
220               *endBadCaptures++ = move;
221           }
222       }
223       ++stage;
224
225       // First killer move
226       move = ss->killers[0];
227       if (    move != MOVE_NONE
228           &&  move != ttMove
229           &&  pos.pseudo_legal(move)
230           && !pos.capture(move))
231           return move;
232
233   case KILLERS:
234       ++stage;
235       move = ss->killers[1]; // Second killer move
236       if (    move != MOVE_NONE
237           &&  move != ttMove
238           &&  pos.pseudo_legal(move)
239           && !pos.capture(move))
240           return move;
241
242   case KILLERS_2:
243       ++stage;
244       move = countermove;
245       if (    move != MOVE_NONE
246           &&  move != ttMove
247           &&  move != ss->killers[0]
248           &&  move != ss->killers[1]
249           &&  pos.pseudo_legal(move)
250           && !pos.capture(move))
251           return move;
252
253   case QUIET_INIT:
254       cur = endBadCaptures;
255       endMoves = generate<QUIETS>(pos, cur);
256       score<QUIETS>();
257       if (depth < 3 * ONE_PLY)
258       {
259           ExtMove* goodQuiet = std::partition(cur, endMoves, [](const ExtMove& m)
260                                              { return m.value > VALUE_ZERO; });
261           insertion_sort(cur, goodQuiet);
262       } else
263           insertion_sort(cur, endMoves);
264       ++stage;
265
266   case QUIET:
267       while (cur < endMoves)
268       {
269           move = *cur++;
270           if (   move != ttMove
271               && move != ss->killers[0]
272               && move != ss->killers[1]
273               && move != countermove)
274               return move;
275       }
276       ++stage;
277       cur = moves; // Point to beginning of bad captures
278
279   case BAD_CAPTURES:
280       if (cur < endBadCaptures)
281           return *cur++;
282       break;
283
284   case ALL_EVASIONS:
285       cur = moves;
286       endMoves = generate<EVASIONS>(pos, cur);
287       if (endMoves - cur > 1)
288           score<EVASIONS>();
289       stage = REMAINING;
290       goto remaining;
291
292   case QCAPTURES_CHECKS_INIT:
293   case QCAPTURES_NO_CHECKS:
294       cur = moves;
295       endMoves = generate<CAPTURES>(pos, cur);
296       score<CAPTURES>();
297       ++stage;
298
299 remaining:
300   case QCAPTURES_CHECKS:
301   case REMAINING:
302       while (cur < endMoves)
303       {
304           move = pick_best(cur++, endMoves);
305           if (move != ttMove)
306               return move;
307       }
308       if (stage == REMAINING)
309           break;
310       cur = moves;
311       endMoves = generate<QUIET_CHECKS>(pos, cur);
312       ++stage;
313
314   case CHECKS:
315       while (cur < endMoves)
316       {
317           move = cur++->move;
318           if (move != ttMove)
319               return move;
320       }
321       break;
322
323   case RECAPTURE:
324       cur = moves;
325       endMoves = generate<CAPTURES>(pos, cur);
326       score<CAPTURES>();
327       ++stage;
328
329   case RECAPTURES:
330       while (cur < endMoves)
331       {
332           move = pick_best(cur++, endMoves);
333           if (to_sq(move) == recaptureSquare)
334               return move;
335       }
336       break;
337
338   case PROBCUT_INIT:
339       cur = moves;
340       endMoves = generate<CAPTURES>(pos, cur);
341       score<CAPTURES>();
342       ++stage;
343
344   case PROBCUT_CAPTURES:
345       while (cur < endMoves)
346       {
347           move = pick_best(cur++, endMoves);
348           if (   move != ttMove
349               && pos.see(move) > threshold)
350               return move;
351       }
352       break;
353
354   default:
355       assert(false);
356   }
357
358   return MOVE_NONE;
359 }