]> git.sesse.net Git - stockfish/blob - src/search.cpp
Always print a best move when requested
[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 Marco Costalba
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <fstream>
27 #include <iostream>
28 #include <sstream>
29
30 #include "book.h"
31 #include "evaluate.h"
32 #include "history.h"
33 #include "misc.h"
34 #include "movepick.h"
35 #include "san.h"
36 #include "search.h"
37 #include "thread.h"
38 #include "tt.h"
39 #include "ucioption.h"
40
41
42 ////
43 //// Local definitions
44 ////
45
46 namespace {
47
48   /// Types
49
50   // The BetaCounterType class is used to order moves at ply one.
51   // Apart for the first one that has its score, following moves
52   // normally have score -VALUE_INFINITE, so are ordered according
53   // to the number of beta cutoffs occurred under their subtree during
54   // the last iteration.
55
56   struct BetaCounterType {
57
58     BetaCounterType();
59     void clear();
60     void add(Color us, Depth d, int threadID);
61     void read(Color us, int64_t& our, int64_t& their);
62
63     int64_t hits[THREAD_MAX][2];
64   };
65
66
67   // The RootMove class is used for moves at the root at the tree.  For each
68   // root move, we store a score, a node count, and a PV (really a refutation
69   // in the case of moves which fail low).
70
71   struct RootMove {
72
73     RootMove();
74     bool operator<(const RootMove&); // used to sort
75
76     Move move;
77     Value score;
78     int64_t nodes, cumulativeNodes;
79     Move pv[PLY_MAX_PLUS_2];
80     int64_t ourBeta, theirBeta;
81   };
82
83
84   // The RootMoveList class is essentially an array of RootMove objects, with
85   // a handful of methods for accessing the data in the individual moves.
86
87   class RootMoveList {
88
89   public:
90     RootMoveList(Position &pos, Move searchMoves[]);
91     inline Move get_move(int moveNum) const;
92     inline Value get_move_score(int moveNum) const;
93     inline void set_move_score(int moveNum, Value score);
94     inline void set_move_nodes(int moveNum, int64_t nodes);
95     inline void set_beta_counters(int moveNum, int64_t our, int64_t their);
96     void set_move_pv(int moveNum, const Move pv[]);
97     inline Move get_move_pv(int moveNum, int i) const;
98     inline int64_t get_move_cumulative_nodes(int moveNum) const;
99     inline int move_count() const;
100     Move scan_for_easy_move() const;
101     inline void sort();
102     void sort_multipv(int n);
103
104   private:
105     static const int MaxRootMoves = 500;
106     RootMove moves[MaxRootMoves];
107     int count;
108   };
109
110
111   /// Constants and variables
112
113   // Minimum number of full depth (i.e. non-reduced) moves at PV and non-PV
114   // nodes:
115   int LMRPVMoves = 15;
116   int LMRNonPVMoves = 4;
117
118   // Depth limit for use of dynamic threat detection:
119   Depth ThreatDepth = 5*OnePly;
120
121   // Depth limit for selective search:
122   Depth SelectiveDepth = 7*OnePly;
123
124   // Use internal iterative deepening?
125   const bool UseIIDAtPVNodes = true;
126   const bool UseIIDAtNonPVNodes = false;
127
128   // Internal iterative deepening margin.  At Non-PV moves, when
129   // UseIIDAtNonPVNodes is true, we do an internal iterative deepening search
130   // when the static evaluation is at most IIDMargin below beta.
131   const Value IIDMargin = Value(0x100);
132
133   // Easy move margin.  An easy move candidate must be at least this much
134   // better than the second best move.
135   const Value EasyMoveMargin = Value(0x200);
136
137   // Problem margin.  If the score of the first move at iteration N+1 has
138   // dropped by more than this since iteration N, the boolean variable
139   // "Problem" is set to true, which will make the program spend some extra
140   // time looking for a better move.
141   const Value ProblemMargin = Value(0x28);
142
143   // No problem margin.  If the boolean "Problem" is true, and a new move
144   // is found at the root which is less than NoProblemMargin worse than the
145   // best move from the previous iteration, Problem is set back to false.
146   const Value NoProblemMargin = Value(0x14);
147
148   // Null move margin.  A null move search will not be done if the approximate
149   // evaluation of the position is more than NullMoveMargin below beta.
150   const Value NullMoveMargin = Value(0x300);
151
152   // Pruning criterions.  See the code and comments in ok_to_prune() to
153   // understand their precise meaning.
154   const bool PruneEscapeMoves = false;
155   const bool PruneDefendingMoves = false;
156   const bool PruneBlockingMoves = false;
157
158   // Use futility pruning?
159   bool UseQSearchFutilityPruning = true;
160   bool UseFutilityPruning = true;
161
162   // Margins for futility pruning in the quiescence search, and at frontier
163   // and near frontier nodes
164   Value FutilityMarginQS = Value(0x80);
165   Value FutilityMargins[6] = { Value(0x100), Value(0x200), Value(0x250),
166                                Value(0x2A0), Value(0x340), Value(0x3A0) };
167
168   // Razoring
169   const bool RazorAtDepthOne = false;
170   Depth RazorDepth = 4*OnePly;
171   Value RazorMargin = Value(0x300);
172
173   // Last seconds noise filtering (LSN)
174   bool UseLSNFiltering = false;
175   bool looseOnTime = false;
176   int LSNTime = 4 * 1000; // In milliseconds
177   Value LSNValue = Value(0x200);
178
179   // Extensions.  Array index 0 is used at non-PV nodes, index 1 at PV nodes.
180   Depth CheckExtension[2] = {OnePly, OnePly};
181   Depth SingleReplyExtension[2] = {OnePly / 2, OnePly / 2};
182   Depth PawnPushTo7thExtension[2] = {OnePly / 2, OnePly / 2};
183   Depth PassedPawnExtension[2] = {Depth(0), Depth(0)};
184   Depth PawnEndgameExtension[2] = {OnePly, OnePly};
185   Depth MateThreatExtension[2] = {Depth(0), Depth(0)};
186
187   // Search depth at iteration 1
188   const Depth InitialDepth = OnePly /*+ OnePly/2*/;
189
190   // Node counters
191   int NodesSincePoll;
192   int NodesBetweenPolls = 30000;
193
194   // Iteration counters
195   int Iteration;
196   BetaCounterType BetaCounter;
197
198   // Scores and number of times the best move changed for each iteration:
199   Value ValueByIteration[PLY_MAX_PLUS_2];
200   int BestMoveChangesByIteration[PLY_MAX_PLUS_2];
201
202   // MultiPV mode
203   int MultiPV = 1;
204
205   // Time managment variables
206   int SearchStartTime;
207   int MaxNodes, MaxDepth;
208   int MaxSearchTime, AbsoluteMaxSearchTime, ExtraSearchTime;
209   Move EasyMove;
210   int RootMoveNumber;
211   bool InfiniteSearch;
212   bool PonderSearch;
213   bool StopOnPonderhit;
214   bool AbortSearch;
215   bool Quit;
216   bool FailHigh;
217   bool Problem;
218   bool PonderingEnabled;
219   int ExactMaxTime;
220
221   // Show current line?
222   bool ShowCurrentLine = false;
223
224   // Log file
225   bool UseLogFile = false;
226   std::ofstream LogFile;
227
228   // MP related variables
229   Depth MinimumSplitDepth = 4*OnePly;
230   int MaxThreadsPerSplitPoint = 4;
231   Thread Threads[THREAD_MAX];
232   Lock MPLock;
233   bool AllThreadsShouldExit = false;
234   const int MaxActiveSplitPoints = 8;
235   SplitPoint SplitPointStack[THREAD_MAX][MaxActiveSplitPoints];
236   bool Idle = true;
237
238 #if !defined(_MSC_VER)
239   pthread_cond_t WaitCond;
240   pthread_mutex_t WaitLock;
241 #else
242   HANDLE SitIdleEvent[THREAD_MAX];
243 #endif
244
245
246   /// Functions
247
248   Value id_loop(const Position &pos, Move searchMoves[]);
249   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml);
250   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
251                   Depth depth, int ply, int threadID);
252   Value search(Position &pos, SearchStack ss[], Value beta,
253                Depth depth, int ply, bool allowNullmove, int threadID);
254   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
255                 Depth depth, int ply, int threadID);
256   void sp_search(SplitPoint *sp, int threadID);
257   void sp_search_pv(SplitPoint *sp, int threadID);
258   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID);
259   void update_pv(SearchStack ss[], int ply);
260   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply);
261   bool connected_moves(const Position &pos, Move m1, Move m2);
262   bool value_is_mate(Value value);
263   bool move_is_killer(Move m, const SearchStack& ss);
264   Depth extension(const Position &pos, Move m, bool pvNode, bool capture, bool check, bool singleReply, bool mateThreat, bool* dangerous);
265   bool ok_to_do_nullmove(const Position &pos);
266   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d);
267   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply);
268   bool ok_to_history(const Position &pos, Move m);
269   void update_history(const Position& pos, Move m, Depth depth, Move movesSearched[], int moveCount);
270   void update_killers(Move m, SearchStack& ss);
271
272   bool fail_high_ply_1();
273   int current_search_time();
274   int nps();
275   void poll();
276   void ponderhit();
277   void print_current_line(SearchStack ss[], int ply, int threadID);
278   void wait_for_stop_or_ponderhit();
279
280   void idle_loop(int threadID, SplitPoint *waitSp);
281   void init_split_point_stack();
282   void destroy_split_point_stack();
283   bool thread_should_stop(int threadID);
284   bool thread_is_available(int slave, int master);
285   bool idle_thread_exists(int master);
286   bool split(const Position &pos, SearchStack *ss, int ply,
287              Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
288              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode);
289   void wake_sleeping_threads();
290
291 #if !defined(_MSC_VER)
292   void *init_thread(void *threadID);
293 #else
294   DWORD WINAPI init_thread(LPVOID threadID);
295 #endif
296
297 }
298
299
300 ////
301 //// Global variables
302 ////
303
304 // The main transposition table
305 TranspositionTable TT = TranspositionTable(TTDefaultSize);
306
307
308 // Number of active threads:
309 int ActiveThreads = 1;
310
311 // Locks.  In principle, there is no need for IOLock to be a global variable,
312 // but it could turn out to be useful for debugging.
313 Lock IOLock;
314
315 History H;  // Should be made local?
316
317 // The empty search stack
318 SearchStack EmptySearchStack;
319
320
321 // SearchStack::init() initializes a search stack. Used at the beginning of a
322 // new search from the root.
323 void SearchStack::init(int ply) {
324
325   pv[ply] = pv[ply + 1] = MOVE_NONE;
326   currentMove = threatMove = MOVE_NONE;
327   reduction = Depth(0);
328   currentMoveCaptureValue = Value(0);
329 }
330
331 void SearchStack::initKillers() {
332
333   mateKiller = MOVE_NONE;
334   for (int i = 0; i < KILLER_MAX; i++)
335       killers[i] = MOVE_NONE;
336 }
337
338
339 ////
340 //// Functions
341 ////
342
343 /// think() is the external interface to Stockfish's search, and is called when
344 /// the program receives the UCI 'go' command.  It initializes various
345 /// search-related global variables, and calls root_search()
346
347 void think(const Position &pos, bool infinite, bool ponder, int side_to_move,
348            int time[], int increment[], int movesToGo, int maxDepth,
349            int maxNodes, int maxTime, Move searchMoves[]) {
350
351   // Look for a book move
352   if (!infinite && !ponder && get_option_value_bool("OwnBook"))
353   {
354       Move bookMove;
355       if (get_option_value_string("Book File") != OpeningBook.file_name())
356       {
357           OpeningBook.close();
358           OpeningBook.open("book.bin");
359       }
360       bookMove = OpeningBook.get_move(pos);
361       if (bookMove != MOVE_NONE)
362       {
363           std::cout << "bestmove " << bookMove << std::endl;
364           return;
365       }
366   }
367
368   // Initialize global search variables
369   Idle = false;
370   SearchStartTime = get_system_time();
371   EasyMove = MOVE_NONE;
372   for (int i = 0; i < THREAD_MAX; i++)
373   {
374       Threads[i].nodes = 0ULL;
375       Threads[i].failHighPly1 = false;
376   }
377   NodesSincePoll = 0;
378   InfiniteSearch = infinite;
379   PonderSearch = ponder;
380   StopOnPonderhit = false;
381   AbortSearch = false;
382   Quit = false;
383   FailHigh = false;
384   Problem = false;
385   ExactMaxTime = maxTime;
386
387   // Read UCI option values
388   TT.set_size(get_option_value_int("Hash"));
389   if (button_was_pressed("Clear Hash"))
390       TT.clear();
391
392   PonderingEnabled = get_option_value_bool("Ponder");
393   MultiPV = get_option_value_int("MultiPV");
394
395   CheckExtension[1] = Depth(get_option_value_int("Check Extension (PV nodes)"));
396   CheckExtension[0] = Depth(get_option_value_int("Check Extension (non-PV nodes)"));
397
398   SingleReplyExtension[1] = Depth(get_option_value_int("Single Reply Extension (PV nodes)"));
399   SingleReplyExtension[0] = Depth(get_option_value_int("Single Reply Extension (non-PV nodes)"));
400
401   PawnPushTo7thExtension[1] = Depth(get_option_value_int("Pawn Push to 7th Extension (PV nodes)"));
402   PawnPushTo7thExtension[0] = Depth(get_option_value_int("Pawn Push to 7th Extension (non-PV nodes)"));
403
404   PassedPawnExtension[1] = Depth(get_option_value_int("Passed Pawn Extension (PV nodes)"));
405   PassedPawnExtension[0] = Depth(get_option_value_int("Passed Pawn Extension (non-PV nodes)"));
406
407   PawnEndgameExtension[1] = Depth(get_option_value_int("Pawn Endgame Extension (PV nodes)"));
408   PawnEndgameExtension[0] = Depth(get_option_value_int("Pawn Endgame Extension (non-PV nodes)"));
409
410   MateThreatExtension[1] = Depth(get_option_value_int("Mate Threat Extension (PV nodes)"));
411   MateThreatExtension[0] = Depth(get_option_value_int("Mate Threat Extension (non-PV nodes)"));
412
413   LMRPVMoves     = get_option_value_int("Full Depth Moves (PV nodes)") + 1;
414   LMRNonPVMoves  = get_option_value_int("Full Depth Moves (non-PV nodes)") + 1;
415   ThreatDepth    = get_option_value_int("Threat Depth") * OnePly;
416   SelectiveDepth = get_option_value_int("Selective Plies") * OnePly;
417
418   Chess960 = get_option_value_bool("UCI_Chess960");
419   ShowCurrentLine = get_option_value_bool("UCI_ShowCurrLine");
420   UseLogFile = get_option_value_bool("Use Search Log");
421   if (UseLogFile)
422       LogFile.open(get_option_value_string("Search Log Filename").c_str(), std::ios::out | std::ios::app);
423
424   UseQSearchFutilityPruning = get_option_value_bool("Futility Pruning (Quiescence Search)");
425   UseFutilityPruning = get_option_value_bool("Futility Pruning (Main Search)");
426
427   FutilityMarginQS = value_from_centipawns(get_option_value_int("Futility Margin (Quiescence Search)"));
428   int fmScale = get_option_value_int("Futility Margin Scale Factor (Main Search)");
429   for (int i = 0; i < 6; i++)
430       FutilityMargins[i] = (FutilityMargins[i] * fmScale) / 100;
431
432   RazorDepth = (get_option_value_int("Maximum Razoring Depth") + 1) * OnePly;
433   RazorMargin = value_from_centipawns(get_option_value_int("Razoring Margin"));
434
435   UseLSNFiltering = get_option_value_bool("LSN filtering");
436   LSNTime = get_option_value_int("LSN Time Margin (sec)") * 1000;
437   LSNValue = value_from_centipawns(get_option_value_int("LSN Value Margin"));
438
439   MinimumSplitDepth = get_option_value_int("Minimum Split Depth") * OnePly;
440   MaxThreadsPerSplitPoint = get_option_value_int("Maximum Number of Threads per Split Point");
441
442   read_weights(pos.side_to_move());
443
444   int newActiveThreads = get_option_value_int("Threads");
445   if (newActiveThreads != ActiveThreads)
446   {
447       ActiveThreads = newActiveThreads;
448       init_eval(ActiveThreads);
449   }
450
451   // Wake up sleeping threads:
452   wake_sleeping_threads();
453
454   for (int i = 1; i < ActiveThreads; i++)
455       assert(thread_is_available(i, 0));
456
457   // Set thinking time:
458   int myTime = time[side_to_move];
459   int myIncrement = increment[side_to_move];
460
461   if (!movesToGo) // Sudden death time control
462   {
463       if (myIncrement)
464       {
465           MaxSearchTime = myTime / 30 + myIncrement;
466           AbsoluteMaxSearchTime = Max(myTime / 4, myIncrement - 100);
467       } else { // Blitz game without increment
468           MaxSearchTime = myTime / 30;
469           AbsoluteMaxSearchTime = myTime / 8;
470       }
471   }
472   else // (x moves) / (y minutes)
473   {
474       if (movesToGo == 1)
475       {
476           MaxSearchTime = myTime / 2;
477           AbsoluteMaxSearchTime = Min(myTime / 2, myTime - 500);
478       } else {
479           MaxSearchTime = myTime / Min(movesToGo, 20);
480           AbsoluteMaxSearchTime = Min((4 * myTime) / movesToGo, myTime / 3);
481       }
482   }
483
484   if (PonderingEnabled)
485   {
486       MaxSearchTime += MaxSearchTime / 4;
487       MaxSearchTime = Min(MaxSearchTime, AbsoluteMaxSearchTime);
488   }
489
490   // Fixed depth or fixed number of nodes?
491   MaxDepth = maxDepth;
492   if (MaxDepth)
493       InfiniteSearch = true; // HACK
494
495   MaxNodes = maxNodes;
496   if (MaxNodes)
497   {
498       NodesBetweenPolls = Min(MaxNodes, 30000);
499       InfiniteSearch = true; // HACK
500   }
501   else
502       NodesBetweenPolls = 30000;
503
504
505   // Write information to search log file:
506   if (UseLogFile)
507       LogFile << "Searching: " << pos.to_fen() << std::endl
508               << "infinite: " << infinite
509               << " ponder: " << ponder
510               << " time: " << myTime
511               << " increment: " << myIncrement
512               << " moves to go: " << movesToGo << std::endl;
513
514
515   // We're ready to start thinking.  Call the iterative deepening loop
516   // function:
517   if (!looseOnTime)
518   {
519       Value v = id_loop(pos, searchMoves);
520       looseOnTime = (   UseLSNFiltering
521                      && myTime < LSNTime
522                      && myIncrement == 0
523                      && v < -LSNValue);
524   }
525   else
526   {
527       looseOnTime = false; // reset for next match
528       while (SearchStartTime + myTime + 1000 > get_system_time())
529           ; // wait here
530       id_loop(pos, searchMoves); // to fail gracefully
531   }
532
533   if (UseLogFile)
534       LogFile.close();
535
536   if (Quit)
537   {
538       OpeningBook.close();
539       stop_threads();
540       quit_eval();
541       exit(0);
542   }
543   Idle = true;
544 }
545
546
547 /// init_threads() is called during startup.  It launches all helper threads,
548 /// and initializes the split point stack and the global locks and condition
549 /// objects.
550
551 void init_threads() {
552
553   volatile int i;
554
555 #if !defined(_MSC_VER)
556   pthread_t pthread[1];
557 #endif
558
559   for (i = 0; i < THREAD_MAX; i++)
560       Threads[i].activeSplitPoints = 0;
561
562   // Initialize global locks:
563   lock_init(&MPLock, NULL);
564   lock_init(&IOLock, NULL);
565
566   init_split_point_stack();
567
568 #if !defined(_MSC_VER)
569   pthread_mutex_init(&WaitLock, NULL);
570   pthread_cond_init(&WaitCond, NULL);
571 #else
572   for (i = 0; i < THREAD_MAX; i++)
573       SitIdleEvent[i] = CreateEvent(0, FALSE, FALSE, 0);
574 #endif
575
576   // All threads except the main thread should be initialized to idle state
577   for (i = 1; i < THREAD_MAX; i++)
578   {
579       Threads[i].stop = false;
580       Threads[i].workIsWaiting = false;
581       Threads[i].idle = true;
582       Threads[i].running = false;
583   }
584
585   // Launch the helper threads
586   for(i = 1; i < THREAD_MAX; i++)
587   {
588 #if !defined(_MSC_VER)
589       pthread_create(pthread, NULL, init_thread, (void*)(&i));
590 #else
591       DWORD iID[1];
592       CreateThread(NULL, 0, init_thread, (LPVOID)(&i), 0, iID);
593 #endif
594
595       // Wait until the thread has finished launching:
596       while (!Threads[i].running);
597   }
598
599   // Init also the empty search stack
600   EmptySearchStack.init(0);
601   EmptySearchStack.initKillers();
602 }
603
604
605 /// stop_threads() is called when the program exits.  It makes all the
606 /// helper threads exit cleanly.
607
608 void stop_threads() {
609
610   ActiveThreads = THREAD_MAX;  // HACK
611   Idle = false;  // HACK
612   wake_sleeping_threads();
613   AllThreadsShouldExit = true;
614   for (int i = 1; i < THREAD_MAX; i++)
615   {
616       Threads[i].stop = true;
617       while(Threads[i].running);
618   }
619   destroy_split_point_stack();
620 }
621
622
623 /// nodes_searched() returns the total number of nodes searched so far in
624 /// the current search.
625
626 int64_t nodes_searched() {
627
628   int64_t result = 0ULL;
629   for (int i = 0; i < ActiveThreads; i++)
630       result += Threads[i].nodes;
631   return result;
632 }
633
634
635 namespace {
636
637   // id_loop() is the main iterative deepening loop.  It calls root_search
638   // repeatedly with increasing depth until the allocated thinking time has
639   // been consumed, the user stops the search, or the maximum search depth is
640   // reached.
641
642   Value id_loop(const Position &pos, Move searchMoves[]) {
643
644     Position p(pos);
645     SearchStack ss[PLY_MAX_PLUS_2];
646
647     // searchMoves are verified, copied, scored and sorted
648     RootMoveList rml(p, searchMoves);
649
650     // Initialize
651     TT.new_search();
652     H.clear();
653     for (int i = 0; i < 3; i++)
654     {
655         ss[i].init(i);
656         ss[i].initKillers();
657     }
658     ValueByIteration[0] = Value(0);
659     ValueByIteration[1] = rml.get_move_score(0);
660     Iteration = 1;
661
662     EasyMove = rml.scan_for_easy_move();
663
664     // Iterative deepening loop
665     while (!AbortSearch && Iteration < PLY_MAX)
666     {
667         // Initialize iteration
668         rml.sort();
669         Iteration++;
670         BestMoveChangesByIteration[Iteration] = 0;
671         if (Iteration <= 5)
672             ExtraSearchTime = 0;
673
674         std::cout << "info depth " << Iteration << std::endl;
675
676         // Search to the current depth
677         ValueByIteration[Iteration] = root_search(p, ss, rml);
678
679         // Erase the easy move if it differs from the new best move
680         if (ss[0].pv[0] != EasyMove)
681             EasyMove = MOVE_NONE;
682
683         Problem = false;
684
685         if (!InfiniteSearch)
686         {
687             // Time to stop?
688             bool stopSearch = false;
689
690             // Stop search early if there is only a single legal move:
691             if (Iteration >= 6 && rml.move_count() == 1)
692                 stopSearch = true;
693
694             // Stop search early when the last two iterations returned a mate score
695             if (  Iteration >= 6
696                 && abs(ValueByIteration[Iteration]) >= abs(VALUE_MATE) - 100
697                 && abs(ValueByIteration[Iteration-1]) >= abs(VALUE_MATE) - 100)
698                 stopSearch = true;
699
700             // Stop search early if one move seems to be much better than the rest
701             int64_t nodes = nodes_searched();
702             if (   Iteration >= 8
703                 && EasyMove == ss[0].pv[0]
704                 && (  (   rml.get_move_cumulative_nodes(0) > (nodes * 85) / 100
705                        && current_search_time() > MaxSearchTime / 16)
706                     ||(   rml.get_move_cumulative_nodes(0) > (nodes * 98) / 100
707                        && current_search_time() > MaxSearchTime / 32)))
708                 stopSearch = true;
709
710             // Add some extra time if the best move has changed during the last two iterations
711             if (Iteration > 5 && Iteration <= 50)
712                 ExtraSearchTime = BestMoveChangesByIteration[Iteration]   * (MaxSearchTime / 2)
713                                 + BestMoveChangesByIteration[Iteration-1] * (MaxSearchTime / 3);
714
715             // Stop search if most of MaxSearchTime is consumed at the end of the
716             // iteration.  We probably don't have enough time to search the first
717             // move at the next iteration anyway.
718             if (current_search_time() > ((MaxSearchTime + ExtraSearchTime)*80) / 128)
719                 stopSearch = true;
720
721             if (stopSearch)
722             {
723                 if (!PonderSearch)
724                     break;
725                 else
726                     StopOnPonderhit = true;
727             }
728         }
729         // Write PV to transposition table, in case the relevant entries have
730         // been overwritten during the search:
731         TT.insert_pv(p, ss[0].pv);
732
733         if (MaxDepth && Iteration >= MaxDepth)
734             break;
735     }
736
737     rml.sort();
738
739     // If we are pondering, we shouldn't print the best move before we
740     // are told to do so
741     if (PonderSearch)
742         wait_for_stop_or_ponderhit();
743     else
744         // Print final search statistics
745         std::cout << "info nodes " << nodes_searched()
746                   << " nps " << nps()
747                   << " time " << current_search_time()
748                   << " hashfull " << TT.full() << std::endl;
749
750     // Print the best move and the ponder move to the standard output
751     if (ss[0].pv[0] == MOVE_NONE)
752     {
753         ss[0].pv[0] = rml.get_move(0);
754         ss[0].pv[1] = MOVE_NONE;
755     }
756     std::cout << "bestmove " << ss[0].pv[0];
757     if (ss[0].pv[1] != MOVE_NONE)
758         std::cout << " ponder " << ss[0].pv[1];
759
760     std::cout << std::endl;
761
762     if (UseLogFile)
763     {
764         if (dbg_show_mean)
765             dbg_print_mean(LogFile);
766
767         if (dbg_show_hit_rate)
768             dbg_print_hit_rate(LogFile);
769
770         StateInfo st;
771         LogFile << "Nodes: " << nodes_searched() << std::endl
772                 << "Nodes/second: " << nps() << std::endl
773                 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
774
775         p.do_move(ss[0].pv[0], st);
776         LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
777                 << std::endl << std::endl;
778     }
779     return rml.get_move_score(0);
780   }
781
782
783   // root_search() is the function which searches the root node.  It is
784   // similar to search_pv except that it uses a different move ordering
785   // scheme (perhaps we should try to use this at internal PV nodes, too?)
786   // and prints some information to the standard output.
787
788   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
789
790     Value alpha = -VALUE_INFINITE;
791     Value beta = VALUE_INFINITE, value;
792     Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
793
794     // Loop through all the moves in the root move list
795     for (int i = 0; i <  rml.move_count() && !AbortSearch; i++)
796     {
797         int64_t nodes;
798         Move move;
799         StateInfo st;
800         Depth ext, newDepth;
801
802         RootMoveNumber = i + 1;
803         FailHigh = false;
804
805         // Remember the node count before the move is searched. The node counts
806         // are used to sort the root moves at the next iteration.
807         nodes = nodes_searched();
808
809         // Reset beta cut-off counters
810         BetaCounter.clear();
811
812         // Pick the next root move, and print the move and the move number to
813         // the standard output.
814         move = ss[0].currentMove = rml.get_move(i);
815         if (current_search_time() >= 1000)
816             std::cout << "info currmove " << move
817                       << " currmovenumber " << i + 1 << std::endl;
818
819         // Decide search depth for this move
820         bool dangerous;
821         ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
822         newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
823
824         // Make the move, and search it
825         pos.do_move(move, st, dcCandidates);
826
827         if (i < MultiPV)
828         {
829             value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
830             // If the value has dropped a lot compared to the last iteration,
831             // set the boolean variable Problem to true. This variable is used
832             // for time managment: When Problem is true, we try to complete the
833             // current iteration before playing a move.
834             Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
835
836             if (Problem && StopOnPonderhit)
837                 StopOnPonderhit = false;
838         }
839         else
840         {
841             value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
842             if (value > alpha)
843             {
844                 // Fail high! Set the boolean variable FailHigh to true, and
845                 // re-search the move with a big window. The variable FailHigh is
846                 // used for time managment: We try to avoid aborting the search
847                 // prematurely during a fail high research.
848                 FailHigh = true;
849                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
850             }
851         }
852
853         pos.undo_move(move);
854
855         // Finished searching the move. If AbortSearch is true, the search
856         // was aborted because the user interrupted the search or because we
857         // ran out of time. In this case, the return value of the search cannot
858         // be trusted, and we break out of the loop without updating the best
859         // move and/or PV:
860         if (AbortSearch)
861             break;
862
863         // Remember the node count for this move. The node counts are used to
864         // sort the root moves at the next iteration.
865         rml.set_move_nodes(i, nodes_searched() - nodes);
866
867         // Remember the beta-cutoff statistics
868         int64_t our, their;
869         BetaCounter.read(pos.side_to_move(), our, their);
870         rml.set_beta_counters(i, our, their);
871
872         assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
873
874         if (value <= alpha && i >= MultiPV)
875             rml.set_move_score(i, -VALUE_INFINITE);
876         else
877         {
878             // New best move!
879
880             // Update PV
881             rml.set_move_score(i, value);
882             update_pv(ss, 0);
883             rml.set_move_pv(i, ss[0].pv);
884
885             if (MultiPV == 1)
886             {
887                 // We record how often the best move has been changed in each
888                 // iteration. This information is used for time managment: When
889                 // the best move changes frequently, we allocate some more time.
890                 if (i > 0)
891                     BestMoveChangesByIteration[Iteration]++;
892
893                 // Print search information to the standard output:
894                 std::cout << "info depth " << Iteration
895                           << " score " << value_to_string(value)
896                           << " time " << current_search_time()
897                           << " nodes " << nodes_searched()
898                           << " nps " << nps()
899                           << " pv ";
900
901                 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
902                     std::cout << ss[0].pv[j] << " ";
903
904                 std::cout << std::endl;
905
906                 if (UseLogFile)
907                     LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
908                             << std::endl;
909
910                 alpha = value;
911
912                 // Reset the global variable Problem to false if the value isn't too
913                 // far below the final value from the last iteration.
914                 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
915                     Problem = false;
916             }
917             else // MultiPV > 1
918             {
919                 rml.sort_multipv(i);
920                 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
921                 {
922                     int k;
923                     std::cout << "info multipv " << j + 1
924                               << " score " << value_to_string(rml.get_move_score(j))
925                               << " depth " << ((j <= i)? Iteration : Iteration - 1)
926                               << " time " << current_search_time()
927                               << " nodes " << nodes_searched()
928                               << " nps " << nps()
929                               << " pv ";
930
931                     for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
932                         std::cout << rml.get_move_pv(j, k) << " ";
933
934                     std::cout << std::endl;
935                 }
936                 alpha = rml.get_move_score(Min(i, MultiPV-1));
937             }
938         }
939     }
940     return alpha;
941   }
942
943
944   // search_pv() is the main search function for PV nodes.
945
946   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
947                   Depth depth, int ply, int threadID) {
948
949     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
950     assert(beta > alpha && beta <= VALUE_INFINITE);
951     assert(ply >= 0 && ply < PLY_MAX);
952     assert(threadID >= 0 && threadID < ActiveThreads);
953
954     if (depth < OnePly)
955         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
956
957     // Initialize, and make an early exit in case of an aborted search,
958     // an instant draw, maximum ply reached, etc.
959     init_node(pos, ss, ply, threadID);
960
961     // After init_node() that calls poll()
962     if (AbortSearch || thread_should_stop(threadID))
963         return Value(0);
964
965     if (pos.is_draw())
966         return VALUE_DRAW;
967
968     EvalInfo ei;
969
970     if (ply >= PLY_MAX - 1)
971         return evaluate(pos, ei, threadID);
972
973     // Mate distance pruning
974     Value oldAlpha = alpha;
975     alpha = Max(value_mated_in(ply), alpha);
976     beta = Min(value_mate_in(ply+1), beta);
977     if (alpha >= beta)
978         return alpha;
979
980     // Transposition table lookup. At PV nodes, we don't use the TT for
981     // pruning, but only for move ordering.
982     const TTEntry* tte = TT.retrieve(pos);
983     Move ttMove = (tte ? tte->move() : MOVE_NONE);
984
985     // Go with internal iterative deepening if we don't have a TT move
986     if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
987     {
988         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
989         ttMove = ss[ply].pv[ply];
990     }
991
992     // Initialize a MovePicker object for the current position, and prepare
993     // to search all moves
994     MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
995
996     Move move, movesSearched[256];
997     int moveCount = 0;
998     Value value, bestValue = -VALUE_INFINITE;
999     Bitboard dcCandidates = mp.discovered_check_candidates();
1000     Color us = pos.side_to_move();
1001     bool isCheck = pos.is_check();
1002     bool mateThreat = pos.has_mate_threat(opposite_color(us));
1003
1004     // Loop through all legal moves until no moves remain or a beta cutoff
1005     // occurs.
1006     while (   alpha < beta
1007            && (move = mp.get_next_move()) != MOVE_NONE
1008            && !thread_should_stop(threadID))
1009     {
1010       assert(move_is_ok(move));
1011
1012       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1013       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1014       bool moveIsCapture = pos.move_is_capture(move);
1015
1016       movesSearched[moveCount++] = ss[ply].currentMove = move;
1017
1018       if (moveIsCapture)
1019           ss[ply].currentMoveCaptureValue =
1020           move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1021       else
1022           ss[ply].currentMoveCaptureValue = Value(0);
1023
1024       // Decide the new search depth
1025       bool dangerous;
1026       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1027       Depth newDepth = depth - OnePly + ext;
1028
1029       // Make and search the move
1030       StateInfo st;
1031       pos.do_move(move, st, dcCandidates);
1032
1033       if (moveCount == 1) // The first move in list is the PV
1034           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1035       else
1036       {
1037         // Try to reduce non-pv search depth by one ply if move seems not problematic,
1038         // if the move fails high will be re-searched at full depth.
1039         if (    depth >= 2*OnePly
1040             &&  moveCount >= LMRPVMoves
1041             && !dangerous
1042             && !moveIsCapture
1043             && !move_promotion(move)
1044             && !move_is_castle(move)
1045             && !move_is_killer(move, ss[ply]))
1046         {
1047             ss[ply].reduction = OnePly;
1048             value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1049         }
1050         else
1051             value = alpha + 1; // Just to trigger next condition
1052
1053         if (value > alpha) // Go with full depth non-pv search
1054         {
1055             ss[ply].reduction = Depth(0);
1056             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1057             if (value > alpha && value < beta)
1058             {
1059                 // When the search fails high at ply 1 while searching the first
1060                 // move at the root, set the flag failHighPly1. This is used for
1061                 // time managment:  We don't want to stop the search early in
1062                 // such cases, because resolving the fail high at ply 1 could
1063                 // result in a big drop in score at the root.
1064                 if (ply == 1 && RootMoveNumber == 1)
1065                     Threads[threadID].failHighPly1 = true;
1066
1067                 // A fail high occurred. Re-search at full window (pv search)
1068                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1069                 Threads[threadID].failHighPly1 = false;
1070           }
1071         }
1072       }
1073       pos.undo_move(move);
1074
1075       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1076
1077       // New best move?
1078       if (value > bestValue)
1079       {
1080           bestValue = value;
1081           if (value > alpha)
1082           {
1083               alpha = value;
1084               update_pv(ss, ply);
1085               if (value == value_mate_in(ply + 1))
1086                   ss[ply].mateKiller = move;
1087           }
1088           // If we are at ply 1, and we are searching the first root move at
1089           // ply 0, set the 'Problem' variable if the score has dropped a lot
1090           // (from the computer's point of view) since the previous iteration:
1091           if (   ply == 1
1092               && Iteration >= 2
1093               && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1094               Problem = true;
1095       }
1096
1097       // Split?
1098       if (   ActiveThreads > 1
1099           && bestValue < beta
1100           && depth >= MinimumSplitDepth
1101           && Iteration <= 99
1102           && idle_thread_exists(threadID)
1103           && !AbortSearch
1104           && !thread_should_stop(threadID)
1105           && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1106                    &moveCount, &mp, dcCandidates, threadID, true))
1107           break;
1108     }
1109
1110     // All legal moves have been searched.  A special case: If there were
1111     // no legal moves, it must be mate or stalemate:
1112     if (moveCount == 0)
1113         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1114
1115     // If the search is not aborted, update the transposition table,
1116     // history counters, and killer moves.
1117     if (AbortSearch || thread_should_stop(threadID))
1118         return bestValue;
1119
1120     if (bestValue <= oldAlpha)
1121         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1122
1123     else if (bestValue >= beta)
1124     {
1125         BetaCounter.add(pos.side_to_move(), depth, threadID);
1126         Move m = ss[ply].pv[ply];
1127         if (ok_to_history(pos, m)) // Only non capture moves are considered
1128         {
1129             update_history(pos, m, depth, movesSearched, moveCount);
1130             update_killers(m, ss[ply]);
1131         }
1132         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1133     }
1134     else
1135         TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1136
1137     return bestValue;
1138   }
1139
1140
1141   // search() is the search function for zero-width nodes.
1142
1143   Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1144                int ply, bool allowNullmove, int threadID) {
1145
1146     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1147     assert(ply >= 0 && ply < PLY_MAX);
1148     assert(threadID >= 0 && threadID < ActiveThreads);
1149
1150     if (depth < OnePly)
1151         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1152
1153     // Initialize, and make an early exit in case of an aborted search,
1154     // an instant draw, maximum ply reached, etc.
1155     init_node(pos, ss, ply, threadID);
1156
1157     // After init_node() that calls poll()
1158     if (AbortSearch || thread_should_stop(threadID))
1159         return Value(0);
1160
1161     if (pos.is_draw())
1162         return VALUE_DRAW;
1163
1164     EvalInfo ei;
1165
1166     if (ply >= PLY_MAX - 1)
1167         return evaluate(pos, ei, threadID);
1168
1169     // Mate distance pruning
1170     if (value_mated_in(ply) >= beta)
1171         return beta;
1172
1173     if (value_mate_in(ply + 1) < beta)
1174         return beta - 1;
1175
1176     // Transposition table lookup
1177     const TTEntry* tte = TT.retrieve(pos);
1178     Move ttMove = (tte ? tte->move() : MOVE_NONE);
1179
1180     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1181     {
1182         ss[ply].currentMove = ttMove; // can be MOVE_NONE
1183         return value_from_tt(tte->value(), ply);
1184     }
1185
1186     Value approximateEval = quick_evaluate(pos);
1187     bool mateThreat = false;
1188     bool isCheck = pos.is_check();
1189
1190     // Null move search
1191     if (    allowNullmove
1192         &&  depth > OnePly
1193         && !isCheck
1194         && !value_is_mate(beta)
1195         &&  ok_to_do_nullmove(pos)
1196         &&  approximateEval >= beta - NullMoveMargin)
1197     {
1198         ss[ply].currentMove = MOVE_NULL;
1199
1200         StateInfo st;
1201         pos.do_null_move(st);
1202         int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1203
1204         Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1205
1206         pos.undo_null_move();
1207
1208         if (value_is_mate(nullValue))
1209         {
1210             /* Do not return unproven mates */
1211         }
1212         else if (nullValue >= beta)
1213         {
1214             if (depth < 6 * OnePly)
1215                 return beta;
1216
1217             // Do zugzwang verification search
1218             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1219             if (v >= beta)
1220                 return beta;
1221         } else {
1222             // The null move failed low, which means that we may be faced with
1223             // some kind of threat. If the previous move was reduced, check if
1224             // the move that refuted the null move was somehow connected to the
1225             // move which was reduced. If a connection is found, return a fail
1226             // low score (which will cause the reduced move to fail high in the
1227             // parent node, which will trigger a re-search with full depth).
1228             if (nullValue == value_mated_in(ply + 2))
1229                 mateThreat = true;
1230
1231             ss[ply].threatMove = ss[ply + 1].currentMove;
1232             if (   depth < ThreatDepth
1233                 && ss[ply - 1].reduction
1234                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1235                 return beta - 1;
1236         }
1237     }
1238     // Null move search not allowed, try razoring
1239     else if (   !value_is_mate(beta)
1240              && approximateEval < beta - RazorMargin
1241              && depth < RazorDepth
1242              && (RazorAtDepthOne || depth > OnePly)
1243              && ttMove == MOVE_NONE
1244              && !pos.has_pawn_on_7th(pos.side_to_move()))
1245     {
1246         Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1247         if (   (v < beta - RazorMargin - RazorMargin / 4)
1248             || (depth < 3*OnePly && v < beta - RazorMargin)
1249             || (depth < 2*OnePly && v < beta - RazorMargin / 2))
1250             return v;
1251     }
1252
1253     // Go with internal iterative deepening if we don't have a TT move
1254     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1255         evaluate(pos, ei, threadID) >= beta - IIDMargin)
1256     {
1257         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1258         ttMove = ss[ply].pv[ply];
1259     }
1260
1261     // Initialize a MovePicker object for the current position, and prepare
1262     // to search all moves:
1263     MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1264
1265     Move move, movesSearched[256];
1266     int moveCount = 0;
1267     Value value, bestValue = -VALUE_INFINITE;
1268     Bitboard dcCandidates = mp.discovered_check_candidates();
1269     Value futilityValue = VALUE_NONE;
1270     bool useFutilityPruning =   UseFutilityPruning
1271                              && depth < SelectiveDepth
1272                              && !isCheck;
1273
1274     // Loop through all legal moves until no moves remain or a beta cutoff
1275     // occurs.
1276     while (   bestValue < beta
1277            && (move = mp.get_next_move()) != MOVE_NONE
1278            && !thread_should_stop(threadID))
1279     {
1280       assert(move_is_ok(move));
1281
1282       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1283       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1284       bool moveIsCapture = pos.move_is_capture(move);
1285
1286       movesSearched[moveCount++] = ss[ply].currentMove = move;
1287
1288       // Decide the new search depth
1289       bool dangerous;
1290       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1291       Depth newDepth = depth - OnePly + ext;
1292
1293       // Futility pruning
1294       if (    useFutilityPruning
1295           && !dangerous
1296           && !moveIsCapture
1297           && !move_promotion(move))
1298       {
1299           // History pruning. See ok_to_prune() definition
1300           if (   moveCount >= 2 + int(depth)
1301               && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1302               continue;
1303
1304           // Value based pruning
1305           if (depth < 7 * OnePly && approximateEval < beta)
1306           {
1307               if (futilityValue == VALUE_NONE)
1308                   futilityValue =  evaluate(pos, ei, threadID)
1309                                  + FutilityMargins[int(depth)/2 - 1]
1310                                  + 32 * (depth & 1);
1311
1312               if (futilityValue < beta)
1313               {
1314                   if (futilityValue > bestValue)
1315                       bestValue = futilityValue;
1316                   continue;
1317               }
1318           }
1319       }
1320
1321       // Make and search the move
1322       StateInfo st;
1323       pos.do_move(move, st, dcCandidates);
1324
1325       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1326       // if the move fails high will be re-searched at full depth.
1327       if (    depth >= 2*OnePly
1328           &&  moveCount >= LMRNonPVMoves
1329           && !dangerous
1330           && !moveIsCapture
1331           && !move_promotion(move)
1332           && !move_is_castle(move)
1333           && !move_is_killer(move, ss[ply]))
1334       {
1335           ss[ply].reduction = OnePly;
1336           value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1337       }
1338       else
1339         value = beta; // Just to trigger next condition
1340
1341       if (value >= beta) // Go with full depth non-pv search
1342       {
1343           ss[ply].reduction = Depth(0);
1344           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1345       }
1346       pos.undo_move(move);
1347
1348       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1349
1350       // New best move?
1351       if (value > bestValue)
1352       {
1353         bestValue = value;
1354         if (value >= beta)
1355             update_pv(ss, ply);
1356
1357         if (value == value_mate_in(ply + 1))
1358             ss[ply].mateKiller = move;
1359       }
1360
1361       // Split?
1362       if (   ActiveThreads > 1
1363           && bestValue < beta
1364           && depth >= MinimumSplitDepth
1365           && Iteration <= 99
1366           && idle_thread_exists(threadID)
1367           && !AbortSearch
1368           && !thread_should_stop(threadID)
1369           && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1370                    &mp, dcCandidates, threadID, false))
1371         break;
1372     }
1373
1374     // All legal moves have been searched.  A special case: If there were
1375     // no legal moves, it must be mate or stalemate.
1376     if (moveCount == 0)
1377         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1378
1379     // If the search is not aborted, update the transposition table,
1380     // history counters, and killer moves.
1381     if (AbortSearch || thread_should_stop(threadID))
1382         return bestValue;
1383
1384     if (bestValue < beta)
1385         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1386     else
1387     {
1388         BetaCounter.add(pos.side_to_move(), depth, threadID);
1389         Move m = ss[ply].pv[ply];
1390         if (ok_to_history(pos, m)) // Only non capture moves are considered
1391         {
1392             update_history(pos, m, depth, movesSearched, moveCount);
1393             update_killers(m, ss[ply]);
1394         }
1395         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1396     }
1397
1398     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1399
1400     return bestValue;
1401   }
1402
1403
1404   // qsearch() is the quiescence search function, which is called by the main
1405   // search function when the remaining depth is zero (or, to be more precise,
1406   // less than OnePly).
1407
1408   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1409                 Depth depth, int ply, int threadID) {
1410
1411     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1412     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1413     assert(depth <= 0);
1414     assert(ply >= 0 && ply < PLY_MAX);
1415     assert(threadID >= 0 && threadID < ActiveThreads);
1416
1417     // Initialize, and make an early exit in case of an aborted search,
1418     // an instant draw, maximum ply reached, etc.
1419     init_node(pos, ss, ply, threadID);
1420
1421     // After init_node() that calls poll()
1422     if (AbortSearch || thread_should_stop(threadID))
1423         return Value(0);
1424
1425     if (pos.is_draw())
1426         return VALUE_DRAW;
1427
1428     // Transposition table lookup, only when not in PV
1429     bool pvNode = (beta - alpha != 1);
1430     if (!pvNode)
1431     {
1432         const TTEntry* tte = TT.retrieve(pos);
1433         if (tte && ok_to_use_TT(tte, depth, beta, ply))
1434             return value_from_tt(tte->value(), ply);
1435     }
1436
1437     // Evaluate the position statically
1438     EvalInfo ei;
1439     bool isCheck = pos.is_check();
1440     Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1441
1442     if (ply == PLY_MAX - 1)
1443         return evaluate(pos, ei, threadID);
1444
1445     // Initialize "stand pat score", and return it immediately if it is
1446     // at least beta.
1447     Value bestValue = staticValue;
1448
1449     if (bestValue >= beta)
1450         return bestValue;
1451
1452     if (bestValue > alpha)
1453         alpha = bestValue;
1454
1455     // Initialize a MovePicker object for the current position, and prepare
1456     // to search the moves.  Because the depth is <= 0 here, only captures,
1457     // queen promotions and checks (only if depth == 0) will be generated.
1458     MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1459     Move move;
1460     int moveCount = 0;
1461     Bitboard dcCandidates = mp.discovered_check_candidates();
1462     Color us = pos.side_to_move();
1463     bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1464
1465     // Loop through the moves until no moves remain or a beta cutoff
1466     // occurs.
1467     while (   alpha < beta
1468            && (move = mp.get_next_move()) != MOVE_NONE)
1469     {
1470       assert(move_is_ok(move));
1471
1472       moveCount++;
1473       ss[ply].currentMove = move;
1474
1475       // Futility pruning
1476       if (    UseQSearchFutilityPruning
1477           &&  enoughMaterial
1478           && !isCheck
1479           && !pvNode
1480           && !move_promotion(move)
1481           && !pos.move_is_check(move, dcCandidates)
1482           && !pos.move_is_passed_pawn_push(move))
1483       {
1484           Value futilityValue = staticValue
1485                               + Max(pos.midgame_value_of_piece_on(move_to(move)),
1486                                     pos.endgame_value_of_piece_on(move_to(move)))
1487                               + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1488                               + FutilityMarginQS
1489                               + ei.futilityMargin;
1490
1491           if (futilityValue < alpha)
1492           {
1493               if (futilityValue > bestValue)
1494                   bestValue = futilityValue;
1495               continue;
1496           }
1497       }
1498
1499       // Don't search captures and checks with negative SEE values
1500       if (   !isCheck
1501           && !move_promotion(move)
1502           && (pos.midgame_value_of_piece_on(move_from(move)) >
1503               pos.midgame_value_of_piece_on(move_to(move)))
1504           &&  pos.see(move) < 0)
1505           continue;
1506
1507       // Make and search the move.
1508       StateInfo st;
1509       pos.do_move(move, st, dcCandidates);
1510       Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1511       pos.undo_move(move);
1512
1513       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1514
1515       // New best move?
1516       if (value > bestValue)
1517       {
1518           bestValue = value;
1519           if (value > alpha)
1520           {
1521               alpha = value;
1522               update_pv(ss, ply);
1523           }
1524        }
1525     }
1526
1527     // All legal moves have been searched.  A special case: If we're in check
1528     // and no legal moves were found, it is checkmate:
1529     if (pos.is_check() && moveCount == 0) // Mate!
1530         return value_mated_in(ply);
1531
1532     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1533
1534     // Update transposition table
1535     TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1536
1537     // Update killers only for good check moves
1538     Move m = ss[ply].currentMove;
1539     if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1540     {
1541         // Wrong to update history when depth is <= 0
1542         update_killers(m, ss[ply]);
1543     }
1544     return bestValue;
1545   }
1546
1547
1548   // sp_search() is used to search from a split point.  This function is called
1549   // by each thread working at the split point.  It is similar to the normal
1550   // search() function, but simpler.  Because we have already probed the hash
1551   // table, done a null move search, and searched the first move before
1552   // splitting, we don't have to repeat all this work in sp_search().  We
1553   // also don't need to store anything to the hash table here:  This is taken
1554   // care of after we return from the split point.
1555
1556   void sp_search(SplitPoint *sp, int threadID) {
1557
1558     assert(threadID >= 0 && threadID < ActiveThreads);
1559     assert(ActiveThreads > 1);
1560
1561     Position pos = Position(sp->pos);
1562     SearchStack *ss = sp->sstack[threadID];
1563     Value value;
1564     Move move;
1565     bool isCheck = pos.is_check();
1566     bool useFutilityPruning =    UseFutilityPruning
1567                               && sp->depth < SelectiveDepth
1568                               && !isCheck;
1569
1570     while (    sp->bestValue < sp->beta
1571            && !thread_should_stop(threadID)
1572            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1573     {
1574       assert(move_is_ok(move));
1575
1576       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1577       bool moveIsCapture = pos.move_is_capture(move);
1578
1579       lock_grab(&(sp->lock));
1580       int moveCount = ++sp->moves;
1581       lock_release(&(sp->lock));
1582
1583       ss[sp->ply].currentMove = move;
1584
1585       // Decide the new search depth.
1586       bool dangerous;
1587       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1588       Depth newDepth = sp->depth - OnePly + ext;
1589
1590       // Prune?
1591       if (    useFutilityPruning
1592           && !dangerous
1593           && !moveIsCapture
1594           && !move_promotion(move)
1595           &&  moveCount >= 2 + int(sp->depth)
1596           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1597         continue;
1598
1599       // Make and search the move.
1600       StateInfo st;
1601       pos.do_move(move, st, sp->dcCandidates);
1602
1603       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1604       // if the move fails high will be re-searched at full depth.
1605       if (   !dangerous
1606           &&  moveCount >= LMRNonPVMoves
1607           && !moveIsCapture
1608           && !move_promotion(move)
1609           && !move_is_castle(move)
1610           && !move_is_killer(move, ss[sp->ply]))
1611       {
1612           ss[sp->ply].reduction = OnePly;
1613           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1614       }
1615       else
1616           value = sp->beta; // Just to trigger next condition
1617
1618       if (value >= sp->beta) // Go with full depth non-pv search
1619       {
1620           ss[sp->ply].reduction = Depth(0);
1621           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1622       }
1623       pos.undo_move(move);
1624
1625       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1626
1627       if (thread_should_stop(threadID))
1628           break;
1629
1630       // New best move?
1631       lock_grab(&(sp->lock));
1632       if (value > sp->bestValue && !thread_should_stop(threadID))
1633       {
1634           sp->bestValue = value;
1635           if (sp->bestValue >= sp->beta)
1636           {
1637               sp_update_pv(sp->parentSstack, ss, sp->ply);
1638               for (int i = 0; i < ActiveThreads; i++)
1639                   if (i != threadID && (i == sp->master || sp->slaves[i]))
1640                       Threads[i].stop = true;
1641
1642               sp->finished = true;
1643         }
1644       }
1645       lock_release(&(sp->lock));
1646     }
1647
1648     lock_grab(&(sp->lock));
1649
1650     // If this is the master thread and we have been asked to stop because of
1651     // a beta cutoff higher up in the tree, stop all slave threads:
1652     if (sp->master == threadID && thread_should_stop(threadID))
1653         for (int i = 0; i < ActiveThreads; i++)
1654             if (sp->slaves[i])
1655                 Threads[i].stop = true;
1656
1657     sp->cpus--;
1658     sp->slaves[threadID] = 0;
1659
1660     lock_release(&(sp->lock));
1661   }
1662
1663
1664   // sp_search_pv() is used to search from a PV split point.  This function
1665   // is called by each thread working at the split point.  It is similar to
1666   // the normal search_pv() function, but simpler.  Because we have already
1667   // probed the hash table and searched the first move before splitting, we
1668   // don't have to repeat all this work in sp_search_pv().  We also don't
1669   // need to store anything to the hash table here:  This is taken care of
1670   // after we return from the split point.
1671
1672   void sp_search_pv(SplitPoint *sp, int threadID) {
1673
1674     assert(threadID >= 0 && threadID < ActiveThreads);
1675     assert(ActiveThreads > 1);
1676
1677     Position pos = Position(sp->pos);
1678     SearchStack *ss = sp->sstack[threadID];
1679     Value value;
1680     Move move;
1681
1682     while (    sp->alpha < sp->beta
1683            && !thread_should_stop(threadID)
1684            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1685     {
1686       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1687       bool moveIsCapture = pos.move_is_capture(move);
1688
1689       assert(move_is_ok(move));
1690
1691       if (moveIsCapture)
1692           ss[sp->ply].currentMoveCaptureValue =
1693           move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1694       else
1695           ss[sp->ply].currentMoveCaptureValue = Value(0);
1696
1697       lock_grab(&(sp->lock));
1698       int moveCount = ++sp->moves;
1699       lock_release(&(sp->lock));
1700
1701       ss[sp->ply].currentMove = move;
1702
1703       // Decide the new search depth.
1704       bool dangerous;
1705       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1706       Depth newDepth = sp->depth - OnePly + ext;
1707
1708       // Make and search the move.
1709       StateInfo st;
1710       pos.do_move(move, st, sp->dcCandidates);
1711
1712       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1713       // if the move fails high will be re-searched at full depth.
1714       if (   !dangerous
1715           &&  moveCount >= LMRPVMoves
1716           && !moveIsCapture
1717           && !move_promotion(move)
1718           && !move_is_castle(move)
1719           && !move_is_killer(move, ss[sp->ply]))
1720       {
1721           ss[sp->ply].reduction = OnePly;
1722           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1723       }
1724       else
1725           value = sp->alpha + 1; // Just to trigger next condition
1726
1727       if (value > sp->alpha) // Go with full depth non-pv search
1728       {
1729           ss[sp->ply].reduction = Depth(0);
1730           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1731
1732           if (value > sp->alpha && value < sp->beta)
1733           {
1734               // When the search fails high at ply 1 while searching the first
1735               // move at the root, set the flag failHighPly1.  This is used for
1736               // time managment:  We don't want to stop the search early in
1737               // such cases, because resolving the fail high at ply 1 could
1738               // result in a big drop in score at the root.
1739               if (sp->ply == 1 && RootMoveNumber == 1)
1740                   Threads[threadID].failHighPly1 = true;
1741
1742               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1743               Threads[threadID].failHighPly1 = false;
1744         }
1745       }
1746       pos.undo_move(move);
1747
1748       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1749
1750       if (thread_should_stop(threadID))
1751           break;
1752
1753       // New best move?
1754       lock_grab(&(sp->lock));
1755       if (value > sp->bestValue && !thread_should_stop(threadID))
1756       {
1757           sp->bestValue = value;
1758           if (value > sp->alpha)
1759           {
1760               sp->alpha = value;
1761               sp_update_pv(sp->parentSstack, ss, sp->ply);
1762               if (value == value_mate_in(sp->ply + 1))
1763                   ss[sp->ply].mateKiller = move;
1764
1765               if(value >= sp->beta)
1766               {
1767                   for(int i = 0; i < ActiveThreads; i++)
1768                       if(i != threadID && (i == sp->master || sp->slaves[i]))
1769                           Threads[i].stop = true;
1770
1771                   sp->finished = true;
1772               }
1773         }
1774         // If we are at ply 1, and we are searching the first root move at
1775         // ply 0, set the 'Problem' variable if the score has dropped a lot
1776         // (from the computer's point of view) since the previous iteration.
1777         if (   sp->ply == 1
1778             && Iteration >= 2
1779             && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1780             Problem = true;
1781       }
1782       lock_release(&(sp->lock));
1783     }
1784
1785     lock_grab(&(sp->lock));
1786
1787     // If this is the master thread and we have been asked to stop because of
1788     // a beta cutoff higher up in the tree, stop all slave threads.
1789     if (sp->master == threadID && thread_should_stop(threadID))
1790         for (int i = 0; i < ActiveThreads; i++)
1791             if (sp->slaves[i])
1792                 Threads[i].stop = true;
1793
1794     sp->cpus--;
1795     sp->slaves[threadID] = 0;
1796
1797     lock_release(&(sp->lock));
1798   }
1799
1800   /// The BetaCounterType class
1801
1802   BetaCounterType::BetaCounterType() { clear(); }
1803
1804   void BetaCounterType::clear() {
1805
1806     for (int i = 0; i < THREAD_MAX; i++)
1807         hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1808   }
1809
1810   void BetaCounterType::add(Color us, Depth d, int threadID) {
1811
1812     // Weighted count based on depth
1813     hits[threadID][us] += int(d);
1814   }
1815
1816   void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1817
1818     our = their = 0UL;
1819     for (int i = 0; i < THREAD_MAX; i++)
1820     {
1821         our += hits[i][us];
1822         their += hits[i][opposite_color(us)];
1823     }
1824   }
1825
1826
1827   /// The RootMove class
1828
1829   // Constructor
1830
1831   RootMove::RootMove() {
1832     nodes = cumulativeNodes = 0ULL;
1833   }
1834
1835   // RootMove::operator<() is the comparison function used when
1836   // sorting the moves.  A move m1 is considered to be better
1837   // than a move m2 if it has a higher score, or if the moves
1838   // have equal score but m1 has the higher node count.
1839
1840   bool RootMove::operator<(const RootMove& m) {
1841
1842     if (score != m.score)
1843         return (score < m.score);
1844
1845     return theirBeta <= m.theirBeta;
1846   }
1847
1848   /// The RootMoveList class
1849
1850   // Constructor
1851
1852   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1853
1854     MoveStack mlist[MaxRootMoves];
1855     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1856
1857     // Generate all legal moves
1858     int lm_count = generate_legal_moves(pos, mlist);
1859
1860     // Add each move to the moves[] array
1861     for (int i = 0; i < lm_count; i++)
1862     {
1863         bool includeMove = includeAllMoves;
1864
1865         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1866             includeMove = (searchMoves[k] == mlist[i].move);
1867
1868         if (includeMove)
1869         {
1870             // Find a quick score for the move
1871             StateInfo st;
1872             SearchStack ss[PLY_MAX_PLUS_2];
1873
1874             moves[count].move = mlist[i].move;
1875             moves[count].nodes = 0ULL;
1876             pos.do_move(moves[count].move, st);
1877             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1878                                           Depth(0), 1, 0);
1879             pos.undo_move(moves[count].move);
1880             moves[count].pv[0] = moves[i].move;
1881             moves[count].pv[1] = MOVE_NONE; // FIXME
1882             count++;
1883         }
1884     }
1885     sort();
1886   }
1887
1888
1889   // Simple accessor methods for the RootMoveList class
1890
1891   inline Move RootMoveList::get_move(int moveNum) const {
1892     return moves[moveNum].move;
1893   }
1894
1895   inline Value RootMoveList::get_move_score(int moveNum) const {
1896     return moves[moveNum].score;
1897   }
1898
1899   inline void RootMoveList::set_move_score(int moveNum, Value score) {
1900     moves[moveNum].score = score;
1901   }
1902
1903   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1904     moves[moveNum].nodes = nodes;
1905     moves[moveNum].cumulativeNodes += nodes;
1906   }
1907
1908   inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1909     moves[moveNum].ourBeta = our;
1910     moves[moveNum].theirBeta = their;
1911   }
1912
1913   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1914     int j;
1915     for(j = 0; pv[j] != MOVE_NONE; j++)
1916       moves[moveNum].pv[j] = pv[j];
1917     moves[moveNum].pv[j] = MOVE_NONE;
1918   }
1919
1920   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1921     return moves[moveNum].pv[i];
1922   }
1923
1924   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1925     return moves[moveNum].cumulativeNodes;
1926   }
1927
1928   inline int RootMoveList::move_count() const {
1929     return count;
1930   }
1931
1932
1933   // RootMoveList::scan_for_easy_move() is called at the end of the first
1934   // iteration, and is used to detect an "easy move", i.e. a move which appears
1935   // to be much bester than all the rest.  If an easy move is found, the move
1936   // is returned, otherwise the function returns MOVE_NONE.  It is very
1937   // important that this function is called at the right moment:  The code
1938   // assumes that the first iteration has been completed and the moves have
1939   // been sorted. This is done in RootMoveList c'tor.
1940
1941   Move RootMoveList::scan_for_easy_move() const {
1942
1943     assert(count);
1944
1945     if (count == 1)
1946         return get_move(0);
1947
1948     // moves are sorted so just consider the best and the second one
1949     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1950         return get_move(0);
1951
1952     return MOVE_NONE;
1953   }
1954
1955   // RootMoveList::sort() sorts the root move list at the beginning of a new
1956   // iteration.
1957
1958   inline void RootMoveList::sort() {
1959
1960     sort_multipv(count - 1); // all items
1961   }
1962
1963
1964   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1965   // list by their scores and depths. It is used to order the different PVs
1966   // correctly in MultiPV mode.
1967
1968   void RootMoveList::sort_multipv(int n) {
1969
1970     for (int i = 1; i <= n; i++)
1971     {
1972       RootMove rm = moves[i];
1973       int j;
1974       for (j = i; j > 0 && moves[j-1] < rm; j--)
1975           moves[j] = moves[j-1];
1976       moves[j] = rm;
1977     }
1978   }
1979
1980
1981   // init_node() is called at the beginning of all the search functions
1982   // (search(), search_pv(), qsearch(), and so on) and initializes the search
1983   // stack object corresponding to the current node.  Once every
1984   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1985   // for user input and checks whether it is time to stop the search.
1986
1987   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1988     assert(ply >= 0 && ply < PLY_MAX);
1989     assert(threadID >= 0 && threadID < ActiveThreads);
1990
1991     Threads[threadID].nodes++;
1992
1993     if(threadID == 0) {
1994       NodesSincePoll++;
1995       if(NodesSincePoll >= NodesBetweenPolls) {
1996         poll();
1997         NodesSincePoll = 0;
1998       }
1999     }
2000
2001     ss[ply].init(ply);
2002     ss[ply+2].initKillers();
2003
2004     if(Threads[threadID].printCurrentLine)
2005       print_current_line(ss, ply, threadID);
2006   }
2007
2008
2009   // update_pv() is called whenever a search returns a value > alpha.  It
2010   // updates the PV in the SearchStack object corresponding to the current
2011   // node.
2012
2013   void update_pv(SearchStack ss[], int ply) {
2014     assert(ply >= 0 && ply < PLY_MAX);
2015
2016     ss[ply].pv[ply] = ss[ply].currentMove;
2017     int p;
2018     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2019       ss[ply].pv[p] = ss[ply+1].pv[p];
2020     ss[ply].pv[p] = MOVE_NONE;
2021   }
2022
2023
2024   // sp_update_pv() is a variant of update_pv for use at split points.  The
2025   // difference between the two functions is that sp_update_pv also updates
2026   // the PV at the parent node.
2027
2028   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2029     assert(ply >= 0 && ply < PLY_MAX);
2030
2031     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2032     int p;
2033     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2034       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2035     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2036   }
2037
2038
2039   // connected_moves() tests whether two moves are 'connected' in the sense
2040   // that the first move somehow made the second move possible (for instance
2041   // if the moving piece is the same in both moves).  The first move is
2042   // assumed to be the move that was made to reach the current position, while
2043   // the second move is assumed to be a move from the current position.
2044
2045   bool connected_moves(const Position &pos, Move m1, Move m2) {
2046     Square f1, t1, f2, t2;
2047
2048     assert(move_is_ok(m1));
2049     assert(move_is_ok(m2));
2050
2051     if(m2 == MOVE_NONE)
2052       return false;
2053
2054     // Case 1: The moving piece is the same in both moves.
2055     f2 = move_from(m2);
2056     t1 = move_to(m1);
2057     if(f2 == t1)
2058       return true;
2059
2060     // Case 2: The destination square for m2 was vacated by m1.
2061     t2 = move_to(m2);
2062     f1 = move_from(m1);
2063     if(t2 == f1)
2064       return true;
2065
2066     // Case 3: Moving through the vacated square:
2067     if(piece_is_slider(pos.piece_on(f2)) &&
2068        bit_is_set(squares_between(f2, t2), f1))
2069       return true;
2070
2071     // Case 4: The destination square for m2 is attacked by the moving piece
2072     // in m1:
2073     if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2074       return true;
2075
2076     // Case 5: Discovered check, checking piece is the piece moved in m1:
2077     if(piece_is_slider(pos.piece_on(t1)) &&
2078        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2079                   f2) &&
2080        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2081                    t2)) {
2082       Bitboard occ = pos.occupied_squares();
2083       Color us = pos.side_to_move();
2084       Square ksq = pos.king_square(us);
2085       clear_bit(&occ, f2);
2086       if(pos.type_of_piece_on(t1) == BISHOP) {
2087         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2088           return true;
2089       }
2090       else if(pos.type_of_piece_on(t1) == ROOK) {
2091         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2092           return true;
2093       }
2094       else {
2095         assert(pos.type_of_piece_on(t1) == QUEEN);
2096         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2097           return true;
2098       }
2099     }
2100
2101     return false;
2102   }
2103
2104
2105   // value_is_mate() checks if the given value is a mate one
2106   // eventually compensated for the ply.
2107
2108   bool value_is_mate(Value value) {
2109
2110     assert(abs(value) <= VALUE_INFINITE);
2111
2112     return   value <= value_mated_in(PLY_MAX)
2113           || value >= value_mate_in(PLY_MAX);
2114   }
2115
2116
2117   // move_is_killer() checks if the given move is among the
2118   // killer moves of that ply.
2119
2120   bool move_is_killer(Move m, const SearchStack& ss) {
2121
2122       const Move* k = ss.killers;
2123       for (int i = 0; i < KILLER_MAX; i++, k++)
2124           if (*k == m)
2125               return true;
2126
2127       return false;
2128   }
2129
2130
2131   // extension() decides whether a move should be searched with normal depth,
2132   // or with extended depth.  Certain classes of moves (checking moves, in
2133   // particular) are searched with bigger depth than ordinary moves and in
2134   // any case are marked as 'dangerous'. Note that also if a move is not
2135   // extended, as example because the corresponding UCI option is set to zero,
2136   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2137
2138   Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2139                   bool singleReply, bool mateThreat, bool* dangerous) {
2140
2141     assert(m != MOVE_NONE);
2142
2143     Depth result = Depth(0);
2144     *dangerous = check || singleReply || mateThreat;
2145
2146     if (check)
2147         result += CheckExtension[pvNode];
2148
2149     if (singleReply)
2150         result += SingleReplyExtension[pvNode];
2151
2152     if (mateThreat)
2153         result += MateThreatExtension[pvNode];
2154
2155     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2156     {
2157         if (pos.move_is_pawn_push_to_7th(m))
2158         {
2159             result += PawnPushTo7thExtension[pvNode];
2160             *dangerous = true;
2161         }
2162         if (pos.move_is_passed_pawn_push(m))
2163         {
2164             result += PassedPawnExtension[pvNode];
2165             *dangerous = true;
2166         }
2167     }
2168
2169     if (   capture
2170         && pos.type_of_piece_on(move_to(m)) != PAWN
2171         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2172             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2173         && !move_promotion(m)
2174         && !move_is_ep(m))
2175     {
2176         result += PawnEndgameExtension[pvNode];
2177         *dangerous = true;
2178     }
2179
2180     if (   pvNode
2181         && capture
2182         && pos.type_of_piece_on(move_to(m)) != PAWN
2183         && pos.see(m) >= 0)
2184     {
2185         result += OnePly/2;
2186         *dangerous = true;
2187     }
2188
2189     return Min(result, OnePly);
2190   }
2191
2192
2193   // ok_to_do_nullmove() looks at the current position and decides whether
2194   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2195   // problems, null moves are not allowed when the side to move has very
2196   // little material left.  Currently, the test is a bit too simple:  Null
2197   // moves are avoided only when the side to move has only pawns left.  It's
2198   // probably a good idea to avoid null moves in at least some more
2199   // complicated endgames, e.g. KQ vs KR.  FIXME
2200
2201   bool ok_to_do_nullmove(const Position &pos) {
2202     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2203       return false;
2204     return true;
2205   }
2206
2207
2208   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2209   // non-tactical moves late in the move list close to the leaves are
2210   // candidates for pruning.
2211
2212   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2213     Square mfrom, mto, tfrom, tto;
2214
2215     assert(move_is_ok(m));
2216     assert(threat == MOVE_NONE || move_is_ok(threat));
2217     assert(!move_promotion(m));
2218     assert(!pos.move_is_check(m));
2219     assert(!pos.move_is_capture(m));
2220     assert(!pos.move_is_passed_pawn_push(m));
2221     assert(d >= OnePly);
2222
2223     mfrom = move_from(m);
2224     mto = move_to(m);
2225     tfrom = move_from(threat);
2226     tto = move_to(threat);
2227
2228     // Case 1: Castling moves are never pruned.
2229     if (move_is_castle(m))
2230         return false;
2231
2232     // Case 2: Don't prune moves which move the threatened piece
2233     if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2234         return false;
2235
2236     // Case 3: If the threatened piece has value less than or equal to the
2237     // value of the threatening piece, don't prune move which defend it.
2238     if (   !PruneDefendingMoves
2239         && threat != MOVE_NONE
2240         && pos.move_is_capture(threat)
2241         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2242             || pos.type_of_piece_on(tfrom) == KING)
2243         && pos.move_attacks_square(m, tto))
2244       return false;
2245
2246     // Case 4: Don't prune moves with good history.
2247     if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2248         return false;
2249
2250     // Case 5: If the moving piece in the threatened move is a slider, don't
2251     // prune safe moves which block its ray.
2252     if (  !PruneBlockingMoves
2253         && threat != MOVE_NONE
2254         && piece_is_slider(pos.piece_on(tfrom))
2255         && bit_is_set(squares_between(tfrom, tto), mto)
2256         && pos.see(m) >= 0)
2257             return false;
2258
2259     return true;
2260   }
2261
2262
2263   // ok_to_use_TT() returns true if a transposition table score
2264   // can be used at a given point in search.
2265
2266   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2267
2268     Value v = value_from_tt(tte->value(), ply);
2269
2270     return   (   tte->depth() >= depth
2271               || v >= Max(value_mate_in(100), beta)
2272               || v < Min(value_mated_in(100), beta))
2273
2274           && (   (is_lower_bound(tte->type()) && v >= beta)
2275               || (is_upper_bound(tte->type()) && v < beta));
2276   }
2277
2278
2279   // ok_to_history() returns true if a move m can be stored
2280   // in history. Should be a non capturing move nor a promotion.
2281
2282   bool ok_to_history(const Position& pos, Move m) {
2283
2284     return !pos.move_is_capture(m) && !move_promotion(m);
2285   }
2286
2287
2288   // update_history() registers a good move that produced a beta-cutoff
2289   // in history and marks as failures all the other moves of that ply.
2290
2291   void update_history(const Position& pos, Move m, Depth depth,
2292                       Move movesSearched[], int moveCount) {
2293
2294     H.success(pos.piece_on(move_from(m)), m, depth);
2295
2296     for (int i = 0; i < moveCount - 1; i++)
2297     {
2298         assert(m != movesSearched[i]);
2299         if (ok_to_history(pos, movesSearched[i]))
2300             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2301     }
2302   }
2303
2304
2305   // update_killers() add a good move that produced a beta-cutoff
2306   // among the killer moves of that ply.
2307
2308   void update_killers(Move m, SearchStack& ss) {
2309
2310     if (m == ss.killers[0])
2311         return;
2312
2313     for (int i = KILLER_MAX - 1; i > 0; i--)
2314         ss.killers[i] = ss.killers[i - 1];
2315
2316     ss.killers[0] = m;
2317   }
2318
2319   // fail_high_ply_1() checks if some thread is currently resolving a fail
2320   // high at ply 1 at the node below the first root node.  This information
2321   // is used for time managment.
2322
2323   bool fail_high_ply_1() {
2324     for(int i = 0; i < ActiveThreads; i++)
2325       if(Threads[i].failHighPly1)
2326         return true;
2327     return false;
2328   }
2329
2330
2331   // current_search_time() returns the number of milliseconds which have passed
2332   // since the beginning of the current search.
2333
2334   int current_search_time() {
2335     return get_system_time() - SearchStartTime;
2336   }
2337
2338
2339   // nps() computes the current nodes/second count.
2340
2341   int nps() {
2342     int t = current_search_time();
2343     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2344   }
2345
2346
2347   // poll() performs two different functions:  It polls for user input, and it
2348   // looks at the time consumed so far and decides if it's time to abort the
2349   // search.
2350
2351   void poll() {
2352
2353     static int lastInfoTime;
2354     int t = current_search_time();
2355
2356     //  Poll for input
2357     if (Bioskey())
2358     {
2359         // We are line oriented, don't read single chars
2360         std::string command;
2361         if (!std::getline(std::cin, command))
2362             command = "quit";
2363
2364         if (command == "quit")
2365         {
2366             AbortSearch = true;
2367             PonderSearch = false;
2368             Quit = true;
2369         }
2370         else if(command == "stop")
2371         {
2372             AbortSearch = true;
2373             PonderSearch = false;
2374         }
2375         else if(command == "ponderhit")
2376             ponderhit();
2377     }
2378     // Print search information
2379     if (t < 1000)
2380         lastInfoTime = 0;
2381
2382     else if (lastInfoTime > t)
2383         // HACK: Must be a new search where we searched less than
2384         // NodesBetweenPolls nodes during the first second of search.
2385         lastInfoTime = 0;
2386
2387     else if (t - lastInfoTime >= 1000)
2388     {
2389         lastInfoTime = t;
2390         lock_grab(&IOLock);
2391         if (dbg_show_mean)
2392             dbg_print_mean();
2393
2394         if (dbg_show_hit_rate)
2395             dbg_print_hit_rate();
2396
2397         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2398                   << " time " << t << " hashfull " << TT.full() << std::endl;
2399         lock_release(&IOLock);
2400         if (ShowCurrentLine)
2401             Threads[0].printCurrentLine = true;
2402     }
2403     // Should we stop the search?
2404     if (PonderSearch)
2405         return;
2406
2407     bool overTime =     t > AbsoluteMaxSearchTime
2408                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2409                      || (  !FailHigh && !fail_high_ply_1() && !Problem
2410                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2411
2412     if (   (Iteration >= 2 && (!InfiniteSearch && overTime))
2413         || (ExactMaxTime && t >= ExactMaxTime)
2414         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2415         AbortSearch = true;
2416   }
2417
2418
2419   // ponderhit() is called when the program is pondering (i.e. thinking while
2420   // it's the opponent's turn to move) in order to let the engine know that
2421   // it correctly predicted the opponent's move.
2422
2423   void ponderhit() {
2424     int t = current_search_time();
2425     PonderSearch = false;
2426     if(Iteration >= 2 &&
2427        (!InfiniteSearch && (StopOnPonderhit ||
2428                             t > AbsoluteMaxSearchTime ||
2429                             (RootMoveNumber == 1 &&
2430                              t > MaxSearchTime + ExtraSearchTime) ||
2431                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2432                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2433       AbortSearch = true;
2434   }
2435
2436
2437   // print_current_line() prints the current line of search for a given
2438   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2439
2440   void print_current_line(SearchStack ss[], int ply, int threadID) {
2441     assert(ply >= 0 && ply < PLY_MAX);
2442     assert(threadID >= 0 && threadID < ActiveThreads);
2443
2444     if(!Threads[threadID].idle) {
2445       lock_grab(&IOLock);
2446       std::cout << "info currline " << (threadID + 1);
2447       for(int p = 0; p < ply; p++)
2448         std::cout << " " << ss[p].currentMove;
2449       std::cout << std::endl;
2450       lock_release(&IOLock);
2451     }
2452     Threads[threadID].printCurrentLine = false;
2453     if(threadID + 1 < ActiveThreads)
2454       Threads[threadID + 1].printCurrentLine = true;
2455   }
2456
2457
2458   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2459   // while the program is pondering.  The point is to work around a wrinkle in
2460   // the UCI protocol:  When pondering, the engine is not allowed to give a
2461   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2462   // We simply wait here until one of these commands is sent, and return,
2463   // after which the bestmove and pondermove will be printed (in id_loop()).
2464
2465   void wait_for_stop_or_ponderhit() {
2466     std::string command;
2467
2468     while(true) {
2469       if(!std::getline(std::cin, command))
2470         command = "quit";
2471
2472       if(command == "quit") {
2473         OpeningBook.close();
2474         stop_threads();
2475         quit_eval();
2476         exit(0);
2477       }
2478       else if(command == "ponderhit" || command == "stop")
2479         break;
2480     }
2481   }
2482
2483
2484   // idle_loop() is where the threads are parked when they have no work to do.
2485   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2486   // object for which the current thread is the master.
2487
2488   void idle_loop(int threadID, SplitPoint *waitSp) {
2489     assert(threadID >= 0 && threadID < THREAD_MAX);
2490
2491     Threads[threadID].running = true;
2492
2493     while(true) {
2494       if(AllThreadsShouldExit && threadID != 0)
2495         break;
2496
2497       // If we are not thinking, wait for a condition to be signaled instead
2498       // of wasting CPU time polling for work:
2499       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2500 #if !defined(_MSC_VER)
2501         pthread_mutex_lock(&WaitLock);
2502         if(Idle || threadID >= ActiveThreads)
2503           pthread_cond_wait(&WaitCond, &WaitLock);
2504         pthread_mutex_unlock(&WaitLock);
2505 #else
2506         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2507 #endif
2508       }
2509
2510       // If this thread has been assigned work, launch a search:
2511       if(Threads[threadID].workIsWaiting) {
2512         Threads[threadID].workIsWaiting = false;
2513         if(Threads[threadID].splitPoint->pvNode)
2514           sp_search_pv(Threads[threadID].splitPoint, threadID);
2515         else
2516           sp_search(Threads[threadID].splitPoint, threadID);
2517         Threads[threadID].idle = true;
2518       }
2519
2520       // If this thread is the master of a split point and all threads have
2521       // finished their work at this split point, return from the idle loop:
2522       if(waitSp != NULL && waitSp->cpus == 0)
2523         return;
2524     }
2525
2526     Threads[threadID].running = false;
2527   }
2528
2529
2530   // init_split_point_stack() is called during program initialization, and
2531   // initializes all split point objects.
2532
2533   void init_split_point_stack() {
2534     for(int i = 0; i < THREAD_MAX; i++)
2535       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2536         SplitPointStack[i][j].parent = NULL;
2537         lock_init(&(SplitPointStack[i][j].lock), NULL);
2538       }
2539   }
2540
2541
2542   // destroy_split_point_stack() is called when the program exits, and
2543   // destroys all locks in the precomputed split point objects.
2544
2545   void destroy_split_point_stack() {
2546     for(int i = 0; i < THREAD_MAX; i++)
2547       for(int j = 0; j < MaxActiveSplitPoints; j++)
2548         lock_destroy(&(SplitPointStack[i][j].lock));
2549   }
2550
2551
2552   // thread_should_stop() checks whether the thread with a given threadID has
2553   // been asked to stop, directly or indirectly.  This can happen if a beta
2554   // cutoff has occured in thre thread's currently active split point, or in
2555   // some ancestor of the current split point.
2556
2557   bool thread_should_stop(int threadID) {
2558     assert(threadID >= 0 && threadID < ActiveThreads);
2559
2560     SplitPoint *sp;
2561
2562     if(Threads[threadID].stop)
2563       return true;
2564     if(ActiveThreads <= 2)
2565       return false;
2566     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2567       if(sp->finished) {
2568         Threads[threadID].stop = true;
2569         return true;
2570       }
2571     return false;
2572   }
2573
2574
2575   // thread_is_available() checks whether the thread with threadID "slave" is
2576   // available to help the thread with threadID "master" at a split point.  An
2577   // obvious requirement is that "slave" must be idle.  With more than two
2578   // threads, this is not by itself sufficient:  If "slave" is the master of
2579   // some active split point, it is only available as a slave to the other
2580   // threads which are busy searching the split point at the top of "slave"'s
2581   // split point stack (the "helpful master concept" in YBWC terminology).
2582
2583   bool thread_is_available(int slave, int master) {
2584     assert(slave >= 0 && slave < ActiveThreads);
2585     assert(master >= 0 && master < ActiveThreads);
2586     assert(ActiveThreads > 1);
2587
2588     if(!Threads[slave].idle || slave == master)
2589       return false;
2590
2591     if(Threads[slave].activeSplitPoints == 0)
2592       // No active split points means that the thread is available as a slave
2593       // for any other thread.
2594       return true;
2595
2596     if(ActiveThreads == 2)
2597       return true;
2598
2599     // Apply the "helpful master" concept if possible.
2600     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2601       return true;
2602
2603     return false;
2604   }
2605
2606
2607   // idle_thread_exists() tries to find an idle thread which is available as
2608   // a slave for the thread with threadID "master".
2609
2610   bool idle_thread_exists(int master) {
2611     assert(master >= 0 && master < ActiveThreads);
2612     assert(ActiveThreads > 1);
2613
2614     for(int i = 0; i < ActiveThreads; i++)
2615       if(thread_is_available(i, master))
2616         return true;
2617     return false;
2618   }
2619
2620
2621   // split() does the actual work of distributing the work at a node between
2622   // several threads at PV nodes.  If it does not succeed in splitting the
2623   // node (because no idle threads are available, or because we have no unused
2624   // split point objects), the function immediately returns false.  If
2625   // splitting is possible, a SplitPoint object is initialized with all the
2626   // data that must be copied to the helper threads (the current position and
2627   // search stack, alpha, beta, the search depth, etc.), and we tell our
2628   // helper threads that they have been assigned work.  This will cause them
2629   // to instantly leave their idle loops and call sp_search_pv().  When all
2630   // threads have returned from sp_search_pv (or, equivalently, when
2631   // splitPoint->cpus becomes 0), split() returns true.
2632
2633   bool split(const Position &p, SearchStack *sstck, int ply,
2634              Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2635              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2636
2637     assert(p.is_ok());
2638     assert(sstck != NULL);
2639     assert(ply >= 0 && ply < PLY_MAX);
2640     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2641     assert(!pvNode || *alpha < *beta);
2642     assert(*beta <= VALUE_INFINITE);
2643     assert(depth > Depth(0));
2644     assert(master >= 0 && master < ActiveThreads);
2645     assert(ActiveThreads > 1);
2646
2647     SplitPoint *splitPoint;
2648     int i;
2649
2650     lock_grab(&MPLock);
2651
2652     // If no other thread is available to help us, or if we have too many
2653     // active split points, don't split:
2654     if(!idle_thread_exists(master) ||
2655        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2656       lock_release(&MPLock);
2657       return false;
2658     }
2659
2660     // Pick the next available split point object from the split point stack:
2661     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2662     Threads[master].activeSplitPoints++;
2663
2664     // Initialize the split point object:
2665     splitPoint->parent = Threads[master].splitPoint;
2666     splitPoint->finished = false;
2667     splitPoint->ply = ply;
2668     splitPoint->depth = depth;
2669     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2670     splitPoint->beta = *beta;
2671     splitPoint->pvNode = pvNode;
2672     splitPoint->dcCandidates = dcCandidates;
2673     splitPoint->bestValue = *bestValue;
2674     splitPoint->master = master;
2675     splitPoint->mp = mp;
2676     splitPoint->moves = *moves;
2677     splitPoint->cpus = 1;
2678     splitPoint->pos.copy(p);
2679     splitPoint->parentSstack = sstck;
2680     for(i = 0; i < ActiveThreads; i++)
2681       splitPoint->slaves[i] = 0;
2682
2683     // Copy the current position and the search stack to the master thread:
2684     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2685     Threads[master].splitPoint = splitPoint;
2686
2687     // Make copies of the current position and search stack for each thread:
2688     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2689         i++)
2690       if(thread_is_available(i, master)) {
2691         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2692         Threads[i].splitPoint = splitPoint;
2693         splitPoint->slaves[i] = 1;
2694         splitPoint->cpus++;
2695       }
2696
2697     // Tell the threads that they have work to do.  This will make them leave
2698     // their idle loop.
2699     for(i = 0; i < ActiveThreads; i++)
2700       if(i == master || splitPoint->slaves[i]) {
2701         Threads[i].workIsWaiting = true;
2702         Threads[i].idle = false;
2703         Threads[i].stop = false;
2704       }
2705
2706     lock_release(&MPLock);
2707
2708     // Everything is set up.  The master thread enters the idle loop, from
2709     // which it will instantly launch a search, because its workIsWaiting
2710     // slot is 'true'.  We send the split point as a second parameter to the
2711     // idle loop, which means that the main thread will return from the idle
2712     // loop when all threads have finished their work at this split point
2713     // (i.e. when // splitPoint->cpus == 0).
2714     idle_loop(master, splitPoint);
2715
2716     // We have returned from the idle loop, which means that all threads are
2717     // finished.  Update alpha, beta and bestvalue, and return:
2718     lock_grab(&MPLock);
2719     if(pvNode) *alpha = splitPoint->alpha;
2720     *beta = splitPoint->beta;
2721     *bestValue = splitPoint->bestValue;
2722     Threads[master].stop = false;
2723     Threads[master].idle = false;
2724     Threads[master].activeSplitPoints--;
2725     Threads[master].splitPoint = splitPoint->parent;
2726     lock_release(&MPLock);
2727
2728     return true;
2729   }
2730
2731
2732   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2733   // to start a new search from the root.
2734
2735   void wake_sleeping_threads() {
2736     if(ActiveThreads > 1) {
2737       for(int i = 1; i < ActiveThreads; i++) {
2738         Threads[i].idle = true;
2739         Threads[i].workIsWaiting = false;
2740       }
2741 #if !defined(_MSC_VER)
2742       pthread_mutex_lock(&WaitLock);
2743       pthread_cond_broadcast(&WaitCond);
2744       pthread_mutex_unlock(&WaitLock);
2745 #else
2746       for(int i = 1; i < THREAD_MAX; i++)
2747         SetEvent(SitIdleEvent[i]);
2748 #endif
2749     }
2750   }
2751
2752
2753   // init_thread() is the function which is called when a new thread is
2754   // launched.  It simply calls the idle_loop() function with the supplied
2755   // threadID.  There are two versions of this function; one for POSIX threads
2756   // and one for Windows threads.
2757
2758 #if !defined(_MSC_VER)
2759
2760   void *init_thread(void *threadID) {
2761     idle_loop(*(int *)threadID, NULL);
2762     return NULL;
2763   }
2764
2765 #else
2766
2767   DWORD WINAPI init_thread(LPVOID threadID) {
2768     idle_loop(*(int *)threadID, NULL);
2769     return NULL;
2770   }
2771
2772 #endif
2773
2774 }