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