]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Disable per-square MVV/LVA for now
[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         movesPicked = 0;
149         break;
150
151     case PH_BAD_CAPTURES:
152         badCapturesPicked = 0;
153         break;
154
155     case PH_NONCAPTURES:
156         numOfMoves = generate_noncaptures(pos, moves);
157         score_noncaptures();
158         movesPicked = 0;
159         break;
160
161     case PH_EVASIONS:
162         assert(pos.is_check());
163         numOfMoves = generate_evasions(pos, moves);
164         score_evasions();
165         movesPicked = 0;
166         break;
167
168     case PH_QCAPTURES:
169         numOfMoves = generate_captures(pos, moves);
170         score_qcaptures();
171         movesPicked = 0;
172         break;
173
174     case PH_QCHECKS:
175         numOfMoves = generate_checks(pos, moves, dc);
176         movesPicked = 0;
177         break;
178
179     case PH_STOP:
180         return MOVE_NONE;
181
182     default:
183         assert(false);
184         return MOVE_NONE;
185     }
186   }
187 }
188
189
190 /// A variant of get_next_move() which takes a lock as a parameter, used to
191 /// prevent multiple threads from picking the same move at a split point.
192
193 Move MovePicker::get_next_move(Lock &lock) {
194
195    lock_grab(&lock);
196    if (finished)
197    {
198        lock_release(&lock);
199        return MOVE_NONE;
200    }
201    Move m = get_next_move();
202    if (m == MOVE_NONE)
203        finished = true;
204
205    lock_release(&lock);
206    return m;
207 }
208
209
210 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
211 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
212 /// numerical move ordering score to each move in a move list.  The moves
213 /// with highest scores will be picked first by pick_move_from_list().
214
215 void MovePicker::score_captures() {
216   // Winning and equal captures in the main search are ordered by MVV/LVA.
217   // Suprisingly, this appears to perform slightly better than SEE based
218   // move ordering.  The reason is probably that in a position with a winning
219   // capture, capturing a more valuable (but sufficiently defended) piece
220   // first usually doesn't hurt.  The opponent will have to recapture, and
221   // the hanging piece will still be hanging (except in the unusual cases
222   // where it is possible to recapture with the hanging piece). Exchanging
223   // big pieces before capturing a hanging piece probably helps to reduce
224   // the subtree size.
225   // While scoring captures it moves all captures with negative SEE values
226   // to the badCaptures[] array.
227   Move m;
228   int seeValue;
229
230   for (int i = 0; i < numOfMoves; i++)
231   {
232       m = moves[i].move;
233       seeValue = pos.see(m);
234       if (seeValue >= 0)
235       {
236           if (move_promotion(m))
237               moves[i].score = QueenValueMidgame;
238           else
239               moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
240                               -int(pos.type_of_piece_on(move_from(m)));
241       }
242       else
243       {
244           // Losing capture, move it to the badCaptures[] array
245           assert(numOfBadCaptures < 63);
246           moves[i].score = seeValue;
247           badCaptures[numOfBadCaptures++] = moves[i];
248           moves[i--] = moves[--numOfMoves];
249       }
250   }
251 }
252
253 void MovePicker::score_noncaptures() {
254   // First score by history, when no history is available then use
255   // piece/square tables values. This seems to be better then a
256   // random choice when we don't have an history for any move.
257   Move m;
258   int hs;
259
260   for (int i = 0; i < numOfMoves; i++)
261   {
262       m = moves[i].move;
263
264       if (m == killer1)
265           hs = HistoryMax + 2;
266       else if (m == killer2)
267           hs = HistoryMax + 1;
268       else
269           hs = H.move_ordering_score(pos.piece_on(move_from(m)), m);
270
271       // Ensure moves in history are always sorted as first
272       if (hs > 0)
273           hs += 1000;
274
275       moves[i].score = hs + pos.mg_pst_delta(m);
276   }
277 }
278
279 void MovePicker::score_evasions() {
280
281   for (int i = 0; i < numOfMoves; i++)
282   {
283       Move m = moves[i].move;
284       if (m == ttMove)
285           moves[i].score = 2*HistoryMax;
286       else if (!pos.square_is_empty(move_to(m)))
287       {
288           int seeScore = pos.see(m);
289           moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
290       } else
291           moves[i].score = H.move_ordering_score(pos.piece_on(move_from(m)), m);
292   }
293   // FIXME try psqt also here
294 }
295
296 void MovePicker::score_qcaptures() {
297
298   // Use MVV/LVA ordering
299   for (int i = 0; i < numOfMoves; i++)
300   {
301       Move m = moves[i].move;
302       if (move_promotion(m))
303           moves[i].score = QueenValueMidgame;
304       else
305           moves[i].score = int(pos.midgame_value_of_piece_on(move_to(m)))
306                           -int(pos.type_of_piece_on(move_from(m)));
307   }
308 }
309
310
311 /// find_best_index() loops across the moves and returns index of\r
312 /// the highest scored one. There is also a second version that\r
313 /// lowers the priority of moves that attack the same square,\r
314 /// so that if the best move that attack a square fails the next\r
315 /// move picked attacks a different square if any, not the same one.
316
317 int MovePicker::find_best_index() {
318
319   int bestScore = -10000000, bestIndex = -1;
320
321   for (int i = movesPicked; i < numOfMoves; i++)
322       if (moves[i].score > bestScore)
323       {
324           bestIndex = i;
325           bestScore = moves[i].score;
326       }
327   return bestIndex;
328 }
329
330 int MovePicker::find_best_index(Bitboard* squares, int values[]) {\r
331 \r
332   int hs;\r
333   Move m;\r
334   Square to;\r
335   int bestScore = -10000000, bestIndex = -1;\r
336 \r
337   for (int i = movesPicked; i < numOfMoves; i++)\r
338   {\r
339       m = moves[i].move;\r
340       to = move_to(m);\r
341       \r
342       if (!bit_is_set(*squares, to))\r
343       {\r
344           // Init at first use\r
345           set_bit(squares, to);\r
346           values[to] = 0;\r
347       }\r
348 \r
349       hs = moves[i].score - values[to];\r
350       if (hs > bestScore)\r
351       {\r
352           bestIndex = i;\r
353           bestScore = hs;\r
354       }\r
355   }\r
356 \r
357   if (bestIndex != -1)\r
358   {\r
359       // Raise value of the picked square, so next attack\r
360       // to the same square will get low priority.\r
361       to = move_to(moves[bestIndex].move);\r
362       values[to] += 0xB00;\r
363   }\r
364   return bestIndex;\r
365 }
366
367
368 /// MovePicker::pick_move_from_list() picks the move with the biggest score
369 /// from a list of generated moves (moves[] or badCaptures[], depending on
370 /// the current move generation phase).  It takes care not to return the
371 /// transposition table move if that has already been serched previously.
372
373 Move MovePicker::pick_move_from_list() {
374
375   int bestIndex;
376   Move move;
377
378   switch (PhaseTable[phaseIndex]) {
379   case PH_GOOD_CAPTURES:
380       assert(!pos.is_check());
381       assert(movesPicked >= 0);
382
383       while (movesPicked < numOfMoves)
384       {
385           bestIndex = find_best_index();
386
387           if (bestIndex != -1) // Found a good capture
388           {
389               move = moves[bestIndex].move;
390               moves[bestIndex] = moves[movesPicked++];
391               if (   move != ttMove
392                   && move != mateKiller
393                   && pos.pl_move_is_legal(move, pinned))
394                   return move;
395           }
396       }
397       break;
398
399   case PH_NONCAPTURES:
400       assert(!pos.is_check());
401       assert(movesPicked >= 0);
402
403       while (movesPicked < numOfMoves)
404       {
405           // If this is a PV node or we have only picked a few moves, scan
406           // the entire move list for the best move.  If many moves have already
407           // been searched and it is not a PV node, we are probably failing low
408           // anyway, so we just pick the first move from the list.
409           bestIndex = (pvNode || movesPicked < 12) ? find_best_index() : movesPicked;
410
411           if (bestIndex != -1)
412           {
413               move = moves[bestIndex].move;
414               moves[bestIndex] = moves[movesPicked++];
415               if (   move != ttMove
416                   && move != mateKiller
417                   && pos.pl_move_is_legal(move, pinned))
418                   return move;
419           }
420       }
421       break;
422
423   case PH_EVASIONS:
424       assert(pos.is_check());
425       assert(movesPicked >= 0);
426
427       while (movesPicked < numOfMoves)
428       {
429           bestIndex = find_best_index();
430
431           if (bestIndex != -1)
432           {
433               move = moves[bestIndex].move;
434               moves[bestIndex] = moves[movesPicked++];
435               return move;
436           }
437     }
438     break;
439
440   case PH_BAD_CAPTURES:
441       assert(!pos.is_check());
442       assert(badCapturesPicked >= 0);
443       // It's probably a good idea to use SEE move ordering here, instead
444       // of just picking the first move.  FIXME
445       while (badCapturesPicked < numOfBadCaptures)
446       {
447           move = badCaptures[badCapturesPicked++].move;
448           if (   move != ttMove
449               && move != mateKiller
450               && pos.pl_move_is_legal(move, pinned))
451               return move;
452       }
453       break;
454
455   case PH_QCAPTURES:
456       assert(!pos.is_check());
457       assert(movesPicked >= 0);
458       while (movesPicked < numOfMoves)
459       {
460           bestIndex = (movesPicked < 4 ? find_best_index() : movesPicked);
461
462           if (bestIndex != -1)
463           {
464               move = moves[bestIndex].move;
465               moves[bestIndex] = moves[movesPicked++];
466               // Remember to change the line below if we decide to hash the qsearch!
467               // Maybe also postpone the legality check until after futility pruning?
468               if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
469                   return move;
470           }
471       }
472       break;
473
474   case PH_QCHECKS:
475       assert(!pos.is_check());
476       assert(movesPicked >= 0);
477       // Perhaps we should do something better than just picking the first
478       // move here?  FIXME
479       while (movesPicked < numOfMoves)
480       {
481           move = moves[movesPicked++].move;
482           // Remember to change the line below if we decide to hash the qsearch!
483           if (/* move != ttMove && */ pos.pl_move_is_legal(move, pinned))
484               return move;
485       }
486       break;
487
488   default:
489       break;
490   }
491   return MOVE_NONE;
492 }
493
494
495 /// MovePicker::current_move_type() returns the type of the just
496 /// picked next move. It can be used in search to further differentiate
497 /// according to the current move type: capture, non capture, escape, etc.
498 MovePicker::MovegenPhase MovePicker::current_move_type() const {
499
500   return PhaseTable[phaseIndex];
501 }
502
503
504 /// MovePicker::init_phase_table() initializes the PhaseTable[],
505 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
506 /// QsearchNoCapturesPhaseIndex, QsearchWithoutChecksPhaseIndex and
507 /// NoMovesPhaseIndex variables. It is only called once during program
508 /// startup, and never again while the program is running.
509
510 void MovePicker::init_phase_table() {
511
512   int i = 0;
513
514   // Main search
515   MainSearchPhaseIndex = i - 1;
516   PhaseTable[i++] = PH_TT_MOVE;
517   PhaseTable[i++] = PH_MATE_KILLER;
518   PhaseTable[i++] = PH_GOOD_CAPTURES;
519   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
520   // PhaseTable[i++] = PH_KILLER_1;
521   // PhaseTable[i++] = PH_KILLER_2;
522   PhaseTable[i++] = PH_NONCAPTURES;
523   PhaseTable[i++] = PH_BAD_CAPTURES;
524   PhaseTable[i++] = PH_STOP;
525
526   // Check evasions
527   EvasionsPhaseIndex = i - 1;
528   PhaseTable[i++] = PH_EVASIONS;
529   PhaseTable[i++] = PH_STOP;
530
531   // Quiescence search with checks
532   QsearchWithChecksPhaseIndex = i - 1;
533   PhaseTable[i++] = PH_QCAPTURES;
534   PhaseTable[i++] = PH_QCHECKS;
535   PhaseTable[i++] = PH_STOP;
536
537   // Quiescence search with checks only and no captures
538   QsearchNoCapturesPhaseIndex = i - 1;
539   PhaseTable[i++] = PH_QCHECKS;
540   PhaseTable[i++] = PH_STOP;
541
542   // Quiescence search without checks
543   QsearchWithoutChecksPhaseIndex = i - 1;
544   PhaseTable[i++] = PH_QCAPTURES;
545   PhaseTable[i++] = PH_STOP;
546
547   // Do not generate any move
548   NoMovesPhaseIndex = i - 1;
549   PhaseTable[i++] = PH_STOP;
550 }