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