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