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