]> git.sesse.net Git - stockfish/blobdiff - src/evaluate.cpp
Small reformat in evaluate_unstoppable_pawns()
[stockfish] / src / evaluate.cpp
index d791ed36ae73c36832c7bd534dc674eceb917759..9c2b70a7acb90509200b56c42f1a287bb44155a2 100644 (file)
@@ -23,6 +23,9 @@
 ////
 
 #include <cassert>
+#include <iostream>
+#include <iomanip>
+#include <sstream>
 
 #include "bitcount.h"
 #include "evaluate.h"
@@ -45,11 +48,6 @@ namespace {
     // Pointer to pawn hash table entry
     PawnInfo* pi;
 
-    // updateKingTables[color] is set to true if we have enough material
-    // to trigger the opponent's king safety calculation. When is false we
-    // skip the time consuming update of the king attackers tables.
-    bool updateKingTables[2];
-
     // attackedBy[color][piece type] is a bitboard representing all squares
     // attacked by a given color and piece type, attackedBy[color][0] contains
     // all squares attacked by the given color.
@@ -133,18 +131,14 @@ namespace {
     V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0),
     V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0),
     V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0),
-    V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0),
-    V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
-    V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) },
+    V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0) },
   {
     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Bishops
     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
     V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0),
     V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0),
     V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0),
-    V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0),
-    V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
-    V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) }
+    V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0) }
   };
 
   // ThreatBonus[attacking][attacked] contains threat bonuses according to
@@ -177,6 +171,11 @@ namespace {
   // right to castle.
   const Value TrappedRookPenalty = Value(180);
 
+  // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
+  // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
+  // happen in Chess960 games.
+  const Score TrappedBishopA1H1Penalty = make_score(100, 100);
+
   // The SpaceMask[Color] contains the area of the board which is considered
   // by the space evaluation. In the middle game, each side is given a bonus
   // based on how many squares inside this area are safe and available for
@@ -199,9 +198,10 @@ namespace {
   const int KingAttackWeights[] = { 0, 0, 2, 2, 3, 5 };
 
   // Bonuses for enemy's safe checks
-  const int QueenContactCheckBonus = 3;
-  const int QueenCheckBonus        = 2;
-  const int RookCheckBonus         = 1;
+  const int QueenContactCheckBonus = 6;
+  const int RookContactCheckBonus  = 4;
+  const int QueenCheckBonus        = 3;
+  const int RookCheckBonus         = 2;
   const int BishopCheckBonus       = 1;
   const int KnightCheckBonus       = 1;
 
@@ -222,22 +222,27 @@ namespace {
   // weighted scores, indexed by color and by a calculated integer number.
   Score KingDangerTable[2][128];
 
-  // Pawn and material hash tables, indexed by the current thread id.
-  // Note that they will be initialized at 0 being global variables.
-  MaterialInfoTable* MaterialTable[MAX_THREADS];
-  PawnInfoTable* PawnTable[MAX_THREADS];
+  // TracedTerms[Color][PieceType || TracedType] contains a breakdown of the
+  // evaluation terms, used when tracing.
+  Score TracedTerms[2][16];
+  std::stringstream TraceStream;
+
+  enum TracedType {
+      PST = 8, IMBALANCE = 9, MOBILITY = 10, THREAT = 11,
+      PASSED = 12, UNSTOPPABLE = 13, SPACE = 14, TOTAL = 15
+  };
 
   // Function prototypes
-  template<bool HasPopCnt>
-  Value do_evaluate(const Position& pos, Value margins[]);
+  template<bool HasPopCnt, bool Trace>
+  Value do_evaluate(const Position& pos, Value& margin);
 
   template<Color Us, bool HasPopCnt>
   void init_eval_info(const Position& pos, EvalInfo& ei);
 
-  template<Color Us, bool HasPopCnt>
+  template<Color Us, bool HasPopCnt, bool Trace>
   Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei, Score& mobility);
 
-  template<Color Us, bool HasPopCnt>
+  template<Color Us, bool HasPopCnt, bool Trace>
   Score evaluate_king(const Position& pos, EvalInfo& ei, Value margins[]);
 
   template<Color Us>
@@ -249,71 +254,68 @@ namespace {
   template<Color Us>
   Score evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
 
-  Score apply_weight(Score v, Score weight);
-  Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]);
+  template<bool HasPopCnt>
+  Score evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei);
+
+  inline Score apply_weight(Score v, Score weight);
+  Value scale_by_game_phase(const Score& v, Phase ph, ScaleFactor sf);
   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
   void init_safety();
 }
 
 
-////
-//// Functions
-////
-
-
-/// Prefetches in pawn hash tables
-
-void prefetchPawn(Key key, int threadID) {
-
-    PawnTable[threadID]->prefetch(key);
-}
-
-
 /// evaluate() is the main evaluation function. It always computes two
 /// values, an endgame score and a middle game score, and interpolates
 /// between them based on the remaining material.
