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