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