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