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