]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
4e998bd4c32f4debc9f8a419cd8ce436ae285168
[stockfish] / src / evaluate.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-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <cassert>
23 #include <cstring>   // For std::memset
24 #include <iomanip>
25 #include <sstream>
26
27 #include "bitboard.h"
28 #include "evaluate.h"
29 #include "material.h"
30 #include "pawns.h"
31
32 namespace {
33
34   namespace Trace {
35
36     enum Tracing {NO_TRACE, TRACE};
37
38     enum Term { // The first 8 entries are for PieceType
39       MATERIAL = 8, IMBALANCE, MOBILITY, THREAT, PASSED, SPACE, TOTAL, TERM_NB
40     };
41
42     double scores[TERM_NB][COLOR_NB][PHASE_NB];
43
44     double to_cp(Value v) { return double(v) / PawnValueEg; }
45
46     void add(int idx, Color c, Score s) {
47       scores[idx][c][MG] = to_cp(mg_value(s));
48       scores[idx][c][EG] = to_cp(eg_value(s));
49     }
50
51     void add(int idx, Score w, Score b = SCORE_ZERO) {
52       add(idx, WHITE, w); add(idx, BLACK, b);
53     }
54
55     std::ostream& operator<<(std::ostream& os, Term t) {
56
57       if (t == MATERIAL || t == IMBALANCE || t == Term(PAWN) || t == TOTAL)
58           os << "  ---   --- |   ---   --- | ";
59       else
60           os << std::setw(5) << scores[t][WHITE][MG] << " "
61              << std::setw(5) << scores[t][WHITE][EG] << " | "
62              << std::setw(5) << scores[t][BLACK][MG] << " "
63              << std::setw(5) << scores[t][BLACK][EG] << " | ";
64
65       os << std::setw(5) << scores[t][WHITE][MG] - scores[t][BLACK][MG] << " "
66          << std::setw(5) << scores[t][WHITE][EG] - scores[t][BLACK][EG] << " \n";
67
68       return os;
69     }
70   }
71
72   using namespace Trace;
73
74   // Evaluation class contains various information computed and collected
75   // by the evaluation functions.
76   template<Tracing T = NO_TRACE>
77   class Evaluation {
78
79   public:
80     Evaluation() = delete;
81     Evaluation(const Position& p) : pos(p) {};
82     Evaluation& operator=(const Evaluation&) = delete;
83
84     Value value();
85
86   private:
87     // Evaluation helpers (used when calling value())
88     template<Color Us> void initialize();
89     template<Color Us> Score evaluate_king();
90     template<Color Us> Score evaluate_threats();
91     template<Color Us> Score evaluate_passer_pawns();
92     template<Color Us> Score evaluate_space();
93     template<Color Us, PieceType Pt> Score evaluate_pieces();
94     ScaleFactor evaluate_scale_factor(Value eg);
95     Score evaluate_initiative(Value eg);
96
97     // Data members
98     const Position& pos;
99     Material::Entry* me;
100     Pawns::Entry* pe;
101     Bitboard mobilityArea[COLOR_NB];
102     Score mobility[COLOR_NB] = { SCORE_ZERO, SCORE_ZERO };
103
104     // attackedBy[color][piece type] is a bitboard representing all squares
105     // attacked by a given color and piece type (can be also ALL_PIECES).
106     Bitboard attackedBy[COLOR_NB][PIECE_TYPE_NB];
107
108     // attackedBy2[color] are the squares attacked by 2 pieces of a given color,
109     // possibly via x-ray or by one pawn and one piece. Diagonal x-ray through
110     // pawn or squares attacked by 2 pawns are not explicitly added.
111     Bitboard attackedBy2[COLOR_NB];
112
113     // kingRing[color] is the zone around the king which is considered
114     // by the king safety evaluation. This consists of the squares directly
115     // adjacent to the king, and (only for a king on its first rank) the
116     // squares two ranks in front of the king. For instance, if black's king
117     // is on g8, kingRing[BLACK] is a bitboard containing the squares f8, h8,
118     // f7, g7, h7, f6, g6 and h6.
119     Bitboard kingRing[COLOR_NB];
120
121     // kingAttackersCount[color] is the number of pieces of the given color
122     // which attack a square in the kingRing of the enemy king.
123     int kingAttackersCount[COLOR_NB];
124
125     // kingAttackersWeight[color] is the sum of the "weights" of the pieces of the
126     // given color which attack a square in the kingRing of the enemy king. The
127     // weights of the individual piece types are given by the elements in the
128     // KingAttackWeights array.
129     int kingAttackersWeight[COLOR_NB];
130
131     // kingAdjacentZoneAttacksCount[color] is the number of attacks by the given
132     // color to squares directly adjacent to the enemy king. Pieces which attack
133     // more than one square are counted multiple times. For instance, if there is
134     // a white knight on g5 and black's king is on g8, this white knight adds 2
135     // to kingAdjacentZoneAttacksCount[WHITE].
136     int kingAdjacentZoneAttacksCount[COLOR_NB];
137   };
138
139   #define V(v) Value(v)
140   #define S(mg, eg) make_score(mg, eg)
141
142   // MobilityBonus[PieceType-2][attacked] contains bonuses for middle and end game,
143   // indexed by piece type and number of attacked squares in the mobility area.
144   const Score MobilityBonus[][32] = {
145     { S(-75,-76), S(-57,-54), S( -9,-28), S( -2,-10), S(  6,  5), S( 14, 12), // Knights
146       S( 22, 26), S( 29, 29), S( 36, 29) },
147     { S(-48,-59), S(-20,-23), S( 16, -3), S( 26, 13), S( 38, 24), S( 51, 42), // Bishops
148       S( 55, 54), S( 63, 57), S( 63, 65), S( 68, 73), S( 81, 78), S( 81, 86),
149       S( 91, 88), S( 98, 97) },
150     { S(-58,-76), S(-27,-18), S(-15, 28), S(-10, 55), S( -5, 69), S( -2, 82), // Rooks
151       S(  9,112), S( 16,118), S( 30,132), S( 29,142), S( 32,155), S( 38,165),
152       S( 46,166), S( 48,169), S( 58,171) },
153     { S(-39,-36), S(-21,-15), S(  3,  8), S(  3, 18), S( 14, 34), S( 22, 54), // Queens
154       S( 28, 61), S( 41, 73), S( 43, 79), S( 48, 92), S( 56, 94), S( 60,104),
155       S( 60,113), S( 66,120), S( 67,123), S( 70,126), S( 71,133), S( 73,136),
156       S( 79,140), S( 88,143), S( 88,148), S( 99,166), S(102,170), S(102,175),
157       S(106,184), S(109,191), S(113,206), S(116,212) }
158   };
159
160   // Outpost[knight/bishop][supported by pawn] contains bonuses for minor
161   // pieces if they can reach an outpost square, bigger if that square is
162   // supported by a pawn. If the minor piece occupies an outpost square
163   // then score is doubled.
164   const Score Outpost[][2] = {
165     { S(22, 6), S(33, 9) }, // Knight
166     { S( 9, 2), S(14, 4) }  // Bishop
167   };
168
169   // RookOnFile[semiopen/open] contains bonuses for each rook when there is no
170   // friendly pawn on the rook file.
171   const Score RookOnFile[] = { S(20, 7), S(45, 20) };
172
173   // ThreatByMinor/ByRook[attacked PieceType] contains bonuses according to
174   // which piece type attacks which one. Attacks on lesser pieces which are
175   // pawn-defended are not considered.
176   const Score ThreatByMinor[PIECE_TYPE_NB] = {
177     S(0, 0), S(0, 33), S(45, 43), S(46, 47), S(72, 107), S(48, 118)
178   };
179
180   const Score ThreatByRook[PIECE_TYPE_NB] = {
181     S(0, 0), S(0, 25), S(40, 62), S(40, 59), S(0, 34), S(35, 48)
182   };
183
184   // ThreatByKing[on one/on many] contains bonuses for king attacks on
185   // pawns or pieces which are not pawn-defended.
186   const Score ThreatByKing[] = { S(3, 62), S(9, 138) };
187
188   // Passed[mg/eg][Rank] contains midgame and endgame bonuses for passed pawns.
189   // We don't use a Score because we process the two components independently.
190   const Value Passed[][RANK_NB] = {
191     { V(5), V( 5), V(31), V(73), V(166), V(252) },
192     { V(7), V(14), V(38), V(73), V(166), V(252) }
193   };
194
195   // PassedFile[File] contains a bonus according to the file of a passed pawn
196   const Score PassedFile[FILE_NB] = {
197     S(  9, 10), S( 2, 10), S( 1, -8), S(-20,-12),
198     S(-20,-12), S( 1, -8), S( 2, 10), S(  9, 10)
199   };
200
201   // KingProtector[PieceType-2] contains a bonus according to distance from king
202   const Score KingProtector[] = { S(-3, -5), S(-4, -3), S(-3, 0), S(-1, 1) };
203
204   // Assorted bonuses and penalties used by evaluation
205   const Score MinorBehindPawn     = S( 16,  0);
206   const Score BishopPawns         = S(  8, 12);
207   const Score RookOnPawn          = S(  8, 24);
208   const Score TrappedRook         = S( 92,  0);
209   const Score WeakQueen           = S( 50, 10);
210   const Score OtherCheck          = S( 10, 10);
211   const Score CloseEnemies        = S(  7,  0);
212   const Score PawnlessFlank       = S( 20, 80);
213   const Score ThreatByHangingPawn = S( 71, 61);
214   const Score ThreatBySafePawn    = S(182,175);
215   const Score ThreatByRank        = S( 16,  3);
216   const Score Hanging             = S( 48, 27);
217   const Score ThreatByPawnPush    = S( 38, 22);
218   const Score HinderPassedPawn    = S(  7,  0);
219
220   // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
221   // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
222   // happen in Chess960 games.
223   const Score TrappedBishopA1H1 = S(50, 50);
224
225   #undef S
226   #undef V
227
228   // KingAttackWeights[PieceType] contains king attack weights by piece type
229   const int KingAttackWeights[PIECE_TYPE_NB] = { 0, 0, 78, 56, 45, 11 };
230
231   // Penalties for enemy's safe checks
232   const int QueenCheck  = 780;
233   const int RookCheck   = 880;
234   const int BishopCheck = 435;
235   const int KnightCheck = 790;
236
237   // Threshold for lazy and space evaluation
238   const Value LazyThreshold  = Value(1500);
239   const Value SpaceThreshold = Value(12222);
240
241
242   // initialize() computes king and pawn attacks, and the king ring bitboard
243   // for a given color. This is done at the beginning of the evaluation.
244
245   template<Tracing T> template<Color Us>
246   void Evaluation<T>::initialize() {
247
248     const Color  Them = (Us == WHITE ? BLACK : WHITE);
249     const Square Up   = (Us == WHITE ? NORTH : SOUTH);
250     const Square Down = (Us == WHITE ? SOUTH : NORTH);
251     const Bitboard LowRanks = (Us == WHITE ? Rank2BB | Rank3BB: Rank7BB | Rank6BB);
252
253     // Find our pawns on the first two ranks, and those which are blocked
254     Bitboard b = pos.pieces(Us, PAWN) & (shift<Down>(pos.pieces()) | LowRanks);
255
256     // Squares occupied by those pawns, by our king, or controlled by enemy pawns
257     // are excluded from the mobility area.
258     mobilityArea[Us] = ~(b | pos.square<KING>(Us) | pe->pawn_attacks(Them));
259
260     // Initialise the attack bitboards with the king and pawn information
261     b = attackedBy[Us][KING] = pos.attacks_from<KING>(pos.square<KING>(Us));
262     attackedBy[Us][PAWN] = pe->pawn_attacks(Us);
263
264     attackedBy2[Us]            = b & attackedBy[Us][PAWN];
265     attackedBy[Us][ALL_PIECES] = b | attackedBy[Us][PAWN];
266
267     // Init our king safety tables only if we are going to use them
268     if (pos.non_pawn_material(Them) >= RookValueMg + KnightValueMg)
269     {
270         kingRing[Us] = b;
271         if (relative_rank(Us, pos.square<KING>(Us)) == RANK_1)
272             kingRing[Us] |= shift<Up>(b);
273
274         kingAttackersCount[Them] = popcount(b & pe->pawn_attacks(Them));
275         kingAdjacentZoneAttacksCount[Them] = kingAttackersWeight[Them] = 0;
276     }
277     else
278         kingRing[Us] = kingAttackersCount[Them] = 0;
279   }
280
281
282   // evaluate_pieces() assigns bonuses and penalties to the pieces of a given
283   // color and type.
284
285   template<Tracing T>  template<Color Us, PieceType Pt>
286   Score Evaluation<T>::evaluate_pieces() {
287
288     const Color Them = (Us == WHITE ? BLACK : WHITE);
289     const Bitboard OutpostRanks = (Us == WHITE ? Rank4BB | Rank5BB | Rank6BB
290                                                : Rank5BB | Rank4BB | Rank3BB);
291     const Square* pl = pos.squares<Pt>(Us);
292
293     Bitboard b, bb;
294     Square s;
295     Score score = SCORE_ZERO;
296
297     attackedBy[Us][Pt] = 0;
298
299     while ((s = *pl++) != SQ_NONE)
300     {
301         // Find attacked squares, including x-ray attacks for bishops and rooks
302         b = Pt == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN))
303           : Pt ==   ROOK ? attacks_bb<  ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN))
304                          : pos.attacks_from<Pt>(s);
305
306         if (pos.pinned_pieces(Us) & s)
307             b &= LineBB[pos.square<KING>(Us)][s];
308
309         attackedBy2[Us] |= attackedBy[Us][ALL_PIECES] & b;
310         attackedBy[Us][ALL_PIECES] |= attackedBy[Us][Pt] |= b;
311
312         if (b & kingRing[Them])
313         {
314             kingAttackersCount[Us]++;
315             kingAttackersWeight[Us] += KingAttackWeights[Pt];
316             kingAdjacentZoneAttacksCount[Us] += popcount(b & attackedBy[Them][KING]);
317         }
318
319         int mob = popcount(b & mobilityArea[Us]);
320
321         mobility[Us] += MobilityBonus[Pt - 2][mob];
322
323         // Bonus for this piece as a king protector
324         score += KingProtector[Pt - 2] * distance(s, pos.square<KING>(Us));
325
326         if (Pt == BISHOP || Pt == KNIGHT)
327         {
328             // Bonus for outpost squares
329             bb = OutpostRanks & ~pe->pawn_attacks_span(Them);
330             if (bb & s)
331                 score += Outpost[Pt == BISHOP][!!(attackedBy[Us][PAWN] & s)] * 2;
332             else
333             {
334                 bb &= b & ~pos.pieces(Us);
335                 if (bb)
336                    score += Outpost[Pt == BISHOP][!!(attackedBy[Us][PAWN] & bb)];
337             }
338
339             // Bonus when behind a pawn
340             if (    relative_rank(Us, s) < RANK_5
341                 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
342                 score += MinorBehindPawn;
343
344             // Penalty for pawns on the same color square as the bishop
345             if (Pt == BISHOP)
346                 score -= BishopPawns * pe->pawns_on_same_color_squares(Us, s);
347
348             // An important Chess960 pattern: A cornered bishop blocked by a friendly
349             // pawn diagonally in front of it is a very serious problem, especially
350             // when that pawn is also blocked.
351             if (   Pt == BISHOP
352                 && pos.is_chess960()
353                 && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
354             {
355                 Square d = pawn_push(Us) + (file_of(s) == FILE_A ? EAST : WEST);
356                 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
357                     score -= !pos.empty(s + d + pawn_push(Us))                ? TrappedBishopA1H1 * 4
358                             : pos.piece_on(s + d + d) == make_piece(Us, PAWN) ? TrappedBishopA1H1 * 2
359                                                                               : TrappedBishopA1H1;
360             }
361         }
362
363         if (Pt == ROOK)
364         {
365             // Bonus for aligning with enemy pawns on the same rank/file
366             if (relative_rank(Us, s) >= RANK_5)
367                 score += RookOnPawn * popcount(pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s]);
368
369             // Bonus when on an open or semi-open file
370             if (pe->semiopen_file(Us, file_of(s)))
371                 score += RookOnFile[!!pe->semiopen_file(Them, file_of(s))];
372
373             // Penalty when trapped by the king, even more if the king cannot castle
374             else if (mob <= 3)
375             {
376                 Square ksq = pos.square<KING>(Us);
377
378                 if (   ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
379                     && !pe->semiopen_side(Us, file_of(ksq), file_of(s) < file_of(ksq)))
380                     score -= (TrappedRook - make_score(mob * 22, 0)) * (1 + !pos.can_castle(Us));
381             }
382         }
383
384         if (Pt == QUEEN)
385         {
386             // Penalty if any relative pin or discovered attack against the queen
387             Bitboard pinners;
388             if (pos.slider_blockers(pos.pieces(Them, ROOK, BISHOP), s, pinners))
389                 score -= WeakQueen;
390         }
391     }
392
393     if (T)
394         Trace::add(Pt, Us, score);
395
396     return score;
397   }
398
399
400   // evaluate_king() assigns bonuses and penalties to a king of a given color
401
402   const Bitboard QueenSide   = FileABB | FileBBB | FileCBB | FileDBB;
403   const Bitboard CenterFiles = FileCBB | FileDBB | FileEBB | FileFBB;
404   const Bitboard KingSide    = FileEBB | FileFBB | FileGBB | FileHBB;
405
406   const Bitboard KingFlank[FILE_NB] = {
407     QueenSide, QueenSide, QueenSide, CenterFiles, CenterFiles, KingSide, KingSide, KingSide
408   };
409
410   template<Tracing T>  template<Color Us>
411   Score Evaluation<T>::evaluate_king() {
412
413     const Color Them    = (Us == WHITE ? BLACK : WHITE);
414     const Square Up     = (Us == WHITE ? NORTH : SOUTH);
415     const Bitboard Camp = (Us == WHITE ? ~Bitboard(0) ^ Rank6BB ^ Rank7BB ^ Rank8BB
416                                        : ~Bitboard(0) ^ Rank1BB ^ Rank2BB ^ Rank3BB);
417
418     const Square ksq = pos.square<KING>(Us);
419     Bitboard undefended, b, b1, b2, safe, other;
420     int kingDanger;
421
422     // King shelter and enemy pawns storm
423     Score score = pe->king_safety<Us>(pos, ksq);
424
425     // Main king safety evaluation
426     if (kingAttackersCount[Them] > (1 - pos.count<QUEEN>(Them)))
427     {
428         // Find the attacked squares which are defended only by our king...
429         undefended =   attackedBy[Them][ALL_PIECES]
430                     &  attackedBy[Us][KING]
431                     & ~attackedBy2[Us];
432
433         // ... and those which are not defended at all in the larger king ring
434         b =  attackedBy[Them][ALL_PIECES] & ~attackedBy[Us][ALL_PIECES]
435            & kingRing[Us] & ~pos.pieces(Them);
436
437         // Initialize the 'kingDanger' variable, which will be transformed
438         // later into a king danger score. The initial value is based on the
439         // number and types of the enemy's attacking pieces, the number of
440         // attacked and undefended squares around our king and the quality of
441         // the pawn shelter (current 'score' value).
442         kingDanger =        kingAttackersCount[Them] * kingAttackersWeight[Them]
443                     + 102 * kingAdjacentZoneAttacksCount[Them]
444                     + 201 * popcount(undefended)
445                     + 143 * (popcount(b) + !!pos.pinned_pieces(Us))
446                     - 848 * !pos.count<QUEEN>(Them)
447                     -   9 * mg_value(score) / 8
448                     +  40;
449
450         // Analyse the safe enemy's checks which are possible on next move
451         safe  = ~pos.pieces(Them);
452         safe &= ~attackedBy[Us][ALL_PIECES] | (undefended & attackedBy2[Them]);
453
454         b1 = pos.attacks_from<  ROOK>(ksq);
455         b2 = pos.attacks_from<BISHOP>(ksq);
456
457         // Enemy queen safe checks
458         if ((b1 | b2) & attackedBy[Them][QUEEN] & safe)
459             kingDanger += QueenCheck;
460
461         // For minors and rooks, also consider the square safe if attacked twice,
462         // and only defended by our queen.
463         safe |=  attackedBy2[Them]
464                & ~(attackedBy2[Us] | pos.pieces(Them))
465                & attackedBy[Us][QUEEN];
466
467         // Some other potential checks are also analysed, even from squares
468         // currently occupied by the opponent own pieces, as long as the square
469         // is not attacked by our pawns, and is not occupied by a blocked pawn.
470         other = ~(   attackedBy[Us][PAWN]
471                   | (pos.pieces(Them, PAWN) & shift<Up>(pos.pieces(PAWN))));
472
473         // Enemy rooks safe and other checks
474         if (b1 & attackedBy[Them][ROOK] & safe)
475             kingDanger += RookCheck;
476
477         else if (b1 & attackedBy[Them][ROOK] & other)
478             score -= OtherCheck;
479
480         // Enemy bishops safe and other checks
481         if (b2 & attackedBy[Them][BISHOP] & safe)
482             kingDanger += BishopCheck;
483
484         else if (b2 & attackedBy[Them][BISHOP] & other)
485             score -= OtherCheck;
486
487         // Enemy knights safe and other checks
488         b = pos.attacks_from<KNIGHT>(ksq) & attackedBy[Them][KNIGHT];
489         if (b & safe)
490             kingDanger += KnightCheck;
491
492         else if (b & other)
493             score -= OtherCheck;
494
495         // Transform the kingDanger units into a Score, and substract it from the evaluation
496         if (kingDanger > 0)
497             score -= make_score(kingDanger * kingDanger / 4096, kingDanger / 16);
498     }
499
500     // King tropism: firstly, find squares that opponent attacks in our king flank
501     File kf = file_of(ksq);
502     b = attackedBy[Them][ALL_PIECES] & KingFlank[kf] & Camp;
503
504     assert(((Us == WHITE ? b << 4 : b >> 4) & b) == 0);
505     assert(popcount(Us == WHITE ? b << 4 : b >> 4) == popcount(b));
506
507     // Secondly, add the squares which are attacked twice in that flank and
508     // which are not defended by our pawns.
509     b =  (Us == WHITE ? b << 4 : b >> 4)
510        | (b & attackedBy2[Them] & ~attackedBy[Us][PAWN]);
511
512     score -= CloseEnemies * popcount(b);
513
514     // Penalty when our king is on a pawnless flank
515     if (!(pos.pieces(PAWN) & KingFlank[kf]))
516         score -= PawnlessFlank;
517
518     if (T)
519         Trace::add(KING, Us, score);
520
521     return score;
522   }
523
524
525   // evaluate_threats() assigns bonuses according to the types of the attacking
526   // and the attacked pieces.
527
528   template<Tracing T>  template<Color Us>
529   Score Evaluation<T>::evaluate_threats() {
530
531     const Color Them        = (Us == WHITE ? BLACK      : WHITE);
532     const Square Up         = (Us == WHITE ? NORTH      : SOUTH);
533     const Square Left       = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
534     const Square Right      = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
535     const Bitboard TRank2BB = (Us == WHITE ? Rank2BB    : Rank7BB);
536     const Bitboard TRank7BB = (Us == WHITE ? Rank7BB    : Rank2BB);
537
538     Bitboard b, weak, defended, stronglyProtected, safeThreats;
539     Score score = SCORE_ZERO;
540
541     // Non-pawn enemies attacked by a pawn
542     weak = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & attackedBy[Us][PAWN];
543
544     if (weak)
545     {
546         b = pos.pieces(Us, PAWN) & ( ~attackedBy[Them][ALL_PIECES]
547                                     | attackedBy[Us][ALL_PIECES]);
548
549         safeThreats = (shift<Right>(b) | shift<Left>(b)) & weak;
550
551         score += ThreatBySafePawn * popcount(safeThreats);
552
553         if (weak ^ safeThreats)
554             score += ThreatByHangingPawn;
555     }
556
557     // Squares strongly protected by the opponent, either because they attack the
558     // square with a pawn, or because they attack the square twice and we don't.
559     stronglyProtected =  attackedBy[Them][PAWN]
560                        | (attackedBy2[Them] & ~attackedBy2[Us]);
561
562     // Non-pawn enemies, strongly protected
563     defended =  (pos.pieces(Them) ^ pos.pieces(Them, PAWN))
564               & stronglyProtected;
565
566     // Enemies not strongly protected and under our attack
567     weak =   pos.pieces(Them)
568           & ~stronglyProtected
569           &  attackedBy[Us][ALL_PIECES];
570
571     // Add a bonus according to the kind of attacking pieces
572     if (defended | weak)
573     {
574         b = (defended | weak) & (attackedBy[Us][KNIGHT] | attackedBy[Us][BISHOP]);
575         while (b)
576         {
577             Square s = pop_lsb(&b);
578             score += ThreatByMinor[type_of(pos.piece_on(s))];
579             if (type_of(pos.piece_on(s)) != PAWN)
580                 score += ThreatByRank * (int)relative_rank(Them, s);
581         }
582
583         b = (pos.pieces(Them, QUEEN) | weak) & attackedBy[Us][ROOK];
584         while (b)
585         {
586             Square s = pop_lsb(&b);
587             score += ThreatByRook[type_of(pos.piece_on(s))];
588             if (type_of(pos.piece_on(s)) != PAWN)
589                 score += ThreatByRank * (int)relative_rank(Them, s);
590         }
591
592         score += Hanging * popcount(weak & ~attackedBy[Them][ALL_PIECES]);
593
594         b = weak & attackedBy[Us][KING];
595         if (b)
596             score += ThreatByKing[more_than_one(b)];
597     }
598
599     // Bonus if some pawns can safely push and attack an enemy piece
600     b = pos.pieces(Us, PAWN) & ~TRank7BB;
601     b = shift<Up>(b | (shift<Up>(b & TRank2BB) & ~pos.pieces()));
602
603     b &=  ~pos.pieces()
604         & ~attackedBy[Them][PAWN]
605         & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
606
607     b =  (shift<Left>(b) | shift<Right>(b))
608        &  pos.pieces(Them)
609        & ~attackedBy[Us][PAWN];
610
611     score += ThreatByPawnPush * popcount(b);
612
613     if (T)
614         Trace::add(THREAT, Us, score);
615
616     return score;
617   }
618
619
620   // evaluate_passer_pawns() evaluates the passed pawns and candidate passed
621   // pawns of the given color.
622
623   template<Tracing T>  template<Color Us>
624   Score Evaluation<T>::evaluate_passer_pawns() {
625
626     const Color Them = (Us == WHITE ? BLACK : WHITE);
627
628     Bitboard b, bb, squaresToQueen, defendedSquares, unsafeSquares;
629     Score score = SCORE_ZERO;
630
631     b = pe->passed_pawns(Us);
632
633     while (b)
634     {
635         Square s = pop_lsb(&b);
636
637         assert(!(pos.pieces(Them, PAWN) & forward_bb(Us, s + pawn_push(Us))));
638
639         bb = forward_bb(Us, s) & (attackedBy[Them][ALL_PIECES] | pos.pieces(Them));
640         score -= HinderPassedPawn * popcount(bb);
641
642         int r = relative_rank(Us, s) - RANK_2;
643         int rr = r * (r - 1);
644
645         Value mbonus = Passed[MG][r], ebonus = Passed[EG][r];
646
647         if (rr)
648         {
649             Square blockSq = s + pawn_push(Us);
650
651             // Adjust bonus based on the king's proximity
652             ebonus +=  distance(pos.square<KING>(Them), blockSq) * 5 * rr
653                      - distance(pos.square<KING>(  Us), blockSq) * 2 * rr;
654
655             // If blockSq is not the queening square then consider also a second push
656             if (relative_rank(Us, blockSq) != RANK_8)
657                 ebonus -= distance(pos.square<KING>(Us), blockSq + pawn_push(Us)) * rr;
658
659             // If the pawn is free to advance, then increase the bonus
660             if (pos.empty(blockSq))
661             {
662                 // If there is a rook or queen attacking/defending the pawn from behind,
663                 // consider all the squaresToQueen. Otherwise consider only the squares
664                 // in the pawn's path attacked or occupied by the enemy.
665                 defendedSquares = unsafeSquares = squaresToQueen = forward_bb(Us, s);
666
667                 bb = forward_bb(Them, s) & pos.pieces(ROOK, QUEEN) & pos.attacks_from<ROOK>(s);
668
669                 if (!(pos.pieces(Us) & bb))
670                     defendedSquares &= attackedBy[Us][ALL_PIECES];
671
672                 if (!(pos.pieces(Them) & bb))
673                     unsafeSquares &= attackedBy[Them][ALL_PIECES] | pos.pieces(Them);
674
675                 // If there aren't any enemy attacks, assign a big bonus. Otherwise
676                 // assign a smaller bonus if the block square isn't attacked.
677                 int k = !unsafeSquares ? 18 : !(unsafeSquares & blockSq) ? 8 : 0;
678
679                 // If the path to the queen is fully defended, assign a big bonus.
680                 // Otherwise assign a smaller bonus if the block square is defended.
681                 if (defendedSquares == squaresToQueen)
682                     k += 6;
683
684                 else if (defendedSquares & blockSq)
685                     k += 4;
686
687                 mbonus += k * rr, ebonus += k * rr;
688             }
689             else if (pos.pieces(Us) & blockSq)
690                 mbonus += rr + r * 2, ebonus += rr + r * 2;
691         } // rr != 0
692
693         // Scale down bonus for candidate passers which need more than one
694         // pawn push to become passed or have a pawn in front of them.
695         if (!pos.pawn_passed(Us, s + pawn_push(Us)) || (pos.pieces(PAWN) & forward_bb(Us, s)))
696             mbonus /= 2, ebonus /= 2;
697
698         score += make_score(mbonus, ebonus) + PassedFile[file_of(s)];
699     }
700
701     if (T)
702         Trace::add(PASSED, Us, score);
703
704     return score;
705   }
706
707
708   // evaluate_space() computes the space evaluation for a given side. The
709   // space evaluation is a simple bonus based on the number of safe squares
710   // available for minor pieces on the central four files on ranks 2--4. Safe
711   // squares one, two or three squares behind a friendly pawn are counted
712   // twice. Finally, the space bonus is multiplied by a weight. The aim is to
713   // improve play on game opening.
714
715   template<Tracing T>  template<Color Us>
716   Score Evaluation<T>::evaluate_space() {
717
718     const Color Them = (Us == WHITE ? BLACK : WHITE);
719     const Bitboard SpaceMask =
720       Us == WHITE ? CenterFiles & (Rank2BB | Rank3BB | Rank4BB)
721                   : CenterFiles & (Rank7BB | Rank6BB | Rank5BB);
722
723     // Find the safe squares for our pieces inside the area defined by
724     // SpaceMask. A square is unsafe if it is attacked by an enemy
725     // pawn, or if it is undefended and attacked by an enemy piece.
726     Bitboard safe =   SpaceMask
727                    & ~pos.pieces(Us, PAWN)
728                    & ~attackedBy[Them][PAWN]
729                    & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
730
731     // Find all squares which are at most three squares behind some friendly pawn
732     Bitboard behind = pos.pieces(Us, PAWN);
733     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
734     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
735
736     // Since SpaceMask[Us] is fully on our half of the board...
737     assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
738
739     // ...count safe + (behind & safe) with a single popcount.
740     int bonus = popcount((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
741     int weight = pos.count<ALL_PIECES>(Us) - 2 * pe->open_files();
742
743     return make_score(bonus * weight * weight / 16, 0);
744   }
745
746
747   // evaluate_initiative() computes the initiative correction value for the
748   // position, i.e., second order bonus/malus based on the known attacking/defending
749   // status of the players.
750
751   template<Tracing T>
752   Score Evaluation<T>::evaluate_initiative(Value eg) {
753
754     int kingDistance =  distance<File>(pos.square<KING>(WHITE), pos.square<KING>(BLACK))
755                       - distance<Rank>(pos.square<KING>(WHITE), pos.square<KING>(BLACK));
756     bool bothFlanks = (pos.pieces(PAWN) & QueenSide) && (pos.pieces(PAWN) & KingSide);
757
758     // Compute the initiative bonus for the attacking side
759     int initiative = 8 * (pe->pawn_asymmetry() + kingDistance - 17) + 12 * pos.count<PAWN>() + 16 * bothFlanks;
760
761     // Now apply the bonus: note that we find the attacking side by extracting
762     // the sign of the endgame value, and that we carefully cap the bonus so
763     // that the endgame score will never change sign after the bonus.
764     int v = ((eg > 0) - (eg < 0)) * std::max(initiative, -abs(eg));
765
766     return make_score(0, v);
767   }
768
769
770   // evaluate_scale_factor() computes the scale factor for the winning side
771
772   template<Tracing T>
773   ScaleFactor Evaluation<T>::evaluate_scale_factor(Value eg) {
774
775     Color strongSide = eg > VALUE_DRAW ? WHITE : BLACK;
776     ScaleFactor sf = me->scale_factor(pos, strongSide);
777
778     // If we don't already have an unusual scale factor, check for certain
779     // types of endgames, and use a lower scale for those.
780     if (sf == SCALE_FACTOR_NORMAL || sf == SCALE_FACTOR_ONEPAWN)
781     {
782         if (pos.opposite_bishops())
783         {
784             // Endgame with opposite-colored bishops and no other pieces (ignoring pawns)
785             // is almost a draw, in case of KBP vs KB, it is even more a draw.
786             if (   pos.non_pawn_material(WHITE) == BishopValueMg
787                 && pos.non_pawn_material(BLACK) == BishopValueMg)
788                 return more_than_one(pos.pieces(PAWN)) ? ScaleFactor(31) : ScaleFactor(9);
789
790             // Endgame with opposite-colored bishops, but also other pieces. Still
791             // a bit drawish, but not as drawish as with only the two bishops.
792             return ScaleFactor(46);
793         }
794         // Endings where weaker side can place his king in front of the opponent's
795         // pawns are drawish.
796         else if (    abs(eg) <= BishopValueEg
797                  &&  pos.count<PAWN>(strongSide) <= 2
798                  && !pos.pawn_passed(~strongSide, pos.square<KING>(~strongSide)))
799             return ScaleFactor(37 + 7 * pos.count<PAWN>(strongSide));
800     }
801
802     return sf;
803   }
804
805
806   // value() is the main function of the class. It computes the various parts of
807   // the evaluation and returns the value of the position from the point of view
808   // of the side to move.
809
810   template<Tracing T>
811   Value Evaluation<T>::value() {
812
813     assert(!pos.checkers());
814
815     // Probe the material hash table
816     me = Material::probe(pos);
817
818     // If we have a specialized evaluation function for the current material
819     // configuration, call it and return.
820     if (me->specialized_eval_exists())
821         return me->evaluate(pos);
822
823     // Initialize score by reading the incrementally updated scores included in
824     // the position object (material + piece square tables) and the material
825     // imbalance. Score is computed internally from the white point of view.
826     Score score = pos.psq_score() + me->imbalance();
827
828     // Probe the pawn hash table
829     pe = Pawns::probe(pos);
830     score += pe->pawns_score();
831
832     // Early exit if score is high
833     Value v = (mg_value(score) + eg_value(score)) / 2;
834     if (abs(v) > LazyThreshold)
835        return pos.side_to_move() == WHITE ? v : -v;
836
837     // Main evaluation begins here
838
839     initialize<WHITE>();
840     initialize<BLACK>();
841
842     score += evaluate_pieces<WHITE, KNIGHT>() - evaluate_pieces<BLACK, KNIGHT>();
843     score += evaluate_pieces<WHITE, BISHOP>() - evaluate_pieces<BLACK, BISHOP>();
844     score += evaluate_pieces<WHITE, ROOK  >() - evaluate_pieces<BLACK, ROOK  >();
845     score += evaluate_pieces<WHITE, QUEEN >() - evaluate_pieces<BLACK, QUEEN >();
846
847     score += mobility[WHITE] - mobility[BLACK];
848
849     score +=  evaluate_king<WHITE>()
850             - evaluate_king<BLACK>();
851
852     score +=  evaluate_threats<WHITE>()
853             - evaluate_threats<BLACK>();
854
855     score +=  evaluate_passer_pawns<WHITE>()
856             - evaluate_passer_pawns<BLACK>();
857
858     if (pos.non_pawn_material() >= SpaceThreshold)
859         score +=  evaluate_space<WHITE>()
860                 - evaluate_space<BLACK>();
861
862     score += evaluate_initiative(eg_value(score));
863
864     // Interpolate between a middlegame and a (scaled by 'sf') endgame score
865     ScaleFactor sf = evaluate_scale_factor(eg_value(score));
866     v =  mg_value(score) * int(me->game_phase())
867        + eg_value(score) * int(PHASE_MIDGAME - me->game_phase()) * sf / SCALE_FACTOR_NORMAL;
868
869     v /= int(PHASE_MIDGAME);
870
871     // In case of tracing add all remaining individual evaluation terms
872     if (T)
873     {
874         Trace::add(MATERIAL, pos.psq_score());
875         Trace::add(IMBALANCE, me->imbalance());
876         Trace::add(PAWN, pe->pawns_score());
877         Trace::add(MOBILITY, mobility[WHITE], mobility[BLACK]);
878         if (pos.non_pawn_material() >= SpaceThreshold)
879             Trace::add(SPACE, evaluate_space<WHITE>()
880                             , evaluate_space<BLACK>());
881         Trace::add(TOTAL, score);
882     }
883
884     return (pos.side_to_move() == WHITE ? v : -v) + Eval::Tempo; // Side to move point of view
885   }
886
887 } // namespace
888
889
890 /// evaluate() is the evaluator for the outer world. It returns a static evaluation
891 /// of the position from the point of view of the side to move.
892
893 Value Eval::evaluate(const Position& pos)
894 {
895    return Evaluation<>(pos).value();
896 }
897
898 /// trace() is like evaluate(), but instead of returning a value, it returns
899 /// a string (suitable for outputting to stdout) that contains the detailed
900 /// descriptions and values of each evaluation term. Useful for debugging.
901
902 std::string Eval::trace(const Position& pos) {
903
904   std::memset(scores, 0, sizeof(scores));
905
906   Value v = Evaluation<TRACE>(pos).value();
907   v = pos.side_to_move() == WHITE ? v : -v; // White's point of view
908
909   std::stringstream ss;
910   ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2)
911      << "      Eval term |    White    |    Black    |    Total    \n"
912      << "                |   MG    EG  |   MG    EG  |   MG    EG  \n"
913      << "----------------+-------------+-------------+-------------\n"
914      << "       Material | " << Term(MATERIAL)
915      << "      Imbalance | " << Term(IMBALANCE)
916      << "          Pawns | " << Term(PAWN)
917      << "        Knights | " << Term(KNIGHT)
918      << "        Bishops | " << Term(BISHOP)
919      << "          Rooks | " << Term(ROOK)
920      << "         Queens | " << Term(QUEEN)
921      << "       Mobility | " << Term(MOBILITY)
922      << "    King safety | " << Term(KING)
923      << "        Threats | " << Term(THREAT)
924      << "   Passed pawns | " << Term(PASSED)
925      << "          Space | " << Term(SPACE)
926      << "----------------+-------------+-------------+-------------\n"
927      << "          Total | " << Term(TOTAL);
928
929   ss << "\nTotal Evaluation: " << to_cp(v) << " (white side)\n";
930
931   return ss.str();
932 }