]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
60fcbaa53364d1ecadd8363908f3163f3ea1db6d
[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 "evaluate.h"
31 #include "movegen.h"
32 #include "movepick.h"
33 #include "search.h"
34 #include "value.h"
35
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   /// Variables
44
45   MovePicker::MovegenPhase PhaseTable[32];
46   int MainSearchPhaseIndex;
47   int EvasionsPhaseIndex;
48   int QsearchWithChecksPhaseIndex;
49   int QsearchWithoutChecksPhaseIndex;
50
51 }
52
53
54 ////
55 //// Functions
56 ////
57
58
59 /// Constructor for the MovePicker class.  Apart from the position for which
60 /// it is asked to pick legal moves, MovePicker also wants some information
61 /// to help it to return the presumably good moves first, to decide which
62 /// moves to return (in the quiescence search, for instance, we only want to
63 /// search captures, promotions and some checks) and about how important good
64 /// move ordering is at the current node.
65
66 MovePicker::MovePicker(const Position& p, bool pv, Move ttm,
67                        const SearchStack& ss, Depth d) : pos(p) {
68   pvNode = pv;
69   ttMove = ttm;
70   mateKiller = (ss.mateKiller == ttm)? MOVE_NONE : ss.mateKiller;
71   killer1 = ss.killers[0];
72   killer2 = ss.killers[1];
73   depth = d;
74   movesPicked = 0;
75   numOfMoves = 0;
76   numOfBadCaptures = 0;
77   checkKillers = checkLegal = false;
78
79   if (p.is_check())
80       phaseIndex = EvasionsPhaseIndex;
81   else if (depth > Depth(0))
82       phaseIndex = MainSearchPhaseIndex;
83   else if (depth == Depth(0))
84       phaseIndex = QsearchWithChecksPhaseIndex;
85   else
86       phaseIndex = QsearchWithoutChecksPhaseIndex;
87
88   Color us = pos.side_to_move();
89
90   dc = p.discovered_check_candidates(us);
91   pinned = p.pinned_pieces(us);
92
93   finished = false;
94 }
95
96
97 /// MovePicker::get_next_move() is the most important method of the MovePicker
98 /// class.  It returns a new legal move every time it is called, until there
99 /// are no more moves left of the types we are interested in.
100
101 Move MovePicker::get_next_move() {
102
103   Move move;
104
105   while (true)
106   {
107     // If we already have a list of generated moves, pick the best move from
108     // the list, and return it.
109     move = pick_move_from_list();
110     if (move != MOVE_NONE)
111     {
112         assert(move_is_ok(move));
113         return move;
114     }
115
116     // Next phase
117     phaseIndex++;
118     switch (PhaseTable[phaseIndex]) {
119
120     case PH_TT_MOVE:
121         if (ttMove != MOVE_NONE)
122         {
123             assert(move_is_ok(ttMove));
124             if (move_is_legal(pos, ttMove, pinned))
125                 return ttMove;
126         }
127         break;
128
129     case PH_MATE_KILLER:
130         if (mateKiller != MOVE_NONE)
131         {
132             assert(move_is_ok(mateKiller));
133             if (move_is_legal(pos, mateKiller, pinned))
134                 return mateKiller;
135         }
136         break;
137
138     case PH_GOOD_CAPTURES:
139         numOfMoves = generate_captures(pos, moves);
140         score_captures();
141         std::sort(moves, moves + numOfMoves);
142         movesPicked = 0;
143         checkLegal = true;
144         break;
145
146     case PH_KILLERS:
147         movesPicked = numOfMoves = 0;
148         checkLegal = false;
149         if (killer1 != MOVE_NONE && move_is_legal(pos, killer1, pinned) && !pos.move_is_capture(killer1))
150             moves[numOfMoves++].move = killer1;
151         if (killer2 != MOVE_NONE && move_is_legal(pos, killer2, pinned) && !pos.move_is_capture(killer2) )
152             moves[numOfMoves++].move = killer2;
153         break;
154
155     case PH_NONCAPTURES:
156         checkKillers = (numOfMoves != 0); // previous phase is PH_KILLERS
157         numOfMoves = generate_noncaptures(pos, moves);
158         score_noncaptures();
159         std::sort(moves, moves + numOfMoves);
160         movesPicked = 0;
161         checkLegal = true;
162         break;
163
164     case PH_BAD_CAPTURES:
165         // It's probably a good idea to use SEE move ordering here. FIXME
166         movesPicked = 0;
167         break;
168
169     case PH_EVASIONS:
170         assert(pos.is_check());
171         numOfMoves = generate_evasions(pos, moves, pinned);
172         score_evasions();
173         std::sort(moves, moves + numOfMoves);
174         movesPicked = 0;
175         break;
176
177     case PH_QCAPTURES:
178         numOfMoves = generate_captures(pos, moves);
179         score_qcaptures();
180         std::sort(moves, moves + numOfMoves);
181         movesPicked = 0;
182         break;
183
184     case PH_QCHECKS:
185         // Perhaps we should order moves move here?  FIXME
186         numOfMoves = generate_non_capture_checks(pos, moves, dc);
187         movesPicked = 0;
188         break;
189
190     case PH_STOP:
191         return MOVE_NONE;
192
193     default:
194         assert(false);
195         return MOVE_NONE;
196     }
197   }
198 }
199
200
201 /// A variant of get_next_move() which takes a lock as a parameter, used to
202 /// prevent multiple threads from picking the same move at a split point.
203
204 Move MovePicker::get_next_move(Lock &lock) {
205
206    lock_grab(&lock);
207    if (finished)
208    {
209        lock_release(&lock);
210        return MOVE_NONE;
211    }
212    Move m = get_next_move();
213    if (m == MOVE_NONE)
214        finished = true;
215
216    lock_release(&lock);
217    return m;
218 }
219
220
221 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
222 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
223 /// numerical move ordering score to each move in a move list.  The moves
224 /// with highest scores will be picked first by pick_move_from_list().
225
226 void MovePicker::score_captures() {
227   // Winning and equal captures in the main search are ordered by MVV/LVA.
228   // Suprisingly, this appears to perform slightly better than SEE based
229   // move ordering.  The reason is probably that in a position with a winning
230   // capture, capturing a more valuable (but sufficiently defended) piece
231   // first usually doesn't hurt.  The opponent will have to recapture, and
232   // the hanging piece will still be hanging (except in the unusual cases
233   // where it is possible to recapture with the hanging piece). Exchanging
234   // big pieces before capturing a hanging piece probably helps to reduce
235   // the subtree size.
236   // While scoring captures it moves all captures with negative SEE values
237   // to the badCaptures[] array.
238   Move m;
239   int seeValue;
240
241   for (int i = 0; i < numOfMoves; i++)
242   {
243       m = moves[i].move;
244       seeValue = pos.see(m);
245       if (seeValue >= 0)
246       {
247           if (move_promotion(m))
248               moves[i].score = QueenValueMidgame;
249           else
250               moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
251                               -int(pos.type_of_piece_on(move_from(m)));
252       }
253       else
254       {
255           // Losing capture, move it to the badCaptures[] array
256           assert(numOfBadCaptures < 63);
257           moves[i].score = seeValue;
258           badCaptures[numOfBadCaptures++] = moves[i];
259           moves[i--] = moves[--numOfMoves];
260       }
261   }
262 }
263
264 void MovePicker::score_noncaptures() {
265   // First score by history, when no history is available then use
266   // piece/square tables values. This seems to be better then a
267   // random choice when we don't have an history for any move.
268   Move m;
269   int hs;
270
271   for (int i = 0; i < numOfMoves; i++)
272   {
273       m = moves[i].move;
274       hs = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
275
276       // Ensure history is always preferred to pst
277       if (hs > 0)
278           hs += 1000;
279
280       // pst based scoring
281       moves[i].score = hs + pos.mg_pst_delta(m);
282   }
283 }
284
285 void MovePicker::score_evasions() {
286
287   for (int i = 0; i < numOfMoves; i++)
288   {
289       Move m = moves[i].move;
290       if (m == ttMove)
291           moves[i].score = 2*HistoryMax;
292       else if (!pos.square_is_empty(move_to(m)))
293       {
294           int seeScore = pos.see(m);
295           moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
296       } else
297           moves[i].score = H.move_ordering_score(pos.piece_on(move_from(m)), move_to(m));
298   }
299 }
300
301 void MovePicker::score_qcaptures() {
302
303   // Use MVV/LVA ordering
304   for (int i = 0; i < numOfMoves; i++)
305   {
306       Move m = moves[i].move;
307       if (move_promotion(m))
308           moves[i].score = QueenValueMidgame;
309       else
310           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
311                           -int(pos.type_of_piece_on(move_from(m)));
312   }
313 }
314
315
316 /// MovePicker::pick_move_from_list() picks the move with the biggest score
317 /// from a list of generated moves (moves[] or badCaptures[], depending on
318 /// the current move generation phase).  It takes care not to return the
319 /// transposition table move if that has already been serched previously.
320
321 Move MovePicker::pick_move_from_list() {
322
323   assert(movesPicked >= 0);
324   assert(!pos.is_check() || PhaseTable[phaseIndex] == PH_EVASIONS || PhaseTable[phaseIndex] == PH_STOP);
325   assert( pos.is_check() || PhaseTable[phaseIndex] != PH_EVASIONS);
326
327   switch (PhaseTable[phaseIndex]) {
328
329   case PH_GOOD_CAPTURES:
330   case PH_KILLERS:
331   case PH_NONCAPTURES:
332       while (movesPicked < numOfMoves)
333       {
334           Move move = moves[movesPicked++].move;
335           if (   move != ttMove
336               && move != mateKiller
337               && (!checkKillers || (move != killer1 && move != killer2))
338               && (!checkLegal || pos.pl_move_is_legal(move, pinned)))
339               return move;
340       }
341       break;
342
343   case PH_EVASIONS:
344       if (movesPicked < numOfMoves)
345           return moves[movesPicked++].move;
346
347       break;
348
349   case PH_BAD_CAPTURES:
350       while (movesPicked < numOfBadCaptures)
351       {
352           Move move = badCaptures[movesPicked++].move;
353           if (   move != ttMove
354               && move != mateKiller
355               && pos.pl_move_is_legal(move, pinned))
356               return move;
357       }
358       break;
359
360   case PH_QCAPTURES:
361   case PH_QCHECKS:
362       while (movesPicked < numOfMoves)
363       {
364           Move move = moves[movesPicked++].move;
365           // Maybe postpone the legality check until after futility pruning?
366           if (   move != ttMove
367               && pos.pl_move_is_legal(move, pinned))
368               return move;
369       }
370       break;
371
372   default:
373       break;
374   }
375   return MOVE_NONE;
376 }
377
378
379 /// MovePicker::init_phase_table() initializes the PhaseTable[],
380 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
381 /// and QsearchWithoutChecksPhaseIndex. It is only called once during
382 /// program startup, and never again while the program is running.
383
384 void MovePicker::init_phase_table() {
385
386   int i = 0;
387
388   // Main search
389   MainSearchPhaseIndex = i - 1;
390   PhaseTable[i++] = PH_TT_MOVE;
391   PhaseTable[i++] = PH_MATE_KILLER;
392   PhaseTable[i++] = PH_GOOD_CAPTURES;
393   PhaseTable[i++] = PH_KILLERS;
394   PhaseTable[i++] = PH_NONCAPTURES;
395   PhaseTable[i++] = PH_BAD_CAPTURES;
396   PhaseTable[i++] = PH_STOP;
397
398   // Check evasions
399   EvasionsPhaseIndex = i - 1;
400   PhaseTable[i++] = PH_EVASIONS;
401   PhaseTable[i++] = PH_STOP;
402
403   // Quiescence search with checks
404   QsearchWithChecksPhaseIndex = i - 1;
405   PhaseTable[i++] = PH_TT_MOVE;
406   PhaseTable[i++] = PH_QCAPTURES;
407   PhaseTable[i++] = PH_QCHECKS;
408   PhaseTable[i++] = PH_STOP;
409
410   // Quiescence search without checks
411   QsearchWithoutChecksPhaseIndex = i - 1;
412   PhaseTable[i++] = PH_TT_MOVE;
413   PhaseTable[i++] = PH_QCAPTURES;
414   PhaseTable[i++] = PH_STOP;
415 }