]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Fix a few minor code style inconsistencies
[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-2018 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, KILLER0, KILLER1, COUNTERMOVE, 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_move()
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_p)
64            : pos(p), mainHistory(mh), captureHistory(cph), contHistory(ch),
65              refutations{killers_p[0], killers_p[1], cm}, depth(d){
66
67   assert(d > DEPTH_ZERO);
68
69   stage = pos.checkers() ? EVASION_TT : MAIN_TT;
70   ttMove = ttm && 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, Square rs)
77            : pos(p), mainHistory(mh), captureHistory(cph), recaptureSquare(rs), depth(d) {
78
79   assert(d <= DEPTH_ZERO);
80
81   stage = pos.checkers() ? EVASION_TT : QSEARCH_TT;
82   ttMove =    ttm
83            && pos.pseudo_legal(ttm)
84            && (depth > DEPTH_QS_RECAPTURES || to_sq(ttm) == recaptureSquare) ? ttm : MOVE_NONE;
85   stage += (ttMove == MOVE_NONE);
86 }
87
88 /// MovePicker constructor for ProbCut: we generate captures with SEE higher
89 /// than or equal to the given threshold.
90 MovePicker::MovePicker(const Position& p, Move ttm, Value th, const CapturePieceToHistory* cph)
91            : pos(p), captureHistory(cph), threshold(th) {
92
93   assert(!pos.checkers());
94
95   stage = PROBCUT_TT;
96   ttMove =   ttm
97           && pos.pseudo_legal(ttm)
98           && pos.capture(ttm)
99           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
100   stage += (ttMove == MOVE_NONE);
101 }
102
103 /// MovePicker::score() assigns a numerical value to each move in a list, used
104 /// for sorting. Captures are ordered by Most Valuable Victim (MVV), preferring
105 /// captures with a good history. Quiets moves are ordered using the histories.
106 template<GenType Type>
107 void MovePicker::score() {
108
109   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
110
111   for (auto& m : *this)
112       if (Type == CAPTURES)
113           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
114                    + (*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))];
115
116       else if (Type == QUIETS)
117           m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
118                    + (*contHistory[0])[pos.moved_piece(m)][to_sq(m)]
119                    + (*contHistory[1])[pos.moved_piece(m)][to_sq(m)]
120                    + (*contHistory[3])[pos.moved_piece(m)][to_sq(m)];
121
122       else // Type == EVASIONS
123       {
124           if (pos.capture(m))
125               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
126                        - Value(type_of(pos.moved_piece(m)));
127           else
128               m.value = (*mainHistory)[pos.side_to_move()][from_to(m)] - (1 << 28);
129       }
130 }
131
132 /// MovePicker::select_move() returns the next move satisfying a predicate function
133 template<PickType T, typename Pred>
134 Move MovePicker::select_move(Pred filter) {
135
136   while (cur < endMoves)
137   {
138       if (T == BEST_SCORE)
139           std::swap(*cur, *std::max_element(cur, endMoves));
140
141       move = *cur++;
142
143       if (move != ttMove && filter())
144           return move;
145   }
146   return move = MOVE_NONE;
147 }
148
149 /// MovePicker::next_move() is the most important method of the MovePicker class. It
150 /// returns a new pseudo legal move every time it is called, until there are no more
151 /// moves left. It picks the move with the highest score from a list of generated moves.
152 Move MovePicker::next_move(bool skipQuiets) {
153
154 top:
155   switch (stage) {
156
157   case MAIN_TT:
158   case EVASION_TT:
159   case QSEARCH_TT:
160   case PROBCUT_TT:
161       ++stage;
162       return ttMove;
163
164   case CAPTURE_INIT:
165   case PROBCUT_INIT:
166   case QCAPTURE_INIT:
167       endBadCaptures = cur = moves;
168       endMoves = generate<CAPTURES>(pos, cur);
169       score<CAPTURES>();
170       ++stage;
171       goto top;
172
173   case GOOD_CAPTURE:
174       if (select_move<BEST_SCORE>([&](){ return  pos.see_ge(move, Value(-55 * (cur-1)->value / 1024)) ?
175                                                  // Move losing capture to endBadCaptures to be tried later
176                                                  true : (*endBadCaptures++ = move, false); }))
177           return move;
178
179       // If the countermove is the same as a killer, skip it
180       if (   refutations[0] == refutations[2]
181           || refutations[1] == refutations[2])
182           refutations[2] = MOVE_NONE;
183       ++stage;
184       /* fallthrough */
185
186   case KILLER0:
187   case KILLER1:
188   case COUNTERMOVE:
189       while (stage <= COUNTERMOVE)
190       {
191           move = refutations[ stage++ - KILLER0];
192           if (    move != MOVE_NONE
193               &&  move != ttMove
194               &&  pos.pseudo_legal(move)
195               && !pos.capture(move))
196               return move;
197       }
198       /* fallthrough */
199
200   case QUIET_INIT:
201       cur = endBadCaptures;
202       endMoves = generate<QUIETS>(pos, cur);
203       score<QUIETS>();
204       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
205       ++stage;
206       /* fallthrough */
207
208   case QUIET:
209       if (   !skipQuiets
210           && select_move<NEXT>([&](){return    move != refutations[0]
211                                             && move != refutations[1]
212                                             && move != refutations[2];}))
213           return move;
214
215       // Point to beginning and end of bad captures
216       cur = moves, endMoves = endBadCaptures;
217       ++stage;
218       /* fallthrough */
219
220   case BAD_CAPTURE:
221       return select_move<NEXT>(Any);
222
223   case EVASION_INIT:
224       cur = moves;
225       endMoves = generate<EVASIONS>(pos, cur);
226       score<EVASIONS>();
227       ++stage;
228       /* fallthrough */
229
230   case EVASION:
231       return select_move<BEST_SCORE>(Any);
232
233   case PROBCUT:
234       return select_move<BEST_SCORE>([&](){ return pos.see_ge(move, threshold); });
235
236   case QCAPTURE:
237       if (select_move<BEST_SCORE>([&](){ return   depth > DEPTH_QS_RECAPTURES
238                                                || to_sq(move) == recaptureSquare; }))
239           return move;
240
241       // If we did not find any move and we do not try checks, we have finished
242       if (depth != DEPTH_QS_CHECKS)
243           return MOVE_NONE;
244
245       ++stage;
246       /* fallthrough */
247
248   case QCHECK_INIT:
249       cur = moves;
250       endMoves = generate<QUIET_CHECKS>(pos, cur);
251       ++stage;
252       /* fallthrough */
253
254   case QCHECK:
255       return select_move<NEXT>(Any);
256   }
257
258   assert(false);
259   return MOVE_NONE; // Silence warning
260 }