]> git.sesse.net Git - stockfish/blob - src/search.cpp
Retire move.h
[stockfish] / src / search.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-2010 Marco Costalba, Joona Kiiski, Tord Romstad
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 #include <cassert>
21 #include <cmath>
22 #include <cstring>
23 #include <iomanip>
24 #include <iostream>
25 #include <sstream>
26 #include <vector>
27 #include <algorithm>
28
29 #include "book.h"
30 #include "evaluate.h"
31 #include "history.h"
32 #include "misc.h"
33 #include "movegen.h"
34 #include "movepick.h"
35 #include "search.h"
36 #include "timeman.h"
37 #include "thread.h"
38 #include "tt.h"
39 #include "ucioption.h"
40
41 using std::cout;
42 using std::endl;
43 using std::string;
44 using Search::Signals;
45 using Search::Limits;
46
47 namespace Search {
48
49   volatile SignalsType Signals;
50   LimitsType Limits;
51   std::vector<Move> RootMoves;
52   Position RootPosition;
53 }
54
55 namespace {
56
57   // Set to true to force running with one thread. Used for debugging
58   const bool FakeSplit = false;
59
60   // Different node types, used as template parameter
61   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
62
63   // RootMove struct is used for moves at the root of the tree. For each root
64   // move, we store a score, a node count, and a PV (really a refutation
65   // in the case of moves which fail low). Score is normally set at
66   // -VALUE_INFINITE for all non-pv moves.
67   struct RootMove {
68
69     // RootMove::operator<() is the comparison function used when
70     // sorting the moves. A move m1 is considered to be better
71     // than a move m2 if it has an higher score
72     bool operator<(const RootMove& m) const { return score < m.score; }
73
74     void extract_pv_from_tt(Position& pos);
75     void insert_pv_in_tt(Position& pos);
76
77     int64_t nodes;
78     Value score;
79     Value prevScore;
80     std::vector<Move> pv;
81   };
82
83   // RootMoveList struct is mainly a std::vector of RootMove objects
84   struct RootMoveList : public std::vector<RootMove> {
85
86     void init(Position& pos, Move rootMoves[]);
87     RootMove* find(const Move& m, int startIndex = 0);
88
89     int bestMoveChanges;
90   };
91
92
93   /// Constants
94
95   // Lookup table to check if a Piece is a slider and its access function
96   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
97   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
98
99   // Step 6. Razoring
100
101   // Maximum depth for razoring
102   const Depth RazorDepth = 4 * ONE_PLY;
103
104   // Dynamic razoring margin based on depth
105   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
106
107   // Maximum depth for use of dynamic threat detection when null move fails low
108   const Depth ThreatDepth = 5 * ONE_PLY;
109
110   // Step 9. Internal iterative deepening
111
112   // Minimum depth for use of internal iterative deepening
113   const Depth IIDDepth[] = { 8 * ONE_PLY, 5 * ONE_PLY };
114
115   // At Non-PV nodes we do an internal iterative deepening search
116   // when the static evaluation is bigger then beta - IIDMargin.
117   const Value IIDMargin = Value(0x100);
118
119   // Step 11. Decide the new search depth
120
121   // Extensions. Array index 0 is used for non-PV nodes, index 1 for PV nodes
122   const Depth CheckExtension[]         = { ONE_PLY / 2, ONE_PLY / 1 };
123   const Depth PawnEndgameExtension[]   = { ONE_PLY / 1, ONE_PLY / 1 };
124   const Depth PawnPushTo7thExtension[] = { ONE_PLY / 2, ONE_PLY / 2 };
125   const Depth PassedPawnExtension[]    = {  DEPTH_ZERO, ONE_PLY / 2 };
126
127   // Minimum depth for use of singular extension
128   const Depth SingularExtensionDepth[] = { 8 * ONE_PLY, 6 * ONE_PLY };
129
130   // Step 12. Futility pruning
131
132   // Futility margin for quiescence search
133   const Value FutilityMarginQS = Value(0x80);
134
135   // Futility lookup tables (initialized at startup) and their access functions
136   Value FutilityMargins[16][64]; // [depth][moveNumber]
137   int FutilityMoveCounts[32];    // [depth]
138
139   inline Value futility_margin(Depth d, int mn) {
140
141     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
142                            : 2 * VALUE_INFINITE;
143   }
144
145   inline int futility_move_count(Depth d) {
146
147     return d < 16 * ONE_PLY ? FutilityMoveCounts[d] : MAX_MOVES;
148   }
149
150   // Step 14. Reduced search
151
152   // Reduction lookup tables (initialized at startup) and their access function
153   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
154
155   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
156
157     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
158   }
159
160   // Easy move margin. An easy move candidate must be at least this much
161   // better than the second best move.
162   const Value EasyMoveMargin = Value(0x150);
163
164
165   /// Namespace variables
166
167   // Root move list
168   RootMoveList Rml;
169
170   // MultiPV mode
171   int MultiPV, UCIMultiPV, MultiPVIdx;
172
173   // Time management variables
174   TimeManager TimeMgr;
175
176   // Skill level adjustment
177   int SkillLevel;
178   bool SkillLevelEnabled;
179
180   // History table
181   History H;
182
183
184   /// Local functions
185
186   Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove);
187
188   template <NodeType NT>
189   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
190
191   template <NodeType NT>
192   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
193
194   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
195   bool connected_moves(const Position& pos, Move m1, Move m2);
196   Value value_to_tt(Value v, int ply);
197   Value value_from_tt(Value v, int ply);
198   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply);
199   bool connected_threat(const Position& pos, Move m, Move threat);
200   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
201   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
202   void do_skill_level(Move* best, Move* ponder);
203
204   int elapsed_time(bool reset = false);
205   string score_to_uci(Value v, Value alpha = -VALUE_INFINITE, Value beta = VALUE_INFINITE);
206   string speed_to_uci(int64_t nodes);
207   string pv_to_uci(const Move pv[], int pvNum, bool chess960);
208   string pretty_pv(Position& pos, int depth, Value score, int time, Move pv[]);
209   string depth_to_uci(Depth depth);
210
211   // MovePickerExt template class extends MovePicker and allows to choose at compile
212   // time the proper moves source according to the type of node. In the default case
213   // we simply create and use a standard MovePicker object.
214   template<bool SpNode> struct MovePickerExt : public MovePicker {
215
216     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
217                   : MovePicker(p, ttm, d, h, ss, b) {}
218   };
219
220   // In case of a SpNode we use split point's shared MovePicker object as moves source
221   template<> struct MovePickerExt<true> : public MovePicker {
222
223     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
224                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
225
226     Move get_next_move() { return mp->get_next_move(); }
227     MovePicker* mp;
228   };
229
230   // Overload operator<<() to make it easier to print moves in a coordinate
231   // notation compatible with UCI protocol.
232   std::ostream& operator<<(std::ostream& os, Move m) {
233
234     bool chess960 = (os.iword(0) != 0); // See set960()
235     return os << move_to_uci(m, chess960);
236   }
237
238   // When formatting a move for std::cout we must know if we are in Chess960
239   // or not. To keep using the handy operator<<() on the move the trick is to
240   // embed this flag in the stream itself. Function-like named enum set960 is
241   // used as a custom manipulator and the stream internal general-purpose array,
242   // accessed through ios_base::iword(), is used to pass the flag to the move's
243   // operator<<() that will read it to properly format castling moves.
244   enum set960 {};
245
246   std::ostream& operator<< (std::ostream& os, const set960& f) {
247
248     os.iword(0) = int(f);
249     return os;
250   }
251
252   // extension() decides whether a move should be searched with normal depth,
253   // or with extended depth. Certain classes of moves (checking moves, in
254   // particular) are searched with bigger depth than ordinary moves and in
255   // any case are marked as 'dangerous'. Note that also if a move is not
256   // extended, as example because the corresponding UCI option is set to zero,
257   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
258   template <bool PvNode>
259   FORCE_INLINE Depth extension(const Position& pos, Move m, bool captureOrPromotion,
260                                bool moveIsCheck, bool* dangerous) {
261     assert(m != MOVE_NONE);
262
263     Depth result = DEPTH_ZERO;
264     *dangerous = moveIsCheck;
265
266     if (moveIsCheck && pos.see_sign(m) >= 0)
267         result += CheckExtension[PvNode];
268
269     if (type_of(pos.piece_on(move_from(m))) == PAWN)
270     {
271         Color c = pos.side_to_move();
272         if (relative_rank(c, move_to(m)) == RANK_7)
273         {
274             result += PawnPushTo7thExtension[PvNode];
275             *dangerous = true;
276         }
277         if (pos.pawn_is_passed(c, move_to(m)))
278         {
279             result += PassedPawnExtension[PvNode];
280             *dangerous = true;
281         }
282     }
283
284     if (   captureOrPromotion
285         && type_of(pos.piece_on(move_to(m))) != PAWN
286         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
287             - PieceValueMidgame[pos.piece_on(move_to(m))] == VALUE_ZERO)
288         && !is_special(m))
289     {
290         result += PawnEndgameExtension[PvNode];
291         *dangerous = true;
292     }
293
294     return std::min(result, ONE_PLY);
295   }
296
297 } // namespace
298
299
300 /// init_search() is called during startup to initialize various lookup tables
301
302 void Search::init() {
303
304   int d;  // depth (ONE_PLY == 2)
305   int hd; // half depth (ONE_PLY == 1)
306   int mc; // moveCount
307
308   // Init reductions array
309   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
310   {
311       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
312       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
313       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
314       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
315   }
316
317   // Init futility margins array
318   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
319       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
320
321   // Init futility move count array
322   for (d = 0; d < 32; d++)
323       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(d, 2.0));
324 }
325
326
327 /// perft() is our utility to verify move generation. All the leaf nodes up to
328 /// the given depth are generated and counted and the sum returned.
329
330 int64_t Search::perft(Position& pos, Depth depth) {
331
332   StateInfo st;
333   int64_t sum = 0;
334
335   // Generate all legal moves
336   MoveList<MV_LEGAL> ml(pos);
337
338   // If we are at the last ply we don't need to do and undo
339   // the moves, just to count them.
340   if (depth <= ONE_PLY)
341       return ml.size();
342
343   // Loop through all legal moves
344   CheckInfo ci(pos);
345   for ( ; !ml.end(); ++ml)
346   {
347       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
348       sum += perft(pos, depth - ONE_PLY);
349       pos.undo_move(ml.move());
350   }
351   return sum;
352 }
353
354
355 /// think() is the external interface to Stockfish's search, and is called by the
356 /// main thread when the program receives the UCI 'go' command. It searches from
357 /// RootPosition and at the end prints the "bestmove" to output.
358
359 void Search::think() {
360
361   static Book book; // Defined static to initialize the PRNG only once
362
363   Position& pos = RootPosition;
364
365   // Reset elapsed search time
366   elapsed_time(true);
367
368   // Set output stream mode: normal or chess960. Castling notation is different
369   cout << set960(pos.is_chess960());
370
371   // Look for a book move
372   if (Options["OwnBook"].value<bool>())
373   {
374       if (Options["Book File"].value<string>() != book.name())
375           book.open(Options["Book File"].value<string>());
376
377       Move bookMove = book.probe(pos, Options["Best Book Move"].value<bool>());
378       if (bookMove != MOVE_NONE)
379       {
380           if (!Signals.stop && (Limits.ponder || Limits.infinite))
381               Threads.wait_for_stop_or_ponderhit();
382
383           cout << "bestmove " << bookMove << endl;
384           return;
385       }
386   }
387
388   // Read UCI options: GUI could change UCI parameters during the game
389   read_evaluation_uci_options(pos.side_to_move());
390   Threads.read_uci_options();
391
392   // Set a new TT size if changed
393   TT.set_size(Options["Hash"].value<int>());
394
395   if (Options["Clear Hash"].value<bool>())
396   {
397       Options["Clear Hash"].set_value("false");
398       TT.clear();
399   }
400
401   UCIMultiPV = Options["MultiPV"].value<int>();
402   SkillLevel = Options["Skill Level"].value<int>();
403
404   // Do we have to play with skill handicap? In this case enable MultiPV that
405   // we will use behind the scenes to retrieve a set of possible moves.
406   SkillLevelEnabled = (SkillLevel < 20);
407   MultiPV = (SkillLevelEnabled ? std::max(UCIMultiPV, 4) : UCIMultiPV);
408
409   // Write current search header to log file
410   if (Options["Use Search Log"].value<bool>())
411   {
412       Log log(Options["Search Log Filename"].value<string>());
413       log << "\nSearching: "  << pos.to_fen()
414           << "\ninfinite: "   << Limits.infinite
415           << " ponder: "      << Limits.ponder
416           << " time: "        << Limits.time
417           << " increment: "   << Limits.increment
418           << " moves to go: " << Limits.movesToGo
419           << endl;
420   }
421
422   // Wake up needed threads and reset maxPly counter
423   for (int i = 0; i < Threads.size(); i++)
424   {
425       Threads[i].maxPly = 0;
426       Threads[i].wake_up();
427   }
428
429   // Set best timer interval to avoid lagging under time pressure. Timer is
430   // used to check for remaining available thinking time.
431    TimeMgr.init(Limits, pos.startpos_ply_counter());
432
433   if (TimeMgr.available_time())
434       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 8, 20)));
435   else
436       Threads.set_timer(100);
437
438   // We're ready to start thinking. Call the iterative deepening loop function
439   Move ponderMove = MOVE_NONE;
440   Move bestMove = id_loop(pos, &RootMoves[0], &ponderMove);
441
442   // Stop timer, no need to check for available time any more
443   Threads.set_timer(0);
444
445   // This makes all the slave threads to go to sleep, if not already sleeping
446   Threads.set_size(1);
447
448   // Write current search final statistics to log file
449   if (Options["Use Search Log"].value<bool>())
450   {
451       int e = elapsed_time();
452
453       Log log(Options["Search Log Filename"].value<string>());
454       log << "Nodes: "          << pos.nodes_searched()
455           << "\nNodes/second: " << (e > 0 ? pos.nodes_searched() * 1000 / e : 0)
456           << "\nBest move: "    << move_to_san(pos, bestMove);
457
458       StateInfo st;
459       pos.do_move(bestMove, st);
460       log << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
461       pos.undo_move(bestMove); // Return from think() with unchanged position
462   }
463
464   // When we reach max depth we arrive here even without a StopRequest, but if
465   // we are pondering or in infinite search, we shouldn't print the best move
466   // before we are told to do so.
467   if (!Signals.stop && (Limits.ponder || Limits.infinite))
468       Threads.wait_for_stop_or_ponderhit();
469
470   // Could be MOVE_NONE when searching on a stalemate position
471   cout << "bestmove " << bestMove;
472
473   // UCI protol is not clear on allowing sending an empty ponder move, instead
474   // it is clear that ponder move is optional. So skip it if empty.
475   if (ponderMove != MOVE_NONE)
476       cout << " ponder " << ponderMove;
477
478   cout << endl;
479 }
480
481
482 namespace {
483
484   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
485   // with increasing depth until the allocated thinking time has been consumed,
486   // user stops the search, or the maximum search depth is reached.
487
488   Move id_loop(Position& pos, Move rootMoves[], Move* ponderMove) {
489
490     SearchStack ss[PLY_MAX_PLUS_2];
491     Value bestValues[PLY_MAX_PLUS_2];
492     int bestMoveChanges[PLY_MAX_PLUS_2];
493     int depth, aspirationDelta;
494     Value bestValue, alpha, beta;
495     Move bestMove, skillBest, skillPonder;
496     bool bestMoveNeverChanged = true;
497
498     // Initialize stuff before a new search
499     memset(ss, 0, 4 * sizeof(SearchStack));
500     TT.new_search();
501     H.clear();
502     *ponderMove = bestMove = skillBest = skillPonder = MOVE_NONE;
503     depth = aspirationDelta = 0;
504     bestValue = alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
505     ss->currentMove = MOVE_NULL; // Hack to skip update gains
506
507     // Moves to search are verified and copied
508     Rml.init(pos, rootMoves);
509
510     // Handle special case of searching on a mate/stalemate position
511     if (!Rml.size())
512     {
513         cout << "info" << depth_to_uci(DEPTH_ZERO)
514              << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW, alpha, beta) << endl;
515
516         return MOVE_NONE;
517     }
518
519     // Iterative deepening loop until requested to stop or target depth reached
520     while (!Signals.stop && ++depth <= PLY_MAX && (!Limits.maxDepth || depth <= Limits.maxDepth))
521     {
522         // Save now last iteration's scores, before Rml moves are reordered
523         for (size_t i = 0; i < Rml.size(); i++)
524             Rml[i].prevScore = Rml[i].score;
525
526         Rml.bestMoveChanges = 0;
527
528         // MultiPV loop. We perform a full root search for each PV line
529         for (MultiPVIdx = 0; MultiPVIdx < std::min(MultiPV, (int)Rml.size()); MultiPVIdx++)
530         {
531             // Calculate dynamic aspiration window based on previous iterations
532             if (depth >= 5 && abs(Rml[MultiPVIdx].prevScore) < VALUE_KNOWN_WIN)
533             {
534                 int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
535                 int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
536
537                 aspirationDelta = std::min(std::max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
538                 aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
539
540                 alpha = std::max(Rml[MultiPVIdx].prevScore - aspirationDelta, -VALUE_INFINITE);
541                 beta  = std::min(Rml[MultiPVIdx].prevScore + aspirationDelta,  VALUE_INFINITE);
542             }
543             else
544             {
545                 alpha = -VALUE_INFINITE;
546                 beta  =  VALUE_INFINITE;
547             }
548
549             // Start with a small aspiration window and, in case of fail high/low,
550             // research with bigger window until not failing high/low anymore.
551             do {
552                 // Search starts from ss+1 to allow referencing (ss-1). This is
553                 // needed by update gains and ss copy when splitting at Root.
554                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
555
556                 // Bring to front the best move. It is critical that sorting is
557                 // done with a stable algorithm because all the values but the first
558                 // and eventually the new best one are set to -VALUE_INFINITE and
559                 // we want to keep the same order for all the moves but the new
560                 // PV that goes to the front. Note that in case of MultiPV search
561                 // the already searched PV lines are preserved.
562                 sort<RootMove>(Rml.begin() + MultiPVIdx, Rml.end());
563
564                 // In case we have found an exact score and we are going to leave
565                 // the fail high/low loop then reorder the PV moves, otherwise
566                 // leave the last PV move in its position so to be searched again.
567                 // Of course this is needed only in MultiPV search.
568                 if (MultiPVIdx && bestValue > alpha && bestValue < beta)
569                     sort<RootMove>(Rml.begin(), Rml.begin() + MultiPVIdx);
570
571                 // Write PV back to transposition table in case the relevant entries
572                 // have been overwritten during the search.
573                 for (int i = 0; i <= MultiPVIdx; i++)
574                     Rml[i].insert_pv_in_tt(pos);
575
576                 // If search has been stopped exit the aspiration window loop,
577                 // note that sorting and writing PV back to TT is safe becuase
578                 // Rml is still valid, although refers to the previous iteration.
579                 if (Signals.stop)
580                     break;
581
582                 // Send full PV info to GUI if we are going to leave the loop or
583                 // if we have a fail high/low and we are deep in the search. UCI
584                 // protocol requires to send all the PV lines also if are still
585                 // to be searched and so refer to the previous search's score.
586                 if ((bestValue > alpha && bestValue < beta) || elapsed_time() > 2000)
587                     for (int i = 0; i < std::min(UCIMultiPV, (int)Rml.size()); i++)
588                     {
589                         bool updated = (i <= MultiPVIdx);
590
591                         if (depth == 1 && !updated)
592                             continue;
593
594                         Depth d = (updated ? depth : depth - 1) * ONE_PLY;
595                         Value s = (updated ? Rml[i].score : Rml[i].prevScore);
596
597                         cout << "info"
598                              << depth_to_uci(d)
599                              << (i == MultiPVIdx ? score_to_uci(s, alpha, beta) : score_to_uci(s))
600                              << speed_to_uci(pos.nodes_searched())
601                              << pv_to_uci(&Rml[i].pv[0], i + 1, pos.is_chess960())
602                              << endl;
603                     }
604
605                 // In case of failing high/low increase aspiration window and
606                 // research, otherwise exit the fail high/low loop.
607                 if (bestValue >= beta)
608                 {
609                     beta = std::min(beta + aspirationDelta, VALUE_INFINITE);
610                     aspirationDelta += aspirationDelta / 2;
611                 }
612                 else if (bestValue <= alpha)
613                 {
614                     Signals.failedLowAtRoot = true;
615                     Signals.stopOnPonderhit = false;
616
617                     alpha = std::max(alpha - aspirationDelta, -VALUE_INFINITE);
618                     aspirationDelta += aspirationDelta / 2;
619                 }
620                 else
621                     break;
622
623             } while (abs(bestValue) < VALUE_KNOWN_WIN);
624         }
625
626         // Collect info about search result
627         bestMove = Rml[0].pv[0];
628         *ponderMove = Rml[0].pv[1];
629         bestValues[depth] = bestValue;
630         bestMoveChanges[depth] = Rml.bestMoveChanges;
631
632         // Skills: Do we need to pick now the best and the ponder moves ?
633         if (SkillLevelEnabled && depth == 1 + SkillLevel)
634             do_skill_level(&skillBest, &skillPonder);
635
636         if (Options["Use Search Log"].value<bool>())
637         {
638             Log log(Options["Search Log Filename"].value<string>());
639             log << pretty_pv(pos, depth, bestValue, elapsed_time(), &Rml[0].pv[0]) << endl;
640         }
641
642         // Filter out startup noise when monitoring best move stability
643         if (depth > 2 && bestMoveChanges[depth])
644             bestMoveNeverChanged = false;
645
646         // Do we have time for the next iteration? Can we stop searching now?
647         if (!Signals.stop && !Signals.stopOnPonderhit && Limits.useTimeManagement())
648         {
649             bool stop = false; // Local variable instead of the volatile Signals.stop
650
651             // Take in account some extra time if the best move has changed
652             if (depth > 4 && depth < 50)
653                 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth - 1]);
654
655             // Stop search if most of available time is already consumed. We probably don't
656             // have enough time to search the first move at the next iteration anyway.
657             if (elapsed_time() > (TimeMgr.available_time() * 62) / 100)
658                 stop = true;
659
660             // Stop search early if one move seems to be much better than others
661             if (   depth >= 10
662                 && !stop
663                 && (   bestMoveNeverChanged
664                     || elapsed_time() > (TimeMgr.available_time() * 40) / 100))
665             {
666                 Value rBeta = bestValue - EasyMoveMargin;
667                 (ss+1)->excludedMove = bestMove;
668                 (ss+1)->skipNullMove = true;
669                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth * ONE_PLY) / 2);
670                 (ss+1)->skipNullMove = false;
671                 (ss+1)->excludedMove = MOVE_NONE;
672
673                 if (v < rBeta)
674                     stop = true;
675             }
676
677             if (stop)
678             {
679                 // If we are allowed to ponder do not stop the search now but
680                 // keep pondering until GUI sends "ponderhit" or "stop".
681                 if (Limits.ponder)
682                     Signals.stopOnPonderhit = true;
683                 else
684                     Signals.stop = true;
685             }
686         }
687     }
688
689     // When using skills overwrite best and ponder moves with the sub-optimal ones
690     if (SkillLevelEnabled)
691     {
692         if (skillBest == MOVE_NONE) // Still unassigned ?
693             do_skill_level(&skillBest, &skillPonder);
694
695         bestMove = skillBest;
696         *ponderMove = skillPonder;
697     }
698
699     return bestMove;
700   }
701
702
703   // search<>() is the main search function for both PV and non-PV nodes and for
704   // normal and SplitPoint nodes. When called just after a split point the search
705   // is simpler because we have already probed the hash table, done a null move
706   // search, and searched the first move before splitting, we don't have to repeat
707   // all this work again. We also don't need to store anything to the hash table
708   // here: This is taken care of after we return from the split point.
709
710   template <NodeType NT>
711   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
712
713     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
714     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
715     const bool RootNode = (NT == Root || NT == SplitPointRoot);
716
717     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
718     assert(beta > alpha && beta <= VALUE_INFINITE);
719     assert(PvNode || alpha == beta - 1);
720     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
721
722     Move movesSearched[MAX_MOVES];
723     int64_t nodes;
724     StateInfo st;
725     const TTEntry *tte;
726     Key posKey;
727     Move ttMove, move, excludedMove, threatMove;
728     Depth ext, newDepth;
729     ValueType vt;
730     Value bestValue, value, oldAlpha;
731     Value refinedValue, nullValue, futilityBase, futilityValue;
732     bool isPvMove, inCheck, singularExtensionNode, givesCheck;
733     bool captureOrPromotion, dangerous, doFullDepthSearch;
734     int moveCount = 0, playedMoveCount = 0;
735     Thread& thread = Threads[pos.thread()];
736     SplitPoint* sp = NULL;
737
738     refinedValue = bestValue = value = -VALUE_INFINITE;
739     oldAlpha = alpha;
740     inCheck = pos.in_check();
741     ss->ply = (ss-1)->ply + 1;
742
743     // Used to send selDepth info to GUI
744     if (PvNode && thread.maxPly < ss->ply)
745         thread.maxPly = ss->ply;
746
747     // Step 1. Initialize node
748     if (!SpNode)
749     {
750         ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
751         (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
752         (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
753     }
754     else
755     {
756         sp = ss->sp;
757         tte = NULL;
758         ttMove = excludedMove = MOVE_NONE;
759         threatMove = sp->threatMove;
760         goto split_point_start;
761     }
762
763     // Step 2. Check for aborted search and immediate draw
764     if ((   Signals.stop
765          || pos.is_draw<false>()
766          || ss->ply > PLY_MAX) && !RootNode)
767         return VALUE_DRAW;
768
769     // Step 3. Mate distance pruning
770     if (!RootNode)
771     {
772         alpha = std::max(value_mated_in(ss->ply), alpha);
773         beta = std::min(value_mate_in(ss->ply+1), beta);
774         if (alpha >= beta)
775             return alpha;
776     }
777
778     // Step 4. Transposition table lookup
779     // We don't want the score of a partial search to overwrite a previous full search
780     // TT value, so we use a different position key in case of an excluded move.
781     excludedMove = ss->excludedMove;
782     posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
783     tte = TT.probe(posKey);
784     ttMove = RootNode ? Rml[MultiPVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
785
786     // At PV nodes we check for exact scores, while at non-PV nodes we check for
787     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
788     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
789     // we should also update RootMoveList to avoid bogus output.
790     if (!RootNode && tte && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
791                                     : can_return_tt(tte, depth, beta, ss->ply)))
792     {
793         TT.refresh(tte);
794         ss->bestMove = move = ttMove; // Can be MOVE_NONE
795         value = value_from_tt(tte->value(), ss->ply);
796
797         if (   value >= beta
798             && move
799             && !pos.is_capture_or_promotion(move)
800             && move != ss->killers[0])
801         {
802             ss->killers[1] = ss->killers[0];
803             ss->killers[0] = move;
804         }
805         return value;
806     }
807
808     // Step 5. Evaluate the position statically and update parent's gain statistics
809     if (inCheck)
810         ss->eval = ss->evalMargin = VALUE_NONE;
811     else if (tte)
812     {
813         assert(tte->static_value() != VALUE_NONE);
814
815         ss->eval = tte->static_value();
816         ss->evalMargin = tte->static_value_margin();
817         refinedValue = refine_eval(tte, ss->eval, ss->ply);
818     }
819     else
820     {
821         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
822         TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
823     }
824
825     // Update gain for the parent non-capture move given the static position
826     // evaluation before and after the move.
827     if (   (move = (ss-1)->currentMove) != MOVE_NULL
828         && (ss-1)->eval != VALUE_NONE
829         && ss->eval != VALUE_NONE
830         && pos.captured_piece_type() == PIECE_TYPE_NONE
831         && !is_special(move))
832     {
833         Square to = move_to(move);
834         H.update_gain(pos.piece_on(to), to, -(ss-1)->eval - ss->eval);
835     }
836
837     // Step 6. Razoring (is omitted in PV nodes)
838     if (   !PvNode
839         &&  depth < RazorDepth
840         && !inCheck
841         &&  refinedValue + razor_margin(depth) < beta
842         &&  ttMove == MOVE_NONE
843         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
844         && !pos.has_pawn_on_7th(pos.side_to_move()))
845     {
846         Value rbeta = beta - razor_margin(depth);
847         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
848         if (v < rbeta)
849             // Logically we should return (v + razor_margin(depth)), but
850             // surprisingly this did slightly weaker in tests.
851             return v;
852     }
853
854     // Step 7. Static null move pruning (is omitted in PV nodes)
855     // We're betting that the opponent doesn't have a move that will reduce
856     // the score by more than futility_margin(depth) if we do a null move.
857     if (   !PvNode
858         && !ss->skipNullMove
859         &&  depth < RazorDepth
860         && !inCheck
861         &&  refinedValue - futility_margin(depth, 0) >= beta
862         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
863         &&  pos.non_pawn_material(pos.side_to_move()))
864         return refinedValue - futility_margin(depth, 0);
865
866     // Step 8. Null move search with verification search (is omitted in PV nodes)
867     if (   !PvNode
868         && !ss->skipNullMove
869         &&  depth > ONE_PLY
870         && !inCheck
871         &&  refinedValue >= beta
872         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
873         &&  pos.non_pawn_material(pos.side_to_move()))
874     {
875         ss->currentMove = MOVE_NULL;
876
877         // Null move dynamic reduction based on depth
878         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
879
880         // Null move dynamic reduction based on value
881         if (refinedValue - PawnValueMidgame > beta)
882             R++;
883
884         pos.do_null_move<true>(st);
885         (ss+1)->skipNullMove = true;
886         nullValue = depth-R*ONE_PLY < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
887                                               : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
888         (ss+1)->skipNullMove = false;
889         pos.do_null_move<false>(st);
890
891         if (nullValue >= beta)
892         {
893             // Do not return unproven mate scores
894             if (nullValue >= VALUE_MATE_IN_PLY_MAX)
895                 nullValue = beta;
896
897             if (depth < 6 * ONE_PLY)
898                 return nullValue;
899
900             // Do verification search at high depths
901             ss->skipNullMove = true;
902             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
903             ss->skipNullMove = false;
904
905             if (v >= beta)
906                 return nullValue;
907         }
908         else
909         {
910             // The null move failed low, which means that we may be faced with
911             // some kind of threat. If the previous move was reduced, check if
912             // the move that refuted the null move was somehow connected to the
913             // move which was reduced. If a connection is found, return a fail
914             // low score (which will cause the reduced move to fail high in the
915             // parent node, which will trigger a re-search with full depth).
916             threatMove = (ss+1)->bestMove;
917
918             if (   depth < ThreatDepth
919                 && (ss-1)->reduction
920                 && threatMove != MOVE_NONE
921                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
922                 return beta - 1;
923         }
924     }
925
926     // Step 9. ProbCut (is omitted in PV nodes)
927     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
928     // and a reduced search returns a value much above beta, we can (almost) safely
929     // prune the previous move.
930     if (   !PvNode
931         &&  depth >= RazorDepth + ONE_PLY
932         && !inCheck
933         && !ss->skipNullMove
934         &&  excludedMove == MOVE_NONE
935         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX)
936     {
937         Value rbeta = beta + 200;
938         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
939
940         assert(rdepth >= ONE_PLY);
941
942         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
943         CheckInfo ci(pos);
944
945         while ((move = mp.get_next_move()) != MOVE_NONE)
946             if (pos.pl_move_is_legal(move, ci.pinned))
947             {
948                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
949                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
950                 pos.undo_move(move);
951                 if (value >= rbeta)
952                     return value;
953             }
954     }
955
956     // Step 10. Internal iterative deepening
957     if (   depth >= IIDDepth[PvNode]
958         && ttMove == MOVE_NONE
959         && (PvNode || (!inCheck && ss->eval + IIDMargin >= beta)))
960     {
961         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
962
963         ss->skipNullMove = true;
964         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
965         ss->skipNullMove = false;
966
967         tte = TT.probe(posKey);
968         ttMove = tte ? tte->move() : MOVE_NONE;
969     }
970
971 split_point_start: // At split points actual search starts from here
972
973     // Initialize a MovePicker object for the current position
974     MovePickerExt<SpNode> mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
975     CheckInfo ci(pos);
976     ss->bestMove = MOVE_NONE;
977     futilityBase = ss->eval + ss->evalMargin;
978     singularExtensionNode =   !RootNode
979                            && !SpNode
980                            && depth >= SingularExtensionDepth[PvNode]
981                            && ttMove != MOVE_NONE
982                            && !excludedMove // Do not allow recursive singular extension search
983                            && (tte->type() & VALUE_TYPE_LOWER)
984                            && tte->depth() >= depth - 3 * ONE_PLY;
985     if (SpNode)
986     {
987         lock_grab(&(sp->lock));
988         bestValue = sp->bestValue;
989     }
990
991     // Step 11. Loop through moves
992     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
993     while (   bestValue < beta
994            && (move = mp.get_next_move()) != MOVE_NONE
995            && !thread.cutoff_occurred())
996     {
997       assert(is_ok(move));
998
999       if (move == excludedMove)
1000           continue;
1001
1002       // At root obey the "searchmoves" option and skip moves not listed in Root
1003       // Move List, as a consequence any illegal move is also skipped. In MultiPV
1004       // mode we also skip PV moves which have been already searched.
1005       if (RootNode && !Rml.find(move, MultiPVIdx))
1006           continue;
1007
1008       // At PV and SpNode nodes we want all moves to be legal since the beginning
1009       if ((PvNode || SpNode) && !pos.pl_move_is_legal(move, ci.pinned))
1010           continue;
1011
1012       if (SpNode)
1013       {
1014           moveCount = ++sp->moveCount;
1015           lock_release(&(sp->lock));
1016       }
1017       else
1018           moveCount++;
1019
1020       if (RootNode)
1021       {
1022           // This is used by time management
1023           Signals.firstRootMove = (moveCount == 1);
1024
1025           // Save the current node count before the move is searched
1026           nodes = pos.nodes_searched();
1027
1028           // For long searches send current move info to GUI
1029           if (pos.thread() == 0 && elapsed_time() > 2000)
1030               cout << "info" << depth_to_uci(depth)
1031                    << " currmove " << move
1032                    << " currmovenumber " << moveCount + MultiPVIdx << endl;
1033       }
1034
1035       isPvMove = (PvNode && moveCount <= 1);
1036       givesCheck = pos.move_gives_check(move, ci);
1037       captureOrPromotion = pos.is_capture_or_promotion(move);
1038
1039       // Step 12. Decide the new search depth
1040       ext = extension<PvNode>(pos, move, captureOrPromotion, givesCheck, &dangerous);
1041
1042       // Singular extension search. If all moves but one fail low on a search of
1043       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1044       // is singular and should be extended. To verify this we do a reduced search
1045       // on all the other moves but the ttMove, if result is lower than ttValue minus
1046       // a margin then we extend ttMove.
1047       if (   singularExtensionNode
1048           && move == ttMove
1049           && pos.pl_move_is_legal(move, ci.pinned)
1050           && ext < ONE_PLY)
1051       {
1052           Value ttValue = value_from_tt(tte->value(), ss->ply);
1053
1054           if (abs(ttValue) < VALUE_KNOWN_WIN)
1055           {
1056               Value rBeta = ttValue - int(depth);
1057               ss->excludedMove = move;
1058               ss->skipNullMove = true;
1059               value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1060               ss->skipNullMove = false;
1061               ss->excludedMove = MOVE_NONE;
1062               ss->bestMove = MOVE_NONE;
1063               if (value < rBeta)
1064                   ext = ONE_PLY;
1065           }
1066       }
1067
1068       // Update current move (this must be done after singular extension search)
1069       newDepth = depth - ONE_PLY + ext;
1070
1071       // Step 13. Futility pruning (is omitted in PV nodes)
1072       if (   !PvNode
1073           && !captureOrPromotion
1074           && !inCheck
1075           && !dangerous
1076           &&  move != ttMove
1077           && !is_castle(move))
1078       {
1079           // Move count based pruning
1080           if (   moveCount >= futility_move_count(depth)
1081               && (!threatMove || !connected_threat(pos, move, threatMove))
1082               && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1083           {
1084               if (SpNode)
1085                   lock_grab(&(sp->lock));
1086
1087               continue;
1088           }
1089
1090           // Value based pruning
1091           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1092           // but fixing this made program slightly weaker.
1093           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
1094           futilityValue =  futilityBase + futility_margin(predictedDepth, moveCount)
1095                          + H.gain(pos.piece_on(move_from(move)), move_to(move));
1096
1097           if (futilityValue < beta)
1098           {
1099               if (SpNode)
1100               {
1101                   lock_grab(&(sp->lock));
1102                   if (futilityValue > sp->bestValue)
1103                       sp->bestValue = bestValue = futilityValue;
1104               }
1105               else if (futilityValue > bestValue)
1106                   bestValue = futilityValue;
1107
1108               continue;
1109           }
1110
1111           // Prune moves with negative SEE at low depths
1112           if (   predictedDepth < 2 * ONE_PLY
1113               && bestValue > VALUE_MATED_IN_PLY_MAX
1114               && pos.see_sign(move) < 0)
1115           {
1116               if (SpNode)
1117                   lock_grab(&(sp->lock));
1118
1119               continue;
1120           }
1121       }
1122
1123       // Check for legality only before to do the move
1124       if (!pos.pl_move_is_legal(move, ci.pinned))
1125       {
1126           moveCount--;
1127           continue;
1128       }
1129
1130       ss->currentMove = move;
1131       if (!SpNode && !captureOrPromotion)
1132           movesSearched[playedMoveCount++] = move;
1133
1134       // Step 14. Make the move
1135       pos.do_move(move, st, ci, givesCheck);
1136
1137       // Step 15. Reduced depth search (LMR). If the move fails high will be
1138       // re-searched at full depth.
1139       if (   depth > 3 * ONE_PLY
1140           && !isPvMove
1141           && !captureOrPromotion
1142           && !dangerous
1143           && !is_castle(move)
1144           &&  ss->killers[0] != move
1145           &&  ss->killers[1] != move)
1146       {
1147           ss->reduction = reduction<PvNode>(depth, moveCount);
1148           Depth d = newDepth - ss->reduction;
1149           alpha = SpNode ? sp->alpha : alpha;
1150
1151           value = d < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1152                               : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1153
1154           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
1155           ss->reduction = DEPTH_ZERO;
1156       }
1157       else
1158           doFullDepthSearch = !isPvMove;
1159
1160       // Step 16. Full depth search, when LMR is skipped or fails high
1161       if (doFullDepthSearch)
1162       {
1163           alpha = SpNode ? sp->alpha : alpha;
1164           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
1165                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1166       }
1167
1168       // Only for PV nodes do a full PV search on the first move or after a fail
1169       // high, in the latter case search only if value < beta, otherwise let the
1170       // parent node to fail low with value <= alpha and to try another move.
1171       if (PvNode && (isPvMove || (value > alpha && (RootNode || value < beta))))
1172           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
1173                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1174
1175       // Step 17. Undo move
1176       pos.undo_move(move);
1177
1178       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1179
1180       // Step 18. Check for new best move
1181       if (SpNode)
1182       {
1183           lock_grab(&(sp->lock));
1184           bestValue = sp->bestValue;
1185           alpha = sp->alpha;
1186       }
1187
1188       // Finished searching the move. If StopRequest is true, the search
1189       // was aborted because the user interrupted the search or because we
1190       // ran out of time. In this case, the return value of the search cannot
1191       // be trusted, and we don't update the best move and/or PV.
1192       if (RootNode && !Signals.stop)
1193       {
1194           // Remember searched nodes counts for this move
1195           RootMove* rm = Rml.find(move);
1196           rm->nodes += pos.nodes_searched() - nodes;
1197
1198           // PV move or new best move ?
1199           if (isPvMove || value > alpha)
1200           {
1201               // Update PV
1202               rm->score = value;
1203               rm->extract_pv_from_tt(pos);
1204
1205               // We record how often the best move has been changed in each
1206               // iteration. This information is used for time management: When
1207               // the best move changes frequently, we allocate some more time.
1208               if (!isPvMove && MultiPV == 1)
1209                   Rml.bestMoveChanges++;
1210           }
1211           else
1212               // All other moves but the PV are set to the lowest value, this
1213               // is not a problem when sorting becuase sort is stable and move
1214               // position in the list is preserved, just the PV is pushed up.
1215               rm->score = -VALUE_INFINITE;
1216
1217       } // RootNode
1218
1219       if (value > bestValue)
1220       {
1221           bestValue = value;
1222           ss->bestMove = move;
1223
1224           if (   PvNode
1225               && value > alpha
1226               && value < beta) // We want always alpha < beta
1227               alpha = value;
1228
1229           if (SpNode && !thread.cutoff_occurred())
1230           {
1231               sp->bestValue = value;
1232               sp->ss->bestMove = move;
1233               sp->alpha = alpha;
1234               sp->is_betaCutoff = (value >= beta);
1235           }
1236       }
1237
1238       // Step 19. Check for split
1239       if (   !SpNode
1240           && depth >= Threads.min_split_depth()
1241           && bestValue < beta
1242           && Threads.available_slave_exists(pos.thread())
1243           && !Signals.stop
1244           && !thread.cutoff_occurred())
1245           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, depth,
1246                                                threatMove, moveCount, &mp, NT);
1247     }
1248
1249     // Step 20. Check for mate and stalemate
1250     // All legal moves have been searched and if there are no legal moves, it
1251     // must be mate or stalemate. Note that we can have a false positive in
1252     // case of StopRequest or thread.cutoff_occurred() are set, but this is
1253     // harmless because return value is discarded anyhow in the parent nodes.
1254     // If we are in a singular extension search then return a fail low score.
1255     if (!SpNode && !moveCount)
1256         return excludedMove ? oldAlpha : inCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1257
1258     // Step 21. Update tables
1259     // If the search is not aborted, update the transposition table,
1260     // history counters, and killer moves.
1261     if (!SpNode && !Signals.stop && !thread.cutoff_occurred())
1262     {
1263         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1264         vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1265              : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1266
1267         TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1268
1269         // Update killers and history only for non capture moves that fails high
1270         if (    bestValue >= beta
1271             && !pos.is_capture_or_promotion(move))
1272         {
1273             if (move != ss->killers[0])
1274             {
1275                 ss->killers[1] = ss->killers[0];
1276                 ss->killers[0] = move;
1277             }
1278             update_history(pos, move, depth, movesSearched, playedMoveCount);
1279         }
1280     }
1281
1282     if (SpNode)
1283     {
1284         // Here we have the lock still grabbed
1285         sp->is_slave[pos.thread()] = false;
1286         sp->nodes += pos.nodes_searched();
1287         lock_release(&(sp->lock));
1288     }
1289
1290     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1291
1292     return bestValue;
1293   }
1294
1295   // qsearch() is the quiescence search function, which is called by the main
1296   // search function when the remaining depth is zero (or, to be more precise,
1297   // less than ONE_PLY).
1298
1299   template <NodeType NT>
1300   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1301
1302     const bool PvNode = (NT == PV);
1303
1304     assert(NT == PV || NT == NonPV);
1305     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1306     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1307     assert(PvNode || alpha == beta - 1);
1308     assert(depth <= 0);
1309     assert(pos.thread() >= 0 && pos.thread() < Threads.size());
1310
1311     StateInfo st;
1312     Move ttMove, move;
1313     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1314     bool inCheck, enoughMaterial, givesCheck, evasionPrunable;
1315     const TTEntry* tte;
1316     Depth ttDepth;
1317     ValueType vt;
1318     Value oldAlpha = alpha;
1319
1320     ss->bestMove = ss->currentMove = MOVE_NONE;
1321     ss->ply = (ss-1)->ply + 1;
1322
1323     // Check for an instant draw or maximum ply reached
1324     if (pos.is_draw<true>() || ss->ply > PLY_MAX)
1325         return VALUE_DRAW;
1326
1327     // Decide whether or not to include checks, this fixes also the type of
1328     // TT entry depth that we are going to use. Note that in qsearch we use
1329     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1330     inCheck = pos.in_check();
1331     ttDepth = (inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1332
1333     // Transposition table lookup. At PV nodes, we don't use the TT for
1334     // pruning, but only for move ordering.
1335     tte = TT.probe(pos.get_key());
1336     ttMove = (tte ? tte->move() : MOVE_NONE);
1337
1338     if (!PvNode && tte && can_return_tt(tte, ttDepth, beta, ss->ply))
1339     {
1340         ss->bestMove = ttMove; // Can be MOVE_NONE
1341         return value_from_tt(tte->value(), ss->ply);
1342     }
1343
1344     // Evaluate the position statically
1345     if (inCheck)
1346     {
1347         bestValue = futilityBase = -VALUE_INFINITE;
1348         ss->eval = evalMargin = VALUE_NONE;
1349         enoughMaterial = false;
1350     }
1351     else
1352     {
1353         if (tte)
1354         {
1355             assert(tte->static_value() != VALUE_NONE);
1356
1357             evalMargin = tte->static_value_margin();
1358             ss->eval = bestValue = tte->static_value();
1359         }
1360         else
1361             ss->eval = bestValue = evaluate(pos, evalMargin);
1362
1363         // Stand pat. Return immediately if static value is at least beta
1364         if (bestValue >= beta)
1365         {
1366             if (!tte)
1367                 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1368
1369             return bestValue;
1370         }
1371
1372         if (PvNode && bestValue > alpha)
1373             alpha = bestValue;
1374
1375         // Futility pruning parameters, not needed when in check
1376         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1377         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1378     }
1379
1380     // Initialize a MovePicker object for the current position, and prepare
1381     // to search the moves. Because the depth is <= 0 here, only captures,
1382     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1383     // be generated.
1384     MovePicker mp(pos, ttMove, depth, H, move_to((ss-1)->currentMove));
1385     CheckInfo ci(pos);
1386
1387     // Loop through the moves until no moves remain or a beta cutoff occurs
1388     while (   bestValue < beta
1389            && (move = mp.get_next_move()) != MOVE_NONE)
1390     {
1391       assert(is_ok(move));
1392
1393       givesCheck = pos.move_gives_check(move, ci);
1394
1395       // Futility pruning
1396       if (   !PvNode
1397           && !inCheck
1398           && !givesCheck
1399           &&  move != ttMove
1400           &&  enoughMaterial
1401           && !is_promotion(move)
1402           && !pos.is_passed_pawn_push(move))
1403       {
1404           futilityValue =  futilityBase
1405                          + PieceValueEndgame[pos.piece_on(move_to(move))]
1406                          + (is_enpassant(move) ? PawnValueEndgame : VALUE_ZERO);
1407
1408           if (futilityValue < beta)
1409           {
1410               if (futilityValue > bestValue)
1411                   bestValue = futilityValue;
1412
1413               continue;
1414           }
1415
1416           // Prune moves with negative or equal SEE
1417           if (   futilityBase < beta
1418               && depth < DEPTH_ZERO
1419               && pos.see(move) <= 0)
1420               continue;
1421       }
1422
1423       // Detect non-capture evasions that are candidate to be pruned
1424       evasionPrunable =   !PvNode
1425                        && inCheck
1426                        && bestValue > VALUE_MATED_IN_PLY_MAX
1427                        && !pos.is_capture(move)
1428                        && !pos.can_castle(pos.side_to_move());
1429
1430       // Don't search moves with negative SEE values
1431       if (   !PvNode
1432           && (!inCheck || evasionPrunable)
1433           &&  move != ttMove
1434           && !is_promotion(move)
1435           &&  pos.see_sign(move) < 0)
1436           continue;
1437
1438       // Don't search useless checks
1439       if (   !PvNode
1440           && !inCheck
1441           &&  givesCheck
1442           &&  move != ttMove
1443           && !pos.is_capture_or_promotion(move)
1444           &&  ss->eval + PawnValueMidgame / 4 < beta
1445           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1446       {
1447           if (ss->eval + PawnValueMidgame / 4 > bestValue)
1448               bestValue = ss->eval + PawnValueMidgame / 4;
1449
1450           continue;
1451       }
1452
1453       // Check for legality only before to do the move
1454       if (!pos.pl_move_is_legal(move, ci.pinned))
1455           continue;
1456
1457       // Update current move
1458       ss->currentMove = move;
1459
1460       // Make and search the move
1461       pos.do_move(move, st, ci, givesCheck);
1462       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1463       pos.undo_move(move);
1464
1465       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1466
1467       // New best move?
1468       if (value > bestValue)
1469       {
1470           bestValue = value;
1471           ss->bestMove = move;
1472
1473           if (   PvNode
1474               && value > alpha
1475               && value < beta) // We want always alpha < beta
1476               alpha = value;
1477        }
1478     }
1479
1480     // All legal moves have been searched. A special case: If we're in check
1481     // and no legal moves were found, it is checkmate.
1482     if (inCheck && bestValue == -VALUE_INFINITE)
1483         return value_mated_in(ss->ply);
1484
1485     // Update transposition table
1486     move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1487     vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1488          : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1489
1490     TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, move, ss->eval, evalMargin);
1491
1492     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1493
1494     return bestValue;
1495   }
1496
1497
1498   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1499   // bestValue is updated only when returning false because in that case move
1500   // will be pruned.
1501
1502   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1503   {
1504     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1505     Square from, to, ksq, victimSq;
1506     Piece pc;
1507     Color them;
1508     Value futilityValue, bv = *bestValue;
1509
1510     from = move_from(move);
1511     to = move_to(move);
1512     them = flip(pos.side_to_move());
1513     ksq = pos.king_square(them);
1514     kingAtt = pos.attacks_from<KING>(ksq);
1515     pc = pos.piece_on(from);
1516
1517     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1518     oldAtt = pos.attacks_from(pc, from, occ);
1519     newAtt = pos.attacks_from(pc,   to, occ);
1520
1521     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1522     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1523
1524     if (!(b && (b & (b - 1))))
1525         return true;
1526
1527     // Rule 2. Queen contact check is very dangerous
1528     if (   type_of(pc) == QUEEN
1529         && bit_is_set(kingAtt, to))
1530         return true;
1531
1532     // Rule 3. Creating new double threats with checks
1533     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1534
1535     while (b)
1536     {
1537         victimSq = pop_1st_bit(&b);
1538         futilityValue = futilityBase + PieceValueEndgame[pos.piece_on(victimSq)];
1539
1540         // Note that here we generate illegal "double move"!
1541         if (   futilityValue >= beta
1542             && pos.see_sign(make_move(from, victimSq)) >= 0)
1543             return true;
1544
1545         if (futilityValue > bv)
1546             bv = futilityValue;
1547     }
1548
1549     // Update bestValue only if check is not dangerous (because we will prune the move)
1550     *bestValue = bv;
1551     return false;
1552   }
1553
1554
1555   // connected_moves() tests whether two moves are 'connected' in the sense
1556   // that the first move somehow made the second move possible (for instance
1557   // if the moving piece is the same in both moves). The first move is assumed
1558   // to be the move that was made to reach the current position, while the
1559   // second move is assumed to be a move from the current position.
1560
1561   bool connected_moves(const Position& pos, Move m1, Move m2) {
1562
1563     Square f1, t1, f2, t2;
1564     Piece p1, p2;
1565     Square ksq;
1566
1567     assert(is_ok(m1));
1568     assert(is_ok(m2));
1569
1570     // Case 1: The moving piece is the same in both moves
1571     f2 = move_from(m2);
1572     t1 = move_to(m1);
1573     if (f2 == t1)
1574         return true;
1575
1576     // Case 2: The destination square for m2 was vacated by m1
1577     t2 = move_to(m2);
1578     f1 = move_from(m1);
1579     if (t2 == f1)
1580         return true;
1581
1582     // Case 3: Moving through the vacated square
1583     p2 = pos.piece_on(f2);
1584     if (   piece_is_slider(p2)
1585         && bit_is_set(squares_between(f2, t2), f1))
1586       return true;
1587
1588     // Case 4: The destination square for m2 is defended by the moving piece in m1
1589     p1 = pos.piece_on(t1);
1590     if (bit_is_set(pos.attacks_from(p1, t1), t2))
1591         return true;
1592
1593     // Case 5: Discovered check, checking piece is the piece moved in m1
1594     ksq = pos.king_square(pos.side_to_move());
1595     if (    piece_is_slider(p1)
1596         &&  bit_is_set(squares_between(t1, ksq), f2))
1597     {
1598         Bitboard occ = pos.occupied_squares();
1599         clear_bit(&occ, f2);
1600         if (bit_is_set(pos.attacks_from(p1, t1, occ), ksq))
1601             return true;
1602     }
1603     return false;
1604   }
1605
1606
1607   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1608   // "plies to mate from the current ply".  Non-mate scores are unchanged.
1609   // The function is called before storing a value to the transposition table.
1610
1611   Value value_to_tt(Value v, int ply) {
1612
1613     if (v >= VALUE_MATE_IN_PLY_MAX)
1614       return v + ply;
1615
1616     if (v <= VALUE_MATED_IN_PLY_MAX)
1617       return v - ply;
1618
1619     return v;
1620   }
1621
1622
1623   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1624   // the transposition table to a mate score corrected for the current ply.
1625
1626   Value value_from_tt(Value v, int ply) {
1627
1628     if (v >= VALUE_MATE_IN_PLY_MAX)
1629       return v - ply;
1630
1631     if (v <= VALUE_MATED_IN_PLY_MAX)
1632       return v + ply;
1633
1634     return v;
1635   }
1636
1637
1638   // connected_threat() tests whether it is safe to forward prune a move or if
1639   // is somehow connected to the threat move returned by null search.
1640
1641   bool connected_threat(const Position& pos, Move m, Move threat) {
1642
1643     assert(is_ok(m));
1644     assert(is_ok(threat));
1645     assert(!pos.is_capture_or_promotion(m));
1646     assert(!pos.is_passed_pawn_push(m));
1647
1648     Square mfrom, mto, tfrom, tto;
1649
1650     mfrom = move_from(m);
1651     mto = move_to(m);
1652     tfrom = move_from(threat);
1653     tto = move_to(threat);
1654
1655     // Case 1: Don't prune moves which move the threatened piece
1656     if (mfrom == tto)
1657         return true;
1658
1659     // Case 2: If the threatened piece has value less than or equal to the
1660     // value of the threatening piece, don't prune moves which defend it.
1661     if (   pos.is_capture(threat)
1662         && (   PieceValueMidgame[pos.piece_on(tfrom)] >= PieceValueMidgame[pos.piece_on(tto)]
1663             || type_of(pos.piece_on(tfrom)) == KING)
1664         && pos.move_attacks_square(m, tto))
1665         return true;
1666
1667     // Case 3: If the moving piece in the threatened move is a slider, don't
1668     // prune safe moves which block its ray.
1669     if (   piece_is_slider(pos.piece_on(tfrom))
1670         && bit_is_set(squares_between(tfrom, tto), mto)
1671         && pos.see_sign(m) >= 0)
1672         return true;
1673
1674     return false;
1675   }
1676
1677
1678   // can_return_tt() returns true if a transposition table score
1679   // can be used to cut-off at a given point in search.
1680
1681   bool can_return_tt(const TTEntry* tte, Depth depth, Value beta, int ply) {
1682
1683     Value v = value_from_tt(tte->value(), ply);
1684
1685     return   (   tte->depth() >= depth
1686               || v >= std::max(VALUE_MATE_IN_PLY_MAX, beta)
1687               || v < std::min(VALUE_MATED_IN_PLY_MAX, beta))
1688
1689           && (   ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1690               || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1691   }
1692
1693
1694   // refine_eval() returns the transposition table score if
1695   // possible otherwise falls back on static position evaluation.
1696
1697   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1698
1699       assert(tte);
1700
1701       Value v = value_from_tt(tte->value(), ply);
1702
1703       if (   ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1704           || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1705           return v;
1706
1707       return defaultEval;
1708   }
1709
1710
1711   // update_history() registers a good move that produced a beta-cutoff
1712   // in history and marks as failures all the other moves of that ply.
1713
1714   void update_history(const Position& pos, Move move, Depth depth,
1715                       Move movesSearched[], int moveCount) {
1716     Move m;
1717     Value bonus = Value(int(depth) * int(depth));
1718
1719     H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1720
1721     for (int i = 0; i < moveCount - 1; i++)
1722     {
1723         m = movesSearched[i];
1724
1725         assert(m != move);
1726
1727         H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1728     }
1729   }
1730
1731
1732   // current_search_time() returns the number of milliseconds which have passed
1733   // since the beginning of the current search.
1734
1735   int elapsed_time(bool reset) {
1736
1737     static int searchStartTime;
1738
1739     if (reset)
1740         searchStartTime = get_system_time();
1741
1742     return get_system_time() - searchStartTime;
1743   }
1744
1745
1746   // score_to_uci() converts a value to a string suitable for use with the UCI
1747   // protocol specifications:
1748   //
1749   // cp <x>     The score from the engine's point of view in centipawns.
1750   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1751   //            use negative values for y.
1752
1753   string score_to_uci(Value v, Value alpha, Value beta) {
1754
1755     std::stringstream s;
1756
1757     if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1758         s << " score cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1759     else
1760         s << " score mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1761
1762     s << (v >= beta ? " lowerbound" : v <= alpha ? " upperbound" : "");
1763
1764     return s.str();
1765   }
1766
1767
1768   // speed_to_uci() returns a string with time stats of current search suitable
1769   // to be sent to UCI gui.
1770
1771   string speed_to_uci(int64_t nodes) {
1772
1773     std::stringstream s;
1774     int t = elapsed_time();
1775
1776     s << " nodes " << nodes
1777       << " nps " << (t > 0 ? int(nodes * 1000 / t) : 0)
1778       << " time "  << t;
1779
1780     return s.str();
1781   }
1782
1783
1784   // pv_to_uci() returns a string with information on the current PV line
1785   // formatted according to UCI specification.
1786
1787   string pv_to_uci(const Move pv[], int pvNum, bool chess960) {
1788
1789     std::stringstream s;
1790
1791     s << " multipv " << pvNum << " pv " << set960(chess960);
1792
1793     for ( ; *pv != MOVE_NONE; pv++)
1794         s << *pv << " ";
1795
1796     return s.str();
1797   }
1798
1799
1800   // depth_to_uci() returns a string with information on the current depth and
1801   // seldepth formatted according to UCI specification.
1802
1803   string depth_to_uci(Depth depth) {
1804
1805     std::stringstream s;
1806
1807     // Retrieve max searched depth among threads
1808     int selDepth = 0;
1809     for (int i = 0; i < Threads.size(); i++)
1810         if (Threads[i].maxPly > selDepth)
1811             selDepth = Threads[i].maxPly;
1812
1813      s << " depth " << depth / ONE_PLY << " seldepth " << selDepth;
1814
1815     return s.str();
1816   }
1817
1818   string time_to_string(int millisecs) {
1819
1820     const int MSecMinute = 1000 * 60;
1821     const int MSecHour   = 1000 * 60 * 60;
1822
1823     int hours = millisecs / MSecHour;
1824     int minutes =  (millisecs % MSecHour) / MSecMinute;
1825     int seconds = ((millisecs % MSecHour) % MSecMinute) / 1000;
1826
1827     std::stringstream s;
1828
1829     if (hours)
1830         s << hours << ':';
1831
1832     s << std::setfill('0') << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
1833     return s.str();
1834   }
1835
1836   string score_to_string(Value v) {
1837
1838     std::stringstream s;
1839
1840     if (v >= VALUE_MATE_IN_PLY_MAX)
1841         s << "#" << (VALUE_MATE - v + 1) / 2;
1842     else if (v <= VALUE_MATED_IN_PLY_MAX)
1843         s << "-#" << (VALUE_MATE + v) / 2;
1844     else
1845         s << std::setprecision(2) << std::fixed << std::showpos << float(v) / PawnValueMidgame;
1846
1847     return s.str();
1848   }
1849
1850
1851   // pretty_pv() creates a human-readable string from a position and a PV.
1852   // It is used to write search information to the log file (which is created
1853   // when the UCI parameter "Use Search Log" is "true").
1854
1855   string pretty_pv(Position& pos, int depth, Value value, int time, Move pv[]) {
1856
1857     const int64_t K = 1000;
1858     const int64_t M = 1000000;
1859     const int startColumn = 28;
1860     const size_t maxLength = 80 - startColumn;
1861
1862     StateInfo state[PLY_MAX_PLUS_2], *st = state;
1863     Move* m = pv;
1864     string san;
1865     std::stringstream s;
1866     size_t length = 0;
1867
1868     // First print depth, score, time and searched nodes...
1869     s << set960(pos.is_chess960())
1870       << std::setw(2) << depth
1871       << std::setw(8) << score_to_string(value)
1872       << std::setw(8) << time_to_string(time);
1873
1874     if (pos.nodes_searched() < M)
1875         s << std::setw(8) << pos.nodes_searched() / 1 << "  ";
1876     else if (pos.nodes_searched() < K * M)
1877         s << std::setw(7) << pos.nodes_searched() / K << "K  ";
1878     else
1879         s << std::setw(7) << pos.nodes_searched() / M << "M  ";
1880
1881     // ...then print the full PV line in short algebraic notation
1882     while (*m != MOVE_NONE)
1883     {
1884         san = move_to_san(pos, *m);
1885         length += san.length() + 1;
1886
1887         if (length > maxLength)
1888         {
1889             length = san.length() + 1;
1890             s << "\n" + string(startColumn, ' ');
1891         }
1892         s << san << ' ';
1893
1894         pos.do_move(*m++, *st++);
1895     }
1896
1897     // Restore original position before to leave
1898     while (m != pv) pos.undo_move(*--m);
1899
1900     return s.str();
1901   }
1902
1903
1904   // When playing with strength handicap choose best move among the MultiPV set
1905   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
1906
1907   void do_skill_level(Move* best, Move* ponder) {
1908
1909     assert(MultiPV > 1);
1910
1911     static RKISS rk;
1912
1913     // Rml list is already sorted by score in descending order
1914     int s;
1915     int max_s = -VALUE_INFINITE;
1916     int size = std::min(MultiPV, (int)Rml.size());
1917     int max = Rml[0].score;
1918     int var = std::min(max - Rml[size - 1].score, int(PawnValueMidgame));
1919     int wk = 120 - 2 * SkillLevel;
1920
1921     // PRNG sequence should be non deterministic
1922     for (int i = abs(get_system_time() % 50); i > 0; i--)
1923         rk.rand<unsigned>();
1924
1925     // Choose best move. For each move's score we add two terms both dependent
1926     // on wk, one deterministic and bigger for weaker moves, and one random,
1927     // then we choose the move with the resulting highest score.
1928     for (int i = 0; i < size; i++)
1929     {
1930         s = Rml[i].score;
1931
1932         // Don't allow crazy blunders even at very low skills
1933         if (i > 0 && Rml[i-1].score > s + EasyMoveMargin)
1934             break;
1935
1936         // This is our magical formula
1937         s += ((max - s) * wk + var * (rk.rand<unsigned>() % wk)) / 128;
1938
1939         if (s > max_s)
1940         {
1941             max_s = s;
1942             *best = Rml[i].pv[0];
1943             *ponder = Rml[i].pv[1];
1944         }
1945     }
1946   }
1947
1948
1949   /// RootMove and RootMoveList method's definitions
1950
1951   void RootMoveList::init(Position& pos, Move rootMoves[]) {
1952
1953     Move* sm;
1954     bestMoveChanges = 0;
1955     clear();
1956
1957     // Generate all legal moves and add them to RootMoveList
1958     for (MoveList<MV_LEGAL> ml(pos); !ml.end(); ++ml)
1959     {
1960         // If we have a rootMoves[] list then verify the move
1961         // is in the list before to add it.
1962         for (sm = rootMoves; *sm && *sm != ml.move(); sm++) {}
1963
1964         if (sm != rootMoves && *sm != ml.move())
1965             continue;
1966
1967         RootMove rm;
1968         rm.pv.push_back(ml.move());
1969         rm.pv.push_back(MOVE_NONE);
1970         rm.score = rm.prevScore = -VALUE_INFINITE;
1971         rm.nodes = 0;
1972         push_back(rm);
1973     }
1974   }
1975
1976   RootMove* RootMoveList::find(const Move& m, int startIndex) {
1977
1978     for (size_t i = startIndex; i < size(); i++)
1979         if ((*this)[i].pv[0] == m)
1980             return &(*this)[i];
1981
1982     return NULL;
1983   }
1984
1985
1986   // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
1987   // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
1988   // allow to always have a ponder move even when we fail high at root and also a
1989   // long PV to print that is important for position analysis.
1990
1991   void RootMove::extract_pv_from_tt(Position& pos) {
1992
1993     StateInfo state[PLY_MAX_PLUS_2], *st = state;
1994     TTEntry* tte;
1995     int ply = 1;
1996     Move m = pv[0];
1997
1998     assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1999
2000     pv.clear();
2001     pv.push_back(m);
2002     pos.do_move(m, *st++);
2003
2004     while (   (tte = TT.probe(pos.get_key())) != NULL
2005            && tte->move() != MOVE_NONE
2006            && pos.is_pseudo_legal(tte->move())
2007            && pos.pl_move_is_legal(tte->move(), pos.pinned_pieces())
2008            && ply < PLY_MAX
2009            && (!pos.is_draw<false>() || ply < 2))
2010     {
2011         pv.push_back(tte->move());
2012         pos.do_move(tte->move(), *st++);
2013         ply++;
2014     }
2015     pv.push_back(MOVE_NONE);
2016
2017     do pos.undo_move(pv[--ply]); while (ply);
2018   }
2019
2020
2021   // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2022   // the PV back into the TT. This makes sure the old PV moves are searched
2023   // first, even if the old TT entries have been overwritten.
2024
2025   void RootMove::insert_pv_in_tt(Position& pos) {
2026
2027     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2028     TTEntry* tte;
2029     Key k;
2030     Value v, m = VALUE_NONE;
2031     int ply = 0;
2032
2033     assert(pv[0] != MOVE_NONE && pos.is_pseudo_legal(pv[0]));
2034
2035     do {
2036         k = pos.get_key();
2037         tte = TT.probe(k);
2038
2039         // Don't overwrite existing correct entries
2040         if (!tte || tte->move() != pv[ply])
2041         {
2042             v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
2043             TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2044         }
2045         pos.do_move(pv[ply], *st++);
2046
2047     } while (pv[++ply] != MOVE_NONE);
2048
2049     do pos.undo_move(pv[--ply]); while (ply);
2050   }
2051
2052 } // namespace
2053
2054
2055 // Thread::idle_loop() is where the thread is parked when it has no work to do.
2056 // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint object
2057 // for which the thread is the master.
2058
2059 void Thread::idle_loop(SplitPoint* sp) {
2060
2061   while (true)
2062   {
2063       // If we are not searching, wait for a condition to be signaled
2064       // instead of wasting CPU time polling for work.
2065       while (   do_sleep
2066              || do_terminate
2067              || (Threads.use_sleeping_threads() && !is_searching))
2068       {
2069           assert((!sp && threadID) || Threads.use_sleeping_threads());
2070
2071           // Slave thread should exit as soon as do_terminate flag raises
2072           if (do_terminate)
2073           {
2074               assert(!sp);
2075               return;
2076           }
2077
2078           // Grab the lock to avoid races with Thread::wake_up()
2079           lock_grab(&sleepLock);
2080
2081           // If we are master and all slaves have finished don't go to sleep
2082           if (sp && Threads.split_point_finished(sp))
2083           {
2084               lock_release(&sleepLock);
2085               break;
2086           }
2087
2088           // Do sleep after retesting sleep conditions under lock protection, in
2089           // particular we need to avoid a deadlock in case a master thread has,
2090           // in the meanwhile, allocated us and sent the wake_up() call before we
2091           // had the chance to grab the lock.
2092           if (do_sleep || !is_searching)
2093               cond_wait(&sleepCond, &sleepLock);
2094
2095           lock_release(&sleepLock);
2096       }
2097
2098       // If this thread has been assigned work, launch a search
2099       if (is_searching)
2100       {
2101           assert(!do_terminate);
2102
2103           // Copy split point position and search stack and call search()
2104           SearchStack ss[PLY_MAX_PLUS_2];
2105           SplitPoint* tsp = splitPoint;
2106           Position pos(*tsp->pos, threadID);
2107
2108           memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2109           (ss+1)->sp = tsp;
2110
2111           if (tsp->nodeType == Root)
2112               search<SplitPointRoot>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2113           else if (tsp->nodeType == PV)
2114               search<SplitPointPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2115           else if (tsp->nodeType == NonPV)
2116               search<SplitPointNonPV>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2117           else
2118               assert(false);
2119
2120           assert(is_searching);
2121
2122           is_searching = false;
2123
2124           // Wake up master thread so to allow it to return from the idle loop in
2125           // case we are the last slave of the split point.
2126           if (   Threads.use_sleeping_threads()
2127               && threadID != tsp->master
2128               && !Threads[tsp->master].is_searching)
2129               Threads[tsp->master].wake_up();
2130       }
2131
2132       // If this thread is the master of a split point and all slaves have
2133       // finished their work at this split point, return from the idle loop.
2134       if (sp && Threads.split_point_finished(sp))
2135       {
2136           // Because sp->is_slave[] is reset under lock protection,
2137           // be sure sp->lock has been released before to return.
2138           lock_grab(&(sp->lock));
2139           lock_release(&(sp->lock));
2140           return;
2141       }
2142   }
2143 }
2144
2145
2146 // do_timer_event() is called by the timer thread when the timer triggers
2147
2148 void do_timer_event() {
2149
2150   static int lastInfoTime;
2151   int e = elapsed_time();
2152
2153   // Print debug information every one second
2154   if (!lastInfoTime || get_system_time() - lastInfoTime >= 1000)
2155   {
2156       lastInfoTime = get_system_time();
2157
2158       dbg_print_mean();
2159       dbg_print_hit_rate();
2160   }
2161
2162   // Should we stop the search?
2163   if (Limits.ponder)
2164       return;
2165
2166   bool stillAtFirstMove =    Signals.firstRootMove
2167                          && !Signals.failedLowAtRoot
2168                          &&  e > TimeMgr.available_time();
2169
2170   bool noMoreTime =   e > TimeMgr.maximum_time()
2171                    || stillAtFirstMove;
2172
2173   if (   (Limits.useTimeManagement() && noMoreTime)
2174       || (Limits.maxTime && e >= Limits.maxTime)
2175          /* missing nodes limit */ ) // FIXME
2176       Signals.stop = true;
2177 }