]> git.sesse.net Git - stockfish/blob - src/search.cpp
03c566ebf29970f77f37d20991794314558ea650
[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     std::cout << "bestmove " << ss[0].pv[0];
752     if (ss[0].pv[1] != MOVE_NONE)
753         std::cout << " ponder " << ss[0].pv[1];
754
755     std::cout << std::endl;
756
757     if (UseLogFile)
758     {
759         if (dbg_show_mean)
760             dbg_print_mean(LogFile);
761
762         if (dbg_show_hit_rate)
763             dbg_print_hit_rate(LogFile);
764
765         StateInfo st;
766         LogFile << "Nodes: " << nodes_searched() << std::endl
767                 << "Nodes/second: " << nps() << std::endl
768                 << "Best move: " << move_to_san(p, ss[0].pv[0]) << std::endl;
769
770         p.do_move(ss[0].pv[0], st);
771         LogFile << "Ponder move: " << move_to_san(p, ss[0].pv[1])
772                 << std::endl << std::endl;
773     }
774     return rml.get_move_score(0);
775   }
776
777
778   // root_search() is the function which searches the root node.  It is
779   // similar to search_pv except that it uses a different move ordering
780   // scheme (perhaps we should try to use this at internal PV nodes, too?)
781   // and prints some information to the standard output.
782
783   Value root_search(Position &pos, SearchStack ss[], RootMoveList &rml) {
784
785     Value alpha = -VALUE_INFINITE;
786     Value beta = VALUE_INFINITE, value;
787     Bitboard dcCandidates = pos.discovered_check_candidates(pos.side_to_move());
788
789     // Loop through all the moves in the root move list
790     for (int i = 0; i <  rml.move_count() && !AbortSearch; i++)
791     {
792         int64_t nodes;
793         Move move;
794         StateInfo st;
795         Depth ext, newDepth;
796
797         RootMoveNumber = i + 1;
798         FailHigh = false;
799
800         // Remember the node count before the move is searched. The node counts
801         // are used to sort the root moves at the next iteration.
802         nodes = nodes_searched();
803
804         // Reset beta cut-off counters
805         BetaCounter.clear();
806
807         // Pick the next root move, and print the move and the move number to
808         // the standard output.
809         move = ss[0].currentMove = rml.get_move(i);
810         if (current_search_time() >= 1000)
811             std::cout << "info currmove " << move
812                       << " currmovenumber " << i + 1 << std::endl;
813
814         // Decide search depth for this move
815         bool dangerous;
816         ext = extension(pos, move, true, pos.move_is_capture(move), pos.move_is_check(move), false, false, &dangerous);
817         newDepth = (Iteration - 2) * OnePly + ext + InitialDepth;
818
819         // Make the move, and search it
820         pos.do_move(move, st, dcCandidates);
821
822         if (i < MultiPV)
823         {
824             value = -search_pv(pos, ss, -beta, VALUE_INFINITE, newDepth, 1, 0);
825             // If the value has dropped a lot compared to the last iteration,
826             // set the boolean variable Problem to true. This variable is used
827             // for time managment: When Problem is true, we try to complete the
828             // current iteration before playing a move.
829             Problem = (Iteration >= 2 && value <= ValueByIteration[Iteration-1] - ProblemMargin);
830
831             if (Problem && StopOnPonderhit)
832                 StopOnPonderhit = false;
833         }
834         else
835         {
836             value = -search(pos, ss, -alpha, newDepth, 1, true, 0);
837             if (value > alpha)
838             {
839                 // Fail high! Set the boolean variable FailHigh to true, and
840                 // re-search the move with a big window. The variable FailHigh is
841                 // used for time managment: We try to avoid aborting the search
842                 // prematurely during a fail high research.
843                 FailHigh = true;
844                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, 1, 0);
845             }
846         }
847
848         pos.undo_move(move);
849
850         // Finished searching the move. If AbortSearch is true, the search
851         // was aborted because the user interrupted the search or because we
852         // ran out of time. In this case, the return value of the search cannot
853         // be trusted, and we break out of the loop without updating the best
854         // move and/or PV:
855         if (AbortSearch)
856             break;
857
858         // Remember the node count for this move. The node counts are used to
859         // sort the root moves at the next iteration.
860         rml.set_move_nodes(i, nodes_searched() - nodes);
861
862         // Remember the beta-cutoff statistics
863         int64_t our, their;
864         BetaCounter.read(pos.side_to_move(), our, their);
865         rml.set_beta_counters(i, our, their);
866
867         assert(value >= -VALUE_INFINITE && value <= VALUE_INFINITE);
868
869         if (value <= alpha && i >= MultiPV)
870             rml.set_move_score(i, -VALUE_INFINITE);
871         else
872         {
873             // New best move!
874
875             // Update PV
876             rml.set_move_score(i, value);
877             update_pv(ss, 0);
878             rml.set_move_pv(i, ss[0].pv);
879
880             if (MultiPV == 1)
881             {
882                 // We record how often the best move has been changed in each
883                 // iteration. This information is used for time managment: When
884                 // the best move changes frequently, we allocate some more time.
885                 if (i > 0)
886                     BestMoveChangesByIteration[Iteration]++;
887
888                 // Print search information to the standard output:
889                 std::cout << "info depth " << Iteration
890                           << " score " << value_to_string(value)
891                           << " time " << current_search_time()
892                           << " nodes " << nodes_searched()
893                           << " nps " << nps()
894                           << " pv ";
895
896                 for (int j = 0; ss[0].pv[j] != MOVE_NONE && j < PLY_MAX; j++)
897                     std::cout << ss[0].pv[j] << " ";
898
899                 std::cout << std::endl;
900
901                 if (UseLogFile)
902                     LogFile << pretty_pv(pos, current_search_time(), Iteration, nodes_searched(), value, ss[0].pv)
903                             << std::endl;
904
905                 alpha = value;
906
907                 // Reset the global variable Problem to false if the value isn't too
908                 // far below the final value from the last iteration.
909                 if (value > ValueByIteration[Iteration - 1] - NoProblemMargin)
910                     Problem = false;
911             }
912             else // MultiPV > 1
913             {
914                 rml.sort_multipv(i);
915                 for (int j = 0; j < Min(MultiPV, rml.move_count()); j++)
916                 {
917                     int k;
918                     std::cout << "info multipv " << j + 1
919                               << " score " << value_to_string(rml.get_move_score(j))
920                               << " depth " << ((j <= i)? Iteration : Iteration - 1)
921                               << " time " << current_search_time()
922                               << " nodes " << nodes_searched()
923                               << " nps " << nps()
924                               << " pv ";
925
926                     for (k = 0; rml.get_move_pv(j, k) != MOVE_NONE && k < PLY_MAX; k++)
927                         std::cout << rml.get_move_pv(j, k) << " ";
928
929                     std::cout << std::endl;
930                 }
931                 alpha = rml.get_move_score(Min(i, MultiPV-1));
932             }
933         }
934     }
935     return alpha;
936   }
937
938
939   // search_pv() is the main search function for PV nodes.
940
941   Value search_pv(Position &pos, SearchStack ss[], Value alpha, Value beta,
942                   Depth depth, int ply, int threadID) {
943
944     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
945     assert(beta > alpha && beta <= VALUE_INFINITE);
946     assert(ply >= 0 && ply < PLY_MAX);
947     assert(threadID >= 0 && threadID < ActiveThreads);
948
949     if (depth < OnePly)
950         return qsearch(pos, ss, alpha, beta, Depth(0), ply, threadID);
951
952     // Initialize, and make an early exit in case of an aborted search,
953     // an instant draw, maximum ply reached, etc.
954     init_node(pos, ss, ply, threadID);
955
956     // After init_node() that calls poll()
957     if (AbortSearch || thread_should_stop(threadID))
958         return Value(0);
959
960     if (pos.is_draw())
961         return VALUE_DRAW;
962
963     EvalInfo ei;
964
965     if (ply >= PLY_MAX - 1)
966         return evaluate(pos, ei, threadID);
967
968     // Mate distance pruning
969     Value oldAlpha = alpha;
970     alpha = Max(value_mated_in(ply), alpha);
971     beta = Min(value_mate_in(ply+1), beta);
972     if (alpha >= beta)
973         return alpha;
974
975     // Transposition table lookup. At PV nodes, we don't use the TT for
976     // pruning, but only for move ordering.
977     const TTEntry* tte = TT.retrieve(pos);
978     Move ttMove = (tte ? tte->move() : MOVE_NONE);
979
980     // Go with internal iterative deepening if we don't have a TT move
981     if (UseIIDAtPVNodes && ttMove == MOVE_NONE && depth >= 5*OnePly)
982     {
983         search_pv(pos, ss, alpha, beta, depth-2*OnePly, ply, threadID);
984         ttMove = ss[ply].pv[ply];
985     }
986
987     // Initialize a MovePicker object for the current position, and prepare
988     // to search all moves
989     MovePicker mp = MovePicker(pos, true, ttMove, ss[ply], depth);
990
991     Move move, movesSearched[256];
992     int moveCount = 0;
993     Value value, bestValue = -VALUE_INFINITE;
994     Bitboard dcCandidates = mp.discovered_check_candidates();
995     Color us = pos.side_to_move();
996     bool isCheck = pos.is_check();
997     bool mateThreat = pos.has_mate_threat(opposite_color(us));
998
999     // Loop through all legal moves until no moves remain or a beta cutoff
1000     // occurs.
1001     while (   alpha < beta
1002            && (move = mp.get_next_move()) != MOVE_NONE
1003            && !thread_should_stop(threadID))
1004     {
1005       assert(move_is_ok(move));
1006
1007       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1008       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1009       bool moveIsCapture = pos.move_is_capture(move);
1010
1011       movesSearched[moveCount++] = ss[ply].currentMove = move;
1012
1013       if (moveIsCapture)
1014           ss[ply].currentMoveCaptureValue =
1015           move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1016       else
1017           ss[ply].currentMoveCaptureValue = Value(0);
1018
1019       // Decide the new search depth
1020       bool dangerous;
1021       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1022       Depth newDepth = depth - OnePly + ext;
1023
1024       // Make and search the move
1025       StateInfo st;
1026       pos.do_move(move, st, dcCandidates);
1027
1028       if (moveCount == 1) // The first move in list is the PV
1029           value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1030       else
1031       {
1032         // Try to reduce non-pv search depth by one ply if move seems not problematic,
1033         // if the move fails high will be re-searched at full depth.
1034         if (    depth >= 2*OnePly
1035             &&  moveCount >= LMRPVMoves
1036             && !dangerous
1037             && !moveIsCapture
1038             && !move_promotion(move)
1039             && !move_is_castle(move)
1040             && !move_is_killer(move, ss[ply]))
1041         {
1042             ss[ply].reduction = OnePly;
1043             value = -search(pos, ss, -alpha, newDepth-OnePly, ply+1, true, threadID);
1044         }
1045         else
1046             value = alpha + 1; // Just to trigger next condition
1047
1048         if (value > alpha) // Go with full depth non-pv search
1049         {
1050             ss[ply].reduction = Depth(0);
1051             value = -search(pos, ss, -alpha, newDepth, ply+1, true, threadID);
1052             if (value > alpha && value < beta)
1053             {
1054                 // When the search fails high at ply 1 while searching the first
1055                 // move at the root, set the flag failHighPly1. This is used for
1056                 // time managment:  We don't want to stop the search early in
1057                 // such cases, because resolving the fail high at ply 1 could
1058                 // result in a big drop in score at the root.
1059                 if (ply == 1 && RootMoveNumber == 1)
1060                     Threads[threadID].failHighPly1 = true;
1061
1062                 // A fail high occurred. Re-search at full window (pv search)
1063                 value = -search_pv(pos, ss, -beta, -alpha, newDepth, ply+1, threadID);
1064                 Threads[threadID].failHighPly1 = false;
1065           }
1066         }
1067       }
1068       pos.undo_move(move);
1069
1070       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1071
1072       // New best move?
1073       if (value > bestValue)
1074       {
1075           bestValue = value;
1076           if (value > alpha)
1077           {
1078               alpha = value;
1079               update_pv(ss, ply);
1080               if (value == value_mate_in(ply + 1))
1081                   ss[ply].mateKiller = move;
1082           }
1083           // If we are at ply 1, and we are searching the first root move at
1084           // ply 0, set the 'Problem' variable if the score has dropped a lot
1085           // (from the computer's point of view) since the previous iteration:
1086           if (   ply == 1
1087               && Iteration >= 2
1088               && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1089               Problem = true;
1090       }
1091
1092       // Split?
1093       if (   ActiveThreads > 1
1094           && bestValue < beta
1095           && depth >= MinimumSplitDepth
1096           && Iteration <= 99
1097           && idle_thread_exists(threadID)
1098           && !AbortSearch
1099           && !thread_should_stop(threadID)
1100           && split(pos, ss, ply, &alpha, &beta, &bestValue, depth,
1101                    &moveCount, &mp, dcCandidates, threadID, true))
1102           break;
1103     }
1104
1105     // All legal moves have been searched.  A special case: If there were
1106     // no legal moves, it must be mate or stalemate:
1107     if (moveCount == 0)
1108         return (isCheck ? value_mated_in(ply) : VALUE_DRAW);
1109
1110     // If the search is not aborted, update the transposition table,
1111     // history counters, and killer moves.
1112     if (AbortSearch || thread_should_stop(threadID))
1113         return bestValue;
1114
1115     if (bestValue <= oldAlpha)
1116         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1117
1118     else if (bestValue >= beta)
1119     {
1120         BetaCounter.add(pos.side_to_move(), depth, threadID);
1121         Move m = ss[ply].pv[ply];
1122         if (ok_to_history(pos, m)) // Only non capture moves are considered
1123         {
1124             update_history(pos, m, depth, movesSearched, moveCount);
1125             update_killers(m, ss[ply]);
1126         }
1127         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1128     }
1129     else
1130         TT.store(pos, value_to_tt(bestValue, ply), depth, ss[ply].pv[ply], VALUE_TYPE_EXACT);
1131
1132     return bestValue;
1133   }
1134
1135
1136   // search() is the search function for zero-width nodes.
1137
1138   Value search(Position &pos, SearchStack ss[], Value beta, Depth depth,
1139                int ply, bool allowNullmove, int threadID) {
1140
1141     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1142     assert(ply >= 0 && ply < PLY_MAX);
1143     assert(threadID >= 0 && threadID < ActiveThreads);
1144
1145     if (depth < OnePly)
1146         return qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1147
1148     // Initialize, and make an early exit in case of an aborted search,
1149     // an instant draw, maximum ply reached, etc.
1150     init_node(pos, ss, ply, threadID);
1151
1152     // After init_node() that calls poll()
1153     if (AbortSearch || thread_should_stop(threadID))
1154         return Value(0);
1155
1156     if (pos.is_draw())
1157         return VALUE_DRAW;
1158
1159     EvalInfo ei;
1160
1161     if (ply >= PLY_MAX - 1)
1162         return evaluate(pos, ei, threadID);
1163
1164     // Mate distance pruning
1165     if (value_mated_in(ply) >= beta)
1166         return beta;
1167
1168     if (value_mate_in(ply + 1) < beta)
1169         return beta - 1;
1170
1171     // Transposition table lookup
1172     const TTEntry* tte = TT.retrieve(pos);
1173     Move ttMove = (tte ? tte->move() : MOVE_NONE);
1174
1175     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1176     {
1177         ss[ply].currentMove = ttMove; // can be MOVE_NONE
1178         return value_from_tt(tte->value(), ply);
1179     }
1180
1181     Value approximateEval = quick_evaluate(pos);
1182     bool mateThreat = false;
1183     bool isCheck = pos.is_check();
1184
1185     // Null move search
1186     if (    allowNullmove
1187         &&  depth > OnePly
1188         && !isCheck
1189         && !value_is_mate(beta)
1190         &&  ok_to_do_nullmove(pos)
1191         &&  approximateEval >= beta - NullMoveMargin)
1192     {
1193         ss[ply].currentMove = MOVE_NULL;
1194
1195         StateInfo st;
1196         pos.do_null_move(st);
1197         int R = (depth >= 4 * OnePly ? 4 : 3); // Null move dynamic reduction
1198
1199         Value nullValue = -search(pos, ss, -(beta-1), depth-R*OnePly, ply+1, false, threadID);
1200
1201         pos.undo_null_move();
1202
1203         if (value_is_mate(nullValue))
1204         {
1205             /* Do not return unproven mates */
1206         }
1207         else if (nullValue >= beta)
1208         {
1209             if (depth < 6 * OnePly)
1210                 return beta;
1211
1212             // Do zugzwang verification search
1213             Value v = search(pos, ss, beta, depth-5*OnePly, ply, false, threadID);
1214             if (v >= beta)
1215                 return beta;
1216         } else {
1217             // The null move failed low, which means that we may be faced with
1218             // some kind of threat. If the previous move was reduced, check if
1219             // the move that refuted the null move was somehow connected to the
1220             // move which was reduced. If a connection is found, return a fail
1221             // low score (which will cause the reduced move to fail high in the
1222             // parent node, which will trigger a re-search with full depth).
1223             if (nullValue == value_mated_in(ply + 2))
1224                 mateThreat = true;
1225
1226             ss[ply].threatMove = ss[ply + 1].currentMove;
1227             if (   depth < ThreatDepth
1228                 && ss[ply - 1].reduction
1229                 && connected_moves(pos, ss[ply - 1].currentMove, ss[ply].threatMove))
1230                 return beta - 1;
1231         }
1232     }
1233     // Null move search not allowed, try razoring
1234     else if (   !value_is_mate(beta)
1235              && approximateEval < beta - RazorMargin
1236              && depth < RazorDepth
1237              && (RazorAtDepthOne || depth > OnePly)
1238              && ttMove == MOVE_NONE
1239              && !pos.has_pawn_on_7th(pos.side_to_move()))
1240     {
1241         Value v = qsearch(pos, ss, beta-1, beta, Depth(0), ply, threadID);
1242         if (   (v < beta - RazorMargin - RazorMargin / 4)
1243             || (depth < 3*OnePly && v < beta - RazorMargin)
1244             || (depth < 2*OnePly && v < beta - RazorMargin / 2))
1245             return v;
1246     }
1247
1248     // Go with internal iterative deepening if we don't have a TT move
1249     if (UseIIDAtNonPVNodes && ttMove == MOVE_NONE && depth >= 8*OnePly &&
1250         evaluate(pos, ei, threadID) >= beta - IIDMargin)
1251     {
1252         search(pos, ss, beta, Min(depth/2, depth-2*OnePly), ply, false, threadID);
1253         ttMove = ss[ply].pv[ply];
1254     }
1255
1256     // Initialize a MovePicker object for the current position, and prepare
1257     // to search all moves:
1258     MovePicker mp = MovePicker(pos, false, ttMove, ss[ply], depth);
1259
1260     Move move, movesSearched[256];
1261     int moveCount = 0;
1262     Value value, bestValue = -VALUE_INFINITE;
1263     Bitboard dcCandidates = mp.discovered_check_candidates();
1264     Value futilityValue = VALUE_NONE;
1265     bool useFutilityPruning =   UseFutilityPruning
1266                              && depth < SelectiveDepth
1267                              && !isCheck;
1268
1269     // Loop through all legal moves until no moves remain or a beta cutoff
1270     // occurs.
1271     while (   bestValue < beta
1272            && (move = mp.get_next_move()) != MOVE_NONE
1273            && !thread_should_stop(threadID))
1274     {
1275       assert(move_is_ok(move));
1276
1277       bool singleReply = (isCheck && mp.number_of_moves() == 1);
1278       bool moveIsCheck = pos.move_is_check(move, dcCandidates);
1279       bool moveIsCapture = pos.move_is_capture(move);
1280
1281       movesSearched[moveCount++] = ss[ply].currentMove = move;
1282
1283       // Decide the new search depth
1284       bool dangerous;
1285       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, singleReply, mateThreat, &dangerous);
1286       Depth newDepth = depth - OnePly + ext;
1287
1288       // Futility pruning
1289       if (    useFutilityPruning
1290           && !dangerous
1291           && !moveIsCapture
1292           && !move_promotion(move))
1293       {
1294           // History pruning. See ok_to_prune() definition
1295           if (   moveCount >= 2 + int(depth)
1296               && ok_to_prune(pos, move, ss[ply].threatMove, depth))
1297               continue;
1298
1299           // Value based pruning
1300           if (depth < 7 * OnePly && approximateEval < beta)
1301           {
1302               if (futilityValue == VALUE_NONE)
1303                   futilityValue =  evaluate(pos, ei, threadID)
1304                                  + FutilityMargins[int(depth)/2 - 1]
1305                                  + 32 * (depth & 1);
1306
1307               if (futilityValue < beta)
1308               {
1309                   if (futilityValue > bestValue)
1310                       bestValue = futilityValue;
1311                   continue;
1312               }
1313           }
1314       }
1315
1316       // Make and search the move
1317       StateInfo st;
1318       pos.do_move(move, st, dcCandidates);
1319
1320       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1321       // if the move fails high will be re-searched at full depth.
1322       if (    depth >= 2*OnePly
1323           &&  moveCount >= LMRNonPVMoves
1324           && !dangerous
1325           && !moveIsCapture
1326           && !move_promotion(move)
1327           && !move_is_castle(move)
1328           && !move_is_killer(move, ss[ply]))
1329       {
1330           ss[ply].reduction = OnePly;
1331           value = -search(pos, ss, -(beta-1), newDepth-OnePly, ply+1, true, threadID);
1332       }
1333       else
1334         value = beta; // Just to trigger next condition
1335
1336       if (value >= beta) // Go with full depth non-pv search
1337       {
1338           ss[ply].reduction = Depth(0);
1339           value = -search(pos, ss, -(beta-1), newDepth, ply+1, true, threadID);
1340       }
1341       pos.undo_move(move);
1342
1343       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1344
1345       // New best move?
1346       if (value > bestValue)
1347       {
1348         bestValue = value;
1349         if (value >= beta)
1350             update_pv(ss, ply);
1351
1352         if (value == value_mate_in(ply + 1))
1353             ss[ply].mateKiller = move;
1354       }
1355
1356       // Split?
1357       if (   ActiveThreads > 1
1358           && bestValue < beta
1359           && depth >= MinimumSplitDepth
1360           && Iteration <= 99
1361           && idle_thread_exists(threadID)
1362           && !AbortSearch
1363           && !thread_should_stop(threadID)
1364           && split(pos, ss, ply, &beta, &beta, &bestValue, depth, &moveCount,
1365                    &mp, dcCandidates, threadID, false))
1366         break;
1367     }
1368
1369     // All legal moves have been searched.  A special case: If there were
1370     // no legal moves, it must be mate or stalemate.
1371     if (moveCount == 0)
1372         return (pos.is_check() ? value_mated_in(ply) : VALUE_DRAW);
1373
1374     // If the search is not aborted, update the transposition table,
1375     // history counters, and killer moves.
1376     if (AbortSearch || thread_should_stop(threadID))
1377         return bestValue;
1378
1379     if (bestValue < beta)
1380         TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_UPPER);
1381     else
1382     {
1383         BetaCounter.add(pos.side_to_move(), depth, threadID);
1384         Move m = ss[ply].pv[ply];
1385         if (ok_to_history(pos, m)) // Only non capture moves are considered
1386         {
1387             update_history(pos, m, depth, movesSearched, moveCount);
1388             update_killers(m, ss[ply]);
1389         }
1390         TT.store(pos, value_to_tt(bestValue, ply), depth, m, VALUE_TYPE_LOWER);
1391     }
1392     return bestValue;
1393   }
1394
1395
1396   // qsearch() is the quiescence search function, which is called by the main
1397   // search function when the remaining depth is zero (or, to be more precise,
1398   // less than OnePly).
1399
1400   Value qsearch(Position &pos, SearchStack ss[], Value alpha, Value beta,
1401                 Depth depth, int ply, int threadID) {
1402
1403     assert(alpha >= -VALUE_INFINITE && alpha <= VALUE_INFINITE);
1404     assert(beta >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
1405     assert(depth <= 0);
1406     assert(ply >= 0 && ply < PLY_MAX);
1407     assert(threadID >= 0 && threadID < ActiveThreads);
1408
1409     // Initialize, and make an early exit in case of an aborted search,
1410     // an instant draw, maximum ply reached, etc.
1411     init_node(pos, ss, ply, threadID);
1412
1413     // After init_node() that calls poll()
1414     if (AbortSearch || thread_should_stop(threadID))
1415         return Value(0);
1416
1417     if (pos.is_draw())
1418         return VALUE_DRAW;
1419
1420     // Transposition table lookup
1421     const TTEntry* tte = TT.retrieve(pos);
1422     if (tte && ok_to_use_TT(tte, depth, beta, ply))
1423         return value_from_tt(tte->value(), ply);
1424
1425     // Evaluate the position statically
1426     EvalInfo ei;
1427     bool isCheck = pos.is_check();
1428     Value staticValue = (isCheck ? -VALUE_INFINITE : evaluate(pos, ei, threadID));
1429
1430     if (ply == PLY_MAX - 1)
1431         return evaluate(pos, ei, threadID);
1432
1433     // Initialize "stand pat score", and return it immediately if it is
1434     // at least beta.
1435     Value bestValue = staticValue;
1436
1437     if (bestValue >= beta)
1438         return bestValue;
1439
1440     if (bestValue > alpha)
1441         alpha = bestValue;
1442
1443     // Initialize a MovePicker object for the current position, and prepare
1444     // to search the moves.  Because the depth is <= 0 here, only captures,
1445     // queen promotions and checks (only if depth == 0) will be generated.
1446     bool pvNode = (beta - alpha != 1);
1447     MovePicker mp = MovePicker(pos, pvNode, MOVE_NONE, EmptySearchStack, depth, isCheck ? NULL : &ei);
1448     Move move;
1449     int moveCount = 0;
1450     Bitboard dcCandidates = mp.discovered_check_candidates();
1451     Color us = pos.side_to_move();
1452     bool enoughMaterial = pos.non_pawn_material(us) > RookValueMidgame;
1453
1454     // Loop through the moves until no moves remain or a beta cutoff
1455     // occurs.
1456     while (   alpha < beta
1457            && (move = mp.get_next_move()) != MOVE_NONE)
1458     {
1459       assert(move_is_ok(move));
1460
1461       moveCount++;
1462       ss[ply].currentMove = move;
1463
1464       // Futility pruning
1465       if (    UseQSearchFutilityPruning
1466           &&  enoughMaterial
1467           && !isCheck
1468           && !pvNode
1469           && !move_promotion(move)
1470           && !pos.move_is_check(move, dcCandidates)
1471           && !pos.move_is_passed_pawn_push(move))
1472       {
1473           Value futilityValue = staticValue
1474                               + Max(pos.midgame_value_of_piece_on(move_to(move)),
1475                                     pos.endgame_value_of_piece_on(move_to(move)))
1476                               + (move_is_ep(move) ? PawnValueEndgame : Value(0))
1477                               + FutilityMarginQS
1478                               + ei.futilityMargin;
1479
1480           if (futilityValue < alpha)
1481           {
1482               if (futilityValue > bestValue)
1483                   bestValue = futilityValue;
1484               continue;
1485           }
1486       }
1487
1488       // Don't search captures and checks with negative SEE values
1489       if (   !isCheck
1490           && !move_promotion(move)
1491           && (pos.midgame_value_of_piece_on(move_from(move)) >
1492               pos.midgame_value_of_piece_on(move_to(move)))
1493           &&  pos.see(move) < 0)
1494           continue;
1495
1496       // Make and search the move.
1497       StateInfo st;
1498       pos.do_move(move, st, dcCandidates);
1499       Value value = -qsearch(pos, ss, -beta, -alpha, depth-OnePly, ply+1, threadID);
1500       pos.undo_move(move);
1501
1502       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1503
1504       // New best move?
1505       if (value > bestValue)
1506       {
1507           bestValue = value;
1508           if (value > alpha)
1509           {
1510               alpha = value;
1511               update_pv(ss, ply);
1512           }
1513        }
1514     }
1515
1516     // All legal moves have been searched.  A special case: If we're in check
1517     // and no legal moves were found, it is checkmate:
1518     if (pos.is_check() && moveCount == 0) // Mate!
1519         return value_mated_in(ply);
1520
1521     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1522
1523     // Update transposition table
1524     TT.store(pos, value_to_tt(bestValue, ply), depth, MOVE_NONE, VALUE_TYPE_EXACT);
1525
1526     // Update killers only for good check moves
1527     Move m = ss[ply].currentMove;
1528     if (alpha >= beta && ok_to_history(pos, m)) // Only non capture moves are considered
1529     {
1530         // Wrong to update history when depth is <= 0
1531         update_killers(m, ss[ply]);
1532     }
1533     return bestValue;
1534   }
1535
1536
1537   // sp_search() is used to search from a split point.  This function is called
1538   // by each thread working at the split point.  It is similar to the normal
1539   // search() function, but simpler.  Because we have already probed the hash
1540   // table, done a null move search, and searched the first move before
1541   // splitting, we don't have to repeat all this work in sp_search().  We
1542   // also don't need to store anything to the hash table here:  This is taken
1543   // care of after we return from the split point.
1544
1545   void sp_search(SplitPoint *sp, int threadID) {
1546
1547     assert(threadID >= 0 && threadID < ActiveThreads);
1548     assert(ActiveThreads > 1);
1549
1550     Position pos = Position(sp->pos);
1551     SearchStack *ss = sp->sstack[threadID];
1552     Value value;
1553     Move move;
1554     bool isCheck = pos.is_check();
1555     bool useFutilityPruning =    UseFutilityPruning
1556                               && sp->depth < SelectiveDepth
1557                               && !isCheck;
1558
1559     while (    sp->bestValue < sp->beta
1560            && !thread_should_stop(threadID)
1561            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1562     {
1563       assert(move_is_ok(move));
1564
1565       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1566       bool moveIsCapture = pos.move_is_capture(move);
1567
1568       lock_grab(&(sp->lock));
1569       int moveCount = ++sp->moves;
1570       lock_release(&(sp->lock));
1571
1572       ss[sp->ply].currentMove = move;
1573
1574       // Decide the new search depth.
1575       bool dangerous;
1576       Depth ext = extension(pos, move, false, moveIsCapture, moveIsCheck, false, false, &dangerous);
1577       Depth newDepth = sp->depth - OnePly + ext;
1578
1579       // Prune?
1580       if (    useFutilityPruning
1581           && !dangerous
1582           && !moveIsCapture
1583           && !move_promotion(move)
1584           &&  moveCount >= 2 + int(sp->depth)
1585           &&  ok_to_prune(pos, move, ss[sp->ply].threatMove, sp->depth))
1586         continue;
1587
1588       // Make and search the move.
1589       StateInfo st;
1590       pos.do_move(move, st, sp->dcCandidates);
1591
1592       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1593       // if the move fails high will be re-searched at full depth.
1594       if (   !dangerous
1595           &&  moveCount >= LMRNonPVMoves
1596           && !moveIsCapture
1597           && !move_promotion(move)
1598           && !move_is_castle(move)
1599           && !move_is_killer(move, ss[sp->ply]))
1600       {
1601           ss[sp->ply].reduction = OnePly;
1602           value = -search(pos, ss, -(sp->beta-1), newDepth - OnePly, sp->ply+1, true, threadID);
1603       }
1604       else
1605           value = sp->beta; // Just to trigger next condition
1606
1607       if (value >= sp->beta) // Go with full depth non-pv search
1608       {
1609           ss[sp->ply].reduction = Depth(0);
1610           value = -search(pos, ss, -(sp->beta - 1), newDepth, sp->ply+1, true, threadID);
1611       }
1612       pos.undo_move(move);
1613
1614       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1615
1616       if (thread_should_stop(threadID))
1617           break;
1618
1619       // New best move?
1620       lock_grab(&(sp->lock));
1621       if (value > sp->bestValue && !thread_should_stop(threadID))
1622       {
1623           sp->bestValue = value;
1624           if (sp->bestValue >= sp->beta)
1625           {
1626               sp_update_pv(sp->parentSstack, ss, sp->ply);
1627               for (int i = 0; i < ActiveThreads; i++)
1628                   if (i != threadID && (i == sp->master || sp->slaves[i]))
1629                       Threads[i].stop = true;
1630
1631               sp->finished = true;
1632         }
1633       }
1634       lock_release(&(sp->lock));
1635     }
1636
1637     lock_grab(&(sp->lock));
1638
1639     // If this is the master thread and we have been asked to stop because of
1640     // a beta cutoff higher up in the tree, stop all slave threads:
1641     if (sp->master == threadID && thread_should_stop(threadID))
1642         for (int i = 0; i < ActiveThreads; i++)
1643             if (sp->slaves[i])
1644                 Threads[i].stop = true;
1645
1646     sp->cpus--;
1647     sp->slaves[threadID] = 0;
1648
1649     lock_release(&(sp->lock));
1650   }
1651
1652
1653   // sp_search_pv() is used to search from a PV split point.  This function
1654   // is called by each thread working at the split point.  It is similar to
1655   // the normal search_pv() function, but simpler.  Because we have already
1656   // probed the hash table and searched the first move before splitting, we
1657   // don't have to repeat all this work in sp_search_pv().  We also don't
1658   // need to store anything to the hash table here:  This is taken care of
1659   // after we return from the split point.
1660
1661   void sp_search_pv(SplitPoint *sp, int threadID) {
1662
1663     assert(threadID >= 0 && threadID < ActiveThreads);
1664     assert(ActiveThreads > 1);
1665
1666     Position pos = Position(sp->pos);
1667     SearchStack *ss = sp->sstack[threadID];
1668     Value value;
1669     Move move;
1670
1671     while (    sp->alpha < sp->beta
1672            && !thread_should_stop(threadID)
1673            && (move = sp->mp->get_next_move(sp->lock)) != MOVE_NONE)
1674     {
1675       bool moveIsCheck = pos.move_is_check(move, sp->dcCandidates);
1676       bool moveIsCapture = pos.move_is_capture(move);
1677
1678       assert(move_is_ok(move));
1679
1680       if (moveIsCapture)
1681           ss[sp->ply].currentMoveCaptureValue =
1682           move_is_ep(move)? PawnValueMidgame : pos.midgame_value_of_piece_on(move_to(move));
1683       else
1684           ss[sp->ply].currentMoveCaptureValue = Value(0);
1685
1686       lock_grab(&(sp->lock));
1687       int moveCount = ++sp->moves;
1688       lock_release(&(sp->lock));
1689
1690       ss[sp->ply].currentMove = move;
1691
1692       // Decide the new search depth.
1693       bool dangerous;
1694       Depth ext = extension(pos, move, true, moveIsCapture, moveIsCheck, false, false, &dangerous);
1695       Depth newDepth = sp->depth - OnePly + ext;
1696
1697       // Make and search the move.
1698       StateInfo st;
1699       pos.do_move(move, st, sp->dcCandidates);
1700
1701       // Try to reduce non-pv search depth by one ply if move seems not problematic,
1702       // if the move fails high will be re-searched at full depth.
1703       if (   !dangerous
1704           &&  moveCount >= LMRPVMoves
1705           && !moveIsCapture
1706           && !move_promotion(move)
1707           && !move_is_castle(move)
1708           && !move_is_killer(move, ss[sp->ply]))
1709       {
1710           ss[sp->ply].reduction = OnePly;
1711           value = -search(pos, ss, -sp->alpha, newDepth - OnePly, sp->ply+1, true, threadID);
1712       }
1713       else
1714           value = sp->alpha + 1; // Just to trigger next condition
1715
1716       if (value > sp->alpha) // Go with full depth non-pv search
1717       {
1718           ss[sp->ply].reduction = Depth(0);
1719           value = -search(pos, ss, -sp->alpha, newDepth, sp->ply+1, true, threadID);
1720
1721           if (value > sp->alpha && value < sp->beta)
1722           {
1723               // When the search fails high at ply 1 while searching the first
1724               // move at the root, set the flag failHighPly1.  This is used for
1725               // time managment:  We don't want to stop the search early in
1726               // such cases, because resolving the fail high at ply 1 could
1727               // result in a big drop in score at the root.
1728               if (sp->ply == 1 && RootMoveNumber == 1)
1729                   Threads[threadID].failHighPly1 = true;
1730
1731               value = -search_pv(pos, ss, -sp->beta, -sp->alpha, newDepth, sp->ply+1, threadID);
1732               Threads[threadID].failHighPly1 = false;
1733         }
1734       }
1735       pos.undo_move(move);
1736
1737       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1738
1739       if (thread_should_stop(threadID))
1740           break;
1741
1742       // New best move?
1743       lock_grab(&(sp->lock));
1744       if (value > sp->bestValue && !thread_should_stop(threadID))
1745       {
1746           sp->bestValue = value;
1747           if (value > sp->alpha)
1748           {
1749               sp->alpha = value;
1750               sp_update_pv(sp->parentSstack, ss, sp->ply);
1751               if (value == value_mate_in(sp->ply + 1))
1752                   ss[sp->ply].mateKiller = move;
1753
1754               if(value >= sp->beta)
1755               {
1756                   for(int i = 0; i < ActiveThreads; i++)
1757                       if(i != threadID && (i == sp->master || sp->slaves[i]))
1758                           Threads[i].stop = true;
1759
1760                   sp->finished = true;
1761               }
1762         }
1763         // If we are at ply 1, and we are searching the first root move at
1764         // ply 0, set the 'Problem' variable if the score has dropped a lot
1765         // (from the computer's point of view) since the previous iteration.
1766         if (   sp->ply == 1
1767             && Iteration >= 2
1768             && -value <= ValueByIteration[Iteration-1] - ProblemMargin)
1769             Problem = true;
1770       }
1771       lock_release(&(sp->lock));
1772     }
1773
1774     lock_grab(&(sp->lock));
1775
1776     // If this is the master thread and we have been asked to stop because of
1777     // a beta cutoff higher up in the tree, stop all slave threads.
1778     if (sp->master == threadID && thread_should_stop(threadID))
1779         for (int i = 0; i < ActiveThreads; i++)
1780             if (sp->slaves[i])
1781                 Threads[i].stop = true;
1782
1783     sp->cpus--;
1784     sp->slaves[threadID] = 0;
1785
1786     lock_release(&(sp->lock));
1787   }
1788
1789   /// The BetaCounterType class
1790
1791   BetaCounterType::BetaCounterType() { clear(); }
1792
1793   void BetaCounterType::clear() {
1794
1795     for (int i = 0; i < THREAD_MAX; i++)
1796         hits[i][WHITE] = hits[i][BLACK] = 0ULL;
1797   }
1798
1799   void BetaCounterType::add(Color us, Depth d, int threadID) {
1800
1801     // Weighted count based on depth
1802     hits[threadID][us] += int(d);
1803   }
1804
1805   void BetaCounterType::read(Color us, int64_t& our, int64_t& their) {
1806
1807     our = their = 0UL;
1808     for (int i = 0; i < THREAD_MAX; i++)
1809     {
1810         our += hits[i][us];
1811         their += hits[i][opposite_color(us)];
1812     }
1813   }
1814
1815
1816   /// The RootMove class
1817
1818   // Constructor
1819
1820   RootMove::RootMove() {
1821     nodes = cumulativeNodes = 0ULL;
1822   }
1823
1824   // RootMove::operator<() is the comparison function used when
1825   // sorting the moves.  A move m1 is considered to be better
1826   // than a move m2 if it has a higher score, or if the moves
1827   // have equal score but m1 has the higher node count.
1828
1829   bool RootMove::operator<(const RootMove& m) {
1830
1831     if (score != m.score)
1832         return (score < m.score);
1833
1834     return theirBeta <= m.theirBeta;
1835   }
1836
1837   /// The RootMoveList class
1838
1839   // Constructor
1840
1841   RootMoveList::RootMoveList(Position& pos, Move searchMoves[]) : count(0) {
1842
1843     MoveStack mlist[MaxRootMoves];
1844     bool includeAllMoves = (searchMoves[0] == MOVE_NONE);
1845
1846     // Generate all legal moves
1847     int lm_count = generate_legal_moves(pos, mlist);
1848
1849     // Add each move to the moves[] array
1850     for (int i = 0; i < lm_count; i++)
1851     {
1852         bool includeMove = includeAllMoves;
1853
1854         for (int k = 0; !includeMove && searchMoves[k] != MOVE_NONE; k++)
1855             includeMove = (searchMoves[k] == mlist[i].move);
1856
1857         if (includeMove)
1858         {
1859             // Find a quick score for the move
1860             StateInfo st;
1861             SearchStack ss[PLY_MAX_PLUS_2];
1862
1863             moves[count].move = mlist[i].move;
1864             moves[count].nodes = 0ULL;
1865             pos.do_move(moves[count].move, st);
1866             moves[count].score = -qsearch(pos, ss, -VALUE_INFINITE, VALUE_INFINITE,
1867                                           Depth(0), 1, 0);
1868             pos.undo_move(moves[count].move);
1869             moves[count].pv[0] = moves[i].move;
1870             moves[count].pv[1] = MOVE_NONE; // FIXME
1871             count++;
1872         }
1873     }
1874     sort();
1875   }
1876
1877
1878   // Simple accessor methods for the RootMoveList class
1879
1880   inline Move RootMoveList::get_move(int moveNum) const {
1881     return moves[moveNum].move;
1882   }
1883
1884   inline Value RootMoveList::get_move_score(int moveNum) const {
1885     return moves[moveNum].score;
1886   }
1887
1888   inline void RootMoveList::set_move_score(int moveNum, Value score) {
1889     moves[moveNum].score = score;
1890   }
1891
1892   inline void RootMoveList::set_move_nodes(int moveNum, int64_t nodes) {
1893     moves[moveNum].nodes = nodes;
1894     moves[moveNum].cumulativeNodes += nodes;
1895   }
1896
1897   inline void RootMoveList::set_beta_counters(int moveNum, int64_t our, int64_t their) {
1898     moves[moveNum].ourBeta = our;
1899     moves[moveNum].theirBeta = their;
1900   }
1901
1902   void RootMoveList::set_move_pv(int moveNum, const Move pv[]) {
1903     int j;
1904     for(j = 0; pv[j] != MOVE_NONE; j++)
1905       moves[moveNum].pv[j] = pv[j];
1906     moves[moveNum].pv[j] = MOVE_NONE;
1907   }
1908
1909   inline Move RootMoveList::get_move_pv(int moveNum, int i) const {
1910     return moves[moveNum].pv[i];
1911   }
1912
1913   inline int64_t RootMoveList::get_move_cumulative_nodes(int moveNum) const {
1914     return moves[moveNum].cumulativeNodes;
1915   }
1916
1917   inline int RootMoveList::move_count() const {
1918     return count;
1919   }
1920
1921
1922   // RootMoveList::scan_for_easy_move() is called at the end of the first
1923   // iteration, and is used to detect an "easy move", i.e. a move which appears
1924   // to be much bester than all the rest.  If an easy move is found, the move
1925   // is returned, otherwise the function returns MOVE_NONE.  It is very
1926   // important that this function is called at the right moment:  The code
1927   // assumes that the first iteration has been completed and the moves have
1928   // been sorted. This is done in RootMoveList c'tor.
1929
1930   Move RootMoveList::scan_for_easy_move() const {
1931
1932     assert(count);
1933
1934     if (count == 1)
1935         return get_move(0);
1936
1937     // moves are sorted so just consider the best and the second one
1938     if (get_move_score(0) > get_move_score(1) + EasyMoveMargin)
1939         return get_move(0);
1940
1941     return MOVE_NONE;
1942   }
1943
1944   // RootMoveList::sort() sorts the root move list at the beginning of a new
1945   // iteration.
1946
1947   inline void RootMoveList::sort() {
1948
1949     sort_multipv(count - 1); // all items
1950   }
1951
1952
1953   // RootMoveList::sort_multipv() sorts the first few moves in the root move
1954   // list by their scores and depths. It is used to order the different PVs
1955   // correctly in MultiPV mode.
1956
1957   void RootMoveList::sort_multipv(int n) {
1958
1959     for (int i = 1; i <= n; i++)
1960     {
1961       RootMove rm = moves[i];
1962       int j;
1963       for (j = i; j > 0 && moves[j-1] < rm; j--)
1964           moves[j] = moves[j-1];
1965       moves[j] = rm;
1966     }
1967   }
1968
1969
1970   // init_node() is called at the beginning of all the search functions
1971   // (search(), search_pv(), qsearch(), and so on) and initializes the search
1972   // stack object corresponding to the current node.  Once every
1973   // NodesBetweenPolls nodes, init_node() also calls poll(), which polls
1974   // for user input and checks whether it is time to stop the search.
1975
1976   void init_node(const Position &pos, SearchStack ss[], int ply, int threadID) {
1977     assert(ply >= 0 && ply < PLY_MAX);
1978     assert(threadID >= 0 && threadID < ActiveThreads);
1979
1980     Threads[threadID].nodes++;
1981
1982     if(threadID == 0) {
1983       NodesSincePoll++;
1984       if(NodesSincePoll >= NodesBetweenPolls) {
1985         poll();
1986         NodesSincePoll = 0;
1987       }
1988     }
1989
1990     ss[ply].init(ply);
1991     ss[ply+2].initKillers();
1992
1993     if(Threads[threadID].printCurrentLine)
1994       print_current_line(ss, ply, threadID);
1995   }
1996
1997
1998   // update_pv() is called whenever a search returns a value > alpha.  It
1999   // updates the PV in the SearchStack object corresponding to the current
2000   // node.
2001
2002   void update_pv(SearchStack ss[], int ply) {
2003     assert(ply >= 0 && ply < PLY_MAX);
2004
2005     ss[ply].pv[ply] = ss[ply].currentMove;
2006     int p;
2007     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2008       ss[ply].pv[p] = ss[ply+1].pv[p];
2009     ss[ply].pv[p] = MOVE_NONE;
2010   }
2011
2012
2013   // sp_update_pv() is a variant of update_pv for use at split points.  The
2014   // difference between the two functions is that sp_update_pv also updates
2015   // the PV at the parent node.
2016
2017   void sp_update_pv(SearchStack *pss, SearchStack ss[], int ply) {
2018     assert(ply >= 0 && ply < PLY_MAX);
2019
2020     ss[ply].pv[ply] = pss[ply].pv[ply] = ss[ply].currentMove;
2021     int p;
2022     for(p = ply + 1; ss[ply+1].pv[p] != MOVE_NONE; p++)
2023       ss[ply].pv[p] = pss[ply].pv[p] = ss[ply+1].pv[p];
2024     ss[ply].pv[p] = pss[ply].pv[p] = MOVE_NONE;
2025   }
2026
2027
2028   // connected_moves() tests whether two moves are 'connected' in the sense
2029   // that the first move somehow made the second move possible (for instance
2030   // if the moving piece is the same in both moves).  The first move is
2031   // assumed to be the move that was made to reach the current position, while
2032   // the second move is assumed to be a move from the current position.
2033
2034   bool connected_moves(const Position &pos, Move m1, Move m2) {
2035     Square f1, t1, f2, t2;
2036
2037     assert(move_is_ok(m1));
2038     assert(move_is_ok(m2));
2039
2040     if(m2 == MOVE_NONE)
2041       return false;
2042
2043     // Case 1: The moving piece is the same in both moves.
2044     f2 = move_from(m2);
2045     t1 = move_to(m1);
2046     if(f2 == t1)
2047       return true;
2048
2049     // Case 2: The destination square for m2 was vacated by m1.
2050     t2 = move_to(m2);
2051     f1 = move_from(m1);
2052     if(t2 == f1)
2053       return true;
2054
2055     // Case 3: Moving through the vacated square:
2056     if(piece_is_slider(pos.piece_on(f2)) &&
2057        bit_is_set(squares_between(f2, t2), f1))
2058       return true;
2059
2060     // Case 4: The destination square for m2 is attacked by the moving piece
2061     // in m1:
2062     if(pos.piece_attacks_square(pos.piece_on(t1), t1, t2))
2063       return true;
2064
2065     // Case 5: Discovered check, checking piece is the piece moved in m1:
2066     if(piece_is_slider(pos.piece_on(t1)) &&
2067        bit_is_set(squares_between(t1, pos.king_square(pos.side_to_move())),
2068                   f2) &&
2069        !bit_is_set(squares_between(t2, pos.king_square(pos.side_to_move())),
2070                    t2)) {
2071       Bitboard occ = pos.occupied_squares();
2072       Color us = pos.side_to_move();
2073       Square ksq = pos.king_square(us);
2074       clear_bit(&occ, f2);
2075       if(pos.type_of_piece_on(t1) == BISHOP) {
2076         if(bit_is_set(bishop_attacks_bb(ksq, occ), t1))
2077           return true;
2078       }
2079       else if(pos.type_of_piece_on(t1) == ROOK) {
2080         if(bit_is_set(rook_attacks_bb(ksq, occ), t1))
2081           return true;
2082       }
2083       else {
2084         assert(pos.type_of_piece_on(t1) == QUEEN);
2085         if(bit_is_set(queen_attacks_bb(ksq, occ), t1))
2086           return true;
2087       }
2088     }
2089
2090     return false;
2091   }
2092
2093
2094   // value_is_mate() checks if the given value is a mate one
2095   // eventually compensated for the ply.
2096
2097   bool value_is_mate(Value value) {
2098
2099     assert(abs(value) <= VALUE_INFINITE);
2100
2101     return   value <= value_mated_in(PLY_MAX)
2102           || value >= value_mate_in(PLY_MAX);
2103   }
2104
2105
2106   // move_is_killer() checks if the given move is among the
2107   // killer moves of that ply.
2108
2109   bool move_is_killer(Move m, const SearchStack& ss) {
2110
2111       const Move* k = ss.killers;
2112       for (int i = 0; i < KILLER_MAX; i++, k++)
2113           if (*k == m)
2114               return true;
2115
2116       return false;
2117   }
2118
2119
2120   // extension() decides whether a move should be searched with normal depth,
2121   // or with extended depth.  Certain classes of moves (checking moves, in
2122   // particular) are searched with bigger depth than ordinary moves and in
2123   // any case are marked as 'dangerous'. Note that also if a move is not
2124   // extended, as example because the corresponding UCI option is set to zero,
2125   // the move is marked as 'dangerous' so, at least, we avoid to prune it.
2126
2127   Depth extension(const Position& pos, Move m, bool pvNode, bool capture, bool check,
2128                   bool singleReply, bool mateThreat, bool* dangerous) {
2129
2130     assert(m != MOVE_NONE);
2131
2132     Depth result = Depth(0);
2133     *dangerous = check || singleReply || mateThreat;
2134
2135     if (check)
2136         result += CheckExtension[pvNode];
2137
2138     if (singleReply)
2139         result += SingleReplyExtension[pvNode];
2140
2141     if (mateThreat)
2142         result += MateThreatExtension[pvNode];
2143
2144     if (pos.type_of_piece_on(move_from(m)) == PAWN)
2145     {
2146         if (pos.move_is_pawn_push_to_7th(m))
2147         {
2148             result += PawnPushTo7thExtension[pvNode];
2149             *dangerous = true;
2150         }
2151         if (pos.move_is_passed_pawn_push(m))
2152         {
2153             result += PassedPawnExtension[pvNode];
2154             *dangerous = true;
2155         }
2156     }
2157
2158     if (   capture
2159         && pos.type_of_piece_on(move_to(m)) != PAWN
2160         && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
2161             - pos.midgame_value_of_piece_on(move_to(m)) == Value(0))
2162         && !move_promotion(m)
2163         && !move_is_ep(m))
2164     {
2165         result += PawnEndgameExtension[pvNode];
2166         *dangerous = true;
2167     }
2168
2169     if (   pvNode
2170         && capture
2171         && pos.type_of_piece_on(move_to(m)) != PAWN
2172         && pos.see(m) >= 0)
2173     {
2174         result += OnePly/2;
2175         *dangerous = true;
2176     }
2177
2178     return Min(result, OnePly);
2179   }
2180
2181
2182   // ok_to_do_nullmove() looks at the current position and decides whether
2183   // doing a 'null move' should be allowed.  In order to avoid zugzwang
2184   // problems, null moves are not allowed when the side to move has very
2185   // little material left.  Currently, the test is a bit too simple:  Null
2186   // moves are avoided only when the side to move has only pawns left.  It's
2187   // probably a good idea to avoid null moves in at least some more
2188   // complicated endgames, e.g. KQ vs KR.  FIXME
2189
2190   bool ok_to_do_nullmove(const Position &pos) {
2191     if(pos.non_pawn_material(pos.side_to_move()) == Value(0))
2192       return false;
2193     return true;
2194   }
2195
2196
2197   // ok_to_prune() tests whether it is safe to forward prune a move.  Only
2198   // non-tactical moves late in the move list close to the leaves are
2199   // candidates for pruning.
2200
2201   bool ok_to_prune(const Position &pos, Move m, Move threat, Depth d) {
2202     Square mfrom, mto, tfrom, tto;
2203
2204     assert(move_is_ok(m));
2205     assert(threat == MOVE_NONE || move_is_ok(threat));
2206     assert(!move_promotion(m));
2207     assert(!pos.move_is_check(m));
2208     assert(!pos.move_is_capture(m));
2209     assert(!pos.move_is_passed_pawn_push(m));
2210     assert(d >= OnePly);
2211
2212     mfrom = move_from(m);
2213     mto = move_to(m);
2214     tfrom = move_from(threat);
2215     tto = move_to(threat);
2216
2217     // Case 1: Castling moves are never pruned.
2218     if (move_is_castle(m))
2219         return false;
2220
2221     // Case 2: Don't prune moves which move the threatened piece
2222     if (!PruneEscapeMoves && threat != MOVE_NONE && mfrom == tto)
2223         return false;
2224
2225     // Case 3: If the threatened piece has value less than or equal to the
2226     // value of the threatening piece, don't prune move which defend it.
2227     if (   !PruneDefendingMoves
2228         && threat != MOVE_NONE
2229         && pos.move_is_capture(threat)
2230         && (   pos.midgame_value_of_piece_on(tfrom) >= pos.midgame_value_of_piece_on(tto)
2231             || pos.type_of_piece_on(tfrom) == KING)
2232         && pos.move_attacks_square(m, tto))
2233       return false;
2234
2235     // Case 4: Don't prune moves with good history.
2236     if (!H.ok_to_prune(pos.piece_on(move_from(m)), m, d))
2237         return false;
2238
2239     // Case 5: If the moving piece in the threatened move is a slider, don't
2240     // prune safe moves which block its ray.
2241     if (  !PruneBlockingMoves
2242         && threat != MOVE_NONE
2243         && piece_is_slider(pos.piece_on(tfrom))
2244         && bit_is_set(squares_between(tfrom, tto), mto)
2245         && pos.see(m) >= 0)
2246             return false;
2247
2248     return true;
2249   }
2250
2251
2252   // ok_to_use_TT() returns true if a transposition table score
2253   // can be used at a given point in search.
2254
2255   bool ok_to_use_TT(const TTEntry* tte, Depth depth, Value beta, int ply) {
2256
2257     Value v = value_from_tt(tte->value(), ply);
2258
2259     return   (   tte->depth() >= depth
2260               || v >= Max(value_mate_in(100), beta)
2261               || v < Min(value_mated_in(100), beta))
2262
2263           && (   (is_lower_bound(tte->type()) && v >= beta)
2264               || (is_upper_bound(tte->type()) && v < beta));
2265   }
2266
2267
2268   // ok_to_history() returns true if a move m can be stored
2269   // in history. Should be a non capturing move nor a promotion.
2270
2271   bool ok_to_history(const Position& pos, Move m) {
2272
2273     return !pos.move_is_capture(m) && !move_promotion(m);
2274   }
2275
2276
2277   // update_history() registers a good move that produced a beta-cutoff
2278   // in history and marks as failures all the other moves of that ply.
2279
2280   void update_history(const Position& pos, Move m, Depth depth,
2281                       Move movesSearched[], int moveCount) {
2282
2283     H.success(pos.piece_on(move_from(m)), m, depth);
2284
2285     for (int i = 0; i < moveCount - 1; i++)
2286     {
2287         assert(m != movesSearched[i]);
2288         if (ok_to_history(pos, movesSearched[i]))
2289             H.failure(pos.piece_on(move_from(movesSearched[i])), movesSearched[i]);
2290     }
2291   }
2292
2293
2294   // update_killers() add a good move that produced a beta-cutoff
2295   // among the killer moves of that ply.
2296
2297   void update_killers(Move m, SearchStack& ss) {
2298
2299     if (m == ss.killers[0])
2300         return;
2301
2302     for (int i = KILLER_MAX - 1; i > 0; i--)
2303         ss.killers[i] = ss.killers[i - 1];
2304
2305     ss.killers[0] = m;
2306   }
2307
2308   // fail_high_ply_1() checks if some thread is currently resolving a fail
2309   // high at ply 1 at the node below the first root node.  This information
2310   // is used for time managment.
2311
2312   bool fail_high_ply_1() {
2313     for(int i = 0; i < ActiveThreads; i++)
2314       if(Threads[i].failHighPly1)
2315         return true;
2316     return false;
2317   }
2318
2319
2320   // current_search_time() returns the number of milliseconds which have passed
2321   // since the beginning of the current search.
2322
2323   int current_search_time() {
2324     return get_system_time() - SearchStartTime;
2325   }
2326
2327
2328   // nps() computes the current nodes/second count.
2329
2330   int nps() {
2331     int t = current_search_time();
2332     return (t > 0)? int((nodes_searched() * 1000) / t) : 0;
2333   }
2334
2335
2336   // poll() performs two different functions:  It polls for user input, and it
2337   // looks at the time consumed so far and decides if it's time to abort the
2338   // search.
2339
2340   void poll() {
2341
2342     static int lastInfoTime;
2343     int t = current_search_time();
2344
2345     //  Poll for input
2346     if (Bioskey())
2347     {
2348         // We are line oriented, don't read single chars
2349         std::string command;
2350         if (!std::getline(std::cin, command))
2351             command = "quit";
2352
2353         if (command == "quit")
2354         {
2355             AbortSearch = true;
2356             PonderSearch = false;
2357             Quit = true;
2358         }
2359         else if(command == "stop")
2360         {
2361             AbortSearch = true;
2362             PonderSearch = false;
2363         }
2364         else if(command == "ponderhit")
2365             ponderhit();
2366     }
2367     // Print search information
2368     if (t < 1000)
2369         lastInfoTime = 0;
2370
2371     else if (lastInfoTime > t)
2372         // HACK: Must be a new search where we searched less than
2373         // NodesBetweenPolls nodes during the first second of search.
2374         lastInfoTime = 0;
2375
2376     else if (t - lastInfoTime >= 1000)
2377     {
2378         lastInfoTime = t;
2379         lock_grab(&IOLock);
2380         if (dbg_show_mean)
2381             dbg_print_mean();
2382
2383         if (dbg_show_hit_rate)
2384             dbg_print_hit_rate();
2385
2386         std::cout << "info nodes " << nodes_searched() << " nps " << nps()
2387                   << " time " << t << " hashfull " << TT.full() << std::endl;
2388         lock_release(&IOLock);
2389         if (ShowCurrentLine)
2390             Threads[0].printCurrentLine = true;
2391     }
2392     // Should we stop the search?
2393     if (PonderSearch)
2394         return;
2395
2396     bool overTime =     t > AbsoluteMaxSearchTime
2397                      || (RootMoveNumber == 1 && t > MaxSearchTime + ExtraSearchTime)
2398                      || (  !FailHigh && !fail_high_ply_1() && !Problem
2399                          && t > 6*(MaxSearchTime + ExtraSearchTime));
2400
2401     if (   (Iteration >= 2 && (!InfiniteSearch && overTime))
2402         || (ExactMaxTime && t >= ExactMaxTime)
2403         || (Iteration >= 3 && MaxNodes && nodes_searched() >= MaxNodes))
2404         AbortSearch = true;
2405   }
2406
2407
2408   // ponderhit() is called when the program is pondering (i.e. thinking while
2409   // it's the opponent's turn to move) in order to let the engine know that
2410   // it correctly predicted the opponent's move.
2411
2412   void ponderhit() {
2413     int t = current_search_time();
2414     PonderSearch = false;
2415     if(Iteration >= 2 &&
2416        (!InfiniteSearch && (StopOnPonderhit ||
2417                             t > AbsoluteMaxSearchTime ||
2418                             (RootMoveNumber == 1 &&
2419                              t > MaxSearchTime + ExtraSearchTime) ||
2420                             (!FailHigh && !fail_high_ply_1() && !Problem &&
2421                              t > 6*(MaxSearchTime + ExtraSearchTime)))))
2422       AbortSearch = true;
2423   }
2424
2425
2426   // print_current_line() prints the current line of search for a given
2427   // thread.  Called when the UCI option UCI_ShowCurrLine is 'true'.
2428
2429   void print_current_line(SearchStack ss[], int ply, int threadID) {
2430     assert(ply >= 0 && ply < PLY_MAX);
2431     assert(threadID >= 0 && threadID < ActiveThreads);
2432
2433     if(!Threads[threadID].idle) {
2434       lock_grab(&IOLock);
2435       std::cout << "info currline " << (threadID + 1);
2436       for(int p = 0; p < ply; p++)
2437         std::cout << " " << ss[p].currentMove;
2438       std::cout << std::endl;
2439       lock_release(&IOLock);
2440     }
2441     Threads[threadID].printCurrentLine = false;
2442     if(threadID + 1 < ActiveThreads)
2443       Threads[threadID + 1].printCurrentLine = true;
2444   }
2445
2446
2447   // wait_for_stop_or_ponderhit() is called when the maximum depth is reached
2448   // while the program is pondering.  The point is to work around a wrinkle in
2449   // the UCI protocol:  When pondering, the engine is not allowed to give a
2450   // "bestmove" before the GUI sends it a "stop" or "ponderhit" command.
2451   // We simply wait here until one of these commands is sent, and return,
2452   // after which the bestmove and pondermove will be printed (in id_loop()).
2453
2454   void wait_for_stop_or_ponderhit() {
2455     std::string command;
2456
2457     while(true) {
2458       if(!std::getline(std::cin, command))
2459         command = "quit";
2460
2461       if(command == "quit") {
2462         OpeningBook.close();
2463         stop_threads();
2464         quit_eval();
2465         exit(0);
2466       }
2467       else if(command == "ponderhit" || command == "stop")
2468         break;
2469     }
2470   }
2471
2472
2473   // idle_loop() is where the threads are parked when they have no work to do.
2474   // The parameter "waitSp", if non-NULL, is a pointer to an active SplitPoint
2475   // object for which the current thread is the master.
2476
2477   void idle_loop(int threadID, SplitPoint *waitSp) {
2478     assert(threadID >= 0 && threadID < THREAD_MAX);
2479
2480     Threads[threadID].running = true;
2481
2482     while(true) {
2483       if(AllThreadsShouldExit && threadID != 0)
2484         break;
2485
2486       // If we are not thinking, wait for a condition to be signaled instead
2487       // of wasting CPU time polling for work:
2488       while(threadID != 0 && (Idle || threadID >= ActiveThreads)) {
2489 #if !defined(_MSC_VER)
2490         pthread_mutex_lock(&WaitLock);
2491         if(Idle || threadID >= ActiveThreads)
2492           pthread_cond_wait(&WaitCond, &WaitLock);
2493         pthread_mutex_unlock(&WaitLock);
2494 #else
2495         WaitForSingleObject(SitIdleEvent[threadID], INFINITE);
2496 #endif
2497       }
2498
2499       // If this thread has been assigned work, launch a search:
2500       if(Threads[threadID].workIsWaiting) {
2501         Threads[threadID].workIsWaiting = false;
2502         if(Threads[threadID].splitPoint->pvNode)
2503           sp_search_pv(Threads[threadID].splitPoint, threadID);
2504         else
2505           sp_search(Threads[threadID].splitPoint, threadID);
2506         Threads[threadID].idle = true;
2507       }
2508
2509       // If this thread is the master of a split point and all threads have
2510       // finished their work at this split point, return from the idle loop:
2511       if(waitSp != NULL && waitSp->cpus == 0)
2512         return;
2513     }
2514
2515     Threads[threadID].running = false;
2516   }
2517
2518
2519   // init_split_point_stack() is called during program initialization, and
2520   // initializes all split point objects.
2521
2522   void init_split_point_stack() {
2523     for(int i = 0; i < THREAD_MAX; i++)
2524       for(int j = 0; j < MaxActiveSplitPoints; j++) {
2525         SplitPointStack[i][j].parent = NULL;
2526         lock_init(&(SplitPointStack[i][j].lock), NULL);
2527       }
2528   }
2529
2530
2531   // destroy_split_point_stack() is called when the program exits, and
2532   // destroys all locks in the precomputed split point objects.
2533
2534   void destroy_split_point_stack() {
2535     for(int i = 0; i < THREAD_MAX; i++)
2536       for(int j = 0; j < MaxActiveSplitPoints; j++)
2537         lock_destroy(&(SplitPointStack[i][j].lock));
2538   }
2539
2540
2541   // thread_should_stop() checks whether the thread with a given threadID has
2542   // been asked to stop, directly or indirectly.  This can happen if a beta
2543   // cutoff has occured in thre thread's currently active split point, or in
2544   // some ancestor of the current split point.
2545
2546   bool thread_should_stop(int threadID) {
2547     assert(threadID >= 0 && threadID < ActiveThreads);
2548
2549     SplitPoint *sp;
2550
2551     if(Threads[threadID].stop)
2552       return true;
2553     if(ActiveThreads <= 2)
2554       return false;
2555     for(sp = Threads[threadID].splitPoint; sp != NULL; sp = sp->parent)
2556       if(sp->finished) {
2557         Threads[threadID].stop = true;
2558         return true;
2559       }
2560     return false;
2561   }
2562
2563
2564   // thread_is_available() checks whether the thread with threadID "slave" is
2565   // available to help the thread with threadID "master" at a split point.  An
2566   // obvious requirement is that "slave" must be idle.  With more than two
2567   // threads, this is not by itself sufficient:  If "slave" is the master of
2568   // some active split point, it is only available as a slave to the other
2569   // threads which are busy searching the split point at the top of "slave"'s
2570   // split point stack (the "helpful master concept" in YBWC terminology).
2571
2572   bool thread_is_available(int slave, int master) {
2573     assert(slave >= 0 && slave < ActiveThreads);
2574     assert(master >= 0 && master < ActiveThreads);
2575     assert(ActiveThreads > 1);
2576
2577     if(!Threads[slave].idle || slave == master)
2578       return false;
2579
2580     if(Threads[slave].activeSplitPoints == 0)
2581       // No active split points means that the thread is available as a slave
2582       // for any other thread.
2583       return true;
2584
2585     if(ActiveThreads == 2)
2586       return true;
2587
2588     // Apply the "helpful master" concept if possible.
2589     if(SplitPointStack[slave][Threads[slave].activeSplitPoints-1].slaves[master])
2590       return true;
2591
2592     return false;
2593   }
2594
2595
2596   // idle_thread_exists() tries to find an idle thread which is available as
2597   // a slave for the thread with threadID "master".
2598
2599   bool idle_thread_exists(int master) {
2600     assert(master >= 0 && master < ActiveThreads);
2601     assert(ActiveThreads > 1);
2602
2603     for(int i = 0; i < ActiveThreads; i++)
2604       if(thread_is_available(i, master))
2605         return true;
2606     return false;
2607   }
2608
2609
2610   // split() does the actual work of distributing the work at a node between
2611   // several threads at PV nodes.  If it does not succeed in splitting the
2612   // node (because no idle threads are available, or because we have no unused
2613   // split point objects), the function immediately returns false.  If
2614   // splitting is possible, a SplitPoint object is initialized with all the
2615   // data that must be copied to the helper threads (the current position and
2616   // search stack, alpha, beta, the search depth, etc.), and we tell our
2617   // helper threads that they have been assigned work.  This will cause them
2618   // to instantly leave their idle loops and call sp_search_pv().  When all
2619   // threads have returned from sp_search_pv (or, equivalently, when
2620   // splitPoint->cpus becomes 0), split() returns true.
2621
2622   bool split(const Position &p, SearchStack *sstck, int ply,
2623              Value *alpha, Value *beta, Value *bestValue, Depth depth, int *moves,
2624              MovePicker *mp, Bitboard dcCandidates, int master, bool pvNode) {
2625
2626     assert(p.is_ok());
2627     assert(sstck != NULL);
2628     assert(ply >= 0 && ply < PLY_MAX);
2629     assert(*bestValue >= -VALUE_INFINITE && *bestValue <= *alpha);
2630     assert(!pvNode || *alpha < *beta);
2631     assert(*beta <= VALUE_INFINITE);
2632     assert(depth > Depth(0));
2633     assert(master >= 0 && master < ActiveThreads);
2634     assert(ActiveThreads > 1);
2635
2636     SplitPoint *splitPoint;
2637     int i;
2638
2639     lock_grab(&MPLock);
2640
2641     // If no other thread is available to help us, or if we have too many
2642     // active split points, don't split:
2643     if(!idle_thread_exists(master) ||
2644        Threads[master].activeSplitPoints >= MaxActiveSplitPoints) {
2645       lock_release(&MPLock);
2646       return false;
2647     }
2648
2649     // Pick the next available split point object from the split point stack:
2650     splitPoint = SplitPointStack[master] + Threads[master].activeSplitPoints;
2651     Threads[master].activeSplitPoints++;
2652
2653     // Initialize the split point object:
2654     splitPoint->parent = Threads[master].splitPoint;
2655     splitPoint->finished = false;
2656     splitPoint->ply = ply;
2657     splitPoint->depth = depth;
2658     splitPoint->alpha = pvNode? *alpha : (*beta - 1);
2659     splitPoint->beta = *beta;
2660     splitPoint->pvNode = pvNode;
2661     splitPoint->dcCandidates = dcCandidates;
2662     splitPoint->bestValue = *bestValue;
2663     splitPoint->master = master;
2664     splitPoint->mp = mp;
2665     splitPoint->moves = *moves;
2666     splitPoint->cpus = 1;
2667     splitPoint->pos.copy(p);
2668     splitPoint->parentSstack = sstck;
2669     for(i = 0; i < ActiveThreads; i++)
2670       splitPoint->slaves[i] = 0;
2671
2672     // Copy the current position and the search stack to the master thread:
2673     memcpy(splitPoint->sstack[master], sstck, (ply+1)*sizeof(SearchStack));
2674     Threads[master].splitPoint = splitPoint;
2675
2676     // Make copies of the current position and search stack for each thread:
2677     for(i = 0; i < ActiveThreads && splitPoint->cpus < MaxThreadsPerSplitPoint;
2678         i++)
2679       if(thread_is_available(i, master)) {
2680         memcpy(splitPoint->sstack[i], sstck, (ply+1)*sizeof(SearchStack));
2681         Threads[i].splitPoint = splitPoint;
2682         splitPoint->slaves[i] = 1;
2683         splitPoint->cpus++;
2684       }
2685
2686     // Tell the threads that they have work to do.  This will make them leave
2687     // their idle loop.
2688     for(i = 0; i < ActiveThreads; i++)
2689       if(i == master || splitPoint->slaves[i]) {
2690         Threads[i].workIsWaiting = true;
2691         Threads[i].idle = false;
2692         Threads[i].stop = false;
2693       }
2694
2695     lock_release(&MPLock);
2696
2697     // Everything is set up.  The master thread enters the idle loop, from
2698     // which it will instantly launch a search, because its workIsWaiting
2699     // slot is 'true'.  We send the split point as a second parameter to the
2700     // idle loop, which means that the main thread will return from the idle
2701     // loop when all threads have finished their work at this split point
2702     // (i.e. when // splitPoint->cpus == 0).
2703     idle_loop(master, splitPoint);
2704
2705     // We have returned from the idle loop, which means that all threads are
2706     // finished.  Update alpha, beta and bestvalue, and return:
2707     lock_grab(&MPLock);
2708     if(pvNode) *alpha = splitPoint->alpha;
2709     *beta = splitPoint->beta;
2710     *bestValue = splitPoint->bestValue;
2711     Threads[master].stop = false;
2712     Threads[master].idle = false;
2713     Threads[master].activeSplitPoints--;
2714     Threads[master].splitPoint = splitPoint->parent;
2715     lock_release(&MPLock);
2716
2717     return true;
2718   }
2719
2720
2721   // wake_sleeping_threads() wakes up all sleeping threads when it is time
2722   // to start a new search from the root.
2723
2724   void wake_sleeping_threads() {
2725     if(ActiveThreads > 1) {
2726       for(int i = 1; i < ActiveThreads; i++) {
2727         Threads[i].idle = true;
2728         Threads[i].workIsWaiting = false;
2729       }
2730 #if !defined(_MSC_VER)
2731       pthread_mutex_lock(&WaitLock);
2732       pthread_cond_broadcast(&WaitCond);
2733       pthread_mutex_unlock(&WaitLock);
2734 #else
2735       for(int i = 1; i < THREAD_MAX; i++)
2736         SetEvent(SitIdleEvent[i]);
2737 #endif
2738     }
2739   }
2740
2741
2742   // init_thread() is the function which is called when a new thread is
2743   // launched.  It simply calls the idle_loop() function with the supplied
2744   // threadID.  There are two versions of this function; one for POSIX threads
2745   // and one for Windows threads.
2746
2747 #if !defined(_MSC_VER)
2748
2749   void *init_thread(void *threadID) {
2750     idle_loop(*(int *)threadID, NULL);
2751     return NULL;
2752   }
2753
2754 #else
2755
2756   DWORD WINAPI init_thread(LPVOID threadID) {
2757     idle_loop(*(int *)threadID, NULL);
2758     return NULL;
2759   }
2760
2761 #endif
2762
2763 }