]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Use a constant instead of value_mate_in(PLY_MAX)
[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-2010 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 "history.h"
24 #include "movegen.h"
25 #include "movepick.h"
26 #include "search.h"
27 #include "types.h"
28
29 namespace {
30
31   enum MovegenPhase {
32     PH_TT_MOVES,       // Transposition table move and mate killer
33     PH_GOOD_CAPTURES,  // Queen promotions and captures with SEE values >= 0
34     PH_KILLERS,        // Killer moves from the current ply
35     PH_NONCAPTURES,    // Non-captures and underpromotions
36     PH_BAD_CAPTURES,   // Queen promotions and captures with SEE values < 0
37     PH_EVASIONS,       // Check evasions
38     PH_QCAPTURES,      // Captures in quiescence search
39     PH_QCHECKS,        // Non-capture checks in quiescence search
40     PH_STOP
41   };
42
43   CACHE_LINE_ALIGNMENT
44   const uint8_t MainSearchPhaseTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP};
45   const uint8_t EvasionsPhaseTable[] = { PH_TT_MOVES, PH_EVASIONS, PH_STOP};
46   const uint8_t QsearchWithChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP};
47   const uint8_t QsearchWithoutChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP};
48 }
49
50
51 /// Constructor for the MovePicker class. Apart from the position for which
52 /// it is asked to pick legal moves, MovePicker also wants some information
53 /// to help it to return the presumably good moves first, to decide which
54 /// moves to return (in the quiescence search, for instance, we only want to
55 /// search captures, promotions and some checks) and about how important good
56 /// move ordering is at the current node.
57
58 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h,
59                        SearchStack* ss, Value beta) : pos(p), H(h) {
60   int searchTT = ttm;
61   ttMoves[0].move = ttm;
62   badCaptureThreshold = 0;
63   badCaptures = moves + MOVES_MAX;
64
65   assert(d > DEPTH_ZERO);
66
67   pinned = p.pinned_pieces(pos.side_to_move());
68
69   if (p.is_check())
70   {
71       ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
72       phasePtr = EvasionsPhaseTable;
73   }
74   else
75   {
76       ttMoves[1].move = (ss->mateKiller == ttm) ? MOVE_NONE : ss->mateKiller;
77       searchTT |= ttMoves[1].move;
78       killers[0].move = ss->killers[0];
79       killers[1].move = ss->killers[1];
80
81       // Consider sligtly negative captures as good if at low
82       // depth and far from beta.
83       if (ss && ss->eval < beta - PawnValueMidgame && d < 3 * ONE_PLY)
84           badCaptureThreshold = -PawnValueMidgame;
85
86       phasePtr = MainSearchPhaseTable;
87   }
88
89   phasePtr += int(!searchTT) - 1;
90   go_next_phase();
91 }
92
93 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const History& h)
94                       : pos(p), H(h) {
95   int searchTT = ttm;
96   ttMoves[0].move = ttm;
97   ttMoves[1].move = MOVE_NONE;
98
99   assert(d <= DEPTH_ZERO);
100
101   pinned = p.pinned_pieces(pos.side_to_move());
102
103   if (p.is_check())
104       phasePtr = EvasionsPhaseTable;
105   else if (d >= DEPTH_QS_CHECKS)
106       phasePtr = QsearchWithChecksPhaseTable;
107   else
108   {
109       phasePtr = QsearchWithoutChecksPhaseTable;
110
111       // Skip TT move if is not a capture or a promotion, this avoids
112       // qsearch tree explosion due to a possible perpetual check or
113       // similar rare cases when TT table is full.
114       if (ttm != MOVE_NONE && !pos.move_is_capture_or_promotion(ttm))
115           searchTT = ttMoves[0].move = MOVE_NONE;
116   }
117
118   phasePtr += int(!searchTT) - 1;
119   go_next_phase();
120 }
121
122
123 /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
124 /// of moves when there are no more moves to try for the current phase.
125
126 void MovePicker::go_next_phase() {
127
128   curMove = moves;
129   phase = *(++phasePtr);
130   switch (phase) {
131
132   case PH_TT_MOVES:
133       curMove = ttMoves;
134       lastMove = curMove + 2;
135       return;
136
137   case PH_GOOD_CAPTURES:
138       lastMove = generate<MV_CAPTURE>(pos, moves);
139       score_captures();
140       return;
141
142   case PH_KILLERS:
143       curMove = killers;
144       lastMove = curMove + 2;
145       return;
146
147   case PH_NONCAPTURES:
148       lastMove = generate<MV_NON_CAPTURE>(pos, moves);
149       score_noncaptures();
150       sort_moves(moves, lastMove, &lastGoodNonCapture);
151       return;
152
153   case PH_BAD_CAPTURES:
154       // Bad captures SEE value is already calculated so just pick
155       // them in order to get SEE move ordering.
156       curMove = badCaptures;
157       lastMove = moves + MOVES_MAX;
158       return;
159
160   case PH_EVASIONS:
161       assert(pos.is_check());
162       lastMove = generate<MV_EVASION>(pos, moves);
163       score_evasions();
164       return;
165
166   case PH_QCAPTURES:
167       lastMove = generate<MV_CAPTURE>(pos, moves);
168       score_captures();
169       return;
170
171   case PH_QCHECKS:
172       lastMove = generate<MV_NON_CAPTURE_CHECK>(pos, moves);
173       return;
174
175   case PH_STOP:
176       lastMove = curMove + 1; // Avoids another go_next_phase() call
177       return;
178
179   default:
180       assert(false);
181       return;
182   }
183 }
184
185
186 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
187 /// MovePicker::score_evasions() assign a numerical move ordering score
188 /// to each move in a move list.  The moves with highest scores will be
189 /// picked first by get_next_move().
190
191 void MovePicker::score_captures() {
192   // Winning and equal captures in the main search are ordered by MVV/LVA.
193   // Suprisingly, this appears to perform slightly better than SEE based
194   // move ordering. The reason is probably that in a position with a winning
195   // capture, capturing a more valuable (but sufficiently defended) piece
196   // first usually doesn't hurt. The opponent will have to recapture, and
197   // the hanging piece will still be hanging (except in the unusual cases
198   // where it is possible to recapture with the hanging piece). Exchanging
199   // big pieces before capturing a hanging piece probably helps to reduce
200   // the subtree size.
201   // In main search we want to push captures with negative SEE values to
202   // badCaptures[] array, but instead of doing it now we delay till when
203   // the move has been picked up in pick_move_from_list(), this way we save
204   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
205   Move m;
206
207   // Use MVV/LVA ordering
208   for (MoveStack* cur = moves; cur != lastMove; cur++)
209   {
210       m = cur->move;
211       if (move_is_promotion(m))
212           cur->score = QueenValueMidgame;
213       else
214           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
215                       - pos.type_of_piece_on(move_from(m));
216   }
217 }
218
219 void MovePicker::score_noncaptures() {
220   // First score by history, when no history is available then use
221   // piece/square tables values. This seems to be better then a
222   // random choice when we don't have an history for any move.
223   Move m;
224   Piece piece;
225   Square from, to;
226
227   for (MoveStack* cur = moves; cur != lastMove; cur++)
228   {
229       m = cur->move;
230       from = move_from(m);
231       to = move_to(m);
232       piece = pos.piece_on(from);
233       cur->score = H.value(piece, to) + H.gain(piece, to);
234   }
235 }
236
237 void MovePicker::score_evasions() {
238   // Try good captures ordered by MVV/LVA, then non-captures if
239   // destination square is not under attack, ordered by history
240   // value, and at the end bad-captures and non-captures with a
241   // negative SEE. This last group is ordered by the SEE score.
242   Move m;
243   int seeScore;
244
245   // Skip if we don't have at least two moves to order
246   if (lastMove < moves + 2)
247       return;
248
249   for (MoveStack* cur = moves; cur != lastMove; cur++)
250   {
251       m = cur->move;
252       if ((seeScore = pos.see_sign(m)) < 0)
253           cur->score = seeScore - History::MaxValue; // Be sure we are at the bottom
254       else if (pos.move_is_capture(m))
255           cur->score =  pos.midgame_value_of_piece_on(move_to(m))
256                       - pos.type_of_piece_on(move_from(m)) + History::MaxValue;
257       else
258           cur->score = H.value(pos.piece_on(move_from(m)), move_to(m));
259   }
260 }
261
262 /// MovePicker::get_next_move() is the most important method of the MovePicker
263 /// class. It returns a new legal move every time it is called, until there
264 /// are no more moves left.
265 /// It picks the move with the biggest score from a list of generated moves taking
266 /// care not to return the tt move if has already been searched previously.
267 /// Note that this function is not thread safe so should be lock protected by
268 /// caller when accessed through a shared MovePicker object.
269
270 Move MovePicker::get_next_move() {
271
272   Move move;
273
274   while (true)
275   {
276       while (curMove != lastMove)
277       {
278           switch (phase) {
279
280           case PH_TT_MOVES:
281               move = (curMove++)->move;
282               if (   move != MOVE_NONE
283                   && move_is_legal(pos, move, pinned))
284                   return move;
285               break;
286
287           case PH_GOOD_CAPTURES:
288               move = pick_best(curMove++, lastMove).move;
289               if (   move != ttMoves[0].move
290                   && move != ttMoves[1].move
291                   && pos.pl_move_is_legal(move, pinned))
292               {
293                   // Check for a non negative SEE now
294                   int seeValue = pos.see_sign(move);
295                   if (seeValue >= badCaptureThreshold)
296                       return move;
297
298                   // Losing capture, move it to the tail of the array, note
299                   // that move has now been already checked for legality.
300                   (--badCaptures)->move = move;
301                   badCaptures->score = seeValue;
302               }
303               break;
304
305           case PH_KILLERS:
306               move = (curMove++)->move;
307               if (   move != MOVE_NONE
308                   && move_is_legal(pos, move, pinned)
309                   && move != ttMoves[0].move
310                   && move != ttMoves[1].move
311                   && !pos.move_is_capture(move))
312                   return move;
313               break;
314
315           case PH_NONCAPTURES:
316
317               // Sort negative scored moves only when we get there
318               if (curMove == lastGoodNonCapture)
319                   insertion_sort<MoveStack>(lastGoodNonCapture, lastMove);
320
321               move = (curMove++)->move;
322               if (   move != ttMoves[0].move
323                   && move != ttMoves[1].move
324                   && move != killers[0].move
325                   && move != killers[1].move
326                   && pos.pl_move_is_legal(move, pinned))
327                   return move;
328               break;
329
330           case PH_BAD_CAPTURES:
331               move = pick_best(curMove++, lastMove).move;
332               return move;
333
334           case PH_EVASIONS:
335           case PH_QCAPTURES:
336               move = pick_best(curMove++, lastMove).move;
337               if (   move != ttMoves[0].move
338                   && pos.pl_move_is_legal(move, pinned))
339                   return move;
340               break;
341
342           case PH_QCHECKS:
343               move = (curMove++)->move;
344               if (   move != ttMoves[0].move
345                   && pos.pl_move_is_legal(move, pinned))
346                   return move;
347               break;
348
349           case PH_STOP:
350               return MOVE_NONE;
351
352           default:
353               assert(false);
354               break;
355           }
356       }
357       go_next_phase();
358   }
359 }