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