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