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