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