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