]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
qsearch(): remove inCheck as a template parameter
[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_SEARCH, CAPTURES_INIT, GOOD_CAPTURES, KILLER0, KILLER1, COUNTERMOVE, QUIET_INIT, QUIET, BAD_CAPTURES,
29     EVASION, EVASIONS_INIT, ALL_EVASIONS,
30     PROBCUT, PROBCUT_CAPTURES_INIT, PROBCUT_CAPTURES,
31     QSEARCH, QCAPTURES_INIT, QCAPTURES, QCHECKS
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   // pick_best() finds the best move in the range (begin, end) and moves it to
50   // the front. It's faster than sorting all the moves in advance when there
51   // are few moves, e.g., the possible captures.
52   Move pick_best(ExtMove* begin, ExtMove* end) {
53
54     std::swap(*begin, *std::max_element(begin, end));
55     return *begin;
56   }
57
58 } // namespace
59
60
61 /// Constructors of the MovePicker class. As arguments we pass information
62 /// to help it to return the (presumably) good moves first, to decide which
63 /// moves to return (in the quiescence search, for instance, we only want to
64 /// search captures, promotions, and some checks) and how important good move
65 /// ordering is at the current node.
66
67 /// MovePicker constructor for the main search
68 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,
69                        const CapturePieceToHistory* cph, const PieceToHistory** ch, Move cm, Move* killers_p)
70            : pos(p), mainHistory(mh), captureHistory(cph), contHistory(ch),
71              refutations{killers_p[0], killers_p[1], cm}, depth(d){
72
73   assert(d > DEPTH_ZERO);
74
75   stage = pos.checkers() ? EVASION : MAIN_SEARCH;
76   ttMove = ttm && pos.pseudo_legal(ttm) ? ttm : MOVE_NONE;
77   stage += (ttMove == MOVE_NONE);
78 }
79
80 /// MovePicker constructor for quiescence search
81 MovePicker::MovePicker(const Position& p, Move ttm, Depth d, const ButterflyHistory* mh,  const CapturePieceToHistory* cph, Square s)
82            : pos(p), mainHistory(mh), captureHistory(cph), recaptureSquare(s), depth(d) {
83
84   assert(d <= DEPTH_ZERO);
85
86   stage = pos.checkers() ? EVASION : QSEARCH;
87   ttMove =    ttm
88            && pos.pseudo_legal(ttm)
89            && (depth > DEPTH_QS_RECAPTURES || to_sq(ttm) == recaptureSquare) ? ttm : MOVE_NONE;
90   stage += (ttMove == MOVE_NONE);
91 }
92
93 /// MovePicker constructor for ProbCut: we generate captures with SEE higher
94 /// than or equal to the given threshold.
95 MovePicker::MovePicker(const Position& p, Move ttm, Value th, const CapturePieceToHistory* cph)
96            : pos(p), captureHistory(cph), threshold(th) {
97
98   assert(!pos.checkers());
99
100   stage = PROBCUT;
101   ttMove =   ttm
102           && pos.pseudo_legal(ttm)
103           && pos.capture(ttm)
104           && pos.see_ge(ttm, threshold) ? ttm : MOVE_NONE;
105   stage += (ttMove == MOVE_NONE);
106 }
107
108 /// score() assigns a numerical value to each move in a list, used for sorting.
109 /// Captures are ordered by Most Valuable Victim (MVV), preferring captures
110 /// with a good history. Quiets are ordered using the histories.
111 template<GenType Type>
112 void MovePicker::score() {
113
114   static_assert(Type == CAPTURES || Type == QUIETS || Type == EVASIONS, "Wrong type");
115
116   for (auto& m : *this)
117       if (Type == CAPTURES)
118           m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
119                    + (*captureHistory)[pos.moved_piece(m)][to_sq(m)][type_of(pos.piece_on(to_sq(m)))];
120
121       else if (Type == QUIETS)
122           m.value =  (*mainHistory)[pos.side_to_move()][from_to(m)]
123                    + (*contHistory[0])[pos.moved_piece(m)][to_sq(m)]
124                    + (*contHistory[1])[pos.moved_piece(m)][to_sq(m)]
125                    + (*contHistory[3])[pos.moved_piece(m)][to_sq(m)];
126
127       else // Type == EVASIONS
128       {
129           if (pos.capture(m))
130               m.value =  PieceValue[MG][pos.piece_on(to_sq(m))]
131                        - Value(type_of(pos.moved_piece(m)));
132           else
133               m.value = (*mainHistory)[pos.side_to_move()][from_to(m)] - (1 << 28);
134       }
135 }
136
137 /// next_move() is the most important method of the MovePicker class. It returns
138 /// a new pseudo legal move every time it is called, until there are no more moves
139 /// left. It picks the move with the biggest value from a list of generated moves
140 /// taking care not to return the ttMove if it has already been searched.
141
142 Move MovePicker::next_move(bool skipQuiets) {
143
144   Move move;
145
146 begin_switch:
147
148   switch (stage) {
149
150   case MAIN_SEARCH:
151   case EVASION:
152   case QSEARCH:
153   case PROBCUT:
154       ++stage;
155       return ttMove;
156
157   case CAPTURES_INIT:
158   case PROBCUT_CAPTURES_INIT:
159   case QCAPTURES_INIT:
160       endBadCaptures = cur = moves;
161       endMoves = generate<CAPTURES>(pos, cur);
162       score<CAPTURES>();
163       ++stage;
164
165       // Rebranch at the top of the switch
166       goto begin_switch;
167
168   case GOOD_CAPTURES:
169       while (cur < endMoves)
170       {
171           move = pick_best(cur++, endMoves);
172           if (move != ttMove)
173           {
174               if (pos.see_ge(move, Value(-55 * (cur-1)->value / 1024)))
175                   return move;
176
177               // Losing capture, move it to the beginning of the array
178               *endBadCaptures++ = move;
179           }
180       }
181       ++stage;
182
183       // If the countermove is the same as a killer, skip it
184       if (   refutations[0] == refutations[2]
185           || refutations[1] == refutations[2])
186          refutations[2] = MOVE_NONE;
187
188       /* fallthrough */
189
190   case KILLER0:
191   case KILLER1:
192   case COUNTERMOVE:
193       while (stage <= COUNTERMOVE)
194       {
195           move = refutations[ stage++ - KILLER0 ];
196           if (    move != MOVE_NONE
197               &&  move != ttMove
198               &&  pos.pseudo_legal(move)
199               && !pos.capture(move))
200               return move;
201       }
202       /* fallthrough */
203
204   case QUIET_INIT:
205       cur = endBadCaptures;
206       endMoves = generate<QUIETS>(pos, cur);
207       score<QUIETS>();
208       partial_insertion_sort(cur, endMoves, -4000 * depth / ONE_PLY);
209       ++stage;
210       /* fallthrough */
211
212   case QUIET:
213       if (!skipQuiets)
214           while (cur < endMoves)
215           {
216               move = *cur++;
217               if (   move != ttMove
218                   && move != refutations[0]
219                   && move != refutations[1]
220                   && move != refutations[2])
221                   return move;
222           }
223       ++stage;
224       cur = moves; // Point to beginning of bad captures
225       /* fallthrough */
226
227   case BAD_CAPTURES:
228       if (cur < endBadCaptures)
229           return *cur++;
230       break;
231
232   case EVASIONS_INIT:
233       cur = moves;
234       endMoves = generate<EVASIONS>(pos, cur);
235       score<EVASIONS>();
236       ++stage;
237       /* fallthrough */
238
239   case ALL_EVASIONS:
240       while (cur < endMoves)
241       {
242           move = pick_best(cur++, endMoves);
243           if (move != ttMove)
244               return move;
245       }
246       break;
247
248   case PROBCUT_CAPTURES:
249       while (cur < endMoves)
250       {
251           move = pick_best(cur++, endMoves);
252           if (   move != ttMove
253               && pos.see_ge(move, threshold))
254               return move;
255       }
256       break;
257
258   case QCAPTURES:
259       while (cur < endMoves)
260       {
261           move = pick_best(cur++, endMoves);
262           if (   move != ttMove
263               && (depth > DEPTH_QS_RECAPTURES || to_sq(move) == recaptureSquare))
264               return move;
265       }
266       if (depth <= DEPTH_QS_NO_CHECKS)
267           break;
268       cur = moves;
269       endMoves = generate<QUIET_CHECKS>(pos, cur);
270       ++stage;
271       /* fallthrough */
272
273   case QCHECKS:
274       while (cur < endMoves)
275       {
276           move = *cur++;
277           if (move != ttMove)
278               return move;
279       }
280       break;
281
282   default:
283       assert(false);
284   }
285
286   return MOVE_NONE;
287 }