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