]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Enable per-square MVV/LVA
[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   // While scoring captures it moves all captures with negative SEE values
216   // to the badCaptures[] array.
217   Move m;
218   int seeValue;
219
220   for (int i = 0; i < numOfMoves; i++)
221   {
222       m = moves[i].move;
223       seeValue = pos.see(m);
224       if (seeValue >= 0)
225       {
226           if (move_promotion(m))
227               moves[i].score = QueenValueMidgame;
228           else
229               moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
230                               -int(pos.type_of_piece_on(move_from(m)));
231       }
232       else
233       {
234           // Losing capture, move it to the badCaptures[] array
235           assert(numOfBadCaptures < 63);
236           moves[i].score = seeValue;
237           badCaptures[numOfBadCaptures++] = moves[i];
238           moves[i--] = moves[--numOfMoves];
239       }
240   }
241 }
242
243 void MovePicker::score_noncaptures() {
244   // First score by history, when no history is available then use
245   // piece/square tables values. This seems to be better then a
246   // random choice when we don't have an history for any move.
247   Move m;
248   int hs;
249
250   for (int i = 0; i < numOfMoves; i++)
251   {
252       m = moves[i].move;
253
254       if (m == killer1)
255           hs = HistoryMax + 2;
256       else if (m == killer2)
257           hs = HistoryMax + 1;
258       else
259           hs = H.move_ordering_score(pos.piece_on(move_from(m)), m);
260
261       // Ensure moves in history are always sorted as first
262       if (hs > 0)
263           hs += 1000;
264
265       moves[i].score = hs + pos.mg_pst_delta(m);
266   }
267 }
268
269 void MovePicker::score_evasions() {
270
271   for (int i = 0; i < numOfMoves; i++)
272   {
273       Move m = moves[i].move;
274       if (m == ttMove)
275           moves[i].score = 2*HistoryMax;
276       else if (!pos.square_is_empty(move_to(m)))
277       {
278           int seeScore = pos.see(m);
279           moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
280       } else
281           moves[i].score = H.move_ordering_score(pos.piece_on(move_from(m)), m);
282   }
283   // FIXME try psqt also here
284 }
285
286 void MovePicker::score_qcaptures() {
287
288   // Use MVV/LVA ordering
289   for (int i = 0; i < numOfMoves; i++)
290   {
291       Move m = moves[i].move;
292       if (move_promotion(m))
293           moves[i].score = QueenValueMidgame;
294       else
295           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
296                           -int(pos.type_of_piece_on(move_from(m)));
297   }
298 }
299
300
301 /// find_best_index() loops across the moves and returns index of\r
302 /// the highest scored one. There is also a second version that\r
303 /// lowers the priority of moves that attack the same square,\r
304 /// so that if the best move that attack a square fails the next\r
305 /// move picked attacks a different square if any, not the same one.
306
307 int MovePicker::find_best_index() {
308
309   int bestScore = -10000000, bestIndex = -1;
310
311   for (int i = movesPicked; i < numOfMoves; i++)
312       if (moves[i].score > bestScore)
313       {
314           bestIndex = i;
315           bestScore = moves[i].score;
316       }
317   return bestIndex;
318 }
319
320 int MovePicker::find_best_index(Bitboard* squares, int values[]) {\r
321 \r
322   int hs;\r
323   Move m;\r
324   Square to;\r
325   int bestScore = -10000000, bestIndex = -1;\r
326 \r
327   for (int i = movesPicked; i < numOfMoves; i++)\r
328   {\r
329       m = moves[i].move;\r
330       to = move_to(m);\r
331       \r
332       if (!bit_is_set(*squares, to))\r
333       {\r
334           // Init at first use\r
335           set_bit(squares, to);\r
336           values[to] = 0;\r
337       }\r
338 \r
339       hs = moves[i].score - values[to];\r
340       if (hs > bestScore)\r
341       {\r
342           bestIndex = i;\r
343           bestScore = hs;\r
344       }\r
345   }\r
346 \r
347   if (bestIndex != -1)\r
348   {\r
349       // Raise value of the picked square, so next attack\r
350       // to the same square will get low priority.\r
351       to = move_to(moves[bestIndex].move);\r
352       values[to] += 0xB00;\r
353   }\r
354   return bestIndex;\r
355 }
356
357
358 /// MovePicker::pick_move_from_list() picks the move with the biggest score
359 /// from a list of generated moves (moves[] or badCaptures[], depending on
360 /// the current move generation phase).  It takes care not to return the
361 /// transposition table move if that has already been serched previously.
362
363 Move MovePicker::pick_move_from_list() {
364
365   int bestIndex;
366   Move move;
367
368   switch (PhaseTable[phaseIndex]) {
369   case PH_GOOD_CAPTURES:
370       assert(!pos.is_check());
371       assert(movesPicked >= 0);
372
373       while (movesPicked < numOfMoves)
374       {
375           bestIndex = find_best_index(&capSquares, capSqValues);
376
377           if (bestIndex != -1) // Found a good capture
378           {
379               move = moves[bestIndex].move;
380               moves[bestIndex] = moves[movesPicked++];
381               if (   move != ttMove
382                   && move != mateKiller
383                   && pos.pl_move_is_legal(move, pinned))
384                   return move;
385           }
386       }
387       break;
388
389   case PH_NONCAPTURES:
390       assert(!pos.is_check());
391       assert(movesPicked >= 0);
392
393       while (movesPicked < numOfMoves)
394       {
395           // If this is a PV node or we have only picked a few moves, scan
396           // the entire move list for the best move.  If many moves have already
397           // been searched and it is not a PV node, we are probably failing low
398           // anyway, so we just pick the first move from the list.
399           bestIndex = (pvNode || movesPicked < 12) ? find_best_index() : movesPicked;
400
401           if (bestIndex != -1)
402           {
403               move = moves[bestIndex].move;
404               moves[bestIndex] = moves[movesPicked++];
405               if (   move != ttMove
406                   && move != mateKiller
407                   && pos.pl_move_is_legal(move, pinned))
408                   return move;
409           }
410       }
411       break;
412
413   case PH_EVASIONS:
414       assert(pos.is_check());
415       assert(movesPicked >= 0);
416
417       while (movesPicked < numOfMoves)
418       {
419           bestIndex = find_best_index();
420
421           if (bestIndex != -1)
422           {
423               move = moves[bestIndex].move;
424               moves[bestIndex] = moves[movesPicked++];
425               return move;
426           }
427     }
428     break;
429
430   case PH_BAD_CAPTURES:
431       assert(!pos.is_check());
432       assert(badCapturesPicked >= 0);
433       // It's probably a good idea to use SEE move ordering here, instead
434       // of just picking the first move.  FIXME
435       while (badCapturesPicked < numOfBadCaptures)
436       {
437           move = badCaptures[badCapturesPicked++].move;
438           if (   move != ttMove
439               && move != mateKiller
440               && pos.pl_move_is_legal(move, pinned))
441               return move;
442       }
443       break;
444
445   case PH_QCAPTURES:
446       assert(!pos.is_check());
447       assert(movesPicked >= 0);
448       while (movesPicked < numOfMoves)
449       {
450           bestIndex = (movesPicked < 4 ? find_best_index() : movesPicked);
451
452           if (bestIndex != -1)
453           {
454               move = moves[bestIndex].move;
455               moves[bestIndex] = moves[movesPicked++];
456               // Remember to change the line below if we decide to hash the qsearch!
457               // Maybe also postpone the legality check until after futility pruning?
458               if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
459                   return move;
460           }
461       }
462       break;
463
464   case PH_QCHECKS:
465       assert(!pos.is_check());
466       assert(movesPicked >= 0);
467       // Perhaps we should do something better than just picking the first
468       // move here?  FIXME
469       while (movesPicked < numOfMoves)
470       {
471           move = moves[movesPicked++].move;
472           // Remember to change the line below if we decide to hash the qsearch!
473           if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
474               return move;
475       }
476       break;
477
478   default:
479       break;
480   }
481   return MOVE_NONE;
482 }
483
484
485 /// MovePicker::current_move_type() returns the type of the just
486 /// picked next move. It can be used in search to further differentiate
487 /// according to the current move type: capture, non capture, escape, etc.
488 MovePicker::MovegenPhase MovePicker::current_move_type() const {
489
490   return PhaseTable[phaseIndex];
491 }
492
493
494 /// MovePicker::init_phase_table() initializes the PhaseTable[],
495 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
496 /// and QsearchWithoutChecksPhaseIndex variables. It is only called once
497 /// during program startup, and never again while the program is running.
498
499 void MovePicker::init_phase_table() {
500
501   int i = 0;
502
503   // Main search
504   MainSearchPhaseIndex = i - 1;
505   PhaseTable[i++] = PH_TT_MOVE;
506   PhaseTable[i++] = PH_MATE_KILLER;
507   PhaseTable[i++] = PH_GOOD_CAPTURES;
508   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
509   // PhaseTable[i++] = PH_KILLER_1;
510   // PhaseTable[i++] = PH_KILLER_2;
511   PhaseTable[i++] = PH_NONCAPTURES;
512   PhaseTable[i++] = PH_BAD_CAPTURES;
513   PhaseTable[i++] = PH_STOP;
514
515   // Check evasions
516   EvasionsPhaseIndex = i - 1;
517   PhaseTable[i++] = PH_EVASIONS;
518   PhaseTable[i++] = PH_STOP;
519
520   // Quiescence search with checks
521   QsearchWithChecksPhaseIndex = i - 1;
522   PhaseTable[i++] = PH_QCAPTURES;
523   PhaseTable[i++] = PH_QCHECKS;
524   PhaseTable[i++] = PH_STOP;
525
526   // Quiescence search without checks
527   QsearchWithoutChecksPhaseIndex = i - 1;
528   PhaseTable[i++] = PH_QCAPTURES;
529   PhaseTable[i++] = PH_STOP;
530 }