]> git.sesse.net Git - stockfish/blob - src/search.cpp
Wrap in a class Skill Level code
[stockfish] / src / search.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2012 Marco Costalba, Joona Kiiski, Tord Romstad
5
6   Stockfish is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   Stockfish is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include <algorithm>
21 #include <cassert>
22 #include <cmath>
23 #include <cstring>
24 #include <iostream>
25 #include <sstream>
26
27 #include "book.h"
28 #include "evaluate.h"
29 #include "history.h"
30 #include "movegen.h"
31 #include "movepick.h"
32 #include "notation.h"
33 #include "search.h"
34 #include "timeman.h"
35 #include "thread.h"
36 #include "tt.h"
37 #include "ucioption.h"
38
39 namespace Search {
40
41   volatile SignalsType Signals;
42   LimitsType Limits;
43   std::vector<RootMove> RootMoves;
44   Position RootPosition;
45   Color RootColor;
46   Time::point SearchTime;
47   StateStackPtr SetupStates;
48 }
49
50 using std::string;
51 using Eval::evaluate;
52 using namespace Search;
53
54 namespace {
55
56   // Set to true to force running with one thread. Used for debugging
57   const bool FakeSplit = false;
58
59   // This is the minimum interval in msec between two check_time() calls
60   const int TimerResolution = 5;
61
62   // Different node types, used as template parameter
63   enum NodeType { Root, PV, NonPV, SplitPointRoot, SplitPointPV, SplitPointNonPV };
64
65   // Lookup table to check if a Piece is a slider and its access function
66   const bool Slidings[18] = { 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1 };
67   inline bool piece_is_slider(Piece p) { return Slidings[p]; }
68
69   // Dynamic razoring margin based on depth
70   inline Value razor_margin(Depth d) { return Value(512 + 16 * int(d)); }
71
72   // Futility lookup tables (initialized at startup) and their access functions
73   Value FutilityMargins[16][64]; // [depth][moveNumber]
74   int FutilityMoveCounts[32];    // [depth]
75
76   inline Value futility_margin(Depth d, int mn) {
77
78     return d < 7 * ONE_PLY ? FutilityMargins[std::max(int(d), 1)][std::min(mn, 63)]
79                            : 2 * VALUE_INFINITE;
80   }
81
82   // Reduction lookup tables (initialized at startup) and their access function
83   int8_t Reductions[2][64][64]; // [pv][depth][moveNumber]
84
85   template <bool PvNode> inline Depth reduction(Depth d, int mn) {
86
87     return (Depth) Reductions[PvNode][std::min(int(d) / ONE_PLY, 63)][std::min(mn, 63)];
88   }
89
90   size_t MultiPV, UCIMultiPV, PVIdx;
91   TimeManager TimeMgr;
92   int BestMoveChanges;
93   bool Chess960;
94   Value DrawValue[COLOR_NB];
95   History H;
96
97   template <NodeType NT>
98   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
99
100   template <NodeType NT>
101   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth);
102
103   void id_loop(Position& pos);
104   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta);
105   bool connected_moves(const Position& pos, Move m1, Move m2);
106   Value value_to_tt(Value v, int ply);
107   Value value_from_tt(Value v, int ply);
108   bool connected_threat(const Position& pos, Move m, Move threat);
109   string uci_pv(const Position& pos, int depth, Value alpha, Value beta);
110
111   struct Skill {
112     Skill(int l) : level(l), best(MOVE_NONE) {}
113    ~Skill() {
114       if (enabled()) // Swap best PV line with the sub-optimal one
115           std::swap(RootMoves[0], *std::find(RootMoves.begin(),
116                     RootMoves.end(), best ? best : pick_move()));
117     }
118
119     bool enabled() const { return level < 20; }
120     bool time_to_pick(int depth) const { return depth == 1 + level; }
121     Move pick_move();
122
123     int level;
124     Move best;
125   };
126
127 } // namespace
128
129
130 /// Search::init() is called during startup to initialize various lookup tables
131
132 void Search::init() {
133
134   int d;  // depth (ONE_PLY == 2)
135   int hd; // half depth (ONE_PLY == 1)
136   int mc; // moveCount
137
138   // Init reductions array
139   for (hd = 1; hd < 64; hd++) for (mc = 1; mc < 64; mc++)
140   {
141       double    pvRed = log(double(hd)) * log(double(mc)) / 3.0;
142       double nonPVRed = 0.33 + log(double(hd)) * log(double(mc)) / 2.25;
143       Reductions[1][hd][mc] = (int8_t) (   pvRed >= 1.0 ? floor(   pvRed * int(ONE_PLY)) : 0);
144       Reductions[0][hd][mc] = (int8_t) (nonPVRed >= 1.0 ? floor(nonPVRed * int(ONE_PLY)) : 0);
145   }
146
147   // Init futility margins array
148   for (d = 1; d < 16; d++) for (mc = 0; mc < 64; mc++)
149       FutilityMargins[d][mc] = Value(112 * int(log(double(d * d) / 2) / log(2.0) + 1.001) - 8 * mc + 45);
150
151   // Init futility move count array
152   for (d = 0; d < 32; d++)
153       FutilityMoveCounts[d] = int(3.001 + 0.25 * pow(double(d), 2.0));
154 }
155
156
157 /// Search::perft() is our utility to verify move generation. All the leaf nodes
158 /// up to the given depth are generated and counted and the sum returned.
159
160 size_t Search::perft(Position& pos, Depth depth) {
161
162   // At the last ply just return the number of legal moves (leaf nodes)
163   if (depth == ONE_PLY)
164       return MoveList<LEGAL>(pos).size();
165
166   StateInfo st;
167   size_t cnt = 0;
168   CheckInfo ci(pos);
169
170   for (MoveList<LEGAL> ml(pos); !ml.end(); ++ml)
171   {
172       pos.do_move(ml.move(), st, ci, pos.move_gives_check(ml.move(), ci));
173       cnt += perft(pos, depth - ONE_PLY);
174       pos.undo_move(ml.move());
175   }
176
177   return cnt;
178 }
179
180
181 /// Search::think() is the external interface to Stockfish's search, and is
182 /// called by the main thread when the program receives the UCI 'go' command. It
183 /// searches from RootPosition and at the end prints the "bestmove" to output.
184
185 void Search::think() {
186
187   static PolyglotBook book; // Defined static to initialize the PRNG only once
188
189   Position& pos = RootPosition;
190   Chess960 = pos.is_chess960();
191   RootColor = pos.side_to_move();
192   TimeMgr.init(Limits, pos.startpos_ply_counter(), pos.side_to_move());
193   TT.new_search();
194   H.clear();
195
196   if (RootMoves.empty())
197   {
198       sync_cout << "info depth 0 score "
199                 << score_to_uci(pos.in_check() ? -VALUE_MATE : VALUE_DRAW) << sync_endl;
200
201       RootMoves.push_back(MOVE_NONE);
202       goto finalize;
203   }
204
205   if (Options["Contempt Factor"] && !Options["UCI_AnalyseMode"])
206   {
207       int cf = Options["Contempt Factor"] * PawnValueMg / 100;  // In centipawns
208       cf = cf * MaterialTable::game_phase(pos) / PHASE_MIDGAME; // Scale down with phase
209       DrawValue[ RootColor] = VALUE_DRAW - Value(cf);
210       DrawValue[~RootColor] = VALUE_DRAW + Value(cf);
211   }
212   else
213       DrawValue[WHITE] = DrawValue[BLACK] = VALUE_DRAW;
214
215   if (Options["OwnBook"] && !Limits.infinite)
216   {
217       Move bookMove = book.probe(pos, Options["Book File"], Options["Best Book Move"]);
218
219       if (bookMove && std::count(RootMoves.begin(), RootMoves.end(), bookMove))
220       {
221           std::swap(RootMoves[0], *std::find(RootMoves.begin(), RootMoves.end(), bookMove));
222           goto finalize;
223       }
224   }
225
226   if (Options["Use Search Log"])
227   {
228       Log log(Options["Search Log Filename"]);
229       log << "\nSearching: "  << pos.to_fen()
230           << "\ninfinite: "   << Limits.infinite
231           << " ponder: "      << Limits.ponder
232           << " time: "        << Limits.time[pos.side_to_move()]
233           << " increment: "   << Limits.inc[pos.side_to_move()]
234           << " moves to go: " << Limits.movestogo
235           << std::endl;
236   }
237
238   Threads.wake_up();
239
240   // Set best timer interval to avoid lagging under time pressure. Timer is
241   // used to check for remaining available thinking time.
242   if (Limits.use_time_management())
243       Threads.set_timer(std::min(100, std::max(TimeMgr.available_time() / 16, TimerResolution)));
244   else if (Limits.nodes)
245       Threads.set_timer(2 * TimerResolution);
246   else
247       Threads.set_timer(100);
248
249   // We're ready to start searching. Call the iterative deepening loop function
250   id_loop(pos);
251
252   Threads.set_timer(0); // Stop timer
253   Threads.sleep();
254
255   if (Options["Use Search Log"])
256   {
257       Time::point elapsed = Time::now() - SearchTime + 1;
258
259       Log log(Options["Search Log Filename"]);
260       log << "Nodes: "          << pos.nodes_searched()
261           << "\nNodes/second: " << pos.nodes_searched() * 1000 / elapsed
262           << "\nBest move: "    << move_to_san(pos, RootMoves[0].pv[0]);
263
264       StateInfo st;
265       pos.do_move(RootMoves[0].pv[0], st);
266       log << "\nPonder move: " << move_to_san(pos, RootMoves[0].pv[1]) << std::endl;
267       pos.undo_move(RootMoves[0].pv[0]);
268   }
269
270 finalize:
271
272   // When we reach max depth we arrive here even without Signals.stop is raised,
273   // but if we are pondering or in infinite search, we shouldn't print the best
274   // move before we are told to do so.
275   if (!Signals.stop && (Limits.ponder || Limits.infinite))
276       pos.this_thread()->wait_for_stop_or_ponderhit();
277
278   // Best move could be MOVE_NONE when searching on a stalemate position
279   sync_cout << "bestmove " << move_to_uci(RootMoves[0].pv[0], Chess960)
280             << " ponder "  << move_to_uci(RootMoves[0].pv[1], Chess960) << sync_endl;
281 }
282
283
284 namespace {
285
286   // id_loop() is the main iterative deepening loop. It calls search() repeatedly
287   // with increasing depth until the allocated thinking time has been consumed,
288   // user stops the search, or the maximum search depth is reached.
289
290   void id_loop(Position& pos) {
291
292     Stack ss[MAX_PLY_PLUS_2];
293     int depth, prevBestMoveChanges;
294     Value bestValue, alpha, beta, delta;
295     bool bestMoveNeverChanged = true;
296
297     memset(ss, 0, 4 * sizeof(Stack));
298     depth = BestMoveChanges = 0;
299     bestValue = delta = -VALUE_INFINITE;
300     ss->currentMove = MOVE_NULL; // Hack to skip update gains
301
302     UCIMultiPV = Options["MultiPV"];
303     Skill skill(Options["Skill Level"]);
304
305     // Do we have to play with skill handicap? In this case enable MultiPV that
306     // we will use behind the scenes to retrieve a set of possible moves.
307     MultiPV = skill.enabled() ? std::max(UCIMultiPV, (size_t)4) : UCIMultiPV;
308
309     // Iterative deepening loop until requested to stop or target depth reached
310     while (++depth <= MAX_PLY && !Signals.stop && (!Limits.depth || depth <= Limits.depth))
311     {
312         // Save last iteration's scores before first PV line is searched and all
313         // the move scores but the (new) PV are set to -VALUE_INFINITE.
314         for (size_t i = 0; i < RootMoves.size(); i++)
315             RootMoves[i].prevScore = RootMoves[i].score;
316
317         prevBestMoveChanges = BestMoveChanges;
318         BestMoveChanges = 0;
319
320         // MultiPV loop. We perform a full root search for each PV line
321         for (PVIdx = 0; PVIdx < std::min(MultiPV, RootMoves.size()); PVIdx++)
322         {
323             // Set aspiration window default width
324             if (depth >= 5 && abs(RootMoves[PVIdx].prevScore) < VALUE_KNOWN_WIN)
325             {
326                 delta = Value(16);
327                 alpha = RootMoves[PVIdx].prevScore - delta;
328                 beta  = RootMoves[PVIdx].prevScore + delta;
329             }
330             else
331             {
332                 alpha = -VALUE_INFINITE;
333                 beta  =  VALUE_INFINITE;
334             }
335
336             // Start with a small aspiration window and, in case of fail high/low,
337             // research with bigger window until not failing high/low anymore.
338             while (true)
339             {
340                 // Search starts from ss+1 to allow referencing (ss-1). This is
341                 // needed by update gains and ss copy when splitting at Root.
342                 bestValue = search<Root>(pos, ss+1, alpha, beta, depth * ONE_PLY);
343
344                 // Bring to front the best move. It is critical that sorting is
345                 // done with a stable algorithm because all the values but the first
346                 // and eventually the new best one are set to -VALUE_INFINITE and
347                 // we want to keep the same order for all the moves but the new
348                 // PV that goes to the front. Note that in case of MultiPV search
349                 // the already searched PV lines are preserved.
350                 sort<RootMove>(RootMoves.begin() + PVIdx, RootMoves.end());
351
352                 // Write PV back to transposition table in case the relevant
353                 // entries have been overwritten during the search.
354                 for (size_t i = 0; i <= PVIdx; i++)
355                     RootMoves[i].insert_pv_in_tt(pos);
356
357                 // If search has been stopped return immediately. Sorting and
358                 // writing PV back to TT is safe becuase RootMoves is still
359                 // valid, although refers to previous iteration.
360                 if (Signals.stop)
361                     return;
362
363                 // In case of failing high/low increase aspiration window and
364                 // research, otherwise exit the loop.
365                 if (bestValue > alpha && bestValue < beta)
366                     break;
367
368                 // Give some update (without cluttering the UI) before to research
369                 if (Time::now() - SearchTime > 3000)
370                     sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
371
372                 if (abs(bestValue) >= VALUE_KNOWN_WIN)
373                 {
374                     alpha = -VALUE_INFINITE;
375                     beta  =  VALUE_INFINITE;
376                 }
377                 else if (bestValue >= beta)
378                 {
379                     beta += delta;
380                     delta += delta / 2;
381                 }
382                 else
383                 {
384                     Signals.failedLowAtRoot = true;
385                     Signals.stopOnPonderhit = false;
386
387                     alpha -= delta;
388                     delta += delta / 2;
389                 }
390
391                 assert(alpha >= -VALUE_INFINITE && beta <= VALUE_INFINITE);
392             }
393
394             // Sort the PV lines searched so far and update the GUI
395             sort<RootMove>(RootMoves.begin(), RootMoves.begin() + PVIdx);
396             sync_cout << uci_pv(pos, depth, alpha, beta) << sync_endl;
397         }
398
399         // Do we need to pick now the sub-optimal best move ?
400         if (skill.enabled() && skill.time_to_pick(depth))
401             skill.pick_move();
402
403         if (Options["Use Search Log"])
404         {
405             Log log(Options["Search Log Filename"]);
406             log << pretty_pv(pos, depth, bestValue, Time::now() - SearchTime, &RootMoves[0].pv[0])
407                 << std::endl;
408         }
409
410         // Filter out startup noise when monitoring best move stability
411         if (depth > 2 && BestMoveChanges)
412             bestMoveNeverChanged = false;
413
414         // Do we have time for the next iteration? Can we stop searching now?
415         if (Limits.use_time_management() && !Signals.stopOnPonderhit)
416         {
417             bool stop = false; // Local variable, not the volatile Signals.stop
418
419             // Take in account some extra time if the best move has changed
420             if (depth > 4 && depth < 50)
421                 TimeMgr.pv_instability(BestMoveChanges, prevBestMoveChanges);
422
423             // Stop search if most of available time is already consumed. We
424             // probably don't have enough time to search the first move at the
425             // next iteration anyway.
426             if (Time::now() - SearchTime > (TimeMgr.available_time() * 62) / 100)
427                 stop = true;
428
429             // Stop search early if one move seems to be much better than others
430             if (    depth >= 12
431                 && !stop
432                 && (   (bestMoveNeverChanged &&  pos.captured_piece_type())
433                     || Time::now() - SearchTime > (TimeMgr.available_time() * 40) / 100))
434             {
435                 Value rBeta = bestValue - 2 * PawnValueMg;
436                 (ss+1)->excludedMove = RootMoves[0].pv[0];
437                 (ss+1)->skipNullMove = true;
438                 Value v = search<NonPV>(pos, ss+1, rBeta - 1, rBeta, (depth - 3) * ONE_PLY);
439                 (ss+1)->skipNullMove = false;
440                 (ss+1)->excludedMove = MOVE_NONE;
441
442                 if (v < rBeta)
443                     stop = true;
444             }
445
446             if (stop)
447             {
448                 // If we are allowed to ponder do not stop the search now but
449                 // keep pondering until GUI sends "ponderhit" or "stop".
450                 if (Limits.ponder)
451                     Signals.stopOnPonderhit = true;
452                 else
453                     Signals.stop = true;
454             }
455         }
456     }
457   }
458
459
460   // search<>() is the main search function for both PV and non-PV nodes and for
461   // normal and SplitPoint nodes. When called just after a split point the search
462   // is simpler because we have already probed the hash table, done a null move
463   // search, and searched the first move before splitting, we don't have to repeat
464   // all this work again. We also don't need to store anything to the hash table
465   // here: This is taken care of after we return from the split point.
466
467   template <NodeType NT>
468   Value search(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
469
470     const bool PvNode   = (NT == PV || NT == Root || NT == SplitPointPV || NT == SplitPointRoot);
471     const bool SpNode   = (NT == SplitPointPV || NT == SplitPointNonPV || NT == SplitPointRoot);
472     const bool RootNode = (NT == Root || NT == SplitPointRoot);
473
474     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
475     assert(PvNode || (alpha == beta - 1));
476     assert(depth > DEPTH_ZERO);
477
478     Move movesSearched[64];
479     StateInfo st;
480     const TTEntry *tte;
481     SplitPoint* sp;
482     Key posKey;
483     Move ttMove, move, excludedMove, bestMove, threatMove;
484     Depth ext, newDepth;
485     Value bestValue, value, ttValue;
486     Value eval, nullValue, futilityValue;
487     bool inCheck, givesCheck, pvMove, singularExtensionNode;
488     bool captureOrPromotion, dangerous, doFullDepthSearch;
489     int moveCount, playedMoveCount;
490
491     // Step 1. Initialize node
492     Thread* thisThread = pos.this_thread();
493     moveCount = playedMoveCount = 0;
494     inCheck = pos.in_check();
495
496     if (SpNode)
497     {
498         sp = ss->sp;
499         bestMove   = sp->bestMove;
500         threatMove = sp->threatMove;
501         bestValue  = sp->bestValue;
502         tte = NULL;
503         ttMove = excludedMove = MOVE_NONE;
504         ttValue = VALUE_NONE;
505
506         assert(sp->bestValue > -VALUE_INFINITE && sp->moveCount > 0);
507
508         goto split_point_start;
509     }
510
511     bestValue = -VALUE_INFINITE;
512     ss->currentMove = threatMove = (ss+1)->excludedMove = bestMove = MOVE_NONE;
513     ss->ply = (ss-1)->ply + 1;
514     (ss+1)->skipNullMove = false; (ss+1)->reduction = DEPTH_ZERO;
515     (ss+2)->killers[0] = (ss+2)->killers[1] = MOVE_NONE;
516
517     // Used to send selDepth info to GUI
518     if (PvNode && thisThread->maxPly < ss->ply)
519         thisThread->maxPly = ss->ply;
520
521     if (!RootNode)
522     {
523         // Step 2. Check for aborted search and immediate draw
524         if (Signals.stop || pos.is_draw<false>() || ss->ply > MAX_PLY)
525             return DrawValue[pos.side_to_move()];
526
527         // Step 3. Mate distance pruning. Even if we mate at the next move our score
528         // would be at best mate_in(ss->ply+1), but if alpha is already bigger because
529         // a shorter mate was found upward in the tree then there is no need to search
530         // further, we will never beat current alpha. Same logic but with reversed signs
531         // applies also in the opposite condition of being mated instead of giving mate,
532         // in this case return a fail-high score.
533         alpha = std::max(mated_in(ss->ply), alpha);
534         beta = std::min(mate_in(ss->ply+1), beta);
535         if (alpha >= beta)
536             return alpha;
537     }
538
539     // Step 4. Transposition table lookup
540     // We don't want the score of a partial search to overwrite a previous full search
541     // TT value, so we use a different position key in case of an excluded move.
542     excludedMove = ss->excludedMove;
543     posKey = excludedMove ? pos.exclusion_key() : pos.key();
544     tte = TT.probe(posKey);
545     ttMove = RootNode ? RootMoves[PVIdx].pv[0] : tte ? tte->move() : MOVE_NONE;
546     ttValue = tte ? value_from_tt(tte->value(), ss->ply) : VALUE_NONE;
547
548     // At PV nodes we check for exact scores, while at non-PV nodes we check for
549     // a fail high/low. Biggest advantage at probing at PV nodes is to have a
550     // smooth experience in analysis mode. We don't probe at Root nodes otherwise
551     // we should also update RootMoveList to avoid bogus output.
552     if (   !RootNode
553         && tte && tte->depth() >= depth
554         && (           PvNode ?  tte->type() == BOUND_EXACT
555             : ttValue >= beta ? (tte->type() & BOUND_LOWER)
556                               : (tte->type() & BOUND_UPPER)))
557     {
558         assert(ttValue != VALUE_NONE); // Due to depth > DEPTH_NONE
559
560         TT.refresh(tte);
561         ss->currentMove = ttMove; // Can be MOVE_NONE
562
563         if (    ttValue >= beta
564             &&  ttMove
565             && !pos.is_capture_or_promotion(ttMove)
566             &&  ttMove != ss->killers[0])
567         {
568             ss->killers[1] = ss->killers[0];
569             ss->killers[0] = ttMove;
570         }
571         return ttValue;
572     }
573
574     // Step 5. Evaluate the position statically and update parent's gain statistics
575     if (inCheck)
576         ss->staticEval = ss->evalMargin = eval = VALUE_NONE;
577
578     else if (tte)
579     {
580         assert(tte->static_value() != VALUE_NONE);
581         assert(ttValue != VALUE_NONE || tte->type() == BOUND_NONE);
582
583         ss->staticEval = eval = tte->static_value();
584         ss->evalMargin = tte->static_value_margin();
585
586         // Can ttValue be used as a better position evaluation?
587         if (   ((tte->type() & BOUND_LOWER) && ttValue > eval)
588             || ((tte->type() & BOUND_UPPER) && ttValue < eval))
589             eval = ttValue;
590     }
591     else
592     {
593         eval = ss->staticEval = evaluate(pos, ss->evalMargin);
594         TT.store(posKey, VALUE_NONE, BOUND_NONE, DEPTH_NONE, MOVE_NONE,
595                  ss->staticEval, ss->evalMargin);
596     }
597
598     // Update gain for the parent non-capture move given the static position
599     // evaluation before and after the move.
600     if (   (move = (ss-1)->currentMove) != MOVE_NULL
601         && (ss-1)->staticEval != VALUE_NONE
602         &&  ss->staticEval != VALUE_NONE
603         && !pos.captured_piece_type()
604         &&  type_of(move) == NORMAL)
605     {
606         Square to = to_sq(move);
607         H.update_gain(pos.piece_on(to), to, -(ss-1)->staticEval - ss->staticEval);
608     }
609
610     // Step 6. Razoring (is omitted in PV nodes)
611     if (   !PvNode
612         &&  depth < 4 * ONE_PLY
613         && !inCheck
614         &&  eval + razor_margin(depth) < beta
615         &&  ttMove == MOVE_NONE
616         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
617         && !pos.pawn_on_7th(pos.side_to_move()))
618     {
619         Value rbeta = beta - razor_margin(depth);
620         Value v = qsearch<NonPV>(pos, ss, rbeta-1, rbeta, DEPTH_ZERO);
621         if (v < rbeta)
622             // Logically we should return (v + razor_margin(depth)), but
623             // surprisingly this did slightly weaker in tests.
624             return v;
625     }
626
627     // Step 7. Static null move pruning (is omitted in PV nodes)
628     // We're betting that the opponent doesn't have a move that will reduce
629     // the score by more than futility_margin(depth) if we do a null move.
630     if (   !PvNode
631         && !ss->skipNullMove
632         &&  depth < 4 * ONE_PLY
633         && !inCheck
634         &&  eval - FutilityMargins[depth][0] >= beta
635         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
636         &&  pos.non_pawn_material(pos.side_to_move()))
637         return eval - FutilityMargins[depth][0];
638
639     // Step 8. Null move search with verification search (is omitted in PV nodes)
640     if (   !PvNode
641         && !ss->skipNullMove
642         &&  depth > ONE_PLY
643         && !inCheck
644         &&  eval >= beta
645         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY
646         &&  pos.non_pawn_material(pos.side_to_move()))
647     {
648         ss->currentMove = MOVE_NULL;
649
650         // Null move dynamic reduction based on depth
651         Depth R = 3 * ONE_PLY + depth / 4;
652
653         // Null move dynamic reduction based on value
654         if (eval - PawnValueMg > beta)
655             R += ONE_PLY;
656
657         pos.do_null_move<true>(st);
658         (ss+1)->skipNullMove = true;
659         nullValue = depth-R < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
660                                       : - search<NonPV>(pos, ss+1, -beta, -alpha, depth-R);
661         (ss+1)->skipNullMove = false;
662         pos.do_null_move<false>(st);
663
664         if (nullValue >= beta)
665         {
666             // Do not return unproven mate scores
667             if (nullValue >= VALUE_MATE_IN_MAX_PLY)
668                 nullValue = beta;
669
670             if (depth < 6 * ONE_PLY)
671                 return nullValue;
672
673             // Do verification search at high depths
674             ss->skipNullMove = true;
675             Value v = search<NonPV>(pos, ss, alpha, beta, depth-R);
676             ss->skipNullMove = false;
677
678             if (v >= beta)
679                 return nullValue;
680         }
681         else
682         {
683             // The null move failed low, which means that we may be faced with
684             // some kind of threat. If the previous move was reduced, check if
685             // the move that refuted the null move was somehow connected to the
686             // move which was reduced. If a connection is found, return a fail
687             // low score (which will cause the reduced move to fail high in the
688             // parent node, which will trigger a re-search with full depth).
689             threatMove = (ss+1)->currentMove;
690
691             if (   depth < 5 * ONE_PLY
692                 && (ss-1)->reduction
693                 && threatMove != MOVE_NONE
694                 && connected_moves(pos, (ss-1)->currentMove, threatMove))
695                 return beta - 1;
696         }
697     }
698
699     // Step 9. ProbCut (is omitted in PV nodes)
700     // If we have a very good capture (i.e. SEE > seeValues[captured_piece_type])
701     // and a reduced search returns a value much above beta, we can (almost) safely
702     // prune the previous move.
703     if (   !PvNode
704         &&  depth >= 5 * ONE_PLY
705         && !inCheck
706         && !ss->skipNullMove
707         &&  excludedMove == MOVE_NONE
708         &&  abs(beta) < VALUE_MATE_IN_MAX_PLY)
709     {
710         Value rbeta = beta + 200;
711         Depth rdepth = depth - ONE_PLY - 3 * ONE_PLY;
712
713         assert(rdepth >= ONE_PLY);
714         assert((ss-1)->currentMove != MOVE_NONE);
715         assert((ss-1)->currentMove != MOVE_NULL);
716
717         MovePicker mp(pos, ttMove, H, pos.captured_piece_type());
718         CheckInfo ci(pos);
719
720         while ((move = mp.next_move<false>()) != MOVE_NONE)
721             if (pos.pl_move_is_legal(move, ci.pinned))
722             {
723                 ss->currentMove = move;
724                 pos.do_move(move, st, ci, pos.move_gives_check(move, ci));
725                 value = -search<NonPV>(pos, ss+1, -rbeta, -rbeta+1, rdepth);
726                 pos.undo_move(move);
727                 if (value >= rbeta)
728                     return value;
729             }
730     }
731
732     // Step 10. Internal iterative deepening
733     if (   depth >= (PvNode ? 5 * ONE_PLY : 8 * ONE_PLY)
734         && ttMove == MOVE_NONE
735         && (PvNode || (!inCheck && ss->staticEval + Value(256) >= beta)))
736     {
737         Depth d = (PvNode ? depth - 2 * ONE_PLY : depth / 2);
738
739         ss->skipNullMove = true;
740         search<PvNode ? PV : NonPV>(pos, ss, alpha, beta, d);
741         ss->skipNullMove = false;
742
743         tte = TT.probe(posKey);
744         ttMove = tte ? tte->move() : MOVE_NONE;
745     }
746
747 split_point_start: // At split points actual search starts from here
748
749     MovePicker mp(pos, ttMove, depth, H, ss, PvNode ? -VALUE_INFINITE : beta);
750     CheckInfo ci(pos);
751     value = bestValue; // Workaround a bogus 'uninitialized' warning under gcc
752     singularExtensionNode =   !RootNode
753                            && !SpNode
754                            &&  depth >= (PvNode ? 6 * ONE_PLY : 8 * ONE_PLY)
755                            &&  ttMove != MOVE_NONE
756                            && !excludedMove // Recursive singular search is not allowed
757                            && (tte->type() & BOUND_LOWER)
758                            &&  tte->depth() >= depth - 3 * ONE_PLY;
759
760     // Step 11. Loop through moves
761     // Loop through all pseudo-legal moves until no moves remain or a beta cutoff occurs
762     while ((move = mp.next_move<SpNode>()) != MOVE_NONE)
763     {
764       assert(is_ok(move));
765
766       if (move == excludedMove)
767           continue;
768
769       // At root obey the "searchmoves" option and skip moves not listed in Root
770       // Move List, as a consequence any illegal move is also skipped. In MultiPV
771       // mode we also skip PV moves which have been already searched.
772       if (RootNode && !std::count(RootMoves.begin() + PVIdx, RootMoves.end(), move))
773           continue;
774
775       if (SpNode)
776       {
777           // Shared counter cannot be decremented later if move turns out to be illegal
778           if (!pos.pl_move_is_legal(move, ci.pinned))
779               continue;
780
781           moveCount = ++sp->moveCount;
782           sp->mutex.unlock();
783       }
784       else
785           moveCount++;
786
787       if (RootNode)
788       {
789           Signals.firstRootMove = (moveCount == 1);
790
791           if (thisThread == Threads.main_thread() && Time::now() - SearchTime > 2000)
792               sync_cout << "info depth " << depth / ONE_PLY
793                         << " currmove " << move_to_uci(move, Chess960)
794                         << " currmovenumber " << moveCount + PVIdx << sync_endl;
795       }
796
797       ext = DEPTH_ZERO;
798       captureOrPromotion = pos.is_capture_or_promotion(move);
799       givesCheck = pos.move_gives_check(move, ci);
800       dangerous =   givesCheck
801                  || pos.is_passed_pawn_push(move)
802                  || type_of(move) == CASTLE
803                  || (   captureOrPromotion // Entering a pawn endgame?
804                      && type_of(pos.piece_on(to_sq(move))) != PAWN
805                      && type_of(move) == NORMAL
806                      && (  pos.non_pawn_material(WHITE) + pos.non_pawn_material(BLACK)
807                          - PieceValue[MG][pos.piece_on(to_sq(move))] == VALUE_ZERO));
808
809       // Step 12. Extend checks and, in PV nodes, also dangerous moves
810       if (PvNode && dangerous)
811           ext = ONE_PLY;
812
813       else if (givesCheck && pos.see_sign(move) >= 0)
814           ext = ONE_PLY / 2;
815
816       // Singular extension search. If all moves but one fail low on a search of
817       // (alpha-s, beta-s), and just one fails high on (alpha, beta), then that move
818       // is singular and should be extended. To verify this we do a reduced search
819       // on all the other moves but the ttMove, if result is lower than ttValue minus
820       // a margin then we extend ttMove.
821       if (    singularExtensionNode
822           &&  move == ttMove
823           && !ext
824           &&  pos.pl_move_is_legal(move, ci.pinned)
825           &&  abs(ttValue) < VALUE_KNOWN_WIN)
826       {
827           assert(ttValue != VALUE_NONE);
828
829           Value rBeta = ttValue - int(depth);
830           ss->excludedMove = move;
831           ss->skipNullMove = true;
832           value = search<NonPV>(pos, ss, rBeta - 1, rBeta, depth / 2);
833           ss->skipNullMove = false;
834           ss->excludedMove = MOVE_NONE;
835
836           if (value < rBeta)
837               ext = rBeta >= beta ? ONE_PLY + ONE_PLY / 2 : ONE_PLY;
838       }
839
840       // Update current move (this must be done after singular extension search)
841       newDepth = depth - ONE_PLY + ext;
842
843       // Step 13. Futility pruning (is omitted in PV nodes)
844       if (   !PvNode
845           && !captureOrPromotion
846           && !inCheck
847           && !dangerous
848           &&  move != ttMove
849           && (bestValue > VALUE_MATED_IN_MAX_PLY || (   bestValue == -VALUE_INFINITE
850                                                      && alpha > VALUE_MATED_IN_MAX_PLY)))
851       {
852           // Move count based pruning
853           if (   depth < 16 * ONE_PLY
854               && moveCount >= FutilityMoveCounts[depth]
855               && (!threatMove || !connected_threat(pos, move, threatMove)))
856           {
857               if (SpNode)
858                   sp->mutex.lock();
859
860               continue;
861           }
862
863           // Value based pruning
864           // We illogically ignore reduction condition depth >= 3*ONE_PLY for predicted depth,
865           // but fixing this made program slightly weaker.
866           Depth predictedDepth = newDepth - reduction<PvNode>(depth, moveCount);
867           futilityValue =  ss->staticEval + ss->evalMargin + futility_margin(predictedDepth, moveCount)
868                          + H.gain(pos.piece_moved(move), to_sq(move));
869
870           if (futilityValue < beta)
871           {
872               if (SpNode)
873                   sp->mutex.lock();
874
875               continue;
876           }
877
878           // Prune moves with negative SEE at low depths
879           if (   predictedDepth < 2 * ONE_PLY
880               && pos.see_sign(move) < 0)
881           {
882               if (SpNode)
883                   sp->mutex.lock();
884
885               continue;
886           }
887       }
888
889       // Check for legality only before to do the move
890       if (!pos.pl_move_is_legal(move, ci.pinned))
891       {
892           moveCount--;
893           continue;
894       }
895
896       pvMove = PvNode ? moveCount == 1 : false;
897       ss->currentMove = move;
898       if (!SpNode && !captureOrPromotion && playedMoveCount < 64)
899           movesSearched[playedMoveCount++] = move;
900
901       // Step 14. Make the move
902       pos.do_move(move, st, ci, givesCheck);
903
904       // Step 15. Reduced depth search (LMR). If the move fails high will be
905       // re-searched at full depth.
906       if (    depth > 3 * ONE_PLY
907           && !pvMove
908           && !captureOrPromotion
909           && !dangerous
910           &&  ss->killers[0] != move
911           &&  ss->killers[1] != move)
912       {
913           ss->reduction = reduction<PvNode>(depth, moveCount);
914           Depth d = std::max(newDepth - ss->reduction, ONE_PLY);
915           alpha = SpNode ? sp->alpha : alpha;
916
917           value = -search<NonPV>(pos, ss+1, -(alpha+1), -alpha, d);
918
919           doFullDepthSearch = (value > alpha && ss->reduction != DEPTH_ZERO);
920           ss->reduction = DEPTH_ZERO;
921       }
922       else
923           doFullDepthSearch = !pvMove;
924
925       // Step 16. Full depth search, when LMR is skipped or fails high
926       if (doFullDepthSearch)
927       {
928           alpha = SpNode ? sp->alpha : alpha;
929           value = newDepth < ONE_PLY ? -qsearch<NonPV>(pos, ss+1, -(alpha+1), -alpha, DEPTH_ZERO)
930                                      : - search<NonPV>(pos, ss+1, -(alpha+1), -alpha, newDepth);
931       }
932
933       // Only for PV nodes do a full PV search on the first move or after a fail
934       // high, in the latter case search only if value < beta, otherwise let the
935       // parent node to fail low with value <= alpha and to try another move.
936       if (PvNode && (pvMove || (value > alpha && (RootNode || value < beta))))
937           value = newDepth < ONE_PLY ? -qsearch<PV>(pos, ss+1, -beta, -alpha, DEPTH_ZERO)
938                                      : - search<PV>(pos, ss+1, -beta, -alpha, newDepth);
939
940       // Step 17. Undo move
941       pos.undo_move(move);
942
943       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
944
945       // Step 18. Check for new best move
946       if (SpNode)
947       {
948           sp->mutex.lock();
949           bestValue = sp->bestValue;
950           alpha = sp->alpha;
951       }
952
953       // Finished searching the move. If Signals.stop is true, the search
954       // was aborted because the user interrupted the search or because we
955       // ran out of time. In this case, the return value of the search cannot
956       // be trusted, and we don't update the best move and/or PV.
957       if (Signals.stop || thisThread->cutoff_occurred())
958           return bestValue;
959
960       if (RootNode)
961       {
962           RootMove& rm = *std::find(RootMoves.begin(), RootMoves.end(), move);
963
964           // PV move or new best move ?
965           if (pvMove || value > alpha)
966           {
967               rm.score = value;
968               rm.extract_pv_from_tt(pos);
969
970               // We record how often the best move has been changed in each
971               // iteration. This information is used for time management: When
972               // the best move changes frequently, we allocate some more time.
973               if (!pvMove && MultiPV == 1)
974                   BestMoveChanges++;
975           }
976           else
977               // All other moves but the PV are set to the lowest value, this
978               // is not a problem when sorting becuase sort is stable and move
979               // position in the list is preserved, just the PV is pushed up.
980               rm.score = -VALUE_INFINITE;
981       }
982
983       if (value > bestValue)
984       {
985           bestValue = value;
986           if (SpNode) sp->bestValue = value;
987
988           if (value > alpha)
989           {
990               bestMove = move;
991               if (SpNode) sp->bestMove = move;
992
993               if (PvNode && value < beta)
994               {
995                   alpha = value; // Update alpha here! Always alpha < beta
996                   if (SpNode) sp->alpha = value;
997               }
998               else // Fail high
999               {
1000                   if (SpNode) sp->cutoff = true;
1001                   break;
1002               }
1003           }
1004       }
1005
1006       // Step 19. Check for splitting the search
1007       if (   !SpNode
1008           &&  depth >= Threads.min_split_depth()
1009           &&  bestValue < beta
1010           &&  Threads.available_slave_exists(thisThread))
1011       {
1012           bestValue = Threads.split<FakeSplit>(pos, ss, alpha, beta, bestValue, &bestMove,
1013                                                depth, threatMove, moveCount, mp, NT);
1014           break;
1015       }
1016     }
1017
1018     if (SpNode)
1019         return bestValue;
1020
1021     // Step 20. Check for mate and stalemate
1022     // All legal moves have been searched and if there are no legal moves, it
1023     // must be mate or stalemate. Note that we can have a false positive in
1024     // case of Signals.stop or thread.cutoff_occurred() are set, but this is
1025     // harmless because return value is discarded anyhow in the parent nodes.
1026     // If we are in a singular extension search then return a fail low score.
1027     // A split node has at least one move, the one tried before to be splitted.
1028     if (!moveCount)
1029         return  excludedMove ? alpha
1030               : inCheck ? mated_in(ss->ply) : DrawValue[pos.side_to_move()];
1031
1032     // If we have pruned all the moves without searching return a fail-low score
1033     if (bestValue == -VALUE_INFINITE)
1034     {
1035         assert(!playedMoveCount);
1036
1037         bestValue = alpha;
1038     }
1039
1040     if (bestValue >= beta) // Failed high
1041     {
1042         TT.store(posKey, value_to_tt(bestValue, ss->ply), BOUND_LOWER, depth,
1043                  bestMove, ss->staticEval, ss->evalMargin);
1044
1045         if (!pos.is_capture_or_promotion(bestMove) && !inCheck)
1046         {
1047             if (bestMove != ss->killers[0])
1048             {
1049                 ss->killers[1] = ss->killers[0];
1050                 ss->killers[0] = bestMove;
1051             }
1052
1053             // Increase history value of the cut-off move
1054             Value bonus = Value(int(depth) * int(depth));
1055             H.add(pos.piece_moved(bestMove), to_sq(bestMove), bonus);
1056
1057             // Decrease history of all the other played non-capture moves
1058             for (int i = 0; i < playedMoveCount - 1; i++)
1059             {
1060                 Move m = movesSearched[i];
1061                 H.add(pos.piece_moved(m), to_sq(m), -bonus);
1062             }
1063         }
1064     }
1065     else // Failed low or PV search
1066         TT.store(posKey, value_to_tt(bestValue, ss->ply),
1067                  PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1068                  depth, bestMove, ss->staticEval, ss->evalMargin);
1069
1070     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1071
1072     return bestValue;
1073   }
1074
1075
1076   // qsearch() is the quiescence search function, which is called by the main
1077   // search function when the remaining depth is zero (or, to be more precise,
1078   // less than ONE_PLY).
1079
1080   template <NodeType NT>
1081   Value qsearch(Position& pos, Stack* ss, Value alpha, Value beta, Depth depth) {
1082
1083     const bool PvNode = (NT == PV);
1084
1085     assert(NT == PV || NT == NonPV);
1086     assert(alpha >= -VALUE_INFINITE && alpha < beta && beta <= VALUE_INFINITE);
1087     assert(PvNode || (alpha == beta - 1));
1088     assert(depth <= DEPTH_ZERO);
1089
1090     StateInfo st;
1091     const TTEntry* tte;
1092     Key posKey;
1093     Move ttMove, move, bestMove;
1094     Value bestValue, value, ttValue, futilityValue, futilityBase;
1095     bool inCheck, givesCheck, enoughMaterial, evasionPrunable;
1096     Depth ttDepth;
1097
1098     inCheck = pos.in_check();
1099     ss->currentMove = bestMove = MOVE_NONE;
1100     ss->ply = (ss-1)->ply + 1;
1101
1102     // Check for an instant draw or maximum ply reached
1103     if (pos.is_draw<true>() || ss->ply > MAX_PLY)
1104         return DrawValue[pos.side_to_move()];
1105
1106     // Transposition table lookup. At PV nodes, we don't use the TT for
1107     // pruning, but only for move ordering.
1108     posKey = pos.key();
1109     tte = TT.probe(posKey);
1110     ttMove = tte ? tte->move() : MOVE_NONE;
1111     ttValue = tte ? value_from_tt(tte->value(),ss->ply) : VALUE_NONE;
1112
1113     // Decide whether or not to include checks, this fixes also the type of
1114     // TT entry depth that we are going to use. Note that in qsearch we use
1115     // only two types of depth in TT: DEPTH_QS_CHECKS or DEPTH_QS_NO_CHECKS.
1116     ttDepth = inCheck || depth >= DEPTH_QS_CHECKS ? DEPTH_QS_CHECKS
1117                                                   : DEPTH_QS_NO_CHECKS;
1118     if (   tte && tte->depth() >= ttDepth
1119         && (           PvNode ?  tte->type() == BOUND_EXACT
1120             : ttValue >= beta ? (tte->type() & BOUND_LOWER)
1121                               : (tte->type() & BOUND_UPPER)))
1122     {
1123         assert(ttValue != VALUE_NONE); // Due to ttDepth > DEPTH_NONE
1124
1125         ss->currentMove = ttMove; // Can be MOVE_NONE
1126         return ttValue;
1127     }
1128
1129     // Evaluate the position statically
1130     if (inCheck)
1131     {
1132         ss->staticEval = ss->evalMargin = VALUE_NONE;
1133         bestValue = futilityBase = -VALUE_INFINITE;
1134         enoughMaterial = false;
1135     }
1136     else
1137     {
1138         if (tte)
1139         {
1140             assert(tte->static_value() != VALUE_NONE);
1141
1142             ss->staticEval = bestValue = tte->static_value();
1143             ss->evalMargin = tte->static_value_margin();
1144         }
1145         else
1146             ss->staticEval = bestValue = evaluate(pos, ss->evalMargin);
1147
1148         // Stand pat. Return immediately if static value is at least beta
1149         if (bestValue >= beta)
1150         {
1151             if (!tte)
1152                 TT.store(pos.key(), value_to_tt(bestValue, ss->ply), BOUND_LOWER,
1153                          DEPTH_NONE, MOVE_NONE, ss->staticEval, ss->evalMargin);
1154
1155             return bestValue;
1156         }
1157
1158         if (PvNode && bestValue > alpha)
1159             alpha = bestValue;
1160
1161         futilityBase = ss->staticEval + ss->evalMargin + Value(128);
1162         enoughMaterial = pos.non_pawn_material(pos.side_to_move()) > RookValueMg;
1163     }
1164
1165     // Initialize a MovePicker object for the current position, and prepare
1166     // to search the moves. Because the depth is <= 0 here, only captures,
1167     // queen promotions and checks (only if depth >= DEPTH_QS_CHECKS) will
1168     // be generated.
1169     MovePicker mp(pos, ttMove, depth, H, to_sq((ss-1)->currentMove));
1170     CheckInfo ci(pos);
1171
1172     // Loop through the moves until no moves remain or a beta cutoff occurs
1173     while ((move = mp.next_move<false>()) != MOVE_NONE)
1174     {
1175       assert(is_ok(move));
1176
1177       givesCheck = pos.move_gives_check(move, ci);
1178
1179       // Futility pruning
1180       if (   !PvNode
1181           && !inCheck
1182           && !givesCheck
1183           &&  move != ttMove
1184           &&  enoughMaterial
1185           &&  type_of(move) != PROMOTION
1186           && !pos.is_passed_pawn_push(move))
1187       {
1188           futilityValue =  futilityBase
1189                          + PieceValue[EG][pos.piece_on(to_sq(move))]
1190                          + (type_of(move) == ENPASSANT ? PawnValueEg : VALUE_ZERO);
1191
1192           if (futilityValue < beta)
1193           {
1194               if (futilityValue > bestValue)
1195                   bestValue = futilityValue;
1196
1197               continue;
1198           }
1199
1200           // Prune moves with negative or equal SEE
1201           if (   futilityBase < beta
1202               && depth < DEPTH_ZERO
1203               && pos.see(move) <= 0)
1204               continue;
1205       }
1206
1207       // Detect non-capture evasions that are candidate to be pruned
1208       evasionPrunable =   !PvNode
1209                        &&  inCheck
1210                        &&  bestValue > VALUE_MATED_IN_MAX_PLY
1211                        && !pos.is_capture(move)
1212                        && !pos.can_castle(pos.side_to_move());
1213
1214       // Don't search moves with negative SEE values
1215       if (   !PvNode
1216           && (!inCheck || evasionPrunable)
1217           &&  move != ttMove
1218           &&  type_of(move) != PROMOTION
1219           &&  pos.see_sign(move) < 0)
1220           continue;
1221
1222       // Don't search useless checks
1223       if (   !PvNode
1224           && !inCheck
1225           &&  givesCheck
1226           &&  move != ttMove
1227           && !pos.is_capture_or_promotion(move)
1228           &&  ss->staticEval + PawnValueMg / 4 < beta
1229           && !check_is_dangerous(pos, move, futilityBase, beta))
1230           continue;
1231
1232       // Check for legality only before to do the move
1233       if (!pos.pl_move_is_legal(move, ci.pinned))
1234           continue;
1235
1236       ss->currentMove = move;
1237
1238       // Make and search the move
1239       pos.do_move(move, st, ci, givesCheck);
1240       value = -qsearch<NT>(pos, ss+1, -beta, -alpha, depth - ONE_PLY);
1241       pos.undo_move(move);
1242
1243       assert(value > -VALUE_INFINITE && value < VALUE_INFINITE);
1244
1245       // Check for new best move
1246       if (value > bestValue)
1247       {
1248           bestValue = value;
1249
1250           if (value > alpha)
1251           {
1252               if (PvNode && value < beta) // Update alpha here! Always alpha < beta
1253               {
1254                   alpha = value;
1255                   bestMove = move;
1256               }
1257               else // Fail high
1258               {
1259                   TT.store(posKey, value_to_tt(value, ss->ply), BOUND_LOWER,
1260                            ttDepth, move, ss->staticEval, ss->evalMargin);
1261
1262                   return value;
1263               }
1264           }
1265        }
1266     }
1267
1268     // All legal moves have been searched. A special case: If we're in check
1269     // and no legal moves were found, it is checkmate.
1270     if (inCheck && bestValue == -VALUE_INFINITE)
1271         return mated_in(ss->ply); // Plies to mate from the root
1272
1273     TT.store(posKey, value_to_tt(bestValue, ss->ply),
1274              PvNode && bestMove != MOVE_NONE ? BOUND_EXACT : BOUND_UPPER,
1275              ttDepth, bestMove, ss->staticEval, ss->evalMargin);
1276
1277     assert(bestValue > -VALUE_INFINITE && bestValue < VALUE_INFINITE);
1278
1279     return bestValue;
1280   }
1281
1282
1283   // check_is_dangerous() tests if a checking move can be pruned in qsearch().
1284   // bestValue is updated only when returning false because in that case move
1285   // will be pruned.
1286
1287   bool check_is_dangerous(Position &pos, Move move, Value futilityBase, Value beta)
1288   {
1289     Bitboard b, occ, oldAtt, newAtt, kingAtt;
1290     Square from, to, ksq;
1291     Piece pc;
1292     Color them;
1293
1294     from = from_sq(move);
1295     to = to_sq(move);
1296     them = ~pos.side_to_move();
1297     ksq = pos.king_square(them);
1298     kingAtt = pos.attacks_from<KING>(ksq);
1299     pc = pos.piece_moved(move);
1300
1301     occ = pos.pieces() ^ from ^ ksq;
1302     oldAtt = pos.attacks_from(pc, from, occ);
1303     newAtt = pos.attacks_from(pc,   to, occ);
1304
1305     // Rule 1. Checks which give opponent's king at most one escape square are dangerous
1306     b = kingAtt & ~pos.pieces(them) & ~newAtt & ~(1ULL << to);
1307
1308     if (!more_than_one(b))
1309         return true;
1310
1311     // Rule 2. Queen contact check is very dangerous
1312     if (type_of(pc) == QUEEN && (kingAtt & to))
1313         return true;
1314
1315     // Rule 3. Creating new double threats with checks
1316     b = pos.pieces(them) & newAtt & ~oldAtt & ~(1ULL << ksq);
1317     while (b)
1318     {
1319         // Note that here we generate illegal "double move"!
1320         if (futilityBase + PieceValue[EG][pos.piece_on(pop_lsb(&b))] >= beta)
1321             return true;
1322     }
1323
1324     return false;
1325   }
1326
1327
1328   // connected_moves() tests whether two moves are 'connected' in the sense
1329   // that the first move somehow made the second move possible (for instance
1330   // if the moving piece is the same in both moves). The first move is assumed
1331   // to be the move that was made to reach the current position, while the
1332   // second move is assumed to be a move from the current position.
1333
1334   bool connected_moves(const Position& pos, Move m1, Move m2) {
1335
1336     Square f1, t1, f2, t2;
1337     Piece p1, p2;
1338     Square ksq;
1339
1340     assert(is_ok(m1));
1341     assert(is_ok(m2));
1342
1343     // Case 1: The moving piece is the same in both moves
1344     f2 = from_sq(m2);
1345     t1 = to_sq(m1);
1346     if (f2 == t1)
1347         return true;
1348
1349     // Case 2: The destination square for m2 was vacated by m1
1350     t2 = to_sq(m2);
1351     f1 = from_sq(m1);
1352     if (t2 == f1)
1353         return true;
1354
1355     // Case 3: Moving through the vacated square
1356     p2 = pos.piece_on(f2);
1357     if (piece_is_slider(p2) && (between_bb(f2, t2) & f1))
1358       return true;
1359
1360     // Case 4: The destination square for m2 is defended by the moving piece in m1
1361     p1 = pos.piece_on(t1);
1362     if (pos.attacks_from(p1, t1) & t2)
1363         return true;
1364
1365     // Case 5: Discovered check, checking piece is the piece moved in m1
1366     ksq = pos.king_square(pos.side_to_move());
1367     if (    piece_is_slider(p1)
1368         && (between_bb(t1, ksq) & f2)
1369         && (pos.attacks_from(p1, t1, pos.pieces() ^ f2) & ksq))
1370         return true;
1371
1372     return false;
1373   }
1374
1375
1376   // value_to_tt() adjusts a mate score from "plies to mate from the root" to
1377   // "plies to mate from the current position". Non-mate scores are unchanged.
1378   // The function is called before storing a value to the transposition table.
1379
1380   Value value_to_tt(Value v, int ply) {
1381
1382     assert(v != VALUE_NONE);
1383
1384     return  v >= VALUE_MATE_IN_MAX_PLY  ? v + ply
1385           : v <= VALUE_MATED_IN_MAX_PLY ? v - ply : v;
1386   }
1387
1388
1389   // value_from_tt() is the inverse of value_to_tt(): It adjusts a mate score
1390   // from the transposition table (where refers to the plies to mate/be mated
1391   // from current position) to "plies to mate/be mated from the root".
1392
1393   Value value_from_tt(Value v, int ply) {
1394
1395     return  v == VALUE_NONE             ? VALUE_NONE
1396           : v >= VALUE_MATE_IN_MAX_PLY  ? v - ply
1397           : v <= VALUE_MATED_IN_MAX_PLY ? v + ply : v;
1398   }
1399
1400
1401   // connected_threat() tests whether it is safe to forward prune a move or if
1402   // is somehow connected to the threat move returned by null search.
1403
1404   bool connected_threat(const Position& pos, Move m, Move threat) {
1405
1406     assert(is_ok(m));
1407     assert(is_ok(threat));
1408     assert(!pos.is_capture_or_promotion(m));
1409     assert(!pos.is_passed_pawn_push(m));
1410
1411     Square mfrom, mto, tfrom, tto;
1412
1413     mfrom = from_sq(m);
1414     mto = to_sq(m);
1415     tfrom = from_sq(threat);
1416     tto = to_sq(threat);
1417
1418     // Case 1: Don't prune moves which move the threatened piece
1419     if (mfrom == tto)
1420         return true;
1421
1422     // Case 2: If the threatened piece has value less than or equal to the
1423     // value of the threatening piece, don't prune moves which defend it.
1424     if (   pos.is_capture(threat)
1425         && (   PieceValue[MG][pos.piece_on(tfrom)] >= PieceValue[MG][pos.piece_on(tto)]
1426             || type_of(pos.piece_on(tfrom)) == KING)
1427         && pos.move_attacks_square(m, tto))
1428         return true;
1429
1430     // Case 3: If the moving piece in the threatened move is a slider, don't
1431     // prune safe moves which block its ray.
1432     if (    piece_is_slider(pos.piece_on(tfrom))
1433         && (between_bb(tfrom, tto) & mto)
1434         &&  pos.see_sign(m) >= 0)
1435         return true;
1436
1437     return false;
1438   }
1439
1440
1441   // When playing with strength handicap choose best move among the MultiPV set
1442   // using a statistical rule dependent on 'level'. Idea by Heinz van Saanen.
1443
1444   Move Skill::pick_move() {
1445
1446     assert(MultiPV > 1);
1447
1448     static RKISS rk;
1449
1450     // PRNG sequence should be not deterministic
1451     for (int i = Time::now() % 50; i > 0; i--)
1452         rk.rand<unsigned>();
1453
1454     // RootMoves are already sorted by score in descending order
1455     size_t size = std::min(MultiPV, RootMoves.size());
1456     int variance = std::min(RootMoves[0].score - RootMoves[size - 1].score, PawnValueMg);
1457     int weakness = 120 - 2 * level;
1458     int max_s = -VALUE_INFINITE;
1459     best = MOVE_NONE;
1460
1461     // Choose best move. For each move score we add two terms both dependent on
1462     // weakness, one deterministic and bigger for weaker moves, and one random,
1463     // then we choose the move with the resulting highest score.
1464     for (size_t i = 0; i < size; i++)
1465     {
1466         int s = RootMoves[i].score;
1467
1468         // Don't allow crazy blunders even at very low skills
1469         if (i > 0 && RootMoves[i-1].score > s + 2 * PawnValueMg)
1470             break;
1471
1472         // This is our magic formula
1473         s += (  weakness * int(RootMoves[0].score - s)
1474               + variance * (rk.rand<unsigned>() % weakness)) / 128;
1475
1476         if (s > max_s)
1477         {
1478             max_s = s;
1479             best = RootMoves[i].pv[0];
1480         }
1481     }
1482     return best;
1483   }
1484
1485
1486   // uci_pv() formats PV information according to UCI protocol. UCI requires
1487   // to send all the PV lines also if are still to be searched and so refer to
1488   // the previous search score.
1489
1490   string uci_pv(const Position& pos, int depth, Value alpha, Value beta) {
1491
1492     std::stringstream s;
1493     Time::point elaspsed = Time::now() - SearchTime + 1;
1494     int selDepth = 0;
1495
1496     for (size_t i = 0; i < Threads.size(); i++)
1497         if (Threads[i].maxPly > selDepth)
1498             selDepth = Threads[i].maxPly;
1499
1500     for (size_t i = 0; i < std::min(UCIMultiPV, RootMoves.size()); i++)
1501     {
1502         bool updated = (i <= PVIdx);
1503
1504         if (depth == 1 && !updated)
1505             continue;
1506
1507         int d = (updated ? depth : depth - 1);
1508         Value v = (updated ? RootMoves[i].score : RootMoves[i].prevScore);
1509
1510         if (s.rdbuf()->in_avail())
1511             s << "\n";
1512
1513         s << "info depth " << d
1514           << " seldepth "  << selDepth
1515           << " score "     << (i == PVIdx ? score_to_uci(v, alpha, beta) : score_to_uci(v))
1516           << " nodes "     << pos.nodes_searched()
1517           << " nps "       << pos.nodes_searched() * 1000 / elaspsed
1518           << " time "      << elaspsed
1519           << " multipv "   << i + 1
1520           << " pv";
1521
1522         for (size_t j = 0; RootMoves[i].pv[j] != MOVE_NONE; j++)
1523             s <<  " " << move_to_uci(RootMoves[i].pv[j], Chess960);
1524     }
1525
1526     return s.str();
1527   }
1528
1529 } // namespace
1530
1531
1532 /// RootMove::extract_pv_from_tt() builds a PV by adding moves from the TT table.
1533 /// We consider also failing high nodes and not only BOUND_EXACT nodes so to
1534 /// allow to always have a ponder move even when we fail high at root, and a
1535 /// long PV to print that is important for position analysis.
1536
1537 void RootMove::extract_pv_from_tt(Position& pos) {
1538
1539   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1540   TTEntry* tte;
1541   int ply = 1;
1542   Move m = pv[0];
1543
1544   assert(m != MOVE_NONE && pos.is_pseudo_legal(m));
1545
1546   pv.clear();
1547   pv.push_back(m);
1548   pos.do_move(m, *st++);
1549
1550   while (   (tte = TT.probe(pos.key())) != NULL
1551          && (m = tte->move()) != MOVE_NONE // Local copy, TT entry could change
1552          && pos.is_pseudo_legal(m)
1553          && pos.pl_move_is_legal(m, pos.pinned_pieces())
1554          && ply < MAX_PLY
1555          && (!pos.is_draw<false>() || ply < 2))
1556   {
1557       pv.push_back(m);
1558       pos.do_move(m, *st++);
1559       ply++;
1560   }
1561   pv.push_back(MOVE_NONE);
1562
1563   do pos.undo_move(pv[--ply]); while (ply);
1564 }
1565
1566
1567 /// RootMove::insert_pv_in_tt() is called at the end of a search iteration, and
1568 /// inserts the PV back into the TT. This makes sure the old PV moves are searched
1569 /// first, even if the old TT entries have been overwritten.
1570
1571 void RootMove::insert_pv_in_tt(Position& pos) {
1572
1573   StateInfo state[MAX_PLY_PLUS_2], *st = state;
1574   TTEntry* tte;
1575   Key k;
1576   Value v, m = VALUE_NONE;
1577   int ply = 0;
1578
1579   assert(pv[ply] != MOVE_NONE && pos.is_pseudo_legal(pv[ply]));
1580
1581   do {
1582       k = pos.key();
1583       tte = TT.probe(k);
1584
1585       // Don't overwrite existing correct entries
1586       if (!tte || tte->move() != pv[ply])
1587       {
1588           v = (pos.in_check() ? VALUE_NONE : evaluate(pos, m));
1589           TT.store(k, VALUE_NONE, BOUND_NONE, DEPTH_NONE, pv[ply], v, m);
1590       }
1591       pos.do_move(pv[ply], *st++);
1592
1593   } while (pv[++ply] != MOVE_NONE);
1594
1595   do pos.undo_move(pv[--ply]); while (ply);
1596 }
1597
1598
1599 /// Thread::idle_loop() is where the thread is parked when it has no work to do
1600
1601 void Thread::idle_loop() {
1602
1603   // Pointer 'sp_master', if non-NULL, points to the active SplitPoint
1604   // object for which the thread is the master.
1605   const SplitPoint* sp_master = splitPointsCnt ? curSplitPoint : NULL;
1606
1607   assert(!sp_master || (sp_master->master == this && is_searching));
1608
1609   // If this thread is the master of a split point and all slaves have
1610   // finished their work at this split point, return from the idle loop.
1611   while (!sp_master || sp_master->slavesMask)
1612   {
1613       // If we are not searching, wait for a condition to be signaled
1614       // instead of wasting CPU time polling for work.
1615       while (   do_sleep
1616              || do_exit
1617              || (!is_searching && Threads.use_sleeping_threads()))
1618       {
1619           if (do_exit)
1620           {
1621               assert(!sp_master);
1622               return;
1623           }
1624
1625           // Grab the lock to avoid races with Thread::wake_up()
1626           mutex.lock();
1627
1628           // If we are master and all slaves have finished don't go to sleep
1629           if (sp_master && !sp_master->slavesMask)
1630           {
1631               mutex.unlock();
1632               break;
1633           }
1634
1635           // Do sleep after retesting sleep conditions under lock protection, in
1636           // particular we need to avoid a deadlock in case a master thread has,
1637           // in the meanwhile, allocated us and sent the wake_up() call before we
1638           // had the chance to grab the lock.
1639           if (do_sleep || !is_searching)
1640               sleepCondition.wait(mutex);
1641
1642           mutex.unlock();
1643       }
1644
1645       // If this thread has been assigned work, launch a search
1646       if (is_searching)
1647       {
1648           assert(!do_sleep && !do_exit);
1649
1650           Threads.mutex.lock();
1651
1652           assert(is_searching);
1653           SplitPoint* sp = curSplitPoint;
1654
1655           Threads.mutex.unlock();
1656
1657           Stack ss[MAX_PLY_PLUS_2];
1658           Position pos(*sp->pos, this);
1659
1660           memcpy(ss, sp->ss - 1, 4 * sizeof(Stack));
1661           (ss+1)->sp = sp;
1662
1663           sp->mutex.lock();
1664
1665           assert(sp->activePositions[idx] == NULL);
1666
1667           sp->activePositions[idx] = &pos;
1668
1669           if (sp->nodeType == Root)
1670               search<SplitPointRoot>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1671           else if (sp->nodeType == PV)
1672               search<SplitPointPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1673           else if (sp->nodeType == NonPV)
1674               search<SplitPointNonPV>(pos, ss+1, sp->alpha, sp->beta, sp->depth);
1675           else
1676               assert(false);
1677
1678           assert(is_searching);
1679
1680           is_searching = false;
1681           sp->activePositions[idx] = NULL;
1682           sp->slavesMask &= ~(1ULL << idx);
1683           sp->nodes += pos.nodes_searched();
1684
1685           // Wake up master thread so to allow it to return from the idle loop in
1686           // case we are the last slave of the split point.
1687           if (    Threads.use_sleeping_threads()
1688               &&  this != sp->master
1689               && !sp->slavesMask)
1690           {
1691               assert(!sp->master->is_searching);
1692               sp->master->wake_up();
1693           }
1694
1695           // After releasing the lock we cannot access anymore any SplitPoint
1696           // related data in a safe way becuase it could have been released under
1697           // our feet by the sp master. Also accessing other Thread objects is
1698           // unsafe because if we are exiting there is a chance are already freed.
1699           sp->mutex.unlock();
1700       }
1701   }
1702 }
1703
1704
1705 /// check_time() is called by the timer thread when the timer triggers. It is
1706 /// used to print debug info and, more important, to detect when we are out of
1707 /// available time and so stop the search.
1708
1709 void check_time() {
1710
1711   static Time::point lastInfoTime = Time::now();
1712   int64_t nodes = 0; // Workaround silly 'uninitialized' gcc warning
1713
1714   if (Time::now() - lastInfoTime >= 1000)
1715   {
1716       lastInfoTime = Time::now();
1717       dbg_print();
1718   }
1719
1720   if (Limits.ponder)
1721       return;
1722
1723   if (Limits.nodes)
1724   {
1725       Threads.mutex.lock();
1726
1727       nodes = RootPosition.nodes_searched();
1728
1729       // Loop across all split points and sum accumulated SplitPoint nodes plus
1730       // all the currently active slaves positions.
1731       for (size_t i = 0; i < Threads.size(); i++)
1732           for (int j = 0; j < Threads[i].splitPointsCnt; j++)
1733           {
1734               SplitPoint& sp = Threads[i].splitPoints[j];
1735
1736               sp.mutex.lock();
1737
1738               nodes += sp.nodes;
1739               Bitboard sm = sp.slavesMask;
1740               while (sm)
1741               {
1742                   Position* pos = sp.activePositions[pop_lsb(&sm)];
1743                   nodes += pos ? pos->nodes_searched() : 0;
1744               }
1745
1746               sp.mutex.unlock();
1747           }
1748
1749       Threads.mutex.unlock();
1750   }
1751
1752   Time::point elapsed = Time::now() - SearchTime;
1753   bool stillAtFirstMove =    Signals.firstRootMove
1754                          && !Signals.failedLowAtRoot
1755                          &&  elapsed > TimeMgr.available_time();
1756
1757   bool noMoreTime =   elapsed > TimeMgr.maximum_time() - 2 * TimerResolution
1758                    || stillAtFirstMove;
1759
1760   if (   (Limits.use_time_management() && noMoreTime)
1761       || (Limits.movetime && elapsed >= Limits.movetime)
1762       || (Limits.nodes && nodes >= Limits.nodes))
1763       Signals.stop = true;
1764 }