]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
MovePicker: introduce per square MVV/LVA ordering
[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 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 <cassert>
27
28 #include "history.h"
29 #include "movegen.h"
30 #include "movepick.h"
31 #include "search.h"
32 #include "value.h"
33
34
35 ////
36 //// Local definitions
37 ////
38
39 namespace {
40
41   /// Variables
42
43   MovePicker::MovegenPhase PhaseTable[32];
44   int MainSearchPhaseIndex;
45   int EvasionsPhaseIndex;
46   int QsearchWithChecksPhaseIndex;
47   int QsearchWithoutChecksPhaseIndex;
48
49 }
50
51
52
53 ////
54 //// Functions
55 ////
56
57
58 /// Constructor for the MovePicker class.  Apart from the position for which
59 /// it is asked to pick legal moves, MovePicker also wants some information
60 /// to help it to return the presumably good moves first, to decide which
61 /// moves to return (in the quiescence search, for instance, we only want to
62 /// search captures, promotions and some checks) and about how important good
63 /// move ordering is at the current node.
64
65 MovePicker::MovePicker(const Position& p, bool pvnode, Move ttm, Move mk,
66                        Move k1, Move k2, Depth d) : pos(p) {
67   pvNode = pvnode;
68   ttMove = ttm;
69   mateKiller = (mk == ttm)? MOVE_NONE : mk;
70   killer1 = k1;
71   killer2 = k2;
72   depth = d;
73   movesPicked = 0;
74   numOfMoves = 0;
75   numOfBadCaptures = 0;
76   dc = p.discovered_check_candidates(p.side_to_move());
77
78   if (p.is_check())
79     phaseIndex = EvasionsPhaseIndex;
80   else if (depth > Depth(0))
81     phaseIndex = MainSearchPhaseIndex;
82   else if (depth == Depth(0))
83     phaseIndex = QsearchWithChecksPhaseIndex;
84   else
85     phaseIndex = QsearchWithoutChecksPhaseIndex;
86
87   pinned = p.pinned_pieces(p.side_to_move());
88
89   finished = false;
90 }
91
92
93 /// MovePicker::get_next_move() is the most important method of the MovePicker
94 /// class.  It returns a new legal move every time it is called, until there
95 /// are no more moves left of the types we are interested in.
96
97 Move MovePicker::get_next_move() {
98
99   Move move;
100
101   while (true)
102   {
103     // If we already have a list of generated moves, pick the best move from
104     // the list, and return it.
105     move = pick_move_from_list();
106     if (move != MOVE_NONE)
107     {
108         assert(move_is_ok(move));
109         return move;
110     }
111
112     // Next phase
113     phaseIndex++;
114     switch (PhaseTable[phaseIndex]) {
115
116     case PH_TT_MOVE:
117         if (ttMove != MOVE_NONE)
118         {
119             assert(move_is_ok(ttMove));
120             if (move_is_legal(pos, ttMove, pinned))
121                 return ttMove;
122         }
123         break;
124
125     case PH_MATE_KILLER:
126         if (mateKiller != MOVE_NONE)
127         {
128             assert(move_is_ok(mateKiller));
129             if (move_is_legal(pos, mateKiller, pinned))
130                 return mateKiller;
131        }
132        break;
133
134     case PH_GOOD_CAPTURES:
135         numOfMoves = generate_captures(pos, moves);
136         score_captures();
137         capSquares = EmptyBoardBB;
138         movesPicked = 0;
139         break;
140
141     case PH_BAD_CAPTURES:
142         badCapturesPicked = 0;
143         break;
144
145     case PH_NONCAPTURES:
146         numOfMoves = generate_noncaptures(pos, moves);
147         score_noncaptures();
148         movesPicked = 0;
149         break;
150
151     case PH_EVASIONS:
152         assert(pos.is_check());
153         numOfMoves = generate_evasions(pos, moves);
154         score_evasions();
155         movesPicked = 0;
156         break;
157
158     case PH_QCAPTURES:
159         numOfMoves = generate_captures(pos, moves);
160         score_qcaptures();
161         movesPicked = 0;
162         break;
163
164     case PH_QCHECKS:
165         numOfMoves = generate_checks(pos, moves, dc);
166         movesPicked = 0;
167         break;
168
169     case PH_STOP:
170         return MOVE_NONE;
171
172     default:
173         assert(false);
174         return MOVE_NONE;
175     }
176   }
177 }
178
179
180 /// A variant of get_next_move() which takes a lock as a parameter, used to
181 /// prevent multiple threads from picking the same move at a split point.
182
183 Move MovePicker::get_next_move(Lock &lock) {
184
185    lock_grab(&lock);
186    if (finished)
187    {
188        lock_release(&lock);
189        return MOVE_NONE;
190    }
191    Move m = get_next_move();
192    if (m == MOVE_NONE)
193        finished = true;
194
195    lock_release(&lock);
196    return m;
197 }
198
199
200 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
201 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
202 /// numerical move ordering score to each move in a move list.  The moves
203 /// with highest scores will be picked first by pick_move_from_list().
204
205 void MovePicker::score_captures() {
206   // Winning and equal captures in the main search are ordered by MVV/LVA.
207   // Suprisingly, this appears to perform slightly better than SEE based
208   // move ordering.  The reason is probably that in a position with a winning
209   // capture, capturing a more valuable (but sufficiently defended) piece
210   // first usually doesn't hurt.  The opponent will have to recapture, and
211   // the hanging piece will still be hanging (except in the unusual cases
212   // where it is possible to recapture with the hanging piece). Exchanging
213   // big pieces before capturing a hanging piece probably helps to reduce
214   // the subtree size.
215   Move m;
216   int seeValue;
217
218   for (int i = 0; i < numOfMoves; i++)
219   {
220       m = moves[i].move;
221       seeValue = pos.see(m);
222       if (seeValue >= 0)
223       {
224           if (move_promotion(m))
225               moves[i].score = QueenValueMidgame;
226           else
227               moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
228                               -int(pos.type_of_piece_on(move_from(m)));
229       } else
230           moves[i].score = seeValue;
231   }
232 }
233
234 void MovePicker::score_noncaptures() {
235   // First score by history, when no history is available then use
236   // piece/square tables values. This seems to be better then a
237   // random choice when we don't have an history for any move.
238   Move m;
239   int hs;
240
241   for (int i = 0; i < numOfMoves; i++)
242   {
243       m = moves[i].move;
244
245       if (m == killer1)
246           hs = HistoryMax + 2;
247       else if (m == killer2)
248           hs = HistoryMax + 1;
249       else
250           hs = H.move_ordering_score(pos.piece_on(move_from(m)), m);
251
252       // Ensure moves in history are always sorted as first
253       if (hs > 0)
254           hs += 1000;
255
256       moves[i].score = hs + pos.mg_pst_delta(m);
257   }
258 }
259
260 void MovePicker::score_evasions() {
261
262   for (int i = 0; i < numOfMoves; i++)
263   {
264       Move m = moves[i].move;
265       if (m == ttMove)
266           moves[i].score = 2*HistoryMax;
267       else if (!pos.square_is_empty(move_to(m)))
268       {
269           int seeScore = pos.see(m);
270           moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
271       } else
272           moves[i].score = H.move_ordering_score(pos.piece_on(move_from(m)), m);
273   }
274   // FIXME try psqt also here
275 }
276
277 void MovePicker::score_qcaptures() {
278
279   // Use MVV/LVA ordering
280   for (int i = 0; i < numOfMoves; i++)
281   {
282       Move m = moves[i].move;
283       if (move_promotion(m))
284           moves[i].score = QueenValueMidgame;
285       else
286           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
287                           -int(pos.type_of_piece_on(move_from(m)));
288   }
289 }
290
291
292 /// find_best_index() loops across the moves and returns index of\r
293 /// the highest scored one. There is also a second version that\r
294 /// lowers the priority of moves that attack the same square,\r
295 /// so that if the best move that attack a square fails the next\r
296 /// move picked attacks a different square if any, not the same one.
297
298 int MovePicker::find_best_index() {
299
300   int bestScore = -10000000, bestIndex = -1;
301
302   for (int i = movesPicked; i < numOfMoves; i++)
303       if (moves[i].score > bestScore)
304       {
305           bestIndex = i;
306           bestScore = moves[i].score;
307       }
308   return bestIndex;
309 }
310
311 int MovePicker::find_best_index(Bitboard* squares, int values[]) {\r
312 \r
313   int hs;\r
314   Move m;\r
315   Square to;\r
316   int bestScore = -10000000, bestIndex = -1;\r
317 \r
318   for (int i = movesPicked; i < numOfMoves; i++)\r
319   {\r
320       m = moves[i].move;\r
321       to = move_to(m);\r
322       \r
323       if (!bit_is_set(*squares, to))\r
324       {\r
325           // Init at first use\r
326           set_bit(squares, to);\r
327           values[to] = 0;\r
328       }\r
329 \r
330       hs = moves[i].score - values[to];\r
331       if (hs > bestScore)\r
332       {\r
333           bestIndex = i;\r
334           bestScore = hs;\r
335       }\r
336   }\r
337 \r
338   if (bestIndex != -1)\r
339   {\r
340       // Raise value of the picked square, so next attack\r
341       // to the same square will get low priority.\r
342       to = move_to(moves[bestIndex].move);\r
343       values[to] += 0xB00;\r
344   }\r
345   return bestIndex;\r
346 }
347
348
349 /// MovePicker::pick_move_from_list() picks the move with the biggest score
350 /// from a list of generated moves (moves[] or badCaptures[], depending on
351 /// the current move generation phase).  It takes care not to return the
352 /// transposition table move if that has already been serched previously.
353 /// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
354 /// non-losing captures in the main search), it moves all captures with
355 /// negative SEE values to the badCaptures[] array.
356
357 Move MovePicker::pick_move_from_list() {
358
359   int bestIndex;
360   Move move;
361
362   switch (PhaseTable[phaseIndex]) {
363   case PH_GOOD_CAPTURES:
364       assert(!pos.is_check());
365       assert(movesPicked >= 0);
366
367       while (movesPicked < numOfMoves)
368       {
369           int bestScore = -10000000;
370           bestIndex = -1;
371           for (int i = movesPicked; i < numOfMoves; i++)
372           {
373               if (moves[i].score < 0)
374               {
375                   // Losing capture, move it to the badCaptures[] array
376                   assert(numOfBadCaptures < 63);
377                   badCaptures[numOfBadCaptures++] = moves[i];
378                   moves[i--] = moves[--numOfMoves];
379               }
380               else if (moves[i].score > bestScore)
381               {
382                   bestIndex = i;
383                   bestScore = moves[i].score;
384               }
385           }
386           if (bestIndex != -1) // Found a good capture
387           {
388               move = moves[bestIndex].move;
389               moves[bestIndex] = moves[movesPicked++];
390               if (   move != ttMove
391                   && move != mateKiller
392                   && pos.pl_move_is_legal(move, pinned))
393                   return move;
394           }
395       }
396       break;
397
398   case PH_NONCAPTURES:
399       assert(!pos.is_check());
400       assert(movesPicked >= 0);
401
402       while (movesPicked < numOfMoves)
403       {
404           // If this is a PV node or we have only picked a few moves, scan
405           // the entire move list for the best move.  If many moves have already
406           // been searched and it is not a PV node, we are probably failing low
407           // anyway, so we just pick the first move from the list.
408           bestIndex = (pvNode || movesPicked < 12) ? find_best_index() : movesPicked;
409
410           if (bestIndex != -1)
411           {
412               move = moves[bestIndex].move;
413               moves[bestIndex] = moves[movesPicked++];
414               if (   move != ttMove
415                   && move != mateKiller
416                   && pos.pl_move_is_legal(move, pinned))
417                   return move;
418           }
419       }
420       break;
421
422   case PH_EVASIONS:
423       assert(pos.is_check());
424       assert(movesPicked >= 0);
425
426       while (movesPicked < numOfMoves)
427       {
428           bestIndex = find_best_index();
429
430           if (bestIndex != -1)
431           {
432               move = moves[bestIndex].move;
433               moves[bestIndex] = moves[movesPicked++];
434               return move;
435           }
436     }
437     break;
438
439   case PH_BAD_CAPTURES:
440       assert(!pos.is_check());
441       assert(badCapturesPicked >= 0);
442       // It's probably a good idea to use SEE move ordering here, instead
443       // of just picking the first move.  FIXME
444       while (badCapturesPicked < numOfBadCaptures)
445       {
446           move = badCaptures[badCapturesPicked++].move;
447           if (   move != ttMove
448               && move != mateKiller
449               && pos.pl_move_is_legal(move, pinned))
450               return move;
451       }
452       break;
453
454   case PH_QCAPTURES:
455       assert(!pos.is_check());
456       assert(movesPicked >= 0);
457       while (movesPicked < numOfMoves)
458       {
459           bestIndex = (movesPicked < 4 ? find_best_index() : movesPicked);
460
461           if (bestIndex != -1)
462           {
463               move = moves[bestIndex].move;
464               moves[bestIndex] = moves[movesPicked++];
465               // Remember to change the line below if we decide to hash the qsearch!
466               // Maybe also postpone the legality check until after futility pruning?
467               if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
468                   return move;
469           }
470       }
471       break;
472
473   case PH_QCHECKS:
474       assert(!pos.is_check());
475       assert(movesPicked >= 0);
476       // Perhaps we should do something better than just picking the first
477       // move here?  FIXME
478       while (movesPicked < numOfMoves)
479       {
480           move = moves[movesPicked++].move;
481           // Remember to change the line below if we decide to hash the qsearch!
482           if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
483               return move;
484       }
485       break;
486
487   default:
488       break;
489   }
490   return MOVE_NONE;
491 }
492
493
494 /// MovePicker::current_move_type() returns the type of the just
495 /// picked next move. It can be used in search to further differentiate
496 /// according to the current move type: capture, non capture, escape, etc.
497 MovePicker::MovegenPhase MovePicker::current_move_type() const {
498
499   return PhaseTable[phaseIndex];
500 }
501
502
503 /// MovePicker::init_phase_table() initializes the PhaseTable[],
504 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
505 /// and QsearchWithoutChecksPhaseIndex variables. It is only called once
506 /// during program startup, and never again while the program is running.
507
508 void MovePicker::init_phase_table() {
509
510   int i = 0;
511
512   // Main search
513   MainSearchPhaseIndex = i - 1;
514   PhaseTable[i++] = PH_TT_MOVE;
515   PhaseTable[i++] = PH_MATE_KILLER;
516   PhaseTable[i++] = PH_GOOD_CAPTURES;
517   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
518   // PhaseTable[i++] = PH_KILLER_1;
519   // PhaseTable[i++] = PH_KILLER_2;
520   PhaseTable[i++] = PH_NONCAPTURES;
521   PhaseTable[i++] = PH_BAD_CAPTURES;
522   PhaseTable[i++] = PH_STOP;
523
524   // Check evasions
525   EvasionsPhaseIndex = i - 1;
526   PhaseTable[i++] = PH_EVASIONS;
527   PhaseTable[i++] = PH_STOP;
528
529   // Quiescence search with checks
530   QsearchWithChecksPhaseIndex = i - 1;
531   PhaseTable[i++] = PH_QCAPTURES;
532   PhaseTable[i++] = PH_QCHECKS;
533   PhaseTable[i++] = PH_STOP;
534
535   // Quiescence search without checks
536   QsearchWithoutChecksPhaseIndex = i - 1;
537   PhaseTable[i++] = PH_QCAPTURES;
538   PhaseTable[i++] = PH_STOP;
539 }