-Value evaluate(const Position& pos, Value margins[]) {
+Value evaluate(const Position& pos, Value& margin) {
 
-    return CpuHasPOPCNT ? do_evaluate<true>(pos, margins)
-                        : do_evaluate<false>(pos, margins);
+    return CpuHasPOPCNT ? do_evaluate<true, false>(pos, margin)
+                        : do_evaluate<false, false>(pos, margin);
 }
 
 namespace {
 
-template<bool HasPopCnt>
-Value do_evaluate(const Position& pos, Value margins[]) {
+double to_cp(Value v) { return double(v) / double(PawnValueMidgame); }
+
+void trace_add(int idx, Score term_w, Score term_b = Score(0)) {
+
+    TracedTerms[WHITE][idx] = term_w;
+    TracedTerms[BLACK][idx] = term_b;
+}
+
+template<bool HasPopCnt, bool Trace>
+Value do_evaluate(const Position& pos, Value& margin) {
 
   EvalInfo ei;
-  ScaleFactor factor[2];
+  Value margins[2];
   Score mobilityWhite, mobilityBlack;
 
   assert(pos.is_ok());
   assert(pos.thread() >= 0 && pos.thread() < MAX_THREADS);
-  assert(!pos.is_check());
+  assert(!pos.in_check());
 
   // Initialize value by reading the incrementally updated scores included
   // in the position object (material + piece square tables).
   Score bonus = pos.value();
 
-  // margins[color] is the uncertainty estimation of position's evaluation
-  // and typically is used by the search for pruning decisions.
+  // margins[] store the uncertainty estimation of position's evaluation
+  // that typically is used by the search for pruning decisions.
   margins[WHITE] = margins[BLACK] = VALUE_ZERO;
 
   // Probe the material hash table
-  MaterialInfo* mi = MaterialTable[pos.thread()]->get_material_info(pos);
+  MaterialInfo* mi = Threads[pos.thread()].materialTable.get_material_info(pos);
   bonus += mi->material_value();
 
   // If we have a specialized evaluation function for the current material
   // configuration, call it and return.
   if (mi->specialized_eval_exists())
+  {
+      margin = VALUE_ZERO;
       return mi->evaluate(pos);
-
-  // After get_material_info() call that modifies them
-  factor[WHITE] = mi->scale_factor(pos, WHITE);
-  factor[BLACK] = mi->scale_factor(pos, BLACK);
+  }
 
   // Probe the pawn hash table
-  ei.pi = PawnTable[pos.thread()]->get_pawn_info(pos);
+  ei.pi = Threads[pos.thread()].pawnTable.get_pawn_info(pos);
   bonus += apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]);
 
   // Initialize attack and king safety bitboards
@@ -321,15 +323,15 @@ Value do_evaluate(const Position& pos, Value margins[]) {
   init_eval_info<BLACK, HasPopCnt>(pos, ei);
 
   // Evaluate pieces and mobility
-  bonus +=  evaluate_pieces_of_color<WHITE, HasPopCnt>(pos, ei, mobilityWhite)
-          - evaluate_pieces_of_color<BLACK, HasPopCnt>(pos, ei, mobilityBlack);
+  bonus +=  evaluate_pieces_of_color<WHITE, HasPopCnt, Trace>(pos, ei, mobilityWhite)
+          - evaluate_pieces_of_color<BLACK, HasPopCnt, Trace>(pos, ei, mobilityBlack);
 
   bonus += apply_weight(mobilityWhite - mobilityBlack, Weights[Mobility]);
 
   // Evaluate kings after all other pieces because we need complete attack
   // information when computing the king safety evaluation.
-  bonus +=  evaluate_king<WHITE, HasPopCnt>(pos, ei, margins)
-          - evaluate_king<BLACK, HasPopCnt>(pos, ei, margins);
+  bonus +=  evaluate_king<WHITE, HasPopCnt, Trace>(pos, ei, margins)
+          - evaluate_king<BLACK, HasPopCnt, Trace>(pos, ei, margins);
 
   // Evaluate tactical threats, we need full attack information including king
   bonus +=  evaluate_threats<WHITE>(pos, ei)
@@ -339,24 +341,33 @@ Value do_evaluate(const Position& pos, Value margins[]) {
   bonus +=  evaluate_passed_pawns<WHITE>(pos, ei)
           - evaluate_passed_pawns<BLACK>(pos, ei);
 
-  Phase phase = mi->game_phase();
+  // If one side has only a king, check whether exists any unstoppable passed pawn
+  if (!pos.non_pawn_material(WHITE) || !pos.non_pawn_material(BLACK))
+      bonus += evaluate_unstoppable_pawns<HasPopCnt>(pos, ei);
 
   // Evaluate space for both sides, only in middle-game.
-  if (phase > PHASE_ENDGAME && mi->space_weight() > 0)
+  if (mi->space_weight())
   {
-      int s = evaluate_space<WHITE, HasPopCnt>(pos, ei) - evaluate_space<BLACK, HasPopCnt>(pos, ei);
-      bonus += apply_weight(make_score(s * mi->space_weight(), 0), Weights[Space]);
+      int s_w = evaluate_space<WHITE, HasPopCnt>(pos, ei);
+      int s_b = evaluate_space<BLACK, HasPopCnt>(pos, ei);
+      bonus += apply_weight(make_score((s_w - s_b) * mi->space_weight(), 0), Weights[Space]);
+
+      if (Trace)
+          trace_add(SPACE, apply_weight(make_score(s_w * mi->space_weight(), make_score(0, 0)), Weights[Space]),
+                           apply_weight(make_score(s_b * mi->space_weight(), make_score(0, 0)), Weights[Space]));
   }
 
+  // Scale winning side if position is more drawish that what it appears
+  ScaleFactor sf = eg_value(bonus) > VALUE_DRAW ? mi->scale_factor(pos, WHITE)
+                                                : mi->scale_factor(pos, BLACK);
+  Phase phase = mi->game_phase();
+
   // If we don't already have an unusual scale factor, check for opposite
-  // colored bishop endgames, and use a lower scale for those
+  // colored bishop endgames, and use a lower scale for those.
   if (   phase < PHASE_MIDGAME
       && pos.opposite_colored_bishops()
-      && (   (factor[WHITE] == SCALE_FACTOR_NORMAL && eg_value(bonus) > VALUE_ZERO)
-          || (factor[BLACK] == SCALE_FACTOR_NORMAL && eg_value(bonus) < VALUE_ZERO)))
+      && sf == SCALE_FACTOR_NORMAL)
   {
-      ScaleFactor sf;
-
       // Only the two bishops ?
       if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
           && pos.non_pawn_material(BLACK) == BishopValueMidgame)
@@ -370,57 +381,40 @@ Value do_evaluate(const Position& pos, Value margins[]) {
           // Endgame with opposite-colored bishops, but also other pieces. Still
           // a bit drawish, but not as drawish as with only the two bishops.
            sf = ScaleFactor(50);
-
-      if (factor[WHITE] == SCALE_FACTOR_NORMAL)
-          factor[WHITE] = sf;
-      if (factor[BLACK] == SCALE_FACTOR_NORMAL)
-          factor[BLACK] = sf;
   }
 
   // Interpolate between the middle game and the endgame score
-  Value v = scale_by_game_phase(bonus, phase, factor);
-  return pos.side_to_move() == WHITE ? v : -v;
-}
-
-} // namespace
-
+  margin = margins[pos.side_to_move()];
+  Value v = scale_by_game_phase(bonus, phase, sf);
 
-/// init_eval() initializes various tables used by the evaluation function
-
-void init_eval(int threads) {
-
-  assert(threads <= MAX_THREADS);
-
-  for (int i = 0; i < MAX_THREADS; i++)
+  if (Trace)
   {
-      if (i >= threads)
-      {
-          delete PawnTable[i];
-          delete MaterialTable[i];
-          PawnTable[i] = NULL;
-          MaterialTable[i] = NULL;
-          continue;
-      }
-      if (!PawnTable[i])
-          PawnTable[i] = new PawnInfoTable();
-
-      if (!MaterialTable[i])
-          MaterialTable[i] = new MaterialInfoTable();
+      trace_add(PST, pos.value());
+      trace_add(IMBALANCE, mi->material_value());
+      trace_add(PAWN, apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]));
+      trace_add(MOBILITY, apply_weight(mobilityWhite, Weights[Mobility]), apply_weight(mobilityBlack, Weights[Mobility]));
+      trace_add(THREAT, evaluate_threats<WHITE>(pos, ei), evaluate_threats<BLACK>(pos, ei));
+      trace_add(PASSED, evaluate_passed_pawns<WHITE>(pos, ei), evaluate_passed_pawns<BLACK>(pos, ei));
+      trace_add(UNSTOPPABLE, evaluate_unstoppable_pawns<HasPopCnt>(pos, ei));
+      trace_add(TOTAL, bonus);
+      TraceStream << "\nUncertainty margin: White: " << to_cp(margins[WHITE])
+                  << ", Black: " << to_cp(margins[BLACK])
+                  << "\nScaling: " << std::noshowpos
+                  << std::setw(6) << 100.0 * phase/128.0 << "% MG, "
+                  << std::setw(6) << 100.0 * (1.0 - phase/128.0) << "% * "
+                  << std::setw(6) << (100.0 * sf) / SCALE_FACTOR_NORMAL << "% EG.\n"
+                  << "Total evaluation: " << to_cp(v);
   }
