]> git.sesse.net Git - stockfish/blob - src/search.cpp
461c057790e18beed7d88940c9df5cbc8626a29a
[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 <fstream>
24 #include <iostream>
25 #include <sstream>
26 #include <vector>
27
28 #include "book.h"
29 #include "evaluate.h"
30 #include "history.h"
31 #include "misc.h"
32 #include "move.h"
33 #include "movegen.h"
34 #include "movepick.h"
35 #include "lock.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
45 namespace {
46
47   // Different node types, used as template parameter
48   enum NodeType { NonPV, PV };
49
50   // Set to true to force running with one thread. Used for debugging.
51   const bool FakeSplit = false;
52
53   // Lookup table to check if a Piece is a slider and its access function
54   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
55   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
56
57   // ThreadsManager class is used to handle all the threads related stuff like init,
58   // starting, parking and, the most important, launching a slave thread at a split
59   // point. All the access to shared thread data is done through this class.
60
61   class ThreadsManager {
62     /* As long as the single ThreadsManager object is defined as a global we don't
63        need to explicitly initialize to zero its data members because variables with
64        static storage duration are automatically set to zero before enter main()
65     */
66   public:
67     Thread& operator[](int threadID) { return threads[threadID]; }
68     void init_threads();
69     void exit_threads();
70
71     int min_split_depth() const { return minimumSplitDepth; }
72     int active_threads() const { return activeThreads; }
73     void set_active_threads(int cnt) { activeThreads = cnt; }
74
75     void read_uci_options();
76     bool available_thread_exists(int master) const;
77     bool thread_is_available(int slave, int master) const;
78     bool cutoff_at_splitpoint(int threadID) const;
79     void idle_loop(int threadID, SplitPoint* sp);
80
81     template <bool Fake>
82     void split(Position& pos, SearchStack* ss, Value* alpha, const Value beta, Value* bestValue,
83                Depth depth, Move threatMove, int moveCount, MovePicker* mp, bool pvNode);
84   private:
85     Lock mpLock;
86     Depth minimumSplitDepth;
87     int maxThreadsPerSplitPoint;
88     bool useSleepingThreads;
89     int activeThreads;
90     volatile bool allThreadsShouldExit;
91     Thread threads[MAX_THREADS];
92   };
93
94
95   // RootMove struct is used for moves at the root of the tree. For each root
96   // move, we store two scores, a node count, and a PV (really a refutation
97   // in the case of moves which fail low). Value pv_score is normally set at
98   // -VALUE_INFINITE for all non-pv moves, while non_pv_score is computed
99   // according to the order in which moves are returned by MovePicker.
100
101   struct RootMove {
102
103     RootMove();
104     RootMove(const RootMove& rm) { *this = rm; }
105     RootMove& operator=(const RootMove& rm);
106
107     // RootMove::operator<() is the comparison function used when
108     // sorting the moves. A move m1 is considered to be better
109     // than a move m2 if it has an higher pv_score, or if it has
110     // equal pv_score but m1 has the higher non_pv_score. In this way
111     // we are guaranteed that PV moves are always sorted as first.
112     bool operator<(const RootMove& m) const {
113       return pv_score != m.pv_score ? pv_score < m.pv_score
114                                     : non_pv_score < m.non_pv_score;
115     }
116
117     void extract_pv_from_tt(Position& pos);
118     void insert_pv_in_tt(Position& pos);
119     std::string pv_info_to_uci(Position& pos, int depth, int selDepth, Value alpha, Value beta, int pvIdx);
120
121     int64_t nodes;
122     Value pv_score;
123     Value non_pv_score;
124     Move pv[PLY_MAX_PLUS_2];
125   };
126
127
128   // RootMoveList struct is just a std::vector<> of RootMove objects,
129   // with an handful of methods above the standard ones.
130
131   struct RootMoveList : public std::vector<RootMove> {
132
133     typedef std::vector<RootMove> Base;
134
135     void init(Position& pos, Move searchMoves[]);
136     void sort() { insertion_sort<RootMove, Base::iterator>(begin(), end()); }
137     void sort_multipv(int n) { insertion_sort<RootMove, Base::iterator>(begin(), begin() + n); }
138
139     int bestMoveChanges;
140   };
141
142
143   // Overload operator<<() to make it easier to print moves in a coordinate
144   // notation compatible with UCI protocol.
145   std::ostream& operator<<(std::ostream& os, Move m) {
146
147     bool chess960 = (os.iword(0) != 0); // See set960()
148     return os << move_to_uci(m, chess960);
149   }
150
151
152   // When formatting a move for std::cout we must know if we are in Chess960
153   // or not. To keep using the handy operator<<() on the move the trick is to
154   // embed this flag in the stream itself. Function-like named enum set960 is
155   // used as a custom manipulator and the stream internal general-purpose array,
156   // accessed through ios_base::iword(), is used to pass the flag to the move's
157   // operator<<() that will read it to properly format castling moves.
158   enum set960 {};
159
160   std::ostream& operator<< (std::ostream& os, const set960& f) {
161
162     os.iword(0) = int(f);
163     return os;
164   }
165
166
167   /// Adjustments
168
169   // Step 6. Razoring
170
171   // Maximum depth for razoring
172   const Depth RazorDepth = 4 * ONE_PLY;
173
174   // Dynamic razoring margin based on depth
175   inline Value razor_margin(Depth d) { return Value(0x200 + 0x10 * int(d)); }
176
177   // Maximum depth for use of dynamic threat detection when null move fails low
178   const Depth ThreatDepth = 5 * ONE_PLY;
179
180   // Step 9. Internal iterative deepening
181
182   // Minimum depth for use of internal iterative deepening
183   const Depth IIDDepth[2] = { 8 * ONE_PLY /* non-PV */, 5 * ONE_PLY /* PV */};
184
185   // At Non-PV nodes we do an internal iterative deepening search
186   // when the static evaluation is bigger then beta - IIDMargin.
187   const Value IIDMargin = Value(0x100);
188
189   // Step 11. Decide the new search depth
190
191   // Extensions. Configurable UCI options
192   // Array index 0 is used at non-PV nodes, index 1 at PV nodes.
193   Depth CheckExtension[2], PawnPushTo7thExtension[2];
194   Depth PassedPawnExtension[2], PawnEndgameExtension[2];
195
196   // Minimum depth for use of singular extension
197   const Depth SingularExtensionDepth[2] = { 8 * ONE_PLY /* non-PV */, 6 * ONE_PLY /* PV */};
198
199   // Step 12. Futility pruning
200
201   // Futility margin for quiescence search
202   const Value FutilityMarginQS = Value(0x80);
203
204   // Futility lookup tables (initialized at startup) and their access functions
205   Value FutilityMarginsMatrix[16][64]; // [depth][moveNumber]
206   int FutilityMoveCountArray[32]; // [depth]
207
208   inline Value futility_margin(Depth d, int mn) { return d < 7 * ONE_PLY ? FutilityMarginsMatrix[Max(d, 1)][Min(mn, 63)] : 2 * VALUE_INFINITE; }
209   inline int futility_move_count(Depth d) { return d < 16 * ONE_PLY ? FutilityMoveCountArray[d] : 512; }
210
211   // Step 14. Reduced search
212
213   // Reduction lookup tables (initialized at startup) and their getter functions
214   int8_t ReductionMatrix[2][64][64]; // [pv][depth][moveNumber]
215
216   template <NodeType PV>
217   inline Depth reduction(Depth d, int mn) { return (Depth) ReductionMatrix[PV][Min(d / ONE_PLY, 63)][Min(mn, 63)]; }
218
219   // Easy move margin. An easy move candidate must be at least this much
220   // better than the second best move.
221   const Value EasyMoveMargin = Value(0x200);
222
223
224   /// Namespace variables
225
226   // Book
227   Book OpeningBook;
228
229   // Root move list
230   RootMoveList Rml;
231
232   // MultiPV mode
233   int MultiPV, UCIMultiPV;
234
235   // Time management variables
236   int MaxNodes, MaxDepth, ExactMaxTime;
237   bool UseTimeManagement, InfiniteSearch, Pondering, StopOnPonderhit;
238   bool FirstRootMove, StopRequest, QuitRequest, AspirationFailLow;
239   TimeManager TimeMgr;
240
241   // Log file
242   bool UseLogFile;
243   std::ofstream LogFile;
244
245   // Skill level adjustment
246   int SkillLevel;
247   bool SkillLevelEnabled;
248   RKISS RK;
249
250   // Multi-threads manager
251   ThreadsManager ThreadsMgr;
252
253   // Node counters, used only by thread[0] but try to keep in different cache
254   // lines (64 bytes each) from the heavy multi-thread read accessed variables.
255   bool SendSearchedNodes;
256   int NodesSincePoll;
257   int NodesBetweenPolls = 30000;
258
259   // History table
260   History H;
261
262
263   /// Local functions
264
265   Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove);
266
267   template <NodeType PvNode, bool SpNode, bool Root>
268   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
269
270   template <NodeType PvNode>
271   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth);
272
273   template <NodeType PvNode>
274   inline Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
275
276     return depth < ONE_PLY ? qsearch<PvNode>(pos, ss, alpha, beta, DEPTH_ZERO)
277                            : search<PvNode, false, false>(pos, ss, alpha, beta, depth);
278   }
279
280   template <NodeType PvNode>
281   Depth extension(const Position& pos, Move m, bool captureOrPromotion, bool moveIsCheck, bool* dangerous);
282
283   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bValue);
284   bool connected_moves(const Position& pos, Move m1, Move m2);
285   Value value_to_tt(Value v, int ply);
286   Value value_from_tt(Value v, int ply);
287   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
288   bool connected_threat(const Position& pos, Move m, Move threat);
289   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply);
290   void update_history(const Position& pos, Move move, Depth depth, Move movesSearched[], int moveCount);
291   void update_gains(const Position& pos, Move move, Value before, Value after);
292   void do_skill_level(Move* best, Move* ponder);
293
294   int current_search_time(int set = 0);
295   std::string value_to_uci(Value v);
296   std::string speed_to_uci(int64_t nodes);
297   void poll(const Position& pos);
298   void wait_for_stop_or_ponderhit();
299
300 #if !defined(_MSC_VER)
301   void* init_thread(void* threadID);
302 #else
303   DWORD WINAPI init_thread(LPVOID threadID);
304 #endif
305
306
307   // MovePickerExt is an extended MovePicker used to choose at compile time
308   // the proper move source according to the type of node.
309   template<bool SpNode, bool Root> struct MovePickerExt;
310
311   // In Root nodes use RootMoveList as source. Score and sort the root moves
312   // before to search them.
313   template<> struct MovePickerExt<false, true> : public MovePicker {
314
315     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
316                  : MovePicker(p, ttm, d, h, ss, b), firstCall(true) {
317       Move move;
318       Value score = VALUE_ZERO;
319
320       // Score root moves using standard ordering used in main search, the moves
321       // are scored according to the order in which they are returned by MovePicker.
322       // This is the second order score that is used to compare the moves when
323       // the first orders pv_score of both moves are equal.
324       while ((move = MovePicker::get_next_move()) != MOVE_NONE)
325           for (rm = Rml.begin(); rm != Rml.end(); ++rm)
326               if (rm->pv[0] == move)
327               {
328                   rm->non_pv_score = score--;
329                   break;
330               }
331
332       Rml.sort();
333       rm = Rml.begin();
334     }
335
336     Move get_next_move() {
337
338       if (!firstCall)
339           ++rm;
340       else
341           firstCall = false;
342
343       return rm != Rml.end() ? rm->pv[0] : MOVE_NONE;
344     }
345
346     RootMoveList::iterator rm;
347     bool firstCall;
348   };
349
350   // In SpNodes use split point's shared MovePicker object as move source
351   template<> struct MovePickerExt<true, false> : public MovePicker {
352
353     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
354                   : MovePicker(p, ttm, d, h, ss, b), mp(ss->sp->mp) {}
355
356     Move get_next_move() { return mp->get_next_move(); }
357
358     RootMoveList::iterator rm; // Dummy, needed to compile
359     MovePicker* mp;
360   };
361
362   // Default case, create and use a MovePicker object as source
363   template<> struct MovePickerExt<false, false> : public MovePicker {
364
365     MovePickerExt(const Position& p, Move ttm, Depth d, const History& h, SearchStack* ss, Value b)
366                   : MovePicker(p, ttm, d, h, ss, b) {}
367
368     RootMoveList::iterator rm; // Dummy, needed to compile
369   };
370
371 } // namespace
372
373
374 /// init_threads() is called during startup. It initializes various lookup tables
375 /// and creates and launches search threads.
376
377 void init_threads() {
378
379   int d;  // depth (ONE_PLY == 2)
380   int hd; // half depth (ONE_PLY == 1)
381   int mc; // moveCount
382
383   // Init reductions array
384   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
385   {
386       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
387       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
388       ReductionMatrix[PV][hd][mc]    = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
389       ReductionMatrix[NonPV][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
390   }
391
392   // Init futility margins array
393   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
394       FutilityMarginsMatrix[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
395
396   // Init futility move count array
397   for (d = 0; d < 32; d++)
398       FutilityMoveCountArray[d] = int(3.001 + 0.25 * pow(d, 2.0));
399
400   // Create and startup threads
401   ThreadsMgr.init_threads();
402 }
403
404
405 /// exit_threads() is a trampoline to access ThreadsMgr from outside of current file
406 void exit_threads() { ThreadsMgr.exit_threads(); }
407
408
409 /// perft() is our utility to verify move generation. All the legal moves up to
410 /// given depth are generated and counted and the sum returned.
411
412 int64_t perft(Position& pos, Depth depth) {
413
414   MoveStack mlist[MOVES_MAX];
415   StateInfo st;
416   Move m;
417   int64_t sum = 0;
418
419   // Generate all legal moves
420   MoveStack* last = generate<MV_LEGAL>(pos, mlist);
421
422   // If we are at the last ply we don't need to do and undo
423   // the moves, just to count them.
424   if (depth <= ONE_PLY)
425       return int(last - mlist);
426
427   // Loop through all legal moves
428   CheckInfo ci(pos);
429   for (MoveStack* cur = mlist; cur != last; cur++)
430   {
431       m = cur->move;
432       pos.do_move(m, st, ci, pos.move_is_check(m, ci));
433       sum += perft(pos, depth - ONE_PLY);
434       pos.undo_move(m);
435   }
436   return sum;
437 }
438
439
440 /// think() is the external interface to Stockfish's search, and is called when
441 /// the program receives the UCI 'go' command. It initializes various global
442 /// variables, and calls id_loop(). It returns false when a quit command is
443 /// received during the search.
444
445 bool think(Position& pos, bool infinite, bool ponder, int time[], int increment[],
446            int movesToGo, int maxDepth, int maxNodes, int maxTime, Move searchMoves[]) {
447
448   // Initialize global search-related variables
449   StopOnPonderhit = StopRequest = QuitRequest = AspirationFailLow = SendSearchedNodes = false;
450   NodesSincePoll = 0;
451   current_search_time(get_system_time());
452   ExactMaxTime = maxTime;
453   MaxDepth = maxDepth;
454   MaxNodes = maxNodes;
455   InfiniteSearch = infinite;
456   Pondering = ponder;
457   UseTimeManagement = !ExactMaxTime && !MaxDepth && !MaxNodes && !InfiniteSearch;
458
459   // Look for a book move, only during games, not tests
460   if (UseTimeManagement && Options["OwnBook"].value<bool>())
461   {
462       if (Options["Book File"].value<std::string>() != OpeningBook.name())
463           OpeningBook.open(Options["Book File"].value<std::string>());
464
465       Move bookMove = OpeningBook.get_move(pos, Options["Best Book Move"].value<bool>());
466       if (bookMove != MOVE_NONE)
467       {
468           if (Pondering)
469               wait_for_stop_or_ponderhit();
470
471           cout << "bestmove " << bookMove << endl;
472           return !QuitRequest;
473       }
474   }
475
476   // Read UCI options
477   CheckExtension[1]         = Options["Check Extension (PV nodes)"].value<Depth>();
478   CheckExtension[0]         = Options["Check Extension (non-PV nodes)"].value<Depth>();
479   PawnPushTo7thExtension[1] = Options["Pawn Push to 7th Extension (PV nodes)"].value<Depth>();
480   PawnPushTo7thExtension[0] = Options["Pawn Push to 7th Extension (non-PV nodes)"].value<Depth>();
481   PassedPawnExtension[1]    = Options["Passed Pawn Extension (PV nodes)"].value<Depth>();
482   PassedPawnExtension[0]    = Options["Passed Pawn Extension (non-PV nodes)"].value<Depth>();
483   PawnEndgameExtension[1]   = Options["Pawn Endgame Extension (PV nodes)"].value<Depth>();
484   PawnEndgameExtension[0]   = Options["Pawn Endgame Extension (non-PV nodes)"].value<Depth>();
485   UCIMultiPV                = Options["MultiPV"].value<int>();
486   SkillLevel                = Options["Skill level"].value<int>();
487   UseLogFile                = Options["Use Search Log"].value<bool>();
488
489   read_evaluation_uci_options(pos.side_to_move());
490
491   if (Options["Clear Hash"].value<bool>())
492   {
493       Options["Clear Hash"].set_value("false");
494       TT.clear();
495   }
496   TT.set_size(Options["Hash"].value<int>());
497
498   // Do we have to play with skill handicap? In this case enable MultiPV that
499   // we will use behind the scenes to retrieve a set of possible moves.
500   SkillLevelEnabled = (SkillLevel < 20);
501   MultiPV = (SkillLevelEnabled ? Max(UCIMultiPV, 4) : UCIMultiPV);
502
503   // Set the number of active threads
504   ThreadsMgr.read_uci_options();
505   init_eval(ThreadsMgr.active_threads());
506
507   // Wake up needed threads and reset maxPly counter
508   for (int i = 0; i < ThreadsMgr.active_threads(); i++)
509   {
510       ThreadsMgr[i].wake_up();
511       ThreadsMgr[i].maxPly = 0;
512   }
513
514   // Set thinking time
515   int myTime = time[pos.side_to_move()];
516   int myIncrement = increment[pos.side_to_move()];
517   if (UseTimeManagement)
518       TimeMgr.init(myTime, myIncrement, movesToGo, pos.startpos_ply_counter());
519
520   // Set best NodesBetweenPolls interval to avoid lagging under time pressure
521   if (MaxNodes)
522       NodesBetweenPolls = Min(MaxNodes, 30000);
523   else if (myTime && myTime < 1000)
524       NodesBetweenPolls = 1000;
525   else if (myTime && myTime < 5000)
526       NodesBetweenPolls = 5000;
527   else
528       NodesBetweenPolls = 30000;
529
530   // Write search information to log file
531   if (UseLogFile)
532   {
533       std::string name = Options["Search Log Filename"].value<std::string>();
534       LogFile.open(name.c_str(), std::ios::out | std::ios::app);
535
536       LogFile << "\nSearching: "  << pos.to_fen()
537               << "\ninfinite: "   << infinite
538               << " ponder: "      << ponder
539               << " time: "        << myTime
540               << " increment: "   << myIncrement
541               << " moves to go: " << movesToGo
542               << endl;
543   }
544
545   // We're ready to start thinking. Call the iterative deepening loop function
546   Move ponderMove = MOVE_NONE;
547   Move bestMove = id_loop(pos, searchMoves, &ponderMove);
548
549   // Print final search statistics
550   cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
551
552   if (UseLogFile)
553   {
554       int t = current_search_time();
555
556       LogFile << "Nodes: "          << pos.nodes_searched()
557               << "\nNodes/second: " << (t > 0 ? int(pos.nodes_searched() * 1000 / t) : 0)
558               << "\nBest move: "    << move_to_san(pos, bestMove);
559
560       StateInfo st;
561       pos.do_move(bestMove, st);
562       LogFile << "\nPonder move: " << move_to_san(pos, ponderMove) << endl;
563       pos.undo_move(bestMove); // Return from think() with unchanged position
564       LogFile.close();
565   }
566
567   // This makes all the threads to go to sleep
568   ThreadsMgr.set_active_threads(1);
569
570   // If we are pondering or in infinite search, we shouldn't print the
571   // best move before we are told to do so.
572   if (!StopRequest && (Pondering || InfiniteSearch))
573       wait_for_stop_or_ponderhit();
574
575   // Could be MOVE_NONE when searching on a stalemate position
576   cout << "bestmove " << bestMove;
577
578   // UCI protol is not clear on allowing sending an empty ponder move, instead
579   // it is clear that ponder move is optional. So skip it if empty.
580   if (ponderMove != MOVE_NONE)
581       cout << " ponder " << ponderMove;
582
583   cout << endl;
584
585   return !QuitRequest;
586 }
587
588
589 namespace {
590
591   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
592   // with increasing depth until the allocated thinking time has been consumed,
593   // user stops the search, or the maximum search depth is reached.
594
595   Move id_loop(Position& pos, Move searchMoves[], Move* ponderMove) {
596
597     SearchStack ss[PLY_MAX_PLUS_2];
598     Value bestValues[PLY_MAX_PLUS_2];
599     int bestMoveChanges[PLY_MAX_PLUS_2];
600     int depth, selDepth, aspirationDelta;
601     Value value, alpha, beta;
602     Move bestMove, easyMove, skillBest, skillPonder;
603
604     // Initialize stuff before a new search
605     memset(ss, 0, 4 * sizeof(SearchStack));
606     TT.new_search();
607     H.clear();
608     *ponderMove = bestMove = easyMove = skillBest = skillPonder = MOVE_NONE;
609     depth = aspirationDelta = 0;
610     alpha = -VALUE_INFINITE, beta = VALUE_INFINITE;
611     ss->currentMove = MOVE_NULL; // Hack to skip update_gains()
612
613     // Moves to search are verified and copied
614     Rml.init(pos, searchMoves);
615
616     // Handle special case of searching on a mate/stalemate position
617     if (Rml.size() == 0)
618     {
619         cout << "info depth 0 score "
620              << value_to_uci(pos.is_check() ? -VALUE_MATE : VALUE_DRAW)
621              << endl;
622
623         return MOVE_NONE;
624     }
625
626     // Iterative deepening loop
627     while (++depth <= PLY_MAX && (!MaxDepth || depth <= MaxDepth) && !StopRequest)
628     {
629         Rml.bestMoveChanges = 0;
630         cout << set960(pos.is_chess960()) << "info depth " << depth << endl;
631
632         // Calculate dynamic aspiration window based on previous iterations
633         if (MultiPV == 1 && depth >= 5 && abs(bestValues[depth - 1]) < VALUE_KNOWN_WIN)
634         {
635             int prevDelta1 = bestValues[depth - 1] - bestValues[depth - 2];
636             int prevDelta2 = bestValues[depth - 2] - bestValues[depth - 3];
637
638             aspirationDelta = Min(Max(abs(prevDelta1) + abs(prevDelta2) / 2, 16), 24);
639             aspirationDelta = (aspirationDelta + 7) / 8 * 8; // Round to match grainSize
640
641             alpha = Max(bestValues[depth - 1] - aspirationDelta, -VALUE_INFINITE);
642             beta  = Min(bestValues[depth - 1] + aspirationDelta,  VALUE_INFINITE);
643         }
644
645         // Start with a small aspiration window and, in case of fail high/low,
646         // research with bigger window until not failing high/low anymore.
647         do {
648             // Search starting from ss+1 to allow calling update_gains()
649             value = search<PV, false, true>(pos, ss+1, alpha, beta, depth * ONE_PLY);
650
651             // Write PV back to transposition table in case the relevant entries
652             // have been overwritten during the search.
653             for (int i = 0; i < Min(MultiPV, (int)Rml.size()); i++)
654                 Rml[i].insert_pv_in_tt(pos);
655
656             // Value cannot be trusted. Break out immediately!
657             if (StopRequest)
658                 break;
659
660             assert(value >= alpha);
661
662             // In case of failing high/low increase aspiration window and research,
663             // otherwise exit the fail high/low loop.
664             if (value >= beta)
665             {
666                 beta = Min(beta + aspirationDelta, VALUE_INFINITE);
667                 aspirationDelta += aspirationDelta / 2;
668             }
669             else if (value <= alpha)
670             {
671                 AspirationFailLow = true;
672                 StopOnPonderhit = false;
673
674                 alpha = Max(alpha - aspirationDelta, -VALUE_INFINITE);
675                 aspirationDelta += aspirationDelta / 2;
676             }
677             else
678                 break;
679
680         } while (abs(value) < VALUE_KNOWN_WIN);
681
682         // Collect info about search result
683         bestMove = Rml[0].pv[0];
684         *ponderMove = Rml[0].pv[1];
685         bestValues[depth] = value;
686         bestMoveChanges[depth] = Rml.bestMoveChanges;
687
688         // Do we need to pick now the best and the ponder moves ?
689         if (SkillLevelEnabled && depth == 1 + SkillLevel)
690             do_skill_level(&skillBest, &skillPonder);
691
692         // Retrieve max searched depth among threads
693         selDepth = 0;
694         for (int i = 0; i < ThreadsMgr.active_threads(); i++)
695             if (ThreadsMgr[i].maxPly > selDepth)
696                 selDepth = ThreadsMgr[i].maxPly;
697
698         // Send PV line to GUI and to log file
699         for (int i = 0; i < Min(UCIMultiPV, (int)Rml.size()); i++)
700             cout << Rml[i].pv_info_to_uci(pos, depth, selDepth, alpha, beta, i) << endl;
701
702         if (UseLogFile)
703             LogFile << pretty_pv(pos, depth, value, current_search_time(), Rml[0].pv) << endl;
704
705         // Init easyMove after first iteration or drop if differs from the best move
706         if (depth == 1 && (Rml.size() == 1 || Rml[0].pv_score > Rml[1].pv_score + EasyMoveMargin))
707             easyMove = bestMove;
708         else if (bestMove != easyMove)
709             easyMove = MOVE_NONE;
710
711         if (UseTimeManagement && !StopRequest)
712         {
713             // Time to stop?
714             bool noMoreTime = false;
715
716             // Stop search early when the last two iterations returned a mate score
717             if (   depth >= 5
718                 && abs(bestValues[depth])     >= abs(VALUE_MATE) - 100
719                 && abs(bestValues[depth - 1]) >= abs(VALUE_MATE) - 100)
720                 noMoreTime = true;
721
722             // Stop search early if one move seems to be much better than the
723             // others or if there is only a single legal move. In this latter
724             // case we search up to Iteration 8 anyway to get a proper score.
725             if (   depth >= 7
726                 && easyMove == bestMove
727                 && (   Rml.size() == 1
728                     ||(   Rml[0].nodes > (pos.nodes_searched() * 85) / 100
729                        && current_search_time() > TimeMgr.available_time() / 16)
730                     ||(   Rml[0].nodes > (pos.nodes_searched() * 98) / 100
731                        && current_search_time() > TimeMgr.available_time() / 32)))
732                 noMoreTime = true;
733
734             // Add some extra time if the best move has changed during the last two iterations
735             if (depth > 4 && depth < 50)
736                 TimeMgr.pv_instability(bestMoveChanges[depth], bestMoveChanges[depth-1]);
737
738             // Stop search if most of MaxSearchTime is consumed at the end of the
739             // iteration. We probably don't have enough time to search the first
740             // move at the next iteration anyway.
741             if (current_search_time() > (TimeMgr.available_time() * 80) / 128)
742                 noMoreTime = true;
743
744             if (noMoreTime)
745             {
746                 if (Pondering)
747                     StopOnPonderhit = true;
748                 else
749                     break;
750             }
751         }
752     }
753
754     // When using skills fake best and ponder moves with the sub-optimal ones
755     if (SkillLevelEnabled)
756     {
757         if (skillBest == MOVE_NONE) // Still unassigned ?
758             do_skill_level(&skillBest, &skillPonder);
759
760         bestMove = skillBest;
761         *ponderMove = skillPonder;
762     }
763
764     return bestMove;
765   }
766
767
768   // search<>() is the main search function for both PV and non-PV nodes and for
769   // normal and SplitPoint nodes. When called just after a split point the search
770   // is simpler because we have already probed the hash table, done a null move
771   // search, and searched the first move before splitting, we don't have to repeat
772   // all this work again. We also don't need to store anything to the hash table
773   // here: This is taken care of after we return from the split point.
774
775   template <NodeType PvNode, bool SpNode, bool Root>
776   Value search(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
777
778     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
779     assert(beta > alpha && beta <= VALUE_INFINITE);
780     assert(PvNode || alpha == beta - 1);
781     assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
782
783     Move movesSearched[MOVES_MAX];
784     int64_t nodes;
785     StateInfo st;
786     const TTEntry *tte;
787     Key posKey;
788     Move ttMove, move, excludedMove, threatMove;
789     Depth ext, newDepth;
790     ValueType vt;
791     Value bestValue, value, oldAlpha;
792     Value refinedValue, nullValue, futilityBase, futilityValueScaled; // Non-PV specific
793     bool isPvMove, isCheck, singularExtensionNode, moveIsCheck, captureOrPromotion, dangerous, isBadCap;
794     int moveCount = 0, playedMoveCount = 0;
795     int threadID = pos.thread();
796     SplitPoint* sp = NULL;
797
798     refinedValue = bestValue = value = -VALUE_INFINITE;
799     oldAlpha = alpha;
800     isCheck = pos.is_check();
801     ss->ply = (ss-1)->ply + 1;
802
803     // Used to send selDepth info to GUI
804     if (PvNode && ThreadsMgr[threadID].maxPly < ss->ply)
805         ThreadsMgr[threadID].maxPly = ss->ply;
806
807     if (SpNode)
808     {
809         sp = ss->sp;
810         tte = NULL;
811         ttMove = excludedMove = MOVE_NONE;
812         threatMove = sp->threatMove;
813         goto split_point_start;
814     }
815     else if (Root)
816         bestValue = alpha;
817
818     // Step 1. Initialize node and poll. Polling can abort search
819     ss->currentMove = ss->bestMove = threatMove = (ss+1)->excludedMove = MOVE_NONE;
820     (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
821     (ss+2)->killers[0] = (ss+2)->killers[1] = (ss+2)->mateKiller = MOVE_NONE;
822
823     if (threadID == 0 && ++NodesSincePoll > NodesBetweenPolls)
824     {
825         NodesSincePoll = 0;
826         poll(pos);
827     }
828
829     // Step 2. Check for aborted search and immediate draw
830     if ((   StopRequest
831          || ThreadsMgr.cutoff_at_splitpoint(threadID)
832          || pos.is_draw()
833          || ss->ply > PLY_MAX) && !Root)
834         return VALUE_DRAW;
835
836     // Step 3. Mate distance pruning
837     alpha = Max(value_mated_in(ss->ply), alpha);
838     beta = Min(value_mate_in(ss->ply+1), beta);
839     if (alpha >= beta)
840         return alpha;
841
842     // Step 4. Transposition table lookup
843     // We don't want the score of a partial search to overwrite a previous full search
844     // TT value, so we use a different position key in case of an excluded move.
845     excludedMove = ss->excludedMove;
846     posKey = excludedMove ? pos.get_exclusion_key() : pos.get_key();
847
848     tte = TT.retrieve(posKey);
849     ttMove = tte ? tte->move() : MOVE_NONE;
850
851     // At PV nodes we check for exact scores, while at non-PV nodes we check for
852     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
853     // smooth experience in analysis mode.
854     if (   !Root
855         && tte
856         && (PvNode ? tte->depth() >= depth && tte->type() == VALUE_TYPE_EXACT
857                    : ok_to_use_TT(tte, depth, beta, ss->ply)))
858     {
859         TT.refresh(tte);
860         ss->bestMove = ttMove; // Can be MOVE_NONE
861         return value_from_tt(tte->value(), ss->ply);
862     }
863
864     // Step 5. Evaluate the position statically and update parent's gain statistics
865     if (isCheck)
866         ss->eval = ss->evalMargin = VALUE_NONE;
867     else if (tte)
868     {
869         assert(tte->static_value() != VALUE_NONE);
870
871         ss->eval = tte->static_value();
872         ss->evalMargin = tte->static_value_margin();
873         refinedValue = refine_eval(tte, ss->eval, ss->ply);
874     }
875     else
876     {
877         refinedValue = ss->eval = evaluate(pos, ss->evalMargin);
878         TT.store(posKey, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, MOVE_NONE, ss->eval, ss->evalMargin);
879     }
880
881     // Save gain for the parent non-capture move
882     update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
883
884     // Step 6. Razoring (is omitted in PV nodes)
885     if (   !PvNode
886         &&  depth < RazorDepth
887         && !isCheck
888         &&  refinedValue + razor_margin(depth) < beta
889         &&  ttMove == MOVE_NONE
890         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
891         && !pos.has_pawn_on_7th(pos.side_to_move()))
892     {
893         Value rbeta = beta - razor_margin(depth);
894         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
895         if (v < rbeta)
896             // Logically we should return (v + razor_margin(depth)), but
897             // surprisingly this did slightly weaker in tests.
898             return v;
899     }
900
901     // Step 7. Static null move pruning (is omitted in PV nodes)
902     // We're betting that the opponent doesn't have a move that will reduce
903     // the score by more than futility_margin(depth) if we do a null move.
904     if (   !PvNode
905         && !ss->skipNullMove
906         &&  depth < RazorDepth
907         && !isCheck
908         &&  refinedValue - futility_margin(depth, 0) >= beta
909         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
910         &&  pos.non_pawn_material(pos.side_to_move()))
911         return refinedValue - futility_margin(depth, 0);
912
913     // Step 8. Null move search with verification search (is omitted in PV nodes)
914     if (   !PvNode
915         && !ss->skipNullMove
916         &&  depth > ONE_PLY
917         && !isCheck
918         &&  refinedValue >= beta
919         &&  abs(beta) < VALUE_MATE_IN_PLY_MAX
920         &&  pos.non_pawn_material(pos.side_to_move()))
921     {
922         ss->currentMove = MOVE_NULL;
923
924         // Null move dynamic reduction based on depth
925         int R = 3 + (depth >= 5 * ONE_PLY ? depth / 8 : 0);
926
927         // Null move dynamic reduction based on value
928         if (refinedValue - PawnValueMidgame > beta)
929             R++;
930
931         pos.do_null_move(st);
932         (ss+1)->skipNullMove = true;
933         nullValue = -search<NonPV>(pos, ss+1, -beta, -alpha, depth-R*ONE_PLY);
934         (ss+1)->skipNullMove = false;
935         pos.undo_null_move();
936
937         if (nullValue >= beta)
938         {
939             // Do not return unproven mate scores
940             if (nullValue >= VALUE_MATE_IN_PLY_MAX)
941                 nullValue = beta;
942
943             if (depth < 6 * ONE_PLY)
944                 return nullValue;
945
946             // Do verification search at high depths
947             ss->skipNullMove = true;
948             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R*ONE_PLY);
949             ss->skipNullMove = false;
950
951             if (v >= beta)
952                 return nullValue;
953         }
954         else
955         {
956             // The null move failed low, which means that we may be faced with
957             // some kind of threat. If the previous move was reduced, check if
958             // the move that refuted the null move was somehow connected to the
959             // move which was reduced. If a connection is found, return a fail
960             // low score (which will cause the reduced move to fail high in the
961             // parent node, which will trigger a re-search with full depth).
962             threatMove = (ss+1)->bestMove;
963
964             if (   depth < ThreatDepth
965                 && (ss-1)->reduction
966                 && threatMove != MOVE_NONE
967                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
968                 return beta - 1;
969         }
970     }
971
972     // Step 9. Internal iterative deepening
973     if (   depth >= IIDDepth[PvNode]
974         && ttMove == MOVE_NONE
975         && (PvNode || (!isCheck && ss->eval + IIDMargin >= beta)))
976     {
977         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
978
979         ss->skipNullMove = true;
980         search<PvNode>(pos, ss, alpha, beta, d);
981         ss->skipNullMove = false;
982
983         ttMove = ss->bestMove;
984         tte = TT.retrieve(posKey);
985     }
986
987 split_point_start: // At split points actual search starts from here
988
989     // Initialize a MovePicker object for the current position
990     MovePickerExt<SpNode, Root> mp(pos, ttMove, depth, H, ss, (PvNode ? -VALUE_INFINITE : beta));
991     CheckInfo ci(pos);
992     ss->bestMove = MOVE_NONE;
993     futilityBase = ss->eval + ss->evalMargin;
994     singularExtensionNode =   !Root
995                            && !SpNode
996                            && depth >= SingularExtensionDepth[PvNode]
997                            && tte
998                            && tte->move()
999                            && !excludedMove // Do not allow recursive singular extension search
1000                            && (tte->type() & VALUE_TYPE_LOWER)
1001                            && tte->depth() >= depth - 3 * ONE_PLY;
1002     if (SpNode)
1003     {
1004         lock_grab(&(sp->lock));
1005         bestValue = sp->bestValue;
1006     }
1007
1008     // Step 10. Loop through moves
1009     // Loop through all legal moves until no moves remain or a beta cutoff occurs
1010     while (   bestValue < beta
1011            && (move = mp.get_next_move()) != MOVE_NONE
1012            && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1013     {
1014       assert(move_is_ok(move));
1015
1016       if (SpNode)
1017       {
1018           moveCount = ++sp->moveCount;
1019           lock_release(&(sp->lock));
1020       }
1021       else if (move == excludedMove)
1022           continue;
1023       else
1024           moveCount++;
1025
1026       if (Root)
1027       {
1028           // This is used by time management
1029           FirstRootMove = (moveCount == 1);
1030
1031           // Save the current node count before the move is searched
1032           nodes = pos.nodes_searched();
1033
1034           // If it's time to send nodes info, do it here where we have the
1035           // correct accumulated node counts searched by each thread.
1036           if (SendSearchedNodes)
1037           {
1038               SendSearchedNodes = false;
1039               cout << "info" << speed_to_uci(pos.nodes_searched()) << endl;
1040           }
1041
1042           if (current_search_time() > 2000)
1043               cout << "info currmove " << move
1044                    << " currmovenumber " << moveCount << endl;
1045       }
1046
1047       // At Root and at first iteration do a PV search on all the moves to score root moves
1048       isPvMove = (PvNode && moveCount <= (Root ? depth <= ONE_PLY ? 1000 : MultiPV : 1));
1049       moveIsCheck = pos.move_is_check(move, ci);
1050       captureOrPromotion = pos.move_is_capture_or_promotion(move);
1051
1052       // Step 11. Decide the new search depth
1053       ext = extension<PvNode>(pos, move, captureOrPromotion, moveIsCheck, &dangerous);
1054
1055       // Singular extension search. If all moves but one fail low on a search of
1056       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
1057       // is singular and should be extended. To verify this we do a reduced search
1058       // on all the other moves but the ttMove, if result is lower than ttValue minus
1059       // a margin then we extend ttMove.
1060       if (   singularExtensionNode
1061           && move == tte->move()
1062           && ext < ONE_PLY)
1063       {
1064           Value ttValue = value_from_tt(tte->value(), ss->ply);
1065
1066           if (abs(ttValue) < VALUE_KNOWN_WIN)
1067           {
1068               Value rBeta = ttValue - int(depth);
1069               ss->excludedMove = move;
1070               ss->skipNullMove = true;
1071               Value v = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
1072               ss->skipNullMove = false;
1073               ss->excludedMove = MOVE_NONE;
1074               ss->bestMove = MOVE_NONE;
1075               if (v < rBeta)
1076                   ext = ONE_PLY;
1077           }
1078       }
1079
1080       // Update current move (this must be done after singular extension search)
1081       ss->currentMove = move;
1082       newDepth = depth - ONE_PLY + ext;
1083
1084       // Step 12. Futility pruning (is omitted in PV nodes)
1085       if (   !PvNode
1086           && !captureOrPromotion
1087           && !isCheck
1088           && !dangerous
1089           &&  move != ttMove
1090           && !move_is_castle(move))
1091       {
1092           // Move count based pruning
1093           if (   moveCount >= futility_move_count(depth)
1094               && (!threatMove || !connected_threat(pos, move, threatMove))
1095               && bestValue > VALUE_MATED_IN_PLY_MAX) // FIXME bestValue is racy
1096           {
1097               if (SpNode)
1098                   lock_grab(&(sp->lock));
1099
1100               continue;
1101           }
1102
1103           // Value based pruning
1104           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
1105           // but fixing this made program slightly weaker.
1106           Depth predictedDepth = newDepth - reduction<NonPV>(depth, moveCount);
1107           futilityValueScaled =  futilityBase + futility_margin(predictedDepth, moveCount)
1108                                + H.gain(pos.piece_on(move_from(move)), move_to(move));
1109
1110           if (futilityValueScaled < beta)
1111           {
1112               if (SpNode)
1113               {
1114                   lock_grab(&(sp->lock));
1115                   if (futilityValueScaled > sp->bestValue)
1116                       sp->bestValue = bestValue = futilityValueScaled;
1117               }
1118               else if (futilityValueScaled > bestValue)
1119                   bestValue = futilityValueScaled;
1120
1121               continue;
1122           }
1123
1124           // Prune moves with negative SEE at low depths
1125           if (   predictedDepth < 2 * ONE_PLY
1126               && bestValue > VALUE_MATED_IN_PLY_MAX
1127               && pos.see_sign(move) < 0)
1128           {
1129               if (SpNode)
1130                   lock_grab(&(sp->lock));
1131
1132               continue;
1133           }
1134       }
1135
1136       // Bad capture detection. Will be used by prob-cut search
1137       isBadCap =   depth >= 3 * ONE_PLY
1138                 && depth < 8 * ONE_PLY
1139                 && captureOrPromotion
1140                 && move != ttMove
1141                 && !dangerous
1142                 && !move_is_promotion(move)
1143                 &&  abs(alpha) < VALUE_MATE_IN_PLY_MAX
1144                 &&  pos.see_sign(move) < 0;
1145
1146       // Step 13. Make the move
1147       pos.do_move(move, st, ci, moveIsCheck);
1148
1149       if (!SpNode && !captureOrPromotion)
1150           movesSearched[playedMoveCount++] = move;
1151
1152       // Step extra. pv search (only in PV nodes)
1153       // The first move in list is the expected PV
1154       if (isPvMove)
1155       {
1156           // Aspiration window is disabled in multi-pv case
1157           if (Root && MultiPV > 1)
1158               alpha = -VALUE_INFINITE;
1159
1160           value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1161       }
1162       else
1163       {
1164           // Step 14. Reduced depth search
1165           // If the move fails high will be re-searched at full depth.
1166           bool doFullDepthSearch = true;
1167           alpha = SpNode ? sp->alpha : alpha;
1168
1169           if (    depth >= 3 * ONE_PLY
1170               && !captureOrPromotion
1171               && !dangerous
1172               && !move_is_castle(move)
1173               &&  ss->killers[0] != move
1174               &&  ss->killers[1] != move)
1175           {
1176               ss->reduction = reduction<PvNode>(depth, moveCount);
1177               if (ss->reduction)
1178               {
1179                   alpha = SpNode ? sp->alpha : alpha;
1180                   Depth d = newDepth - ss->reduction;
1181                   value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
1182
1183                   doFullDepthSearch = (value > alpha);
1184               }
1185               ss->reduction = DEPTH_ZERO; // Restore original reduction
1186           }
1187
1188           // Probcut search for bad captures. If a reduced search returns a value
1189           // very below beta then we can (almost) safely prune the bad capture.
1190           if (isBadCap)
1191           {
1192               ss->reduction = 3 * ONE_PLY;
1193               Value rAlpha = alpha - 300;
1194               Depth d = newDepth - ss->reduction;
1195               value = -search<NonPV>(pos, ss+1, -(rAlpha+1), -rAlpha, d);
1196               doFullDepthSearch = (value > rAlpha);
1197               ss->reduction = DEPTH_ZERO; // Restore original reduction
1198           }
1199
1200           // Step 15. Full depth search
1201           if (doFullDepthSearch)
1202           {
1203               alpha = SpNode ? sp->alpha : alpha;
1204               value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
1205
1206               // Step extra. pv search (only in PV nodes)
1207               // Search only for possible new PV nodes, if instead value >= beta then
1208               // parent node fails low with value <= alpha and tries another move.
1209               if (PvNode && value > alpha && (Root || value < beta))
1210                   value = -search<PV>(pos, ss+1, -beta, -alpha, newDepth);
1211           }
1212       }
1213
1214       // Step 16. Undo move
1215       pos.undo_move(move);
1216
1217       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1218
1219       // Step 17. Check for new best move
1220       if (SpNode)
1221       {
1222           lock_grab(&(sp->lock));
1223           bestValue = sp->bestValue;
1224           alpha = sp->alpha;
1225       }
1226
1227       if (value > bestValue && !(SpNode && ThreadsMgr.cutoff_at_splitpoint(threadID)))
1228       {
1229           bestValue = value;
1230
1231           if (SpNode)
1232               sp->bestValue = value;
1233
1234           if (!Root && value > alpha)
1235           {
1236               if (PvNode && value < beta) // We want always alpha < beta
1237               {
1238                   alpha = value;
1239
1240                   if (SpNode)
1241                       sp->alpha = value;
1242               }
1243               else if (SpNode)
1244                   sp->betaCutoff = true;
1245
1246               if (value == value_mate_in(ss->ply + 1))
1247                   ss->mateKiller = move;
1248
1249               ss->bestMove = move;
1250
1251               if (SpNode)
1252                   sp->ss->bestMove = move;
1253           }
1254       }
1255
1256       if (Root)
1257       {
1258           // Finished searching the move. If StopRequest is true, the search
1259           // was aborted because the user interrupted the search or because we
1260           // ran out of time. In this case, the return value of the search cannot
1261           // be trusted, and we break out of the loop without updating the best
1262           // move and/or PV.
1263           if (StopRequest)
1264               break;
1265
1266           // Remember searched nodes counts for this move
1267           mp.rm->nodes += pos.nodes_searched() - nodes;
1268
1269           // PV move or new best move ?
1270           if (isPvMove || value > alpha)
1271           {
1272               // Update PV
1273               ss->bestMove = move;
1274               mp.rm->pv_score = value;
1275               mp.rm->extract_pv_from_tt(pos);
1276
1277               // We record how often the best move has been changed in each
1278               // iteration. This information is used for time management: When
1279               // the best move changes frequently, we allocate some more time.
1280               if (!isPvMove && MultiPV == 1)
1281                   Rml.bestMoveChanges++;
1282
1283               Rml.sort_multipv(moveCount);
1284
1285               // Update alpha. In multi-pv we don't use aspiration window, so
1286               // set alpha equal to minimum score among the PV lines.
1287               if (MultiPV > 1)
1288                   alpha = Rml[Min(moveCount, MultiPV) - 1].pv_score; // FIXME why moveCount?
1289               else if (value > alpha)
1290                   alpha = value;
1291           }
1292           else
1293               mp.rm->pv_score = -VALUE_INFINITE;
1294
1295       } // Root
1296
1297       // Step 18. Check for split
1298       if (   !Root
1299           && !SpNode
1300           && depth >= ThreadsMgr.min_split_depth()
1301           && ThreadsMgr.active_threads() > 1
1302           && bestValue < beta
1303           && ThreadsMgr.available_thread_exists(threadID)
1304           && !StopRequest
1305           && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1306           ThreadsMgr.split<FakeSplit>(pos, ss, &alpha, beta, &bestValue, depth,
1307                                       threatMove, moveCount, &mp, PvNode);
1308     }
1309
1310     // Step 19. Check for mate and stalemate
1311     // All legal moves have been searched and if there are
1312     // no legal moves, it must be mate or stalemate.
1313     // If one move was excluded return fail low score.
1314     if (!SpNode && !moveCount)
1315         return excludedMove ? oldAlpha : isCheck ? value_mated_in(ss->ply) : VALUE_DRAW;
1316
1317     // Step 20. Update tables
1318     // If the search is not aborted, update the transposition table,
1319     // history counters, and killer moves.
1320     if (!SpNode && !StopRequest && !ThreadsMgr.cutoff_at_splitpoint(threadID))
1321     {
1322         move = bestValue <= oldAlpha ? MOVE_NONE : ss->bestMove;
1323         vt   = bestValue <= oldAlpha ? VALUE_TYPE_UPPER
1324              : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT;
1325
1326         TT.store(posKey, value_to_tt(bestValue, ss->ply), vt, depth, move, ss->eval, ss->evalMargin);
1327
1328         // Update killers and history only for non capture moves that fails high
1329         if (    bestValue >= beta
1330             && !pos.move_is_capture_or_promotion(move))
1331         {
1332             if (move != ss->killers[0])
1333             {
1334                 ss->killers[1] = ss->killers[0];
1335                 ss->killers[0] = move;
1336             }
1337             update_history(pos, move, depth, movesSearched, playedMoveCount);
1338         }
1339     }
1340
1341     if (SpNode)
1342     {
1343         // Here we have the lock still grabbed
1344         sp->slaves[threadID] = 0;
1345         sp->nodes += pos.nodes_searched();
1346         lock_release(&(sp->lock));
1347     }
1348
1349     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1350
1351     return bestValue;
1352   }
1353
1354   // qsearch() is the quiescence search function, which is called by the main
1355   // search function when the remaining depth is zero (or, to be more precise,
1356   // less than ONE_PLY).
1357
1358   template <NodeType PvNode>
1359   Value qsearch(Position& pos, SearchStack* ss, Value alpha, Value beta, Depth depth) {
1360
1361     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1362     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1363     assert(PvNode || alpha == beta - 1);
1364     assert(depth <= 0);
1365     assert(pos.thread() >= 0 && pos.thread() < ThreadsMgr.active_threads());
1366
1367     StateInfo st;
1368     Move ttMove, move;
1369     Value bestValue, value, evalMargin, futilityValue, futilityBase;
1370     bool isCheck, enoughMaterial, moveIsCheck, evasionPrunable;
1371     const TTEntry* tte;
1372     Depth ttDepth;
1373     Value oldAlpha = alpha;
1374
1375     ss->bestMove = ss->currentMove = MOVE_NONE;
1376     ss->ply = (ss-1)->ply + 1;
1377
1378     // Check for an instant draw or maximum ply reached
1379     if (ss->ply > PLY_MAX || pos.is_draw())
1380         return VALUE_DRAW;
1381
1382     // Decide whether or not to include checks, this fixes also the type of
1383     // TT entry depth that we are going to use. Note that in qsearch we use
1384     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1385     isCheck = pos.is_check();
1386     ttDepth = (isCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS : DEPTH_QS_NO_CHECKS);
1387
1388     // Transposition table lookup. At PV nodes, we don't use the TT for
1389     // pruning, but only for move ordering.
1390     tte = TT.retrieve(pos.get_key());
1391     ttMove = (tte ? tte->move() : MOVE_NONE);
1392
1393     if (!PvNode && tte && ok_to_use_TT(tte, ttDepth, beta, ss->ply))
1394     {
1395         ss->bestMove = ttMove; // Can be MOVE_NONE
1396         return value_from_tt(tte->value(), ss->ply);
1397     }
1398
1399     // Evaluate the position statically
1400     if (isCheck)
1401     {
1402         bestValue = futilityBase = -VALUE_INFINITE;
1403         ss->eval = evalMargin = VALUE_NONE;
1404         enoughMaterial = false;
1405     }
1406     else
1407     {
1408         if (tte)
1409         {
1410             assert(tte->static_value() != VALUE_NONE);
1411
1412             evalMargin = tte->static_value_margin();
1413             ss->eval = bestValue = tte->static_value();
1414         }
1415         else
1416             ss->eval = bestValue = evaluate(pos, evalMargin);
1417
1418         update_gains(pos, (ss-1)->currentMove, (ss-1)->eval, ss->eval);
1419
1420         // Stand pat. Return immediately if static value is at least beta
1421         if (bestValue >= beta)
1422         {
1423             if (!tte)
1424                 TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), VALUE_TYPE_LOWER, DEPTH_NONE, MOVE_NONE, ss->eval, evalMargin);
1425
1426             return bestValue;
1427         }
1428
1429         if (PvNode && bestValue > alpha)
1430             alpha = bestValue;
1431
1432         // Futility pruning parameters, not needed when in check
1433         futilityBase = ss->eval + evalMargin + FutilityMarginQS;
1434         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMidgame;
1435     }
1436
1437     // Initialize a MovePicker object for the current position, and prepare
1438     // to search the moves. Because the depth is <= 0 here, only captures,
1439     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1440     // be generated.
1441     MovePicker mp(pos, ttMove, depth, H);
1442     CheckInfo ci(pos);
1443
1444     // Loop through the moves until no moves remain or a beta cutoff occurs
1445     while (   alpha < beta
1446            && (move = mp.get_next_move()) != MOVE_NONE)
1447     {
1448       assert(move_is_ok(move));
1449
1450       moveIsCheck = pos.move_is_check(move, ci);
1451
1452       // Futility pruning
1453       if (   !PvNode
1454           && !isCheck
1455           && !moveIsCheck
1456           &&  move != ttMove
1457           &&  enoughMaterial
1458           && !move_is_promotion(move)
1459           && !pos.move_is_passed_pawn_push(move))
1460       {
1461           futilityValue =  futilityBase
1462                          + pos.endgame_value_of_piece_on(move_to(move))
1463                          + (move_is_ep(move) ? PawnValueEndgame : VALUE_ZERO);
1464
1465           if (futilityValue < alpha)
1466           {
1467               if (futilityValue > bestValue)
1468                   bestValue = futilityValue;
1469               continue;
1470           }
1471
1472           // Prune moves with negative or equal SEE
1473           if (   futilityBase < beta
1474               && depth < DEPTH_ZERO
1475               && pos.see(move) <= 0)
1476               continue;
1477       }
1478
1479       // Detect non-capture evasions that are candidate to be pruned
1480       evasionPrunable =   isCheck
1481                        && bestValue > VALUE_MATED_IN_PLY_MAX
1482                        && !pos.move_is_capture(move)
1483                        && !pos.can_castle(pos.side_to_move());
1484
1485       // Don't search moves with negative SEE values
1486       if (   !PvNode
1487           && (!isCheck || evasionPrunable)
1488           &&  move != ttMove
1489           && !move_is_promotion(move)
1490           &&  pos.see_sign(move) < 0)
1491           continue;
1492
1493       // Don't search useless checks
1494       if (   !PvNode
1495           && !isCheck
1496           &&  moveIsCheck
1497           &&  move != ttMove
1498           && !pos.move_is_capture_or_promotion(move)
1499           &&  ss->eval + PawnValueMidgame / 4 < beta
1500           && !check_is_dangerous(pos, move, futilityBase, beta, &bestValue))
1501       {
1502           if (ss->eval + PawnValueMidgame / 4 > bestValue)
1503               bestValue = ss->eval + PawnValueMidgame / 4;
1504
1505           continue;
1506       }
1507
1508       // Update current move
1509       ss->currentMove = move;
1510
1511       // Make and search the move
1512       pos.do_move(move, st, ci, moveIsCheck);
1513       value = -qsearch<PvNode>(pos, ss+1, -beta, -alpha, depth-ONE_PLY);
1514       pos.undo_move(move);
1515
1516       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1517
1518       // New best move?
1519       if (value > bestValue)
1520       {
1521           bestValue = value;
1522           if (value > alpha)
1523           {
1524               alpha = value;
1525               ss->bestMove = move;
1526           }
1527        }
1528     }
1529
1530     // All legal moves have been searched. A special case: If we're in check
1531     // and no legal moves were found, it is checkmate.
1532     if (isCheck && bestValue == -VALUE_INFINITE)
1533         return value_mated_in(ss->ply);
1534
1535     // Update transposition table
1536     ValueType vt = (bestValue <= oldAlpha ? VALUE_TYPE_UPPER : bestValue >= beta ? VALUE_TYPE_LOWER : VALUE_TYPE_EXACT);
1537     TT.store(pos.get_key(), value_to_tt(bestValue, ss->ply), vt, ttDepth, ss->bestMove, ss->eval, evalMargin);
1538
1539     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1540
1541     return bestValue;
1542   }
1543
1544
1545   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1546   // bestValue is updated only when returning false because in that case move
1547   // will be pruned.
1548
1549   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta, Value *bestValue)
1550   {
1551     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1552     Square from, to, ksq, victimSq;
1553     Piece pc;
1554     Color them;
1555     Value futilityValue, bv = *bestValue;
1556
1557     from = move_from(move);
1558     to = move_to(move);
1559     them = opposite_color(pos.side_to_move());
1560     ksq = pos.king_square(them);
1561     kingAtt = pos.attacks_from<KING>(ksq);
1562     pc = pos.piece_on(from);
1563
1564     occ = pos.occupied_squares() & ~(1ULL << from) & ~(1ULL << ksq);
1565     oldAtt = pos.attacks_from(pc, from, occ);
1566     newAtt = pos.attacks_from(pc,   to, occ);
1567
1568     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1569     b = kingAtt & ~pos.pieces_of_color(them) & ~newAtt & ~(1ULL << to);
1570
1571     if (!(b && (b & (b - 1))))
1572         return true;
1573
1574     // Rule 2. Queen contact check is very dangerous
1575     if (   type_of_piece(pc) == QUEEN
1576         && bit_is_set(kingAtt, to))
1577         return true;
1578
1579     // Rule 3. Creating new double threats with checks
1580     b = pos.pieces_of_color(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1581
1582     while (b)
1583     {
1584         victimSq = pop_1st_bit(&b);
1585         futilityValue = futilityBase + pos.endgame_value_of_piece_on(victimSq);
1586
1587         // Note that here we generate illegal "double move"!
1588         if (   futilityValue >= beta
1589             && pos.see_sign(make_move(from, victimSq)) >= 0)
1590             return true;
1591
1592         if (futilityValue > bv)
1593             bv = futilityValue;
1594     }
1595
1596     // Update bestValue only if check is not dangerous (because we will prune the move)
1597     *bestValue = bv;
1598     return false;
1599   }
1600
1601
1602   // connected_moves() tests whether two moves are 'connected' in the sense
1603   // that the first move somehow made the second move possible (for instance
1604   // if the moving piece is the same in both moves). The first move is assumed
1605   // to be the move that was made to reach the current position, while the
1606   // second move is assumed to be a move from the current position.
1607
1608   bool connected_moves(const Position& pos, Move m1, Move m2) {
1609
1610     Square f1, t1, f2, t2;
1611     Piece p;
1612
1613     assert(m1 && move_is_ok(m1));
1614     assert(m2 && move_is_ok(m2));
1615
1616     // Case 1: The moving piece is the same in both moves
1617     f2 = move_from(m2);
1618     t1 = move_to(m1);
1619     if (f2 == t1)
1620         return true;
1621
1622     // Case 2: The destination square for m2 was vacated by m1
1623     t2 = move_to(m2);
1624     f1 = move_from(m1);
1625     if (t2 == f1)
1626         return true;
1627
1628     // Case 3: Moving through the vacated square
1629     if (   piece_is_slider(pos.piece_on(f2))
1630         && bit_is_set(squares_between(f2, t2), f1))
1631       return true;
1632
1633     // Case 4: The destination square for m2 is defended by the moving piece in m1
1634     p = pos.piece_on(t1);
1635     if (bit_is_set(pos.attacks_from(p, t1), t2))
1636         return true;
1637
1638     // Case 5: Discovered check, checking piece is the piece moved in m1
1639     if (    piece_is_slider(p)
1640         &&  bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), f2)
1641         && !bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())), t2))
1642     {
1643         // discovered_check_candidates() works also if the Position's side to
1644         // move is the opposite of the checking piece.
1645         Color them = opposite_color(pos.side_to_move());
1646         Bitboard dcCandidates = pos.discovered_check_candidates(them);
1647
1648         if (bit_is_set(dcCandidates, f2))
1649             return true;
1650     }
1651     return false;
1652   }
1653
1654
1655   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1656   // "plies to mate from the current ply".  Non-mate scores are unchanged.
1657   // The function is called before storing a value to the transposition table.
1658
1659   Value value_to_tt(Value v, int ply) {
1660
1661     if (v >= VALUE_MATE_IN_PLY_MAX)
1662       return v + ply;
1663
1664     if (v <= VALUE_MATED_IN_PLY_MAX)
1665       return v - ply;
1666
1667     return v;
1668   }
1669
1670
1671   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score from
1672   // the transposition table to a mate score corrected for the current ply.
1673
1674   Value value_from_tt(Value v, int ply) {
1675
1676     if (v >= VALUE_MATE_IN_PLY_MAX)
1677       return v - ply;
1678
1679     if (v <= VALUE_MATED_IN_PLY_MAX)
1680       return v + ply;
1681
1682     return v;
1683   }
1684
1685
1686   // extension() decides whether a move should be searched with normal depth,
1687   // or with extended depth. Certain classes of moves (checking moves, in
1688   // particular) are searched with bigger depth than ordinary moves and in
1689   // any case are marked as 'dangerous'. Note that also if a move is not
1690   // extended, as example because the corresponding UCI option is set to zero,
1691   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
1692   template <NodeType PvNode>
1693   Depth extension(const Position& pos, Move m, bool captureOrPromotion,
1694                   bool moveIsCheck, bool* dangerous) {
1695
1696     assert(m != MOVE_NONE);
1697
1698     Depth result = DEPTH_ZERO;
1699     *dangerous = moveIsCheck;
1700
1701     if (moveIsCheck && pos.see_sign(m) >= 0)
1702         result += CheckExtension[PvNode];
1703
1704     if (pos.type_of_piece_on(move_from(m)) == PAWN)
1705     {
1706         Color c = pos.side_to_move();
1707         if (relative_rank(c, move_to(m)) == RANK_7)
1708         {
1709             result += PawnPushTo7thExtension[PvNode];
1710             *dangerous = true;
1711         }
1712         if (pos.pawn_is_passed(c, move_to(m)))
1713         {
1714             result += PassedPawnExtension[PvNode];
1715             *dangerous = true;
1716         }
1717     }
1718
1719     if (   captureOrPromotion
1720         && pos.type_of_piece_on(move_to(m)) != PAWN
1721         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
1722             - pos.midgame_value_of_piece_on(move_to(m)) == VALUE_ZERO)
1723         && !move_is_special(m))
1724     {
1725         result += PawnEndgameExtension[PvNode];
1726         *dangerous = true;
1727     }
1728
1729     return Min(result, ONE_PLY);
1730   }
1731
1732
1733   // connected_threat() tests whether it is safe to forward prune a move or if
1734   // is somehow connected to the threat move returned by null search.
1735
1736   bool connected_threat(const Position& pos, Move m, Move threat) {
1737
1738     assert(move_is_ok(m));
1739     assert(threat && move_is_ok(threat));
1740     assert(!pos.move_is_check(m));
1741     assert(!pos.move_is_capture_or_promotion(m));
1742     assert(!pos.move_is_passed_pawn_push(m));
1743
1744     Square mfrom, mto, tfrom, tto;
1745
1746     mfrom = move_from(m);
1747     mto = move_to(m);
1748     tfrom = move_from(threat);
1749     tto = move_to(threat);
1750
1751     // Case 1: Don't prune moves which move the threatened piece
1752     if (mfrom == tto)
1753         return true;
1754
1755     // Case 2: If the threatened piece has value less than or equal to the
1756     // value of the threatening piece, don't prune moves which defend it.
1757     if (   pos.move_is_capture(threat)
1758         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
1759             || pos.type_of_piece_on(tfrom) == KING)
1760         && pos.move_attacks_square(m, tto))
1761         return true;
1762
1763     // Case 3: If the moving piece in the threatened move is a slider, don't
1764     // prune safe moves which block its ray.
1765     if (   piece_is_slider(pos.piece_on(tfrom))
1766         && bit_is_set(squares_between(tfrom, tto), mto)
1767         && pos.see_sign(m) >= 0)
1768         return true;
1769
1770     return false;
1771   }
1772
1773
1774   // ok_to_use_TT() returns true if a transposition table score
1775   // can be used at a given point in search.
1776
1777   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
1778
1779     Value v = value_from_tt(tte->value(), ply);
1780
1781     return   (   tte->depth() >= depth
1782               || v >= Max(VALUE_MATE_IN_PLY_MAX, beta)
1783               || v < Min(VALUE_MATED_IN_PLY_MAX, beta))
1784
1785           && (   ((tte->type() & VALUE_TYPE_LOWER) && v >= beta)
1786               || ((tte->type() & VALUE_TYPE_UPPER) && v < beta));
1787   }
1788
1789
1790   // refine_eval() returns the transposition table score if
1791   // possible otherwise falls back on static position evaluation.
1792
1793   Value refine_eval(const TTEntry* tte, Value defaultEval, int ply) {
1794
1795       assert(tte);
1796
1797       Value v = value_from_tt(tte->value(), ply);
1798
1799       if (   ((tte->type() & VALUE_TYPE_LOWER) && v >= defaultEval)
1800           || ((tte->type() & VALUE_TYPE_UPPER) && v < defaultEval))
1801           return v;
1802
1803       return defaultEval;
1804   }
1805
1806
1807   // update_history() registers a good move that produced a beta-cutoff
1808   // in history and marks as failures all the other moves of that ply.
1809
1810   void update_history(const Position& pos, Move move, Depth depth,
1811                       Move movesSearched[], int moveCount) {
1812     Move m;
1813     Value bonus = Value(int(depth) * int(depth));
1814
1815     H.update(pos.piece_on(move_from(move)), move_to(move), bonus);
1816
1817     for (int i = 0; i < moveCount - 1; i++)
1818     {
1819         m = movesSearched[i];
1820
1821         assert(m != move);
1822
1823         H.update(pos.piece_on(move_from(m)), move_to(m), -bonus);
1824     }
1825   }
1826
1827
1828   // update_gains() updates the gains table of a non-capture move given
1829   // the static position evaluation before and after the move.
1830
1831   void update_gains(const Position& pos, Move m, Value before, Value after) {
1832
1833     if (   m != MOVE_NULL
1834         && before != VALUE_NONE
1835         && after != VALUE_NONE
1836         && pos.captured_piece_type() == PIECE_TYPE_NONE
1837         && !move_is_special(m))
1838         H.update_gain(pos.piece_on(move_to(m)), move_to(m), -(before + after));
1839   }
1840
1841
1842   // current_search_time() returns the number of milliseconds which have passed
1843   // since the beginning of the current search.
1844
1845   int current_search_time(int set) {
1846
1847     static int searchStartTime;
1848
1849     if (set)
1850         searchStartTime = set;
1851
1852     return get_system_time() - searchStartTime;
1853   }
1854
1855
1856   // value_to_uci() converts a value to a string suitable for use with the UCI
1857   // protocol specifications:
1858   //
1859   // cp <x>     The score from the engine's point of view in centipawns.
1860   // mate <y>   Mate in y moves, not plies. If the engine is getting mated
1861   //            use negative values for y.
1862
1863   std::string value_to_uci(Value v) {
1864
1865     std::stringstream s;
1866
1867     if (abs(v) < VALUE_MATE - PLY_MAX * ONE_PLY)
1868         s << "cp " << int(v) * 100 / int(PawnValueMidgame); // Scale to centipawns
1869     else
1870         s << "mate " << (v > 0 ? VALUE_MATE - v + 1 : -VALUE_MATE - v) / 2;
1871
1872     return s.str();
1873   }
1874
1875
1876   // speed_to_uci() returns a string with time stats of current search suitable
1877   // to be sent to UCI gui.
1878
1879   std::string speed_to_uci(int64_t nodes) {
1880
1881     std::stringstream s;
1882     int t = current_search_time();
1883
1884     s << " nodes " << nodes
1885       << " nps "   << (t > 0 ? int(nodes * 1000 / t) : 0)
1886       << " time "  << t;
1887
1888     return s.str();
1889   }
1890
1891
1892   // poll() performs two different functions: It polls for user input, and it
1893   // looks at the time consumed so far and decides if it's time to abort the
1894   // search.
1895
1896   void poll(const Position& pos) {
1897
1898     static int lastInfoTime;
1899     int t = current_search_time();
1900
1901     //  Poll for input
1902     if (input_available())
1903     {
1904         // We are line oriented, don't read single chars
1905         std::string command;
1906
1907         if (!std::getline(std::cin, command) || command == "quit")
1908         {
1909             // Quit the program as soon as possible
1910             Pondering = false;
1911             QuitRequest = StopRequest = true;
1912             return;
1913         }
1914         else if (command == "stop")
1915         {
1916             // Stop calculating as soon as possible, but still send the "bestmove"
1917             // and possibly the "ponder" token when finishing the search.
1918             Pondering = false;
1919             StopRequest = true;
1920         }
1921         else if (command == "ponderhit")
1922         {
1923             // The opponent has played the expected move. GUI sends "ponderhit" if
1924             // we were told to ponder on the same move the opponent has played. We
1925             // should continue searching but switching from pondering to normal search.
1926             Pondering = false;
1927
1928             if (StopOnPonderhit)
1929                 StopRequest = true;
1930         }
1931     }
1932
1933     // Print search information
1934     if (t < 1000)
1935         lastInfoTime = 0;
1936
1937     else if (lastInfoTime > t)
1938         // HACK: Must be a new search where we searched less than
1939         // NodesBetweenPolls nodes during the first second of search.
1940         lastInfoTime = 0;
1941
1942     else if (t - lastInfoTime >= 1000)
1943     {
1944         lastInfoTime = t;
1945
1946         dbg_print_mean();
1947         dbg_print_hit_rate();
1948
1949         // Send info on searched nodes as soon as we return to root
1950         SendSearchedNodes = true;
1951     }
1952
1953     // Should we stop the search?
1954     if (Pondering)
1955         return;
1956
1957     bool stillAtFirstMove =    FirstRootMove
1958                            && !AspirationFailLow
1959                            &&  t > TimeMgr.available_time();
1960
1961     bool noMoreTime =   t > TimeMgr.maximum_time()
1962                      || stillAtFirstMove;
1963
1964     if (   (UseTimeManagement && noMoreTime)
1965         || (ExactMaxTime && t >= ExactMaxTime)
1966         || (MaxNodes && pos.nodes_searched() >= MaxNodes)) // FIXME
1967         StopRequest = true;
1968   }
1969
1970
1971   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
1972   // while the program is pondering. The point is to work around a wrinkle in
1973   // the UCI protocol: When pondering, the engine is not allowed to give a
1974   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
1975   // We simply wait here until one of these commands is sent, and return,
1976   // after which the bestmove and pondermove will be printed.
1977
1978   void wait_for_stop_or_ponderhit() {
1979
1980     std::string command;
1981
1982     // Wait for a command from stdin
1983     while (   std::getline(std::cin, command)
1984            && command != "ponderhit" && command != "stop" && command != "quit") {};
1985
1986     if (command != "ponderhit" && command != "stop")
1987         QuitRequest = true; // Must be "quit" or getline() returned false
1988   }
1989
1990
1991   // init_thread() is the function which is called when a new thread is
1992   // launched. It simply calls the idle_loop() function with the supplied
1993   // threadID. There are two versions of this function; one for POSIX
1994   // threads and one for Windows threads.
1995
1996 #if !defined(_MSC_VER)
1997
1998   void* init_thread(void* threadID) {
1999
2000     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
2001     return NULL;
2002   }
2003
2004 #else
2005
2006   DWORD WINAPI init_thread(LPVOID threadID) {
2007
2008     ThreadsMgr.idle_loop(*(int*)threadID, NULL);
2009     return 0;
2010   }
2011
2012 #endif
2013
2014
2015   /// The ThreadsManager class
2016
2017
2018   // read_uci_options() updates number of active threads and other internal
2019   // parameters according to the UCI options values. It is called before
2020   // to start a new search.
2021
2022   void ThreadsManager::read_uci_options() {
2023
2024     maxThreadsPerSplitPoint = Options["Maximum Number of Threads per Split Point"].value<int>();
2025     minimumSplitDepth       = Options["Minimum Split Depth"].value<int>() * ONE_PLY;
2026     useSleepingThreads      = Options["Use Sleeping Threads"].value<bool>();
2027     activeThreads           = Options["Threads"].value<int>();
2028   }
2029
2030
2031   // idle_loop() is where the threads are parked when they have no work to do.
2032   // The parameter 'sp', if non-NULL, is a pointer to an active SplitPoint
2033   // object for which the current thread is the master.
2034
2035   void ThreadsManager::idle_loop(int threadID, SplitPoint* sp) {
2036
2037     assert(threadID >= 0 && threadID < MAX_THREADS);
2038
2039     int i;
2040     bool allFinished;
2041
2042     while (true)
2043     {
2044         // Slave threads can exit as soon as AllThreadsShouldExit raises,
2045         // master should exit as last one.
2046         if (allThreadsShouldExit)
2047         {
2048             assert(!sp);
2049             threads[threadID].state = THREAD_TERMINATED;
2050             return;
2051         }
2052
2053         // If we are not thinking, wait for a condition to be signaled
2054         // instead of wasting CPU time polling for work.
2055         while (   threadID >= activeThreads
2056                || threads[threadID].state == THREAD_INITIALIZING
2057                || (useSleepingThreads && threads[threadID].state == THREAD_AVAILABLE))
2058         {
2059             assert(!sp || useSleepingThreads);
2060             assert(threadID != 0 || useSleepingThreads);
2061
2062             if (threads[threadID].state == THREAD_INITIALIZING)
2063                 threads[threadID].state = THREAD_AVAILABLE;
2064
2065             // Grab the lock to avoid races with Thread::wake_up()
2066             lock_grab(&threads[threadID].sleepLock);
2067
2068             // If we are master and all slaves have finished do not go to sleep
2069             for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2070             allFinished = (i == activeThreads);
2071
2072             if (allFinished || allThreadsShouldExit)
2073             {
2074                 lock_release(&threads[threadID].sleepLock);
2075                 break;
2076             }
2077
2078             // Do sleep here after retesting sleep conditions
2079             if (threadID >= activeThreads || threads[threadID].state == THREAD_AVAILABLE)
2080                 cond_wait(&threads[threadID].sleepCond, &threads[threadID].sleepLock);
2081
2082             lock_release(&threads[threadID].sleepLock);
2083         }
2084
2085         // If this thread has been assigned work, launch a search
2086         if (threads[threadID].state == THREAD_WORKISWAITING)
2087         {
2088             assert(!allThreadsShouldExit);
2089
2090             threads[threadID].state = THREAD_SEARCHING;
2091
2092             // Copy split point position and search stack and call search()
2093             // with SplitPoint template parameter set to true.
2094             SearchStack ss[PLY_MAX_PLUS_2];
2095             SplitPoint* tsp = threads[threadID].splitPoint;
2096             Position pos(*tsp->pos, threadID);
2097
2098             memcpy(ss, tsp->ss - 1, 4 * sizeof(SearchStack));
2099             (ss+1)->sp = tsp;
2100
2101             if (tsp->pvNode)
2102                 search<PV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2103             else
2104                 search<NonPV, true, false>(pos, ss+1, tsp->alpha, tsp->beta, tsp->depth);
2105
2106             assert(threads[threadID].state == THREAD_SEARCHING);
2107
2108             threads[threadID].state = THREAD_AVAILABLE;
2109
2110             // Wake up master thread so to allow it to return from the idle loop in
2111             // case we are the last slave of the split point.
2112             if (   useSleepingThreads
2113                 && threadID != tsp->master
2114                 && threads[tsp->master].state == THREAD_AVAILABLE)
2115                 threads[tsp->master].wake_up();
2116         }
2117
2118         // If this thread is the master of a split point and all slaves have
2119         // finished their work at this split point, return from the idle loop.
2120         for (i = 0; sp && i < activeThreads && !sp->slaves[i]; i++) {}
2121         allFinished = (i == activeThreads);
2122
2123         if (allFinished)
2124         {
2125             // Because sp->slaves[] is reset under lock protection,
2126             // be sure sp->lock has been released before to return.
2127             lock_grab(&(sp->lock));
2128             lock_release(&(sp->lock));
2129
2130             // In helpful master concept a master can help only a sub-tree, and
2131             // because here is all finished is not possible master is booked.
2132             assert(threads[threadID].state == THREAD_AVAILABLE);
2133
2134             threads[threadID].state = THREAD_SEARCHING;
2135             return;
2136         }
2137     }
2138   }
2139
2140
2141   // init_threads() is called during startup. Initializes locks and condition
2142   // variables and launches all threads sending them immediately to sleep.
2143
2144   void ThreadsManager::init_threads() {
2145
2146     int i, arg[MAX_THREADS];
2147     bool ok;
2148
2149     // This flag is needed to properly end the threads when program exits
2150     allThreadsShouldExit = false;
2151
2152     // Threads will sent to sleep as soon as created, only main thread is kept alive
2153     activeThreads = 1;
2154
2155     lock_init(&mpLock);
2156
2157     for (i = 0; i < MAX_THREADS; i++)
2158     {
2159         // Initialize thread and split point locks
2160         lock_init(&threads[i].sleepLock);
2161         cond_init(&threads[i].sleepCond);
2162
2163         for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2164             lock_init(&(threads[i].splitPoints[j].lock));
2165
2166         // All threads but first should be set to THREAD_INITIALIZING
2167         threads[i].state = (i == 0 ? THREAD_SEARCHING : THREAD_INITIALIZING);
2168     }
2169
2170     // Create and startup the threads
2171     for (i = 1; i < MAX_THREADS; i++)
2172     {
2173         arg[i] = i;
2174
2175 #if !defined(_MSC_VER)
2176         pthread_t pthread[1];
2177         ok = (pthread_create(pthread, NULL, init_thread, (void*)(&arg[i])) == 0);
2178         pthread_detach(pthread[0]);
2179 #else
2180         ok = (CreateThread(NULL, 0, init_thread, (LPVOID)(&arg[i]), 0, NULL) != NULL);
2181 #endif
2182         if (!ok)
2183         {
2184             cout << "Failed to create thread number " << i << endl;
2185             exit(EXIT_FAILURE);
2186         }
2187
2188         // Wait until the thread has finished launching and is gone to sleep
2189         while (threads[i].state == THREAD_INITIALIZING) {}
2190     }
2191   }
2192
2193
2194   // exit_threads() is called when the program exits. It makes all the
2195   // helper threads exit cleanly.
2196
2197   void ThreadsManager::exit_threads() {
2198
2199     // Force the woken up threads to exit idle_loop() and hence terminate
2200     allThreadsShouldExit = true;
2201
2202     for (int i = 0; i < MAX_THREADS; i++)
2203     {
2204         // Wake up all the threads and waits for termination
2205         if (i != 0)
2206         {
2207             threads[i].wake_up();
2208             while (threads[i].state != THREAD_TERMINATED) {}
2209         }
2210
2211         // Now we can safely destroy the locks and wait conditions
2212         lock_destroy(&threads[i].sleepLock);
2213         cond_destroy(&threads[i].sleepCond);
2214
2215         for (int j = 0; j < MAX_ACTIVE_SPLIT_POINTS; j++)
2216             lock_destroy(&(threads[i].splitPoints[j].lock));
2217     }
2218
2219     lock_destroy(&mpLock);
2220   }
2221
2222
2223   // cutoff_at_splitpoint() checks whether a beta cutoff has occurred in
2224   // the thread's currently active split point, or in some ancestor of
2225   // the current split point.
2226
2227   bool ThreadsManager::cutoff_at_splitpoint(int threadID) const {
2228
2229     assert(threadID >= 0 && threadID < activeThreads);
2230
2231     SplitPoint* sp = threads[threadID].splitPoint;
2232
2233     for ( ; sp && !sp->betaCutoff; sp = sp->parent) {}
2234     return sp != NULL;
2235   }
2236
2237
2238   // thread_is_available() checks whether the thread with threadID "slave" is
2239   // available to help the thread with threadID "master" at a split point. An
2240   // obvious requirement is that "slave" must be idle. With more than two
2241   // threads, this is not by itself sufficient:  If "slave" is the master of
2242   // some active split point, it is only available as a slave to the other
2243   // threads which are busy searching the split point at the top of "slave"'s
2244   // split point stack (the "helpful master concept" in YBWC terminology).
2245
2246   bool ThreadsManager::thread_is_available(int slave, int master) const {
2247
2248     assert(slave >= 0 && slave < activeThreads);
2249     assert(master >= 0 && master < activeThreads);
2250     assert(activeThreads > 1);
2251
2252     if (threads[slave].state != THREAD_AVAILABLE || slave == master)
2253         return false;
2254
2255     // Make a local copy to be sure doesn't change under our feet
2256     int localActiveSplitPoints = threads[slave].activeSplitPoints;
2257
2258     // No active split points means that the thread is available as
2259     // a slave for any other thread.
2260     if (localActiveSplitPoints == 0 || activeThreads == 2)
2261         return true;
2262
2263     // Apply the "helpful master" concept if possible. Use localActiveSplitPoints
2264     // that is known to be > 0, instead of threads[slave].activeSplitPoints that
2265     // could have been set to 0 by another thread leading to an out of bound access.
2266     if (threads[slave].splitPoints[localActiveSplitPoints - 1].slaves[master])
2267         return true;
2268
2269     return false;
2270   }
2271
2272
2273   // available_thread_exists() tries to find an idle thread which is available as
2274   // a slave for the thread with threadID "master".
2275
2276   bool ThreadsManager::available_thread_exists(int master) const {
2277
2278     assert(master >= 0 && master < activeThreads);
2279     assert(activeThreads > 1);
2280
2281     for (int i = 0; i < activeThreads; i++)
2282         if (thread_is_available(i, master))
2283             return true;
2284
2285     return false;
2286   }
2287
2288
2289   // split() does the actual work of distributing the work at a node between
2290   // several available threads. If it does not succeed in splitting the
2291   // node (because no idle threads are available, or because we have no unused
2292   // split point objects), the function immediately returns. If splitting is
2293   // possible, a SplitPoint object is initialized with all the data that must be
2294   // copied to the helper threads and we tell our helper threads that they have
2295   // been assigned work. This will cause them to instantly leave their idle loops and
2296   // call search().When all threads have returned from search() then split() returns.
2297
2298   template <bool Fake>
2299   void ThreadsManager::split(Position& pos, SearchStack* ss, Value* alpha, const Value beta,
2300                              Value* bestValue, Depth depth, Move threatMove,
2301                              int moveCount, MovePicker* mp, bool pvNode) {
2302     assert(pos.is_ok());
2303     assert(*bestValue >= -VALUE_INFINITE);
2304     assert(*bestValue <= *alpha);
2305     assert(*alpha < beta);
2306     assert(beta <= VALUE_INFINITE);
2307     assert(depth > DEPTH_ZERO);
2308     assert(pos.thread() >= 0 && pos.thread() < activeThreads);
2309     assert(activeThreads > 1);
2310
2311     int i, master = pos.thread();
2312     Thread& masterThread = threads[master];
2313
2314     lock_grab(&mpLock);
2315
2316     // If no other thread is available to help us, or if we have too many
2317     // active split points, don't split.
2318     if (   !available_thread_exists(master)
2319         || masterThread.activeSplitPoints >= MAX_ACTIVE_SPLIT_POINTS)
2320     {
2321         lock_release(&mpLock);
2322         return;
2323     }
2324
2325     // Pick the next available split point object from the split point stack
2326     SplitPoint& splitPoint = masterThread.splitPoints[masterThread.activeSplitPoints++];
2327
2328     // Initialize the split point object
2329     splitPoint.parent = masterThread.splitPoint;
2330     splitPoint.master = master;
2331     splitPoint.betaCutoff = false;
2332     splitPoint.depth = depth;
2333     splitPoint.threatMove = threatMove;
2334     splitPoint.alpha = *alpha;
2335     splitPoint.beta = beta;
2336     splitPoint.pvNode = pvNode;
2337     splitPoint.bestValue = *bestValue;
2338     splitPoint.mp = mp;
2339     splitPoint.moveCount = moveCount;
2340     splitPoint.pos = &pos;
2341     splitPoint.nodes = 0;
2342     splitPoint.ss = ss;
2343     for (i = 0; i < activeThreads; i++)
2344         splitPoint.slaves[i] = 0;
2345
2346     masterThread.splitPoint = &splitPoint;
2347
2348     // If we are here it means we are not available
2349     assert(masterThread.state != THREAD_AVAILABLE);
2350
2351     int workersCnt = 1; // At least the master is included
2352
2353     // Allocate available threads setting state to THREAD_BOOKED
2354     for (i = 0; !Fake && i < activeThreads && workersCnt < maxThreadsPerSplitPoint; i++)
2355         if (thread_is_available(i, master))
2356         {
2357             threads[i].state = THREAD_BOOKED;
2358             threads[i].splitPoint = &splitPoint;
2359             splitPoint.slaves[i] = 1;
2360             workersCnt++;
2361         }
2362
2363     assert(Fake || workersCnt > 1);
2364
2365     // We can release the lock because slave threads are already booked and master is not available
2366     lock_release(&mpLock);
2367
2368     // Tell the threads that they have work to do. This will make them leave
2369     // their idle loop.
2370     for (i = 0; i < activeThreads; i++)
2371         if (i == master || splitPoint.slaves[i])
2372         {
2373             assert(i == master || threads[i].state == THREAD_BOOKED);
2374
2375             threads[i].state = THREAD_WORKISWAITING; // This makes the slave to exit from idle_loop()
2376
2377             if (useSleepingThreads && i != master)
2378                 threads[i].wake_up();
2379         }
2380
2381     // Everything is set up. The master thread enters the idle loop, from
2382     // which it will instantly launch a search, because its state is
2383     // THREAD_WORKISWAITING.  We send the split point as a second parameter to the
2384     // idle loop, which means that the main thread will return from the idle
2385     // loop when all threads have finished their work at this split point.
2386     idle_loop(master, &splitPoint);
2387
2388     // We have returned from the idle loop, which means that all threads are
2389     // finished. Update alpha and bestValue, and return.
2390     lock_grab(&mpLock);
2391
2392     *alpha = splitPoint.alpha;
2393     *bestValue = splitPoint.bestValue;
2394     masterThread.activeSplitPoints--;
2395     masterThread.splitPoint = splitPoint.parent;
2396     pos.set_nodes_searched(pos.nodes_searched() + splitPoint.nodes);
2397
2398     lock_release(&mpLock);
2399   }
2400
2401
2402   /// RootMove and RootMoveList method's definitions
2403
2404   RootMove::RootMove() {
2405
2406     nodes = 0;
2407     pv_score = non_pv_score = -VALUE_INFINITE;
2408     pv[0] = MOVE_NONE;
2409   }
2410
2411   RootMove& RootMove::operator=(const RootMove& rm) {
2412
2413     const Move* src = rm.pv;
2414     Move* dst = pv;
2415
2416     // Avoid a costly full rm.pv[] copy
2417     do *dst++ = *src; while (*src++ != MOVE_NONE);
2418
2419     nodes = rm.nodes;
2420     pv_score = rm.pv_score;
2421     non_pv_score = rm.non_pv_score;
2422     return *this;
2423   }
2424
2425   // extract_pv_from_tt() builds a PV by adding moves from the transposition table.
2426   // We consider also failing high nodes and not only VALUE_TYPE_EXACT nodes. This
2427   // allow to always have a ponder move even when we fail high at root and also a
2428   // long PV to print that is important for position analysis.
2429
2430   void RootMove::extract_pv_from_tt(Position& pos) {
2431
2432     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2433     TTEntry* tte;
2434     int ply = 1;
2435
2436     assert(pv[0] != MOVE_NONE && pos.move_is_legal(pv[0]));
2437
2438     pos.do_move(pv[0], *st++);
2439
2440     while (   (tte = TT.retrieve(pos.get_key())) != NULL
2441            && tte->move() != MOVE_NONE
2442            && pos.move_is_legal(tte->move())
2443            && ply < PLY_MAX
2444            && (!pos.is_draw() || ply < 2))
2445     {
2446         pv[ply] = tte->move();
2447         pos.do_move(pv[ply++], *st++);
2448     }
2449     pv[ply] = MOVE_NONE;
2450
2451     do pos.undo_move(pv[--ply]); while (ply);
2452   }
2453
2454   // insert_pv_in_tt() is called at the end of a search iteration, and inserts
2455   // the PV back into the TT. This makes sure the old PV moves are searched
2456   // first, even if the old TT entries have been overwritten.
2457
2458   void RootMove::insert_pv_in_tt(Position& pos) {
2459
2460     StateInfo state[PLY_MAX_PLUS_2], *st = state;
2461     TTEntry* tte;
2462     Key k;
2463     Value v, m = VALUE_NONE;
2464     int ply = 0;
2465
2466     assert(pv[0] != MOVE_NONE && pos.move_is_legal(pv[0]));
2467
2468     do {
2469         k = pos.get_key();
2470         tte = TT.retrieve(k);
2471
2472         // Don't overwrite existing correct entries
2473         if (!tte || tte->move() != pv[ply])
2474         {
2475             v = (pos.is_check() ? VALUE_NONE : evaluate(pos, m));
2476             TT.store(k, VALUE_NONE, VALUE_TYPE_NONE, DEPTH_NONE, pv[ply], v, m);
2477         }
2478         pos.do_move(pv[ply], *st++);
2479
2480     } while (pv[++ply] != MOVE_NONE);
2481
2482     do pos.undo_move(pv[--ply]); while (ply);
2483   }
2484
2485   // pv_info_to_uci() returns a string with information on the current PV line
2486   // formatted according to UCI specification.
2487
2488   std::string RootMove::pv_info_to_uci(Position& pos, int depth, int selDepth, Value alpha,
2489                                        Value beta, int pvIdx) {
2490     std::stringstream s;
2491
2492     s << "info depth " << depth
2493       << " seldepth " << selDepth
2494       << " multipv " << pvIdx + 1
2495       << " score " << value_to_uci(pv_score)
2496       << (pv_score >= beta ? " lowerbound" : pv_score <= alpha ? " upperbound" : "")
2497       << speed_to_uci(pos.nodes_searched())
2498       << " pv ";
2499
2500     for (Move* m = pv; *m != MOVE_NONE; m++)
2501         s << *m << " ";
2502
2503     return s.str();
2504   }
2505
2506
2507   void RootMoveList::init(Position& pos, Move searchMoves[]) {
2508
2509     MoveStack mlist[MOVES_MAX];
2510     Move* sm;
2511
2512     clear();
2513     bestMoveChanges = 0;
2514
2515     // Generate all legal moves and add them to RootMoveList
2516     MoveStack* last = generate<MV_LEGAL>(pos, mlist);
2517     for (MoveStack* cur = mlist; cur != last; cur++)
2518     {
2519         // If we have a searchMoves[] list then verify cur->move
2520         // is in the list before to add it.
2521         for (sm = searchMoves; *sm && *sm != cur->move; sm++) {}
2522
2523         if (searchMoves[0] && *sm != cur->move)
2524             continue;
2525
2526         RootMove rm;
2527         rm.pv[0] = cur->move;
2528         rm.pv[1] = MOVE_NONE;
2529         rm.pv_score = -VALUE_INFINITE;
2530         push_back(rm);
2531     }
2532   }
2533
2534
2535   // When playing with strength handicap choose best move among the MultiPV set
2536   // using a statistical rule dependent on SkillLevel. Idea by Heinz van Saanen.
2537   void do_skill_level(Move* best, Move* ponder) {
2538
2539     assert(MultiPV > 1);
2540
2541     // Rml list is already sorted by pv_score in descending order
2542     int s;
2543     int max_s = -VALUE_INFINITE;
2544     int size = Min(MultiPV, (int)Rml.size());
2545     int max = Rml[0].pv_score;
2546     int var = Min(max - Rml[size - 1].pv_score, PawnValueMidgame);
2547     int wk = 120 - 2 * SkillLevel;
2548
2549     // PRNG sequence should be non deterministic
2550     for (int i = abs(get_system_time() % 50); i > 0; i--)
2551         RK.rand<unsigned>();
2552
2553     // Choose best move. For each move's score we add two terms both dependent
2554     // on wk, one deterministic and bigger for weaker moves, and one random,
2555     // then we choose the move with the resulting highest score.
2556     for (int i = 0; i < size; i++)
2557     {
2558         s = Rml[i].pv_score;
2559
2560         // Don't allow crazy blunders even at very low skills
2561         if (i > 0 && Rml[i-1].pv_score > s + EasyMoveMargin)
2562             break;
2563
2564         // This is our magical formula
2565         s += ((max - s) * wk + var * (RK.rand<unsigned>() % wk)) / 128;
2566
2567         if (s > max_s)
2568         {
2569             max_s = s;
2570             *best = Rml[i].pv[0];
2571             *ponder = Rml[i].pv[1];
2572         }
2573     }
2574   }
2575
2576 } // namespace