]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
33c65670ffe10afd9c738b1ddf5ac4e9f95f687c
[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-2017 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
25 namespace {
26
27   enum Stages {
28     MAIN_SEARCH, CAPTURES_INIT, GOOD_CAPTURES, KILLERS, COUNTERMOVE, QUIET_INIT, QUIET, BAD_CAPTURES,
29     EVASION, EVASIONS_INIT, ALL_EVASIONS,
30     PROBCUT, PROBCUT_INIT, PROBCUT_CAPTURES,
31     QSEARCH_WITH_CHECKS, QCAPTURES_1_INIT, QCAPTURES_1, QCHECKS,
32     QSEARCH_NO_CHECKS, QCAPTURES_2_INIT, QCAPTURES_2,
33     QSEARCH_RECAPTURES, QRECAPTURES
34   };
35
36   // partial_insertion_sort() sorts moves in descending order up to and including
37   // a given limit. The order of moves smaller than the limit is left unspecified.
38   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
39
40     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
41         if (p->value >= limit)
42         {
43             ExtMove tmp = *p, *q;
44             *p = *++sortedEnd;
45             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
46                 *q = *(q - 1);
47             *q = tmp;
48         }
49   }
50
51   // pick_best() finds the best move in the range (begin, end) and moves it to
52   // the front. It's faster than sorting all the moves in advance when there
53   // are few moves, e.g., the possible captures.
54   Move pick_best(ExtMove* begin, ExtMove* end) {
55
56     std::swap(*begin, *std::max_element(begin, end));
57     return *begin;
58   }
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 constructor for the main search
70 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
71                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Move cm, Move* killers_p)
72            : pos(p), mainHistory(mh), captureHistory(cph), contHistory(ch), countermove(cm),
73              killers{killers_p[0], killers_p[1]}, depth(d){
74
75   assert(d > DEPTH_ZERO);
76
77   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
78   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
79   stage += (ttMove == MOVE_NONE);
80 }
81
82 /// MovePicker constructor for quiescence search
83 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,  const CapturePieceToHistory* cph, Square s)
84            : pos(p), mainHistory(mh), captureHistory(cph) {
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_NO_CHECKS;
96
97   else
98   {
99       stage = QSEARCH_RECAPTURES;
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 constructor for ProbCut: we generate captures with SEE higher
109 /// than or equal to the given threshold.
110 MovePicker::MovePicker(const Position& p, Move ttm, Value th, const CapturePieceToHistory* cph)
111            : pos(p), captureHistory(cph), threshold(th) {
112
113   assert(!pos.checkers());
114
115   stage = PROBCUT;
116   ttMove =   ttm
117           && pos.pseudo_legal(ttm)
118           && pos.capture(ttm)
119           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
120
121   stage += (ttMove == MOVE_NONE);
122 }
123
124 /// score() assigns a numerical value to each move in a list, used for sorting.
125 /// Captures are ordered by Most Valuable Victim (MVV), preferring captures
126 /// with a good history. Quiets are ordered using the histories.
127 template<GenType Type>
128 void MovePicker::score() {
129
130   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
131
132   for (auto& m : *this)
133       if (Type == CAPTURES)
134           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
135                    + Value((*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))]);
136
137       else if (Type == QUIETS)
138           m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
139                    + (*contHistory[0])[pos.moved_piece(m)][to_sq(m)]
140                    + (*contHistory[1])[pos.moved_piece(m)][to_sq(m)]
141                    + (*contHistory[3])[pos.moved_piece(m)][to_sq(m)];
142
143       else // Type == EVASIONS
144       {
145           if (pos.capture(m))
146               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
147                        - Value(type_of(pos.moved_piece(m)));
148           else
149               m.value = (*mainHistory)[pos.side_to_move()][from_to(m)] - (1 << 28);
150       }
151 }
152
153 /// next_move() is the most important method of the MovePicker class. It returns
154 /// a new pseudo legal move every time it is called, until there are no more moves
155 /// left. It picks the move with the biggest value from a list of generated moves
156 /// taking care not to return the ttMove if it has already been searched.
157
158 Move MovePicker::next_move(bool skipQuiets) {
159
160   Move move;
161
162   switch (stage) {
163
164   case MAIN_SEARCH: case EVASION: case QSEARCH_WITH_CHECKS:
165   case QSEARCH_NO_CHECKS: case PROBCUT:
166       ++stage;
167       return ttMove;
168
169   case CAPTURES_INIT:
170       endBadCaptures = cur = moves;
171       endMoves = generate<CAPTURES>(pos, cur);
172       score<CAPTURES>();
173       ++stage;
174       /* fallthrough */
175
176   case GOOD_CAPTURES:
177       while (cur < endMoves)
178       {
179           move = pick_best(cur++, endMoves);
180           if (move != ttMove)
181           {
182               if (pos.see_ge(move))
183                   return move;
184
185               if (   type_of(pos.piece_on(to_sq(move))) == KNIGHT
186                   && type_of(pos.moved_piece(move)) == BISHOP
187                   && (cur-1)->value > 1090)
188                   return move;
189
190               // Losing capture, move it to the beginning of the array
191               *endBadCaptures++ = move;
192           }
193       }
194
195       ++stage;
196       move = killers[0];  // First killer move
197       if (    move != MOVE_NONE
198           &&  move != ttMove
199           &&  pos.pseudo_legal(move)
200           && !pos.capture(move))
201           return move;
202       /* fallthrough */
203
204   case KILLERS:
205       ++stage;
206       move = killers[1]; // Second killer move
207       if (    move != MOVE_NONE
208           &&  move != ttMove
209           &&  pos.pseudo_legal(move)
210           && !pos.capture(move))
211           return move;
212       /* fallthrough */
213
214   case COUNTERMOVE:
215       ++stage;
216       move = countermove;
217       if (    move != MOVE_NONE
218           &&  move != ttMove
219           &&  move != killers[0]
220           &&  move != killers[1]
221           &&  pos.pseudo_legal(move)
222           && !pos.capture(move))
223           return move;
224       /* fallthrough */
225
226   case QUIET_INIT:
227       cur = endBadCaptures;
228       endMoves = generate<QUIETS>(pos, cur);
229       score<QUIETS>();
230       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
231       ++stage;
232       /* fallthrough */
233
234   case QUIET:
235       while (    cur < endMoves
236              && (!skipQuiets || cur->value >= VALUE_ZERO))
237       {
238           move = *cur++;
239
240           if (   move != ttMove
241               && move != killers[0]
242               && move != killers[1]
243               && move != countermove)
244               return move;
245       }
246       ++stage;
247       cur = moves; // Point to beginning of bad captures
248       /* fallthrough */
249
250   case BAD_CAPTURES:
251       if (cur < endBadCaptures)
252           return *cur++;
253       break;
254
255   case EVASIONS_INIT:
256       cur = moves;
257       endMoves = generate<EVASIONS>(pos, cur);
258       score<EVASIONS>();
259       ++stage;
260       /* fallthrough */
261
262   case ALL_EVASIONS:
263       while (cur < endMoves)
264       {
265           move = pick_best(cur++, endMoves);
266           if (move != ttMove)
267               return move;
268       }
269       break;
270
271   case PROBCUT_INIT:
272       cur = moves;
273       endMoves = generate<CAPTURES>(pos, cur);
274       score<CAPTURES>();
275       ++stage;
276       /* fallthrough */
277
278   case PROBCUT_CAPTURES:
279       while (cur < endMoves)
280       {
281           move = pick_best(cur++, endMoves);
282           if (   move != ttMove
283               && pos.see_ge(move, threshold))
284               return move;
285       }
286       break;
287
288   case QCAPTURES_1_INIT: case QCAPTURES_2_INIT:
289       cur = moves;
290       endMoves = generate<CAPTURES>(pos, cur);
291       score<CAPTURES>();
292       ++stage;
293       /* fallthrough */
294
295   case QCAPTURES_1: case QCAPTURES_2:
296       while (cur < endMoves)
297       {
298           move = pick_best(cur++, endMoves);
299           if (move != ttMove)
300               return move;
301       }
302       if (stage == QCAPTURES_2)
303           break;
304       cur = moves;
305       endMoves = generate<QUIET_CHECKS>(pos, cur);
306       ++stage;
307       /* fallthrough */
308
309   case QCHECKS:
310       while (cur < endMoves)
311       {
312           move = cur++->move;
313           if (move != ttMove)
314               return move;
315       }
316       break;
317
318   case QSEARCH_RECAPTURES:
319       cur = moves;
320       endMoves = generate<CAPTURES>(pos, cur);
321       score<CAPTURES>();
322       ++stage;
323       /* fallthrough */
324
325   case QRECAPTURES:
326       while (cur < endMoves)
327       {
328           move = pick_best(cur++, endMoves);
329           if (to_sq(move) == recaptureSquare)
330               return move;
331       }
332       break;
333
334   default:
335       assert(false);
336   }
337
338   return MOVE_NONE;
339 }