]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Simplify Killer Move Penalty
[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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2019 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
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 #include <cassert>
22
23 #include "movepick.h"
24
25 namespace {
26
27   enum Stages {
28     MAIN_TT, CAPTURE_INIT, GOOD_CAPTURE, REFUTATION, QUIET_INIT, QUIET, BAD_CAPTURE,
29     EVASION_TT, EVASION_INIT, EVASION,
30     PROBCUT_TT, PROBCUT_INIT, PROBCUT,
31     QSEARCH_TT, QCAPTURE_INIT, QCAPTURE, QCHECK_INIT, QCHECK
32   };
33
34   // Helper filter used with select()
35   const auto Any = [](){ return true; };
36
37   // partial_insertion_sort() sorts moves in descending order up to and including
38   // a given limit. The order of moves smaller than the limit is left unspecified.
39   void partial_insertion_sort(ExtMove* begin, ExtMove* end, int limit) {
40
41     for (ExtMove *sortedEnd = begin, *p = begin + 1; p < end; ++p)
42         if (p->value >= limit)
43         {
44             ExtMove tmp = *p, *q;
45             *p = *++sortedEnd;
46             for (q = sortedEnd; q != begin && *(q - 1) < tmp; --q)
47                 *q = *(q - 1);
48             *q = tmp;
49         }
50   }
51
52 } // namespace
53
54
55 /// Constructors of the MovePicker class. As arguments we pass information
56 /// to help it to return the (presumably) good moves first, to decide which
57 /// moves to return (in the quiescence search, for instance, we only want to
58 /// search captures, promotions, and some checks) and how important good move
59 /// ordering is at the current node.
60
61 /// MovePicker constructor for the main search
62 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
63                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Move cm, Move* killers)
64            : pos(p), mainHistory(mh), captureHistory(cph), continuationHistory(ch),
65              refutations{{killers[0], 0}, {killers[1], 0}, {cm, 0}}, depth(d) {
66
67   assert(d > DEPTH_ZERO);
68
69   stage = pos.checkers() ? EVASION_TT : MAIN_TT;
70   ttMove = pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
71   stage += (ttMove == MOVE_NONE);
72 }
73
74 /// MovePicker constructor for quiescence search
75 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
76                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Square rs)
77            : pos(p), mainHistory(mh), captureHistory(cph), continuationHistory(ch), recaptureSquare(rs), depth(d) {
78
79   assert(d <= DEPTH_ZERO);
80
81   stage = pos.checkers() ? EVASION_TT : QSEARCH_TT;
82   ttMove =   pos.pseudo_legal(ttm)
83           && (depth > DEPTH_QS_RECAPTURES || to_sq(ttm) == recaptureSquare) ? ttm : MOVE_NONE;
84   stage += (ttMove == MOVE_NONE);
85 }
86
87 /// MovePicker constructor for ProbCut: we generate captures with SEE greater
88 /// than or equal to the given threshold.
89 MovePicker::MovePicker(const Position& p, Move ttm, Value th, const CapturePieceToHistory* cph)
90            : pos(p), captureHistory(cph), threshold(th) {
91
92   assert(!pos.checkers());
93
94   stage = PROBCUT_TT;
95   ttMove =   pos.pseudo_legal(ttm)
96           && pos.capture(ttm)
97           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
98   stage += (ttMove == MOVE_NONE);
99 }
100
101 /// MovePicker::score() assigns a numerical value to each move in a list, used
102 /// for sorting. Captures are ordered by Most Valuable Victim (MVV), preferring
103 /// captures with a good history. Quiets moves are ordered using the histories.
104 template<GenType Type>
105 void MovePicker::score() {
106
107   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
108
109   for (auto& m : *this)
110       if (Type == CAPTURES)
111           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
112                    + (*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))] / 8;
113
114       else if (Type == QUIETS)
115           m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
116                    + (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
117                    + (*continuationHistory[1])[pos.moved_piece(m)][to_sq(m)]
118                    + (*continuationHistory[3])[pos.moved_piece(m)][to_sq(m)];
119
120       else // Type == EVASIONS
121       {
122           if (pos.capture(m))
123               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
124                        - Value(type_of(pos.moved_piece(m)));
125           else
126               m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
127                        + (*continuationHistory[0])[pos.moved_piece(m)][to_sq(m)]
128                        - (1 << 28);
129       }
130 }
131
132 /// MovePicker::select() returns the next move satisfying a predicate function.
133 /// It never returns the TT move.
134 template<MovePicker::PickType T, typename Pred>
135 Move MovePicker::select(Pred filter) {
136
137   while (cur < endMoves)
138   {
139       if (T == Best)
140           std::swap(*cur, *std::max_element(cur, endMoves));
141
142       move = *cur++;
143
144       if (move != ttMove && filter())
145           return move;
146   }
147   return move = MOVE_NONE;
148 }
149
150 /// MovePicker::next_move() is the most important method of the MovePicker class. It
151 /// returns a new pseudo legal move every time it is called until there are no more
152 /// moves left, picking the move with the highest score from a list of generated moves.
153 Move MovePicker::next_move(bool skipQuiets) {
154
155 top:
156   switch (stage) {
157
158   case MAIN_TT:
159   case EVASION_TT:
160   case QSEARCH_TT:
161   case PROBCUT_TT:
162       ++stage;
163       return ttMove;
164
165   case CAPTURE_INIT:
166   case PROBCUT_INIT:
167   case QCAPTURE_INIT:
168       cur = endBadCaptures = moves;
169       endMoves = generate<CAPTURES>(pos, cur);
170
171       score<CAPTURES>();
172       ++stage;
173       goto top;
174
175   case GOOD_CAPTURE:
176       if (select<Best>([&](){
177                        return pos.see_ge(move, Value(-55 * (cur-1)->value / 1024)) ?
178                               // Move losing capture to endBadCaptures to be tried later
179                               true : (*endBadCaptures++ = move, false); }))
180           return move;
181
182       // Prepare the pointers to loop over the refutations array
183       cur = std::begin(refutations);
184       endMoves = std::end(refutations);
185
186       // If the countermove is the same as a killer, skip it
187       if (   refutations[0].move == refutations[2].move
188           || refutations[1].move == refutations[2].move)
189           --endMoves;
190
191       ++stage;
192       /* fallthrough */
193
194   case REFUTATION:
195       if (select<Next>([&](){ return   !pos.capture(move)
196                                     &&  pos.pseudo_legal(move); }))
197           return move;
198       ++stage;
199       /* fallthrough */
200
201   case QUIET_INIT:
202       cur = endBadCaptures;
203       endMoves = generate<QUIETS>(pos, cur);
204
205       score<QUIETS>();
206       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
207       ++stage;
208       /* fallthrough */
209
210   case QUIET:
211       if (   !skipQuiets
212           && select<Next>([&](){return   move != refutations[0]
213                                       && move != refutations[1]
214                                       && move != refutations[2];}))
215           return move;
216
217       // Prepare the pointers to loop over the bad captures
218       cur = moves;
219       endMoves = endBadCaptures;
220
221       ++stage;
222       /* fallthrough */
223
224   case BAD_CAPTURE:
225       return select<Next>(Any);
226
227   case EVASION_INIT:
228       cur = moves;
229       endMoves = generate<EVASIONS>(pos, cur);
230
231       score<EVASIONS>();
232       ++stage;
233       /* fallthrough */
234
235   case EVASION:
236       return select<Best>(Any);
237
238   case PROBCUT:
239       return select<Best>([&](){ return pos.see_ge(move, threshold); });
240
241   case QCAPTURE:
242       if (select<Best>([&](){ return   depth > DEPTH_QS_RECAPTURES
243                                     || to_sq(move) == recaptureSquare; }))
244           return move;
245
246       // If we did not find any move and we do not try checks, we have finished
247       if (depth != DEPTH_QS_CHECKS)
248           return MOVE_NONE;
249
250       ++stage;
251       /* fallthrough */
252
253   case QCHECK_INIT:
254       cur = moves;
255       endMoves = generate<QUIET_CHECKS>(pos, cur);
256
257       ++stage;
258       /* fallthrough */
259
260   case QCHECK:
261       return select<Next>(Any);
262   }
263
264   assert(false);
265   return MOVE_NONE; // Silence warning
266 }