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