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