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