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