-}
-
-
-/// quit_eval() releases heap-allocated memory at program termination
-
-void quit_eval() {
 
-  init_eval(0);
+  return pos.side_to_move() == WHITE ? v : -v;
 }
 
+} // namespace
+
 
 /// read_weights() reads evaluation weights from the corresponding UCI parameters
 
-void read_weights(Color us) {
+void read_evaluation_uci_options(Color us) {
 
   // King safety is asymmetrical. Our king danger level is weighted by
   // "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
@@ -436,7 +430,7 @@ void read_weights(Color us) {
 
   // If running in analysis mode, make sure we use symmetrical king safety. We do this
   // by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
-  if (get_option_value_bool("UCI_AnalyseMode"))
+  if (Options["UCI_AnalyseMode"].value<bool>())
       Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
 
   init_safety();
@@ -451,18 +445,22 @@ namespace {
   template<Color Us, bool HasPopCnt>
   void init_eval_info(const Position& pos, EvalInfo& ei) {
 
+    const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
     const Color Them = (Us == WHITE ? BLACK : WHITE);
 
     Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
-    ei.kingZone[Us] = (b | (Us == WHITE ? b >> 8 : b << 8));
     ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
-    ei.updateKingTables[Us] = pos.piece_count(Us, QUEEN) && pos.non_pawn_material(Us) >= QueenValueMidgame + RookValueMidgame;
-    if (ei.updateKingTables[Us])
+
+    // Init king safety tables only if we are going to use them
+    if (   pos.piece_count(Us, QUEEN)
+        && pos.non_pawn_material(Us) >= QueenValueMidgame + RookValueMidgame)
     {
+        ei.kingZone[Us] = (b | (Us == WHITE ? b >> 8 : b << 8));
         b &= ei.attackedBy[Us][PAWN];
-        ei.kingAttackersCount[Us] = b ? count_1s_max_15<HasPopCnt>(b) / 2 : EmptyBoardBB;
-        ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = EmptyBoardBB;
-    }
+        ei.kingAttackersCount[Us] = b ? count_1s<Max15>(b) / 2 : 0;
+        ei.kingAdjacentZoneAttacksCount[Us] = ei.kingAttackersWeight[Us] = 0;
+    } else
+        ei.kingZone[Us] = ei.kingAttackersCount[Us] = 0;
   }
 
 
@@ -494,8 +492,8 @@ namespace {
 
   // evaluate_pieces<>() assigns bonuses and penalties to the pieces of a given color
 
-  template<PieceType Piece, Color Us, bool HasPopCnt>
-  Score evaluate_pieces(const Position& pos, EvalInfo& ei, Score& mobility, Bitboard no_mob_area) {
+  template<PieceType Piece, Color Us, bool HasPopCnt, bool Trace>
+  Score evaluate_pieces(const Position& pos, EvalInfo& ei, Score& mobility, Bitboard mobilityArea) {
 
     Bitboard b;
     Square s, ksq;
@@ -503,6 +501,8 @@ namespace {
     File f;
     Score bonus = SCORE_ZERO;
 
+    const BitCountType Full  = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64 : CNT32;
+    const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
     const Color Them = (Us == WHITE ? BLACK : WHITE);
     const Square* ptr = pos.piece_list_begin(Us, Piece);
 
@@ -524,18 +524,18 @@ namespace {
         ei.attackedBy[Us][Piece] |= b;
 
         // King attacks
-        if (ei.updateKingTables[Us] && (b & ei.kingZone[Us]))
+        if (b & ei.kingZone[Us])
         {
             ei.kingAttackersCount[Us]++;
             ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
             Bitboard bb = (b & ei.attackedBy[Them][KING]);
             if (bb)
-                ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
+                ei.kingAdjacentZoneAttacksCount[Us] += count_1s<Max15>(bb);
         }
 
         // Mobility
-        mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & no_mob_area)
-                              : count_1s<HasPopCnt>(b & no_mob_area));
+        mob = (Piece != QUEEN ? count_1s<Max15>(b & mobilityArea)
+                              : count_1s<Full >(b & mobilityArea));
 
         mobility += MobilityBonus[Piece][mob];
 
@@ -556,6 +556,27 @@ namespace {
             bonus += (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
         }
 
+        // Special extra evaluation for bishops
+        if (Piece == BISHOP && pos.is_chess960())
+        {
+            // An important Chess960 pattern: A cornered bishop blocked by
+            // a friendly pawn diagonally in front of it is a very serious
+            // problem, especially when that pawn is also blocked.
+            if (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1))
+            {
+                Square d = pawn_push(Us) + (square_file(s) == FILE_A ? DELTA_E : DELTA_W);
+                if (pos.piece_on(s + d) == make_piece(Us, PAWN))
+                {
+                    if (!pos.square_is_empty(s + d + pawn_push(Us)))
+                        bonus -= 2*TrappedBishopA1H1Penalty;
+                    else if (pos.piece_on(s + 2*d) == make_piece(Us, PAWN))
+                        bonus -= TrappedBishopA1H1Penalty;
+                    else
+                        bonus -= TrappedBishopA1H1Penalty / 2;
+                }
+            }
+        }
+
         // Special extra evaluation for rooks
         if (Piece == ROOK)
         {
@@ -596,6 +617,10 @@ namespace {
             }
         }
     }
+
+    if (Trace)
+        TracedTerms[Us][Piece] = bonus;
+
     return bonus;
   }
 
@@ -636,7 +661,7 @@ namespace {
   // evaluate_pieces_of_color<>() assigns bonuses and penalties to all the
   // pieces of a given color.
 
-  template<Color Us, bool HasPopCnt>
+  template<Color Us, bool HasPopCnt, bool Trace>
   Score evaluate_pieces_of_color(const Position& pos, EvalInfo& ei, Score& mobility) {
 
     const Color Them = (Us == WHITE ? BLACK : WHITE);
@@ -644,12 +669,12 @@ namespace {
     Score bonus = mobility = SCORE_ZERO;
 
     // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
-    const Bitboard no_mob_area = ~(ei.attackedBy[Them][PAWN] | pos.pieces_of_color(Us));
+    const Bitboard mobilityArea = ~(ei.attackedBy[Them][PAWN] | pos.pieces_of_color(Us));
 
-    bonus += evaluate_pieces<KNIGHT, Us, HasPopCnt>(pos, ei, mobility, no_mob_area);
-    bonus += evaluate_pieces<BISHOP, Us, HasPopCnt>(pos, ei, mobility, no_mob_area);
-    bonus += evaluate_pieces<ROOK,   Us, HasPopCnt>(pos, ei, mobility, no_mob_area);
-    bonus += evaluate_pieces<QUEEN,  Us, HasPopCnt>(pos, ei, mobility, no_mob_area);
+    bonus += evaluate_pieces<KNIGHT, Us, HasPopCnt, Trace>(pos, ei, mobility, mobilityArea);
+    bonus += evaluate_pieces<BISHOP, Us, HasPopCnt, Trace>(pos, ei, mobility, mobilityArea);
+    bonus += evaluate_pieces<ROOK,   Us, HasPopCnt, Trace>(pos, ei, mobility, mobilityArea);
+    bonus += evaluate_pieces<QUEEN,  Us, HasPopCnt, Trace>(pos, ei, mobility, mobilityArea);
 
     // Sum up all attacked squares
     ei.attackedBy[Us][0] =   ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
@@ -661,9 +686,10 @@ namespace {
 
   // evaluate_king<>() assigns bonuses and penalties to a king of a given color
 
-  template<Color Us, bool HasPopCnt>
+  template<Color Us, bool HasPopCnt, bool Trace>
   Score evaluate_king(const Position& pos, EvalInfo& ei, Value margins[]) {
 
+    const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
     const Color Them = (Us == WHITE ? BLACK : WHITE);
 
     Bitboard undefended, b, b1, b2, safe;
@@ -675,8 +701,7 @@ namespace {
 
     // King safety. This is quite complicated, and is almost certainly far
     // from optimally tuned.
-    if (   ei.updateKingTables[Them]
-        && ei.kingAttackersCount[Them] >= 2
+    if (   ei.kingAttackersCount[Them] >= 2
         && ei.kingAdjacentZoneAttacksCount[Them])
     {
         // Find the attacked squares around the king which has no defenders
@@ -692,7 +717,7 @@ namespace {
         // attacked and undefended squares around our king, the square of the
         // king, and the quality of the pawn shelter.
         attackUnits =  Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
-                     + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
+                     + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s<Max15>(undefended))
                      + InitKingDanger[relative_square(Us, ksq)]
                      - mg_value(ei.pi->king_shelter<Us>(pos, ksq)) / 32;
 
@@ -706,7 +731,25 @@ namespace {
                   | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][ROOK]);
             if (b)
                 attackUnits +=  QueenContactCheckBonus
-                              * count_1s_max_15<HasPopCnt>(b)
+                              * count_1s<Max15>(b)
+                              * (Them == pos.side_to_move() ? 2 : 1);
+        }
+
+        // Analyse enemy's safe rook contact checks. First find undefended
+        // squares around the king attacked by enemy rooks...
+        b = undefended & ei.attackedBy[Them][ROOK] & ~pos.pieces_of_color(Them);
+
+        // Consider only squares where the enemy rook gives check
+        b &= RookPseudoAttacks[ksq];
+
+        if (b)
+        {
+            // ...then remove squares not supported by another enemy piece
+            b &= (  ei.attackedBy[Them][PAWN]   | ei.attackedBy[Them][KNIGHT]
+                  | ei.attackedBy[Them][BISHOP] | ei.attackedBy[Them][QUEEN]);
+            if (b)
+                attackUnits +=  RookContactCheckBonus
+                              * count_1s<Max15>(b)
                               * (Them == pos.side_to_move() ? 2 : 1);
         }
 
@@ -719,22 +762,22 @@ namespace {
         // Enemy queen safe checks
         b = (b1 | b2) & ei.attackedBy[Them][QUEEN];
         if (b)
-            attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b);
+            attackUnits += QueenCheckBonus * count_1s<Max15>(b);
 
         // Enemy rooks safe checks
         b = b1 & ei.attackedBy[Them][ROOK];
         if (b)
-            attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b);
+            attackUnits += RookCheckBonus * count_1s<Max15>(b);
 
         // Enemy bishops safe checks
         b = b2 & ei.attackedBy[Them][BISHOP];
         if (b)
-            attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b);
+            attackUnits += BishopCheckBonus * count_1s<Max15>(b);
 
         // Enemy knights safe checks
         b = pos.attacks_from<KNIGHT>(ksq) & ei.attackedBy[Them][KNIGHT] & safe;
         if (b)
-            attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b);
+            attackUnits += KnightCheckBonus * count_1s<Max15>(b);
 
         // To index KingDangerTable[] attackUnits must be in [0, 99] range
         attackUnits = Min(99, Max(0, attackUnits));
@@ -747,6 +790,10 @@ namespace {
         bonus -= KingDangerTable[Us][attackUnits];
         margins[Us] += mg_value(KingDangerTable[Us][attackUnits]);
     }
+
+    if (Trace)
+        TracedTerms[Us][KING] = bonus;
+
     return bonus;
   }
 
@@ -795,8 +842,8 @@ namespace {
                 // If there is an enemy rook or queen attacking the pawn from behind,
                 // add all X-ray attacks by the rook or queen. Otherwise consider only
                 // the squares in the pawn's path attacked or occupied by the enemy.
-                if (   (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them))
-                    && (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<ROOK>(s)))
+                if (   (squares_in_front_of(Them, s) & pos.pieces(ROOK, QUEEN, Them))
+                    && (squares_in_front_of(Them, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<ROOK>(s)))
                     unsafeSquares = squaresToQueen;
                 else
                     unsafeSquares = squaresToQueen & (ei.attackedBy[Them][0] | pos.pieces_of_color(Them));
@@ -849,6 +896,173 @@ namespace {
   }
 
 
+  // evaluate_unstoppable_pawns() evaluates the unstoppable passed pawns for both sides
+
+  template<bool HasPopCnt>
+  Score evaluate_unstoppable_pawns(const Position& pos, EvalInfo& ei) {
+
+    const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
+
+    Bitboard b1, b2, queeningPath, candidates, supBB, sacBB;
+    Square s1, s2, queeningSquare, supSq, sacSq;
+    Color c, winnerSide, loserSide;
+    bool pathDefended, opposed;
+    int pliesToGo, movesToGo, oppMovesToGo;
+    int pliesToQueen[] = { 256, 256 };
+
+    // Step 1. Hunt for unstoppable pawns. If we find at least one, record how many plies
+    // are required for promotion
+    for (c = WHITE; c <= BLACK; c++)
+    {
+        // Skip if other side has non-pawn pieces
+        if (pos.non_pawn_material(opposite_color(c)))
+            continue;
+
+        b1 = ei.pi->passed_pawns(c);
+
+        while (b1)
+        {
+            s1 = pop_1st_bit(&b1);
+            queeningSquare = relative_square(c, make_square(square_file(s1), RANK_8));
+            queeningPath = squares_in_front_of(c, s1);
+
+            // Compute plies from queening and check direct advancement
+            movesToGo = rank_distance(s1, queeningSquare) - int(relative_rank(c, s1) == RANK_2);
+            oppMovesToGo = square_distance(pos.king_square(opposite_color(c)), queeningSquare) - int(c != pos.side_to_move());
+            pathDefended = ((ei.attackedBy[c][0] & queeningPath) == queeningPath);
+
+            if (movesToGo >= oppMovesToGo && !pathDefended)
+                continue;
+
+            // Opponent king cannot block because path is defended and position
+            // is not in check. So only friendly pieces can be blockers.
+            assert(!pos.in_check());
+            assert(queeningPath & pos.occupied_squares() == queeningPath & pos.pieces_of_color(c));
+
+            // Add moves needed to free the path from friendly pieces and retest condition
+            movesToGo += count_1s<Max15>(queeningPath & pos.pieces_of_color(c));
+
+            if (movesToGo >= oppMovesToGo && !pathDefended)
+                continue;
+
+            pliesToGo = 2 * movesToGo - int(c == pos.side_to_move());
+
+            if (pliesToGo < pliesToQueen[c])
+                pliesToQueen[c] = pliesToGo;
+        }
+    }
+
+    // Step 2. If either side cannot promote at least three plies before the other side then situation
+    // becomes too complex and we give up. Otherwise we determine the possibly "winning side"
+    if (abs(pliesToQueen[WHITE] - pliesToQueen[BLACK]) < 3)
+        return SCORE_ZERO;
+
+    winnerSide = (pliesToQueen[WHITE] < pliesToQueen[BLACK] ? WHITE : BLACK);
+    loserSide = opposite_color(winnerSide);
+
+    // Step 3. Can the losing side possibly create a new passed pawn and thus prevent the loss?
+    // We collect the potential candidates in potentialBB.
+    b1 = candidates = pos.pieces(PAWN, loserSide);
+
+    while (b1)
+    {
+        s1 = pop_1st_bit(&b1);
+
+        // Compute plies from queening
+        queeningSquare = relative_square(loserSide, make_square(square_file(s1), RANK_8));
+        movesToGo = rank_distance(s1, queeningSquare) - int(relative_rank(loserSide, s1) == RANK_2);
+        pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
+
+        // Check if (without even considering any obstacles) we're too far away or doubled
+        if (   pliesToQueen[winnerSide] + 3 <= pliesToGo
+            || (squares_in_front_of(loserSide, s1) & pos.pieces(PAWN, loserSide)))
+            clear_bit(&candidates, s1);
+    }
+
+    // If any candidate is already a passed pawn it _may_ promote in time. We give up.
+    if (candidates & ei.pi->passed_pawns(loserSide))
+        return SCORE_ZERO;
+
+    // Step 4. Check new passed pawn creation through king capturing and sacrifices
+    b1 = candidates;
+
+    while (b1)
+    {
+        s1 = pop_1st_bit(&b1);
+
+        // Compute plies from queening
+        queeningSquare = relative_square(loserSide, make_square(square_file(s1), RANK_8));
+        movesToGo = rank_distance(s1, queeningSquare) - int(relative_rank(loserSide, s1) == RANK_2);
+        pliesToGo = 2 * movesToGo - int(loserSide == pos.side_to_move());
+
+        // Generate list of obstacles
+        opposed = squares_in_front_of(loserSide, s1) & pos.pieces(PAWN, winnerSide);
+        b2 = passed_pawn_mask(loserSide, s1) & pos.pieces(PAWN, winnerSide);
+
+        assert(b2);
+
+        // How many plies does it take to remove all the obstacles?
+        int sacptg = 0;
+        int realObsCount = 0;
+        int minKingDist = 256;
+        int kingptg = 256;
+
+        while (b2)
+        {
+            s2 = pop_1st_bit(&b2);
+            movesToGo = 256;
+
+            // Check pawns that can give support to overcome obstacle, for instance
+            // black pawns: a4, b4 white: b2 then pawn in b4 is giving support.
+            if (!opposed && square_file(s1) != square_file(s2))
+            {
+                supBB = in_front_bb(winnerSide, s2 + pawn_push(winnerSide)) & neighboring_files_bb(s1) & candidates;
+
+                while (supBB) // This while-loop could be replaced with supSq = LSB/MSB(supBB) (depending on color)
+                {
+                    supSq = pop_1st_bit(&supBB);
+                    movesToGo = Min(movesToGo, square_distance(s2, supSq) - 2);
+                }
+            }
+
+            // Check pawns that can be sacrificed
+            sacBB = passed_pawn_mask(winnerSide, s2) & neighboring_files_bb(s2) & candidates & ~(1ULL << s1);
+
+            while (sacBB) // This while-loop could be replaced with sacSq = LSB/MSB(sacBB) (depending on color)
+            {
+                sacSq = pop_1st_bit(&sacBB);
+                movesToGo = Min(movesToGo, square_distance(s2, sacSq) - 2);
+            }
+
+            // Good, obstacle can be destroyed with an immediate pawn sacrifice,
+            // it's not a real obstacle and we have nothing to add to pliesToGo.
+            if (movesToGo <= 0)
+                continue;
+
+            // Plies needed to sacrifice the pawn
+            sacptg += movesToGo * 2;
+            realObsCount++;
+
+            // Plies needed for the king to capture opposing pawn
+            minKingDist = Min(minKingDist, square_distance(pos.king_square(loserSide), s2));
+            kingptg = (minKingDist + realObsCount) * 2;
+        }
+
+        // Check if pawn sacrifice plan _may_ save the day
+        if (pliesToQueen[winnerSide] + 3 > pliesToGo + sacptg)
+            return SCORE_ZERO;
+
+        // Check if king capture plan _may_ save the day (contains some false positives)
+        if (pliesToQueen[winnerSide] + 3 > pliesToGo + kingptg)
+            return SCORE_ZERO;
+    }
+
+    // Winning pawn is unstoppable and will promote as first, return big score
+    Score score = make_score(0, (Value) 0x500 - 0x20 * pliesToQueen[winnerSide]);
+    return winnerSide == WHITE ? score : -score;
+  }
+
+
   // evaluate_space() computes the space evaluation for a given side. The
   // space evaluation is a simple bonus based on the number of safe squares
   // available for minor pieces on the central four files on ranks 2--4. Safe
@@ -858,6 +1072,7 @@ namespace {
   template<Color Us, bool HasPopCnt>
   int evaluate_space(const Position& pos, EvalInfo& ei) {
 
+    const BitCountType Max15 = HasPopCnt ? CNT_POPCNT : CpuIs64Bit ? CNT64_MAX15 : CNT32_MAX15;
     const Color Them = (Us == WHITE ? BLACK : WHITE);
 
     // Find the safe squares for our pieces inside the area defined by
@@ -873,7 +1088,7 @@ namespace {
     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
 
-    return count_1s_max_15<HasPopCnt>(safe) + count_1s_max_15<HasPopCnt>(behind & safe);
+    return count_1s<Max15>(safe) + count_1s<Max15>(behind & safe);
   }
 
 
@@ -888,18 +1103,15 @@ namespace {
   // scale_by_game_phase() interpolates between a middle game and an endgame score,
   // based on game phase. It also scales the return value by a ScaleFactor array.
 
-  Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]) {
+  Value scale_by_game_phase(const Score& v, Phase ph, ScaleFactor sf) {
 
     assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
     assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
     assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
 
-    Value eg = eg_value(v);
-    ScaleFactor f = sf[eg > VALUE_ZERO ? WHITE : BLACK];
-    Value ev = Value((eg * int(f)) / SCALE_FACTOR_NORMAL);
-
+    int ev = (eg_value(v) * int(sf)) / SCALE_FACTOR_NORMAL;
     int result = (mg_value(v) * int(ph) + ev * int(128 - ph)) / 128;
-    return Value(result & ~(GrainSize - 1));
+    return Value((result + GrainSize / 2) & ~(GrainSize - 1));
   }
 
 
@@ -909,8 +1121,8 @@ namespace {
   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
 
     // Scale option value from 100 to 256
-    int mg = get_option_value_int(mgOpt) * 256 / 100;
-    int eg = get_option_value_int(egOpt) * 256 / 100;
+    int mg = Options[mgOpt].value<int>() * 256 / 100;
+    int eg = Options[egOpt].value<int>() * 256 / 100;
 
     return apply_weight(make_score(mg, eg), internalWeight);
   }
@@ -941,4 +1153,75 @@ namespace {
         for (int i = 0; i < 100; i++)
             KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);
   }
+
+
+  // trace_row() is an helper function used by tracing code to register the
+  // values of a single evaluation term.
+
+  void trace_row(const char *name, int idx) {
+
+    Score term_w = TracedTerms[WHITE][idx];
+    Score term_b = TracedTerms[BLACK][idx];
+
+    switch (idx) {
+    case PST: case IMBALANCE: case PAWN: case UNSTOPPABLE: case TOTAL:
+        TraceStream << std::setw(20) << name << " |   ---   --- |   ---   --- | "
+                    << std::setw(6)  << to_cp(mg_value(term_w)) << " "
+                    << std::setw(6)  << to_cp(eg_value(term_w)) << " \n";
+        break;
+    default:
+        TraceStream << std::setw(20) << name << " | " << std::noshowpos
+                    << std::setw(5)  << to_cp(mg_value(term_w)) << " "
+                    << std::setw(5)  << to_cp(eg_value(term_w)) << " | "
+                    << std::setw(5)  << to_cp(mg_value(term_b)) << " "
+                    << std::setw(5)  << to_cp(eg_value(term_b)) << " | "
+                    << std::showpos
+                    << std::setw(6)  << to_cp(mg_value(term_w - term_b)) << " "
+                    << std::setw(6)  << to_cp(eg_value(term_w - term_b)) << " \n";
+    }
+  }
+}
+
+
+/// trace_evaluate() is like evaluate() but instead of a value returns a string
+/// suitable to be print on stdout with the detailed descriptions and values of
+/// each evaluation term. Used mainly for debugging.
+
+std::string trace_evaluate(const Position& pos) {
+
+    Value margin;
+    std::string totals;
+
+    TraceStream.str("");
+    TraceStream << std::showpoint << std::showpos << std::fixed << std::setprecision(2);
+    memset(TracedTerms, 0, 2 * 16 * sizeof(Score));
+
+    do_evaluate<false, true>(pos, margin);
+
+    totals = TraceStream.str();
+    TraceStream.str("");
+
+    TraceStream << std::setw(21) << "Eval term " << "|    White    |    Black    |     Total     \n"
+                <<             "                     |   MG    EG  |   MG    EG  |   MG     EG   \n"
+                <<             "---------------------+-------------+-------------+---------------\n";
+
+    trace_row("Material, PST, Tempo", PST);
+    trace_row("Material imbalance", IMBALANCE);
+    trace_row("Pawns", PAWN);
+    trace_row("Knights", KNIGHT);
+    trace_row("Bishops", BISHOP);
+    trace_row("Rooks", ROOK);
+    trace_row("Queens", QUEEN);
+    trace_row("Mobility", MOBILITY);
+    trace_row("King safety", KING);
+    trace_row("Threats", THREAT);
+    trace_row("Passed pawns", PASSED);
+    trace_row("Unstoppable pawns", UNSTOPPABLE);
+    trace_row("Space", SPACE);
+
+    TraceStream <<             "---------------------+-------------+-------------+---------------\n";
+    trace_row("Total", TOTAL);
+    TraceStream << totals;
+
+    return TraceStream.str();
 }