]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Prevent Stockfish from exiting if DTZ table is not present
[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_passed_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   const Score TrappedBishopA1H1   = S( 50, 50);
220
221   #undef S
222   #undef V
223
224   // KingAttackWeights[PieceType] contains king attack weights by piece type
225   const int KingAttackWeights[PIECE_TYPE_NB] = { 0, 0, 78, 56, 45, 11 };
226
227   // Penalties for enemy's safe checks
228   const int QueenCheck  = 780;
229   const int RookCheck   = 880;
230   const int BishopCheck = 435;
231   const int KnightCheck = 790;
232
233   // Threshold for lazy and space evaluation
234   const Value LazyThreshold  = Value(1500);
235   const Value SpaceThreshold = Value(12222);
236
237
238   // initialize() computes king and pawn attacks, and the king ring bitboard
239   // for a given color. This is done at the beginning of the evaluation.
240
241   template<Tracing T> template<Color Us>
242   void Evaluation<T>::initialize() {
243
244     const Color  Them = (Us == WHITE ? BLACK : WHITE);
245     const Square Up   = (Us == WHITE ? NORTH : SOUTH);
246     const Square Down = (Us == WHITE ? SOUTH : NORTH);
247     const Bitboard LowRanks = (Us == WHITE ? Rank2BB | Rank3BB: Rank7BB | Rank6BB);
248
249     // Find our pawns on the first two ranks, and those which are blocked
250     Bitboard b = pos.pieces(Us, PAWN) & (shift<Down>(pos.pieces()) | LowRanks);
251
252     // Squares occupied by those pawns, by our king, or controlled by enemy pawns
253     // are excluded from the mobility area.
254     mobilityArea[Us] = ~(b | pos.square<KING>(Us) | pe->pawn_attacks(Them));
255
256     // Initialise the attack bitboards with the king and pawn information
257     b = attackedBy[Us][KING] = pos.attacks_from<KING>(pos.square<KING>(Us));
258     attackedBy[Us][PAWN] = pe->pawn_attacks(Us);
259
260     attackedBy2[Us]            = b & attackedBy[Us][PAWN];
261     attackedBy[Us][ALL_PIECES] = b | attackedBy[Us][PAWN];
262
263     // Init our king safety tables only if we are going to use them
264     if (pos.non_pawn_material(Them) >= RookValueMg + KnightValueMg)
265     {
266         kingRing[Us] = b;
267         if (relative_rank(Us, pos.square<KING>(Us)) == RANK_1)
268             kingRing[Us] |= shift<Up>(b);
269
270         kingAttackersCount[Them] = popcount(b & pe->pawn_attacks(Them));
271         kingAdjacentZoneAttacksCount[Them] = kingAttackersWeight[Them] = 0;
272     }
273     else
274         kingRing[Us] = kingAttackersCount[Them] = 0;
275   }
276
277
278   // evaluate_pieces() assigns bonuses and penalties to the pieces of a given
279   // color and type.
280
281   template<Tracing T>  template<Color Us, PieceType Pt>
282   Score Evaluation<T>::evaluate_pieces() {
283
284     const Color Them = (Us == WHITE ? BLACK : WHITE);
285     const Bitboard OutpostRanks = (Us == WHITE ? Rank4BB | Rank5BB | Rank6BB
286                                                : Rank5BB | Rank4BB | Rank3BB);
287     const Square* pl = pos.squares<Pt>(Us);
288
289     Bitboard b, bb;
290     Square s;
291     Score score = SCORE_ZERO;
292
293     attackedBy[Us][Pt] = 0;
294
295     while ((s = *pl++) != SQ_NONE)
296     {
297         // Find attacked squares, including x-ray attacks for bishops and rooks
298         b = Pt == BISHOP ? attacks_bb<BISHOP>(s, pos.pieces() ^ pos.pieces(Us, QUEEN))
299           : Pt ==   ROOK ? attacks_bb<  ROOK>(s, pos.pieces() ^ pos.pieces(Us, ROOK, QUEEN))
300                          : pos.attacks_from<Pt>(s);
301
302         if (pos.pinned_pieces(Us) & s)
303             b &= LineBB[pos.square<KING>(Us)][s];
304
305         attackedBy2[Us] |= attackedBy[Us][ALL_PIECES] & b;
306         attackedBy[Us][ALL_PIECES] |= attackedBy[Us][Pt] |= b;
307
308         if (b & kingRing[Them])
309         {
310             kingAttackersCount[Us]++;
311             kingAttackersWeight[Us] += KingAttackWeights[Pt];
312             kingAdjacentZoneAttacksCount[Us] += popcount(b & attackedBy[Them][KING]);
313         }
314
315         int mob = popcount(b & mobilityArea[Us]);
316
317         mobility[Us] += MobilityBonus[Pt - 2][mob];
318
319         // Bonus for this piece as a king protector
320         score += KingProtector[Pt - 2] * distance(s, pos.square<KING>(Us));
321
322         if (Pt == BISHOP || Pt == KNIGHT)
323         {
324             // Bonus for outpost squares
325             bb = OutpostRanks & ~pe->pawn_attacks_span(Them);
326             if (bb & s)
327                 score += Outpost[Pt == BISHOP][!!(attackedBy[Us][PAWN] & s)] * 2;
328             else
329             {
330                 bb &= b & ~pos.pieces(Us);
331                 if (bb)
332                    score += Outpost[Pt == BISHOP][!!(attackedBy[Us][PAWN] & bb)];
333             }
334
335             // Bonus when behind a pawn
336             if (    relative_rank(Us, s) < RANK_5
337                 && (pos.pieces(PAWN) & (s + pawn_push(Us))))
338                 score += MinorBehindPawn;
339
340             // Penalty for pawns on the same color square as the bishop
341             if (Pt == BISHOP)
342                 score -= BishopPawns * pe->pawns_on_same_color_squares(Us, s);
343
344             // An important Chess960 pattern: A cornered bishop blocked by a friendly
345             // pawn diagonally in front of it is a very serious problem, especially
346             // when that pawn is also blocked.
347             if (   Pt == BISHOP
348                 && pos.is_chess960()
349                 && (s == relative_square(Us, SQ_A1) || s == relative_square(Us, SQ_H1)))
350             {
351                 Square d = pawn_push(Us) + (file_of(s) == FILE_A ? EAST : WEST);
352                 if (pos.piece_on(s + d) == make_piece(Us, PAWN))
353                     score -= !pos.empty(s + d + pawn_push(Us))                ? TrappedBishopA1H1 * 4
354                             : pos.piece_on(s + d + d) == make_piece(Us, PAWN) ? TrappedBishopA1H1 * 2
355                                                                               : TrappedBishopA1H1;
356             }
357         }
358
359         if (Pt == ROOK)
360         {
361             // Bonus for aligning with enemy pawns on the same rank/file
362             if (relative_rank(Us, s) >= RANK_5)
363                 score += RookOnPawn * popcount(pos.pieces(Them, PAWN) & PseudoAttacks[ROOK][s]);
364
365             // Bonus when on an open or semi-open file
366             if (pe->semiopen_file(Us, file_of(s)))
367                 score += RookOnFile[!!pe->semiopen_file(Them, file_of(s))];
368
369             // Penalty when trapped by the king, even more if the king cannot castle
370             else if (mob <= 3)
371             {
372                 Square ksq = pos.square<KING>(Us);
373
374                 if (   ((file_of(ksq) < FILE_E) == (file_of(s) < file_of(ksq)))
375                     && !pe->semiopen_side(Us, file_of(ksq), file_of(s) < file_of(ksq)))
376                     score -= (TrappedRook - make_score(mob * 22, 0)) * (1 + !pos.can_castle(Us));
377             }
378         }
379
380         if (Pt == QUEEN)
381         {
382             // Penalty if any relative pin or discovered attack against the queen
383             Bitboard pinners;
384             if (pos.slider_blockers(pos.pieces(Them, ROOK, BISHOP), s, pinners))
385                 score -= WeakQueen;
386         }
387     }
388
389     if (T)
390         Trace::add(Pt, Us, score);
391
392     return score;
393   }
394
395
396   // evaluate_king() assigns bonuses and penalties to a king of a given color
397
398   const Bitboard QueenSide   = FileABB | FileBBB | FileCBB | FileDBB;
399   const Bitboard CenterFiles = FileCBB | FileDBB | FileEBB | FileFBB;
400   const Bitboard KingSide    = FileEBB | FileFBB | FileGBB | FileHBB;
401
402   const Bitboard KingFlank[FILE_NB] = {
403     QueenSide, QueenSide, QueenSide, CenterFiles, CenterFiles, KingSide, KingSide, KingSide
404   };
405
406   template<Tracing T>  template<Color Us>
407   Score Evaluation<T>::evaluate_king() {
408
409     const Color Them    = (Us == WHITE ? BLACK : WHITE);
410     const Square Up     = (Us == WHITE ? NORTH : SOUTH);
411     const Bitboard Camp = (Us == WHITE ? AllSquares ^ Rank6BB ^ Rank7BB ^ Rank8BB
412                                        : AllSquares ^ Rank1BB ^ Rank2BB ^ Rank3BB);
413
414     const Square ksq = pos.square<KING>(Us);
415     Bitboard kingOnlyDefended, undefended, b, b1, b2, safe, other;
416     int kingDanger;
417
418     // King shelter and enemy pawns storm
419     Score score = pe->king_safety<Us>(pos, ksq);
420
421     // Main king safety evaluation
422     if (kingAttackersCount[Them] > (1 - pos.count<QUEEN>(Them)))
423     {
424         // Find the attacked squares which are defended only by our king...
425         kingOnlyDefended =   attackedBy[Them][ALL_PIECES]
426                           &  attackedBy[Us][KING]
427                           & ~attackedBy2[Us];
428
429         // ... and those which are not defended at all in the larger king ring
430         undefended =   attackedBy[Them][ALL_PIECES]
431                     & ~attackedBy[Us][ALL_PIECES]
432                     &  kingRing[Us]
433                     & ~pos.pieces(Them);
434
435         // Initialize the 'kingDanger' variable, which will be transformed
436         // later into a king danger score. The initial value is based on the
437         // number and types of the enemy's attacking pieces, the number of
438         // attacked and weak squares around our king, the absence of queen and
439         // the quality of the pawn shelter (current 'score' value).
440         kingDanger =        kingAttackersCount[Them] * kingAttackersWeight[Them]
441                     + 102 * kingAdjacentZoneAttacksCount[Them]
442                     + 191 * popcount(kingOnlyDefended | undefended)
443                     + 143 * !!pos.pinned_pieces(Us)
444                     - 848 * !pos.count<QUEEN>(Them)
445                     -   9 * mg_value(score) / 8
446                     +  40;
447
448         // Analyse the safe enemy's checks which are possible on next move
449         safe  = ~pos.pieces(Them);
450         safe &= ~attackedBy[Us][ALL_PIECES] | (kingOnlyDefended & attackedBy2[Them]);
451
452         b1 = pos.attacks_from<  ROOK>(ksq);
453         b2 = pos.attacks_from<BISHOP>(ksq);
454
455         // Enemy queen safe checks
456         if ((b1 | b2) & attackedBy[Them][QUEEN] & safe)
457             kingDanger += QueenCheck;
458
459         // For minors and rooks, also consider the square safe if attacked twice,
460         // and only defended by our queen.
461         safe |=  attackedBy2[Them]
462                & ~(attackedBy2[Us] | pos.pieces(Them))
463                & attackedBy[Us][QUEEN];
464
465         // Some other potential checks are also analysed, even from squares
466         // currently occupied by the opponent own pieces, as long as the square
467         // is not attacked by our pawns, and is not occupied by a blocked pawn.
468         other = ~(   attackedBy[Us][PAWN]
469                   | (pos.pieces(Them, PAWN) & shift<Up>(pos.pieces(PAWN))));
470
471         // Enemy rooks safe and other checks
472         if (b1 & attackedBy[Them][ROOK] & safe)
473             kingDanger += RookCheck;
474
475         else if (b1 & attackedBy[Them][ROOK] & other)
476             score -= OtherCheck;
477
478         // Enemy bishops safe and other checks
479         if (b2 & attackedBy[Them][BISHOP] & safe)
480             kingDanger += BishopCheck;
481
482         else if (b2 & attackedBy[Them][BISHOP] & other)
483             score -= OtherCheck;
484
485         // Enemy knights safe and other checks
486         b = pos.attacks_from<KNIGHT>(ksq) & attackedBy[Them][KNIGHT];
487         if (b & safe)
488             kingDanger += KnightCheck;
489
490         else if (b & other)
491             score -= OtherCheck;
492
493         // Transform the kingDanger units into a Score, and substract it from the evaluation
494         if (kingDanger > 0)
495             score -= make_score(kingDanger * kingDanger / 4096, kingDanger / 16);
496     }
497
498     // King tropism: firstly, find squares that opponent attacks in our king flank
499     File kf = file_of(ksq);
500     b = attackedBy[Them][ALL_PIECES] & KingFlank[kf] & Camp;
501
502     assert(((Us == WHITE ? b << 4 : b >> 4) & b) == 0);
503     assert(popcount(Us == WHITE ? b << 4 : b >> 4) == popcount(b));
504
505     // Secondly, add the squares which are attacked twice in that flank and
506     // which are not defended by our pawns.
507     b =  (Us == WHITE ? b << 4 : b >> 4)
508        | (b & attackedBy2[Them] & ~attackedBy[Us][PAWN]);
509
510     score -= CloseEnemies * popcount(b);
511
512     // Penalty when our king is on a pawnless flank
513     if (!(pos.pieces(PAWN) & KingFlank[kf]))
514         score -= PawnlessFlank;
515
516     if (T)
517         Trace::add(KING, Us, score);
518
519     return score;
520   }
521
522
523   // evaluate_threats() assigns bonuses according to the types of the attacking
524   // and the attacked pieces.
525
526   template<Tracing T>  template<Color Us>
527   Score Evaluation<T>::evaluate_threats() {
528
529     const Color Them        = (Us == WHITE ? BLACK      : WHITE);
530     const Square Up         = (Us == WHITE ? NORTH      : SOUTH);
531     const Square Left       = (Us == WHITE ? NORTH_WEST : SOUTH_EAST);
532     const Square Right      = (Us == WHITE ? NORTH_EAST : SOUTH_WEST);
533     const Bitboard TRank3BB = (Us == WHITE ? Rank3BB    : Rank6BB);
534
535     Bitboard b, weak, defended, stronglyProtected, safeThreats;
536     Score score = SCORE_ZERO;
537
538     // Non-pawn enemies attacked by a pawn
539     weak = (pos.pieces(Them) ^ pos.pieces(Them, PAWN)) & attackedBy[Us][PAWN];
540
541     if (weak)
542     {
543         b = pos.pieces(Us, PAWN) & ( ~attackedBy[Them][ALL_PIECES]
544                                     | attackedBy[Us][ALL_PIECES]);
545
546         safeThreats = (shift<Right>(b) | shift<Left>(b)) & weak;
547
548         score += ThreatBySafePawn * popcount(safeThreats);
549
550         if (weak ^ safeThreats)
551             score += ThreatByHangingPawn;
552     }
553
554     // Squares strongly protected by the opponent, either because they attack the
555     // square with a pawn, or because they attack the square twice and we don't.
556     stronglyProtected =  attackedBy[Them][PAWN]
557                        | (attackedBy2[Them] & ~attackedBy2[Us]);
558
559     // Non-pawn enemies, strongly protected
560     defended =  (pos.pieces(Them) ^ pos.pieces(Them, PAWN))
561               & stronglyProtected;
562
563     // Enemies not strongly protected and under our attack
564     weak =   pos.pieces(Them)
565           & ~stronglyProtected
566           &  attackedBy[Us][ALL_PIECES];
567
568     // Add a bonus according to the kind of attacking pieces
569     if (defended | weak)
570     {
571         b = (defended | weak) & (attackedBy[Us][KNIGHT] | attackedBy[Us][BISHOP]);
572         while (b)
573         {
574             Square s = pop_lsb(&b);
575             score += ThreatByMinor[type_of(pos.piece_on(s))];
576             if (type_of(pos.piece_on(s)) != PAWN)
577                 score += ThreatByRank * (int)relative_rank(Them, s);
578         }
579
580         b = (pos.pieces(Them, QUEEN) | weak) & attackedBy[Us][ROOK];
581         while (b)
582         {
583             Square s = pop_lsb(&b);
584             score += ThreatByRook[type_of(pos.piece_on(s))];
585             if (type_of(pos.piece_on(s)) != PAWN)
586                 score += ThreatByRank * (int)relative_rank(Them, s);
587         }
588
589         score += Hanging * popcount(weak & ~attackedBy[Them][ALL_PIECES]);
590
591         b = weak & attackedBy[Us][KING];
592         if (b)
593             score += ThreatByKing[more_than_one(b)];
594     }
595
596     // Find squares where our pawns can push on the next move
597     b  = shift<Up>(pos.pieces(Us, PAWN)) & ~pos.pieces();
598     b |= shift<Up>(b & TRank3BB) & ~pos.pieces();
599
600     // Keep only the squares which are not completely unsafe
601     b &= ~attackedBy[Them][PAWN]
602         & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
603
604     // Add a bonus for each new pawn threats from those squares
605     b =  (shift<Left>(b) | shift<Right>(b))
606        &  pos.pieces(Them)
607        & ~attackedBy[Us][PAWN];
608
609     score += ThreatByPawnPush * popcount(b);
610
611     if (T)
612         Trace::add(THREAT, Us, score);
613
614     return score;
615   }
616
617
618   // evaluate_passed_pawns() evaluates the passed pawns and candidate passed
619   // pawns of the given color.
620
621   template<Tracing T>  template<Color Us>
622   Score Evaluation<T>::evaluate_passed_pawns() {
623
624     const Color Them = (Us == WHITE ? BLACK : WHITE);
625     const Square Up  = (Us == WHITE ? NORTH : SOUTH);
626
627     Bitboard b, bb, squaresToQueen, defendedSquares, unsafeSquares;
628     Score score = SCORE_ZERO;
629
630     b = pe->passed_pawns(Us);
631
632     while (b)
633     {
634         Square s = pop_lsb(&b);
635
636         assert(!(pos.pieces(Them, PAWN) & forward_file_bb(Us, s + Up)));
637
638         bb = forward_file_bb(Us, s) & (attackedBy[Them][ALL_PIECES] | pos.pieces(Them));
639         score -= HinderPassedPawn * popcount(bb);
640
641         int r = relative_rank(Us, s) - RANK_2;
642         int rr = r * (r - 1);
643
644         Value mbonus = Passed[MG][r], ebonus = Passed[EG][r];
645
646         if (rr)
647         {
648             Square blockSq = s + Up;
649
650             // Adjust bonus based on the king's proximity
651             ebonus +=  distance(pos.square<KING>(Them), blockSq) * 5 * rr
652                      - distance(pos.square<KING>(  Us), blockSq) * 2 * rr;
653
654             // If blockSq is not the queening square then consider also a second push
655             if (relative_rank(Us, blockSq) != RANK_8)
656                 ebonus -= distance(pos.square<KING>(Us), blockSq + Up) * rr;
657
658             // If the pawn is free to advance, then increase the bonus
659             if (pos.empty(blockSq))
660             {
661                 // If there is a rook or queen attacking/defending the pawn from behind,
662                 // consider all the squaresToQueen. Otherwise consider only the squares
663                 // in the pawn's path attacked or occupied by the enemy.
664                 defendedSquares = unsafeSquares = squaresToQueen = forward_file_bb(Us, s);
665
666                 bb = forward_file_bb(Them, s) & pos.pieces(ROOK, QUEEN) & pos.attacks_from<ROOK>(s);
667
668                 if (!(pos.pieces(Us) & bb))
669                     defendedSquares &= attackedBy[Us][ALL_PIECES];
670
671                 if (!(pos.pieces(Them) & bb))
672                     unsafeSquares &= attackedBy[Them][ALL_PIECES] | pos.pieces(Them);
673
674                 // If there aren't any enemy attacks, assign a big bonus. Otherwise
675                 // assign a smaller bonus if the block square isn't attacked.
676                 int k = !unsafeSquares ? 18 : !(unsafeSquares & blockSq) ? 8 : 0;
677
678                 // If the path to the queen is fully defended, assign a big bonus.
679                 // Otherwise assign a smaller bonus if the block square is defended.
680                 if (defendedSquares == squaresToQueen)
681                     k += 6;
682
683                 else if (defendedSquares & blockSq)
684                     k += 4;
685
686                 mbonus += k * rr, ebonus += k * rr;
687             }
688             else if (pos.pieces(Us) & blockSq)
689                 mbonus += rr + r * 2, ebonus += rr + r * 2;
690         } // rr != 0
691
692         // Scale down bonus for candidate passers which need more than one
693         // pawn push to become passed or have a pawn in front of them.
694         if (!pos.pawn_passed(Us, s + Up) || (pos.pieces(PAWN) & forward_file_bb(Us, s)))
695             mbonus /= 2, ebonus /= 2;
696
697         score += make_score(mbonus, ebonus) + PassedFile[file_of(s)];
698     }
699
700     if (T)
701         Trace::add(PASSED, Us, score);
702
703     return score;
704   }
705
706
707   // evaluate_space() computes the space evaluation for a given side. The
708   // space evaluation is a simple bonus based on the number of safe squares
709   // available for minor pieces on the central four files on ranks 2--4. Safe
710   // squares one, two or three squares behind a friendly pawn are counted
711   // twice. Finally, the space bonus is multiplied by a weight. The aim is to
712   // improve play on game opening.
713
714   template<Tracing T>  template<Color Us>
715   Score Evaluation<T>::evaluate_space() {
716
717     const Color Them = (Us == WHITE ? BLACK : WHITE);
718     const Bitboard SpaceMask =
719       Us == WHITE ? CenterFiles & (Rank2BB | Rank3BB | Rank4BB)
720                   : CenterFiles & (Rank7BB | Rank6BB | Rank5BB);
721
722     // Find the safe squares for our pieces inside the area defined by
723     // SpaceMask. A square is unsafe if it is attacked by an enemy
724     // pawn, or if it is undefended and attacked by an enemy piece.
725     Bitboard safe =   SpaceMask
726                    & ~pos.pieces(Us, PAWN)
727                    & ~attackedBy[Them][PAWN]
728                    & (attackedBy[Us][ALL_PIECES] | ~attackedBy[Them][ALL_PIECES]);
729
730     // Find all squares which are at most three squares behind some friendly pawn
731     Bitboard behind = pos.pieces(Us, PAWN);
732     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
733     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
734
735     // Since SpaceMask[Us] is fully on our half of the board...
736     assert(unsigned(safe >> (Us == WHITE ? 32 : 0)) == 0);
737
738     // ...count safe + (behind & safe) with a single popcount.
739     int bonus = popcount((Us == WHITE ? safe << 32 : safe >> 32) | (behind & safe));
740     int weight = pos.count<ALL_PIECES>(Us) - 2 * pe->open_files();
741
742     return make_score(bonus * weight * weight / 16, 0);
743   }
744
745
746   // evaluate_initiative() computes the initiative correction value for the
747   // position, i.e., second order bonus/malus based on the known attacking/defending
748   // status of the players.
749
750   template<Tracing T>
751   Score Evaluation<T>::evaluate_initiative(Value eg) {
752
753     int kingDistance =  distance<File>(pos.square<KING>(WHITE), pos.square<KING>(BLACK))
754                       - distance<Rank>(pos.square<KING>(WHITE), pos.square<KING>(BLACK));
755     bool bothFlanks = (pos.pieces(PAWN) & QueenSide) && (pos.pieces(PAWN) & KingSide);
756
757     // Compute the initiative bonus for the attacking side
758     int initiative = 8 * (pe->pawn_asymmetry() + kingDistance - 17) + 12 * pos.count<PAWN>() + 16 * bothFlanks;
759
760     // Now apply the bonus: note that we find the attacking side by extracting
761     // the sign of the endgame value, and that we carefully cap the bonus so
762     // that the endgame score will never change sign after the bonus.
763     int v = ((eg > 0) - (eg < 0)) * std::max(initiative, -abs(eg));
764
765     return make_score(0, v);
766   }
767
768
769   // evaluate_scale_factor() computes the scale factor for the winning side
770
771   template<Tracing T>
772   ScaleFactor Evaluation<T>::evaluate_scale_factor(Value eg) {
773
774     Color strongSide = eg > VALUE_DRAW ? WHITE : BLACK;
775     ScaleFactor sf = me->scale_factor(pos, strongSide);
776
777     // If we don't already have an unusual scale factor, check for certain
778     // types of endgames, and use a lower scale for those.
779     if (sf == SCALE_FACTOR_NORMAL || sf == SCALE_FACTOR_ONEPAWN)
780     {
781         if (pos.opposite_bishops())
782         {
783             // Endgame with opposite-colored bishops and no other pieces (ignoring pawns)
784             // is almost a draw, in case of KBP vs KB, it is even more a draw.
785             if (   pos.non_pawn_material(WHITE) == BishopValueMg
786                 && pos.non_pawn_material(BLACK) == BishopValueMg)
787                 return more_than_one(pos.pieces(PAWN)) ? ScaleFactor(31) : ScaleFactor(9);
788
789             // Endgame with opposite-colored bishops, but also other pieces. Still
790             // a bit drawish, but not as drawish as with only the two bishops.
791             return ScaleFactor(46);
792         }
793         // Endings where weaker side can place his king in front of the opponent's
794         // pawns are drawish.
795         else if (    abs(eg) <= BishopValueEg
796                  &&  pos.count<PAWN>(strongSide) <= 2
797                  && !pos.pawn_passed(~strongSide, pos.square<KING>(~strongSide)))
798             return ScaleFactor(37 + 7 * pos.count<PAWN>(strongSide));
799     }
800
801     return sf;
802   }
803
804
805   // value() is the main function of the class. It computes the various parts of
806   // the evaluation and returns the value of the position from the point of view
807   // of the side to move.
808
809   template<Tracing T>
810   Value Evaluation<T>::value() {
811
812     assert(!pos.checkers());
813
814     // Probe the material hash table
815     me = Material::probe(pos);
816
817     // If we have a specialized evaluation function for the current material
818     // configuration, call it and return.
819     if (me->specialized_eval_exists())
820         return me->evaluate(pos);
821
822     // Initialize score by reading the incrementally updated scores included in
823     // the position object (material + piece square tables) and the material
824     // imbalance. Score is computed internally from the white point of view.
825     Score score = pos.psq_score() + me->imbalance();
826
827     // Probe the pawn hash table
828     pe = Pawns::probe(pos);
829     score += pe->pawns_score();
830
831     // Early exit if score is high
832     Value v = (mg_value(score) + eg_value(score)) / 2;
833     if (abs(v) > LazyThreshold)
834        return pos.side_to_move() == WHITE ? v : -v;
835
836     // Main evaluation begins here
837
838     initialize<WHITE>();
839     initialize<BLACK>();
840
841     score += evaluate_pieces<WHITE, KNIGHT>() - evaluate_pieces<BLACK, KNIGHT>();
842     score += evaluate_pieces<WHITE, BISHOP>() - evaluate_pieces<BLACK, BISHOP>();
843     score += evaluate_pieces<WHITE, ROOK  >() - evaluate_pieces<BLACK, ROOK  >();
844     score += evaluate_pieces<WHITE, QUEEN >() - evaluate_pieces<BLACK, QUEEN >();
845
846     score += mobility[WHITE] - mobility[BLACK];
847
848     score +=  evaluate_king<WHITE>()
849             - evaluate_king<BLACK>();
850
851     score +=  evaluate_threats<WHITE>()
852             - evaluate_threats<BLACK>();
853
854     score +=  evaluate_passed_pawns<WHITE>()
855             - evaluate_passed_pawns<BLACK>();
856
857     if (pos.non_pawn_material() >= SpaceThreshold)
858         score +=  evaluate_space<WHITE>()
859                 - evaluate_space<BLACK>();
860
861     score += evaluate_initiative(eg_value(score));
862
863     // Interpolate between a middlegame and a (scaled by 'sf') endgame score
864     ScaleFactor sf = evaluate_scale_factor(eg_value(score));
865     v =  mg_value(score) * int(me->game_phase())
866        + eg_value(score) * int(PHASE_MIDGAME - me->game_phase()) * sf / SCALE_FACTOR_NORMAL;
867
868     v /= int(PHASE_MIDGAME);
869
870     // In case of tracing add all remaining individual evaluation terms
871     if (T)
872     {
873         Trace::add(MATERIAL, pos.psq_score());
874         Trace::add(IMBALANCE, me->imbalance());
875         Trace::add(PAWN, pe->pawns_score());
876         Trace::add(MOBILITY, mobility[WHITE], mobility[BLACK]);
877         if (pos.non_pawn_material() >= SpaceThreshold)
878             Trace::add(SPACE, evaluate_space<WHITE>()
879                             , evaluate_space<BLACK>());
880         Trace::add(TOTAL, score);
881     }
882
883     return (pos.side_to_move() == WHITE ? v : -v) + Eval::Tempo; // Side to move point of view
884   }
885
886 } // namespace
887
888
889 /// evaluate() is the evaluator for the outer world. It returns a static evaluation
890 /// of the position from the point of view of the side to move.
891
892 Value Eval::evaluate(const Position& pos)
893 {
894    return Evaluation<>(pos).value();
895 }
896
897 /// trace() is like evaluate(), but instead of returning a value, it returns
898 /// a string (suitable for outputting to stdout) that contains the detailed
899 /// descriptions and values of each evaluation term. Useful for debugging.
900
901 std::string Eval::trace(const Position& pos) {
902
903   std::memset(scores, 0, sizeof(scores));
904
905   Value v = Evaluation<TRACE>(pos).value();
906   v = pos.side_to_move() == WHITE ? v : -v; // White's point of view
907
908   std::stringstream ss;
909   ss << std::showpoint << std::noshowpos << std::fixed << std::setprecision(2)
910      << "      Eval term |    White    |    Black    |    Total    \n"
911      << "                |   MG    EG  |   MG    EG  |   MG    EG  \n"
912      << "----------------+-------------+-------------+-------------\n"
913      << "       Material | " << Term(MATERIAL)
914      << "      Imbalance | " << Term(IMBALANCE)
915      << "          Pawns | " << Term(PAWN)
916      << "        Knights | " << Term(KNIGHT)
917      << "        Bishops | " << Term(BISHOP)
918      << "          Rooks | " << Term(ROOK)
919      << "         Queens | " << Term(QUEEN)
920      << "       Mobility | " << Term(MOBILITY)
921      << "    King safety | " << Term(KING)
922      << "        Threats | " << Term(THREAT)
923      << "   Passed pawns | " << Term(PASSED)
924      << "          Space | " << Term(SPACE)
925      << "----------------+-------------+-------------+-------------\n"
926      << "          Total | " << Term(TOTAL);
927
928   ss << "\nTotal Evaluation: " << to_cp(v) << " (white side)\n";
929
930   return ss.str();
931 }