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