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