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