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