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