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