]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Skip TT_MOVES phase when possible
[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-2009 Marco Costalba
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 <algorithm>
27 #include <cassert>
28
29 #include "history.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "search.h"
33 #include "value.h"
34
35
36 ////
37 //// Local definitions
38 ////
39
40 namespace {
41
42   CACHE_LINE_ALIGNMENT
43   const MovegenPhaseT MainSearchPhaseTable[] = { PH_TT_MOVES, PH_GOOD_CAPTURES, PH_KILLERS, PH_NONCAPTURES, PH_BAD_CAPTURES, PH_STOP};
44   const MovegenPhaseT EvasionsPhaseTable[] = { PH_EVASIONS, PH_STOP};
45   const MovegenPhaseT QsearchWithChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_QCHECKS, PH_STOP};
46   const MovegenPhaseT QsearchWithoutChecksPhaseTable[] = { PH_TT_MOVES, PH_QCAPTURES, PH_STOP};
47 }
48
49
50 ////
51 //// Functions
52 ////
53
54
55 /// Constructor for the MovePicker class. Apart from the position for which
56 /// it is asked to pick legal moves, MovePicker also wants some information
57 /// to help it to return the presumably good moves first, to decide which
58 /// moves to return (in the quiescence search, for instance, we only want to
59 /// search captures, promotions and some checks) and about how important good
60 /// move ordering is at the current node.
61
62 MovePicker::MovePicker(const Position& p, Move ttm, Depth d,
63                        const History& h, SearchStack* ss) : pos(p), H(h) {
64   int searchTT = ttm;
65   ttMoves[0].move = ttm;
66   if (ss)
67   {
68       ttMoves[1].move = (ss->mateKiller == ttm)? MOVE_NONE : ss->mateKiller;
69       searchTT |= ttMoves[1].move;
70       killers[0].move = ss->killers[0];
71       killers[1].move = ss->killers[1];
72   } else
73       ttMoves[1].move = killers[0].move = killers[1].move = MOVE_NONE;
74
75   finished = false;
76   numOfBadCaptures = 0;
77
78   Color us = pos.side_to_move();
79
80   dc = p.discovered_check_candidates(us);
81   pinned = p.pinned_pieces(us);
82
83   if (p.is_check())
84       phasePtr = EvasionsPhaseTable;
85   else if (d > Depth(0))
86       phasePtr = MainSearchPhaseTable + !searchTT;
87   else if (d == Depth(0))
88       phasePtr = QsearchWithChecksPhaseTable + !searchTT;
89   else
90       phasePtr = QsearchWithoutChecksPhaseTable + !searchTT;
91
92   phasePtr--;
93   go_next_phase();
94 }
95
96
97 /// MovePicker::go_next_phase() generates, scores and sorts the next bunch
98 /// of moves when there are no more moves to try for the current phase.
99
100 void MovePicker::go_next_phase() {
101
102   curMove = moves;
103   phase = *(++phasePtr);
104   switch (phase) {
105
106   case PH_TT_MOVES:
107       curMove = ttMoves;
108       lastMove = curMove + 2;
109       return;
110
111   case PH_GOOD_CAPTURES:
112       lastMove = generate_captures(pos, moves);
113       score_captures();
114       std::sort(moves, lastMove);
115       return;
116
117   case PH_KILLERS:
118       curMove = killers;
119       lastMove = curMove + 2;
120       return;
121
122   case PH_NONCAPTURES:
123       lastMove = generate_noncaptures(pos, moves);
124       score_noncaptures();
125       std::sort(moves, lastMove);
126       return;
127
128   case PH_BAD_CAPTURES:
129       // Bad captures SEE value is already calculated so just sort them
130       // to get SEE move ordering.
131       curMove = badCaptures;
132       lastMove = badCaptures + numOfBadCaptures;
133       std::sort(badCaptures, lastMove);
134       return;
135
136   case PH_EVASIONS:
137       assert(pos.is_check());
138       lastMove = generate_evasions(pos, moves, pinned);
139       score_evasions();
140       std::sort(moves, lastMove);
141       return;
142
143   case PH_QCAPTURES:
144       lastMove = generate_captures(pos, moves);
145       score_captures();
146       std::sort(moves, lastMove);
147       return;
148
149   case PH_QCHECKS:
150       // Perhaps we should order moves move here?  FIXME
151       lastMove = generate_non_capture_checks(pos, moves, dc);
152       return;
153
154   case PH_STOP:
155       lastMove = curMove + 1; // hack to be friendly for get_next_move()
156       return;
157
158   default:
159       assert(false);
160       return;
161   }
162 }
163
164
165 /// MovePicker::score_captures(), MovePicker::score_noncaptures() and
166 /// MovePicker::score_evasions() assign a numerical move ordering score
167 /// to each move in a move list.  The moves with highest scores will be
168 /// picked first by get_next_move().
169
170 void MovePicker::score_captures() {
171   // Winning and equal captures in the main search are ordered by MVV/LVA.
172   // Suprisingly, this appears to perform slightly better than SEE based
173   // move ordering. The reason is probably that in a position with a winning
174   // capture, capturing a more valuable (but sufficiently defended) piece
175   // first usually doesn't hurt. The opponent will have to recapture, and
176   // the hanging piece will still be hanging (except in the unusual cases
177   // where it is possible to recapture with the hanging piece). Exchanging
178   // big pieces before capturing a hanging piece probably helps to reduce
179   // the subtree size.
180   // In main search we want to push captures with negative SEE values to
181   // badCaptures[] array, but instead of doing it now we delay till when
182   // the move has been picked up in pick_move_from_list(), this way we save
183   // some SEE calls in case we get a cutoff (idea from Pablo Vazquez).
184   Move m;
185
186   // Use MVV/LVA ordering
187   for (MoveStack* cur = moves; cur != lastMove; cur++)
188   {
189       m = cur->move;
190       if (move_is_promotion(m))
191           cur->score = QueenValueMidgame;
192       else
193           cur->score = int(pos.midgame_value_of_piece_on(move_to(m)))
194                       -int(pos.type_of_piece_on(move_from(m)));
195   }
196 }
197
198 void MovePicker::score_noncaptures() {
199   // First score by history, when no history is available then use
200   // piece/square tables values. This seems to be better then a
201   // random choice when we don't have an history for any move.
202   Move m;
203   Piece piece;
204   Square from, to;
205   int hs;
206
207   for (MoveStack* cur = moves; cur != lastMove; cur++)
208   {
209       m = cur->move;
210       from = move_from(m);
211       to = move_to(m);
212       piece = pos.piece_on(from);
213       hs = H.move_ordering_score(piece, to);
214
215       // Ensure history is always preferred to pst
216       if (hs > 0)
217           hs += 1000;
218
219       // pst based scoring
220       cur->score = hs + pos.pst_delta<Position::MidGame>(piece, from, to);
221   }
222 }
223
224 void MovePicker::score_evasions() {
225
226   Move m;
227
228   for (MoveStack* cur = moves; cur != lastMove; cur++)
229   {
230       m = cur->move;
231       if (m == ttMoves[0].move)
232           cur->score = 2 * HistoryMax;
233       else if (!pos.square_is_empty(move_to(m)))
234       {
235           int seeScore = pos.see(m);
236           cur->score = seeScore + (seeScore >= 0 ? HistoryMax : 0);
237       } else
238           cur->score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
239   }
240 }
241
242 /// MovePicker::get_next_move() is the most important method of the MovePicker
243 /// class. It returns a new legal move every time it is called, until there
244 /// are no more moves left.
245 /// It picks the move with the biggest score from a list of generated moves taking
246 /// care not to return the tt move if that has already been serched previously.
247
248 Move MovePicker::get_next_move() {
249
250   assert(!pos.is_check() || *phasePtr == PH_EVASIONS || *phasePtr == PH_STOP);
251   assert( pos.is_check() || *phasePtr != PH_EVASIONS);
252
253   Move move;
254
255   while (true)
256   {
257       while (curMove != lastMove)
258       {
259           move = (curMove++)->move;
260
261           switch (phase) {
262
263           case PH_TT_MOVES:
264               if (   move != MOVE_NONE
265                   && move_is_legal(pos, move, pinned))
266                   return move;
267               break;
268
269           case PH_GOOD_CAPTURES:
270               if (   move != ttMoves[0].move
271                   && move != ttMoves[1].move
272                   && pos.pl_move_is_legal(move, pinned))
273               {
274                   // Check for a non negative SEE now
275                   int seeValue = pos.see_sign(move);
276                   if (seeValue >= 0)
277                       return move;
278
279                   // Losing capture, move it to the badCaptures[] array, note
280                   // that move has now been already checked for legality.
281                   assert(numOfBadCaptures < 63);
282                   badCaptures[numOfBadCaptures].move = move;
283                   badCaptures[numOfBadCaptures++].score = seeValue;
284               }
285               break;
286
287           case PH_KILLERS:
288               if (   move != MOVE_NONE
289                   && move != ttMoves[0].move
290                   && move != ttMoves[1].move
291                   && move_is_legal(pos, move, pinned)
292                   && !pos.move_is_capture(move))
293                   return move;
294               break;
295
296           case PH_NONCAPTURES:
297               if (   move != ttMoves[0].move
298                   && move != ttMoves[1].move
299                   && move != killers[0].move
300                   && move != killers[1].move
301                   && pos.pl_move_is_legal(move, pinned))
302                   return move;
303               break;
304
305           case PH_EVASIONS:
306           case PH_BAD_CAPTURES:
307               return move;
308
309           case PH_QCAPTURES:
310           case PH_QCHECKS:
311               // Maybe postpone the legality check until after futility pruning?
312               if (   move != ttMoves[0].move
313                   && pos.pl_move_is_legal(move, pinned))
314                   return move;
315               break;
316
317           case PH_STOP:
318               return MOVE_NONE;
319
320           default:
321               assert(false);
322               break;
323           }
324       }
325       go_next_phase();
326   }
327 }
328
329 /// A variant of get_next_move() which takes a lock as a parameter, used to
330 /// prevent multiple threads from picking the same move at a split point.
331
332 Move MovePicker::get_next_move(Lock &lock) {
333
334    lock_grab(&lock);
335    if (finished)
336    {
337        lock_release(&lock);
338        return MOVE_NONE;
339    }
340    Move m = get_next_move();
341    if (m == MOVE_NONE)
342        finished = true;
343
344    lock_release(&lock);
345    return m;
346 }