]> git.sesse.net Git - stockfish/blob - src/movepick.cpp
Better comment previous patch
[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(Position &p, bool pvnode, Move ttm, Move mk,
64                        Move k1, Move k2, Depth dpth) {
65   pos = &p;
66   pvNode = pvnode;
67   ttMove = ttm;
68   mateKiller = (mk == ttm)? MOVE_NONE : mk;
69   killer1 = k1;
70   killer2 = k2;
71   depth = dpth;
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   Move move;
98
99   while(true) {
100     // If we already have a list of generated moves, pick the best move from
101     // the list, and return it:
102     move = this->pick_move_from_list();
103     if(move != MOVE_NONE) {
104       assert(move_is_ok(move));
105       return move;
106     }
107
108     // Next phase:
109     phaseIndex++;
110     switch(PhaseTable[phaseIndex]) {
111
112     case PH_TT_MOVE:
113       if(ttMove != MOVE_NONE) {
114         assert(move_is_ok(ttMove));
115         Move m = generate_move_if_legal(*pos, ttMove, pinned);
116         if(m != MOVE_NONE) {
117           assert(m == ttMove);
118           return m;
119         }
120       }
121       break;
122
123     case PH_MATE_KILLER:
124       if(mateKiller != MOVE_NONE) {
125         assert(move_is_ok(mateKiller));
126         Move m = generate_move_if_legal(*pos, mateKiller, pinned);
127         if(m != MOVE_NONE) {
128           assert(m == mateKiller);
129           return m;
130         }
131       }
132       break;
133
134     case PH_GOOD_CAPTURES:
135       // pinned = pos->pinned_pieces(pos->side_to_move());
136       numOfMoves = generate_captures(*pos, moves);
137       this->score_captures();
138       movesPicked = 0;
139       break;
140
141     case PH_BAD_CAPTURES:
142       badCapturesPicked = 0;
143       break;
144
145     case PH_NONCAPTURES:
146       numOfMoves = generate_noncaptures(*pos, moves);
147       this->score_noncaptures();
148       movesPicked = 0;
149       break;
150
151     case PH_EVASIONS:
152       assert(pos->is_check());
153       // pinned = pos->pinned_pieces(pos->side_to_move());
154       numOfMoves = generate_evasions(*pos, moves);
155       this->score_evasions();
156       movesPicked = 0;
157       break;
158
159     case PH_QCAPTURES:
160       // pinned = pos->pinned_pieces(pos->side_to_move());
161       numOfMoves = generate_captures(*pos, moves);
162       this->score_qcaptures();
163       movesPicked = 0;
164       break;
165
166     case PH_QCHECKS:
167       numOfMoves = generate_checks(*pos, moves, dc);
168       movesPicked = 0;
169       break;
170
171     case PH_STOP:
172       return MOVE_NONE;
173
174     default:
175       assert(false);
176       return MOVE_NONE;
177     }
178   }
179
180   assert(false);
181
182   return MOVE_NONE;
183 }
184
185
186 /// A variant of get_next_move() which takes a lock as a parameter, used to
187 /// prevent multiple threads from picking the same move at a split point.
188
189 Move MovePicker::get_next_move(Lock &lock) {
190    Move m;
191
192    lock_grab(&lock);
193    if(finished) {
194      lock_release(&lock);
195      return MOVE_NONE;
196    }
197    m = this->get_next_move();
198    if(m == MOVE_NONE)
199      finished = true;
200    lock_release(&lock);
201    
202    return m;
203 }
204
205  
206 /// MovePicker::number_of_moves() simply returns the numOfMoves member
207 /// variable.  It is intended to be used in positions where the side to move
208 /// is in check, for detecting checkmates or situations where there is only
209 /// a single reply to check.
210
211 int MovePicker::number_of_moves() const {
212   return numOfMoves;
213 }
214
215
216 /// MovePicker::score_captures(), MovePicker::score_noncaptures(),
217 /// MovePicker::score_evasions() and MovePicker::score_qcaptures() assign a
218 /// numerical move ordering score to each move in a move list.  The moves
219 /// with highest scores will be picked first by
220 /// MovePicker::pick_move_from_list().
221
222 void MovePicker::score_captures() {
223   // Winning and equal captures in the main search are ordered by MVV/LVA.
224   // Suprisingly, this appears to perform slightly better than SEE based
225   // move ordering.  The reason is probably that in a position with a winning
226   // capture, capturing a more valuable (but sufficiently defended) piece
227   // first usually doesn't hurt.  The opponent will have to recapture, and
228   // the hanging piece will still be hanging (except in the unusual cases
229   // where it is possible to recapture with the hanging piece).  Exchanging
230   // big pieces before capturing a hanging piece probably helps to reduce
231   // the subtree size.
232   for(int i = 0; i < numOfMoves; i++) {
233     int seeValue = pos->see(moves[i].move);
234     if(seeValue >= 0) {
235       if(move_promotion(moves[i].move))
236         moves[i].score = QueenValueMidgame;
237       else 
238         moves[i].score =
239           int(pos->midgame_value_of_piece_on(move_to(moves[i].move))) -
240           int(pos->type_of_piece_on(move_from(moves[i].move)));
241     }
242     else
243       moves[i].score = seeValue;
244         
245   }
246 }
247
248 void MovePicker::score_noncaptures() {
249
250   for (int i = 0; i < numOfMoves; i++)
251   {
252       Move m = moves[i].move;
253       if (m == killer1)
254           moves[i].score = HistoryMax + 2;
255       else if (m == killer2)
256           moves[i].score = HistoryMax + 1;
257       else
258           moves[i].score = H.move_ordering_score(pos->piece_on(move_from(m)), m);
259
260       // Ensure moves in history are always sorted as first
261       if (moves[i].score > 0)
262           moves[i].score += 1000;
263
264       moves[i].score += pos->mg_pst_delta(moves[i].move);
265   }
266 }
267
268 void MovePicker::score_evasions() {
269   for(int i = 0; i < numOfMoves; i++) {
270     Move m = moves[i].move;
271     if(m == ttMove)
272       moves[i].score = 2*HistoryMax;
273     else if(!pos->square_is_empty(move_to(m))) {
274       int seeScore = pos->see(m);
275       moves[i].score = (seeScore >= 0)? seeScore + HistoryMax : seeScore;
276     }
277     else
278       moves[i].score = H.move_ordering_score(pos->piece_on(move_from(m)), m);
279   }
280 }
281
282 void MovePicker::score_qcaptures() {
283   // Use MVV/LVA ordering.
284   for(int i = 0; i < numOfMoves; i++) {
285     Move m = moves[i].move;
286     if(move_promotion(m))
287       moves[i].score = QueenValueMidgame;
288     else
289       moves[i].score =
290         int(pos->midgame_value_of_piece_on(move_to(m))) -
291         int(pos->midgame_value_of_piece_on(move_to(m))) / 64;
292   }
293 }
294
295
296 /// MovePicker::pick_move_from_list() picks the move with the biggest score
297 /// from a list of generated moves (moves[] or badCaptures[], depending on
298 /// the current move generation phase).  It takes care not to return the
299 /// transposition table move if that has already been serched previously.
300 /// While picking captures in the PH_GOOD_CAPTURES phase (i.e. while picking
301 /// non-losing captures in the main search), it moves all captures with
302 /// negative SEE values to the badCaptures[] array.
303
304 Move MovePicker::pick_move_from_list() {
305   int bestScore = -10000000;
306   int bestIndex;
307   Move move;
308
309   switch(PhaseTable[phaseIndex]) {
310
311   case PH_GOOD_CAPTURES:
312     assert(!pos->is_check());
313     assert(movesPicked >= 0);
314     while(movesPicked < numOfMoves) {
315       bestScore = -10000000;
316       bestIndex = -1;
317       for(int i = movesPicked; i < numOfMoves; i++) {
318         if(moves[i].score < 0) {
319           // Losing capture, move it to the badCaptures[] array
320           assert(numOfBadCaptures < 63);
321           badCaptures[numOfBadCaptures++] = moves[i];
322           moves[i--] = moves[--numOfMoves];
323         }
324         else if(moves[i].score > bestScore) {
325           bestIndex = i;
326           bestScore = moves[i].score;
327         }
328       }
329       if(bestIndex != -1) { // Found a good capture
330         move = moves[bestIndex].move;\r
331         moves[bestIndex] = moves[movesPicked++];
332         if(move != ttMove && move != mateKiller &&
333            pos->move_is_legal(move, pinned))
334           return move;
335       }
336     }
337     break;
338
339   case PH_NONCAPTURES:
340     assert(!pos->is_check());
341     assert(movesPicked >= 0);
342     while(movesPicked < numOfMoves) {
343       bestScore = -10000000;
344
345       // If this is a PV node or we have only picked a few moves, scan
346       // the entire move list for the best move.  If many moves have already
347       // been searched and it is not a PV node, we are probably failing low
348       // anyway, so we just pick the first move from the list.
349       if(pvNode || movesPicked < 12) {
350         bestIndex = -1;
351         for(int i = movesPicked; i < numOfMoves; i++)
352           if(moves[i].score > bestScore) {
353             bestIndex = i;
354             bestScore = moves[i].score;
355           }
356       }
357       else
358         bestIndex = movesPicked;
359
360       if(bestIndex != -1) {
361         move = moves[bestIndex].move;\r
362         moves[bestIndex] = moves[movesPicked++];
363         if(move != ttMove && move != mateKiller &&
364            pos->move_is_legal(move, pinned))
365           return move;
366       }
367     }
368     break;
369
370   case PH_EVASIONS:
371     assert(pos->is_check());
372     assert(movesPicked >= 0);
373     while(movesPicked < numOfMoves) {
374       bestScore = -10000000;
375       bestIndex = -1;
376       for(int i = movesPicked; i < numOfMoves; i++)
377         if(moves[i].score > bestScore) {
378           bestIndex = i;
379           bestScore = moves[i].score;
380         }
381
382       if(bestIndex != -1) {
383         move = moves[bestIndex].move;\r
384         moves[bestIndex] = moves[movesPicked++];
385         return move;
386       }
387     }
388     break;
389
390   case PH_BAD_CAPTURES:
391     assert(!pos->is_check());
392     assert(badCapturesPicked >= 0);
393     // It's probably a good idea to use SEE move ordering here, instead
394     // of just picking the first move.  FIXME
395     while(badCapturesPicked < numOfBadCaptures) {
396       move = badCaptures[badCapturesPicked++].move;
397       if(move != ttMove && move != mateKiller && 
398          pos->move_is_legal(move, pinned))
399         return move;
400     }
401     break;
402
403   case PH_QCAPTURES:
404     assert(!pos->is_check());
405     assert(movesPicked >= 0);
406     while(movesPicked < numOfMoves) {
407       bestScore = -10000000;
408       if(movesPicked < 4) {
409         bestIndex = -1;
410         for(int i = movesPicked; i < numOfMoves; i++)
411           if(moves[i].score > bestScore) {
412             bestIndex = i;
413             bestScore = moves[i].score;
414           }
415       }
416       else
417         bestIndex = movesPicked;
418
419       if(bestIndex != -1) {
420         move = moves[bestIndex].move;\r
421         moves[bestIndex] = moves[movesPicked++];
422         // Remember to change the line below if we decide to hash the qsearch!
423         // Maybe also postpone the legality check until after futility pruning?
424         if(/* move != ttMove && */ pos->move_is_legal(move, pinned))
425           return move;
426       }
427     }
428     break;
429
430   case PH_QCHECKS:
431     assert(!pos->is_check());
432     assert(movesPicked >= 0);
433     // Perhaps we should do something better than just picking the first
434     // move here?  FIXME
435     while(movesPicked < numOfMoves) {
436       move = moves[movesPicked++].move;
437       // Remember to change the line below if we decide to hash the qsearch!
438       if(/* move != ttMove && */ pos->move_is_legal(move, pinned))
439         return move;
440     }
441     break;
442
443   default:
444     break;
445   }
446
447   return MOVE_NONE;
448 }
449
450 MovePicker::MovegenPhase MovePicker::current_move_type() const {
451   return PhaseTable[phaseIndex];
452 }
453
454 /// MovePicker::init_phase_table() initializes the PhaseTable[],
455 /// MainSearchPhaseIndex, EvasionPhaseIndex, QsearchWithChecksPhaseIndex
456 /// and QsearchWithoutChecksPhaseIndex variables.  It is only called once
457 /// during program startup, and never again while the program is running.
458
459 void MovePicker::init_phase_table() {
460   int i = 0;
461
462   // Main search
463   MainSearchPhaseIndex = i - 1;
464   PhaseTable[i++] = PH_TT_MOVE;
465   PhaseTable[i++] = PH_MATE_KILLER;
466   PhaseTable[i++] = PH_GOOD_CAPTURES;
467   // PH_KILLER_1 and PH_KILLER_2 are not yet used.
468   // PhaseTable[i++] = PH_KILLER_1;
469   // PhaseTable[i++] = PH_KILLER_2;
470   PhaseTable[i++] = PH_NONCAPTURES;
471   PhaseTable[i++] = PH_BAD_CAPTURES;
472   PhaseTable[i++] = PH_STOP;
473
474   // Check evasions
475   EvasionsPhaseIndex = i - 1;
476   PhaseTable[i++] = PH_EVASIONS;
477   PhaseTable[i++] = PH_STOP;
478
479   // Quiescence search with checks
480   QsearchWithChecksPhaseIndex = i - 1;
481   PhaseTable[i++] = PH_QCAPTURES;
482   PhaseTable[i++] = PH_QCHECKS;
483   PhaseTable[i++] = PH_STOP;
484
485   // Quiescence search without checks
486   QsearchWithoutChecksPhaseIndex = i - 1;
487   PhaseTable[i++] = PH_QCAPTURES;
488   PhaseTable[i++] = PH_STOP;
489 }