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