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