]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
eb4cbef7be2eeedb9df4591dcc234eba618bedc2
[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-2010 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
21 ////
22 //// Includes
23 ////
24
25 #include <cassert>
26 #include <cstring>
27
28 #include "bitcount.h"
29 #include "evaluate.h"
30 #include "material.h"
31 #include "pawns.h"
32 #include "thread.h"
33 #include "ucioption.h"
34
35
36 ////
37 //// Local definitions
38 ////
39
40 namespace {
41
42   const int Sign[2] = { 1, -1 };
43
44   // Evaluation grain size, must be a power of 2
45   const int GrainSize = 8;
46
47   // Evaluation weights, initialized from UCI options
48   enum { Mobility, PawnStructure, PassedPawns, Space, KingDangerUs, KingDangerThem };
49   Score Weights[6];
50
51   typedef Value V;
52   #define S(mg, eg) make_score(mg, eg)
53
54   // Internal evaluation weights. These are applied on top of the evaluation
55   // weights read from UCI parameters. The purpose is to be able to change
56   // the evaluation weights while keeping the default values of the UCI
57   // parameters at 100, which looks prettier.
58   //
59   // Values modified by Joona Kiiski
60   const Score WeightsInternal[] = {
61       S(248, 271), S(233, 201), S(252, 259), S(46, 0), S(247, 0), S(259, 0)
62   };
63
64   // MobilityBonus[PieceType][attacked] contains mobility bonuses for middle and
65   // end game, indexed by piece type and number of attacked squares not occupied
66   // by friendly pieces.
67   const Score MobilityBonus[][32] = {
68      {}, {},
69      { S(-38,-33), S(-25,-23), S(-12,-13), S( 0, -3), S(12,  7), S(25, 17), // Knights
70        S( 31, 22), S( 38, 27), S( 38, 27) },
71      { S(-25,-30), S(-11,-16), S(  3, -2), S(17, 12), S(31, 26), S(45, 40), // Bishops
72        S( 57, 52), S( 65, 60), S( 71, 65), S(74, 69), S(76, 71), S(78, 73),
73        S( 79, 74), S( 80, 75), S( 81, 76), S(81, 76) },
74      { S(-20,-36), S(-14,-19), S( -8, -3), S(-2, 13), S( 4, 29), S(10, 46), // Rooks
75        S( 14, 62), S( 19, 79), S( 23, 95), S(26,106), S(27,111), S(28,114),
76        S( 29,116), S( 30,117), S( 31,118), S(32,118) },
77      { S(-10,-18), S( -8,-13), S( -6, -7), S(-3, -2), S(-1,  3), S( 1,  8), // Queens
78        S(  3, 13), S(  5, 19), S(  8, 23), S(10, 27), S(12, 32), S(15, 34),
79        S( 16, 35), S( 17, 35), S( 18, 35), S(20, 35), S(20, 35), S(20, 35),
80        S( 20, 35), S( 20, 35), S( 20, 35), S(20, 35), S(20, 35), S(20, 35),
81        S( 20, 35), S( 20, 35), S( 20, 35), S(20, 35), S(20, 35), S(20, 35),
82        S( 20, 35), S( 20, 35) }
83   };
84
85   // OutpostBonus[PieceType][Square] contains outpost bonuses of knights and
86   // bishops, indexed by piece type and square (from white's point of view).
87   const Value OutpostBonus[][64] = {
88   {
89   //  A     B     C     D     E     F     G     H
90     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Knights
91     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
92     V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0),
93     V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0),
94     V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0),
95     V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0),
96     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
97     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) },
98   {
99     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // Bishops
100     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
101     V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0),
102     V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0),
103     V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0),
104     V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0),
105     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0),
106     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0) }
107   };
108
109   // ThreatBonus[attacking][attacked] contains threat bonuses according to
110   // which piece type attacks which one.
111   const Score ThreatBonus[][8] = {
112     {}, {},
113     { S(0, 0), S( 7, 39), S( 0,  0), S(24, 49), S(41,100), S(41,100) }, // KNIGHT
114     { S(0, 0), S( 7, 39), S(24, 49), S( 0,  0), S(41,100), S(41,100) }, // BISHOP
115     { S(0, 0), S(-1, 29), S(15, 49), S(15, 49), S( 0,  0), S(24, 49) }, // ROOK
116     { S(0, 0), S(15, 39), S(15, 39), S(15, 39), S(15, 39), S( 0,  0) }  // QUEEN
117   };
118
119   // ThreatedByPawnPenalty[PieceType] contains a penalty according to which
120   // piece type is attacked by an enemy pawn.
121   const Score ThreatedByPawnPenalty[] = {
122     S(0, 0), S(0, 0), S(56, 70), S(56, 70), S(76, 99), S(86, 118)
123   };
124
125   #undef S
126
127   // Rooks and queens on the 7th rank (modified by Joona Kiiski)
128   const Score RookOn7thBonus  = make_score(47, 98);
129   const Score QueenOn7thBonus = make_score(27, 54);
130
131   // Rooks on open files (modified by Joona Kiiski)
132   const Score RookOpenFileBonus = make_score(43, 43);
133   const Score RookHalfOpenFileBonus = make_score(19, 19);
134
135   // Penalty for rooks trapped inside a friendly king which has lost the
136   // right to castle.
137   const Value TrappedRookPenalty = Value(180);
138
139   // The SpaceMask[Color] contains the area of the board which is considered
140   // by the space evaluation. In the middle game, each side is given a bonus
141   // based on how many squares inside this area are safe and available for
142   // friendly minor pieces.
143   const Bitboard SpaceMask[2] = {
144     (1ULL << SQ_C2) | (1ULL << SQ_D2) | (1ULL << SQ_E2) | (1ULL << SQ_F2) |
145     (1ULL << SQ_C3) | (1ULL << SQ_D3) | (1ULL << SQ_E3) | (1ULL << SQ_F3) |
146     (1ULL << SQ_C4) | (1ULL << SQ_D4) | (1ULL << SQ_E4) | (1ULL << SQ_F4),
147     (1ULL << SQ_C7) | (1ULL << SQ_D7) | (1ULL << SQ_E7) | (1ULL << SQ_F7) |
148     (1ULL << SQ_C6) | (1ULL << SQ_D6) | (1ULL << SQ_E6) | (1ULL << SQ_F6) |
149     (1ULL << SQ_C5) | (1ULL << SQ_D5) | (1ULL << SQ_E5) | (1ULL << SQ_F5)
150   };
151
152   // King danger constants and variables. The king danger scores are taken
153   // from the KingDangerTable[]. Various little "meta-bonuses" measuring
154   // the strength of the enemy attack are added up into an integer, which
155   // is used as an index to KingDangerTable[].
156   //
157   // KingAttackWeights[PieceType] contains king attack weights by piece type
158   const int KingAttackWeights[] = { 0, 0, 2, 2, 3, 5 };
159
160   // Bonuses for enemy's safe checks
161   const int QueenContactCheckBonus = 3;
162   const int QueenCheckBonus        = 2;
163   const int RookCheckBonus         = 1;
164   const int BishopCheckBonus       = 1;
165   const int KnightCheckBonus       = 1;
166
167   // InitKingDanger[Square] contains penalties based on the position of the
168   // defending king, indexed by king's square (from white's point of view).
169   const int InitKingDanger[] = {
170      2,  0,  2,  5,  5,  2,  0,  2,
171      2,  2,  4,  8,  8,  4,  2,  2,
172      7, 10, 12, 12, 12, 12, 10,  7,
173     15, 15, 15, 15, 15, 15, 15, 15,
174     15, 15, 15, 15, 15, 15, 15, 15,
175     15, 15, 15, 15, 15, 15, 15, 15,
176     15, 15, 15, 15, 15, 15, 15, 15,
177     15, 15, 15, 15, 15, 15, 15, 15
178   };
179
180   // KingDangerTable[Color][attackUnits] contains the actual king danger
181   // weighted scores, indexed by color and by a calculated integer number.
182   Score KingDangerTable[2][128];
183
184   // Pawn and material hash tables, indexed by the current thread id.
185   // Note that they will be initialized at 0 being global variables.
186   MaterialInfoTable* MaterialTable[MAX_THREADS];
187   PawnInfoTable* PawnTable[MAX_THREADS];
188
189   // Function prototypes
190   template<bool HasPopCnt>
191   Value do_evaluate(const Position& pos, EvalInfo& ei);
192
193   template<Color Us, bool HasPopCnt>
194   void init_attack_tables(const Position& pos, EvalInfo& ei);
195
196   template<Color Us, bool HasPopCnt>
197   void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei);
198
199   template<Color Us, bool HasPopCnt>
200   void evaluate_king(const Position& pos, EvalInfo& ei);
201
202   template<Color Us>
203   void evaluate_threats(const Position& pos, EvalInfo& ei);
204
205   template<Color Us, bool HasPopCnt>
206   int evaluate_space(const Position& pos, EvalInfo& ei);
207
208   template<Color Us>
209   void evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
210
211   inline Score apply_weight(Score v, Score weight);
212   Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]);
213   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
214   void init_safety();
215 }
216
217
218 ////
219 //// Functions
220 ////
221
222
223 /// Prefetches in pawn hash tables
224
225 void prefetchPawn(Key key, int threadID) {
226
227     PawnTable[threadID]->prefetch(key);
228 }
229
230 /// evaluate() is the main evaluation function. It always computes two
231 /// values, an endgame score and a middle game score, and interpolates
232 /// between them based on the remaining material.
233 Value evaluate(const Position& pos, EvalInfo& ei) {
234
235     return CpuHasPOPCNT ? do_evaluate<true>(pos, ei)
236                         : do_evaluate<false>(pos, ei);
237 }
238
239 namespace {
240
241 template<bool HasPopCnt>
242 Value do_evaluate(const Position& pos, EvalInfo& ei) {
243
244   ScaleFactor factor[2];
245
246   assert(pos.is_ok());
247   assert(pos.thread() >= 0 && pos.thread() < MAX_THREADS);
248   assert(!pos.is_check());
249
250   memset(&ei, 0, sizeof(EvalInfo));
251
252   // Initialize by reading the incrementally updated scores included in the
253   // position object (material + piece square tables)
254   ei.value = pos.value();
255
256   // Probe the material hash table
257   ei.mi = MaterialTable[pos.thread()]->get_material_info(pos);
258   ei.value += ei.mi->material_value();
259
260   // If we have a specialized evaluation function for the current material
261   // configuration, call it and return
262   if (ei.mi->specialized_eval_exists())
263       return ei.mi->evaluate(pos);
264
265   // After get_material_info() call that modifies them
266   factor[WHITE] = ei.mi->scale_factor(pos, WHITE);
267   factor[BLACK] = ei.mi->scale_factor(pos, BLACK);
268
269   // Probe the pawn hash table
270   ei.pi = PawnTable[pos.thread()]->get_pawn_info(pos);
271   ei.value += apply_weight(ei.pi->pawns_value(), Weights[PawnStructure]);
272
273   // Initialize attack bitboards with pawns evaluation
274   init_attack_tables<WHITE, HasPopCnt>(pos, ei);
275   init_attack_tables<BLACK, HasPopCnt>(pos, ei);
276
277   // Evaluate pieces
278   evaluate_pieces_of_color<WHITE, HasPopCnt>(pos, ei);
279   evaluate_pieces_of_color<BLACK, HasPopCnt>(pos, ei);
280
281   // Kings. Kings are evaluated after all other pieces for both sides,
282   // because we need complete attack information for all pieces when computing
283   // the king safety evaluation.
284   evaluate_king<WHITE, HasPopCnt>(pos, ei);
285   evaluate_king<BLACK, HasPopCnt>(pos, ei);
286
287   // Evaluate tactical threats, we need full attack info including king
288   evaluate_threats<WHITE>(pos, ei);
289   evaluate_threats<BLACK>(pos, ei);
290
291   // Evaluate passed pawns, we need full attack info including king
292   evaluate_passed_pawns<WHITE>(pos, ei);
293   evaluate_passed_pawns<BLACK>(pos, ei);
294
295   Phase phase = ei.mi->game_phase();
296
297   // Middle-game specific evaluation terms
298   if (phase > PHASE_ENDGAME)
299   {
300       // Evaluate pawn storms in positions with opposite castling
301       if (   square_file(pos.king_square(WHITE)) >= FILE_E
302           && square_file(pos.king_square(BLACK)) <= FILE_D)
303
304           ei.value += make_score(ei.pi->queenside_storm_value(WHITE) - ei.pi->kingside_storm_value(BLACK), 0);
305
306       else if (   square_file(pos.king_square(WHITE)) <= FILE_D
307                && square_file(pos.king_square(BLACK)) >= FILE_E)
308
309           ei.value += make_score(ei.pi->kingside_storm_value(WHITE) - ei.pi->queenside_storm_value(BLACK), 0);
310
311       // Evaluate space for both sides
312       if (ei.mi->space_weight() > 0)
313       {
314           int s = evaluate_space<WHITE, HasPopCnt>(pos, ei) - evaluate_space<BLACK, HasPopCnt>(pos, ei);
315           ei.value += apply_weight(make_score(s * ei.mi->space_weight(), 0), Weights[Space]);
316       }
317   }
318
319   // Mobility
320   ei.value += apply_weight(ei.mobility, Weights[Mobility]);
321
322   // If we don't already have an unusual scale factor, check for opposite
323   // colored bishop endgames, and use a lower scale for those
324   if (   phase < PHASE_MIDGAME
325       && pos.opposite_colored_bishops()
326       && (   (factor[WHITE] == SCALE_FACTOR_NORMAL && eg_value(ei.value) > VALUE_ZERO)
327           || (factor[BLACK] == SCALE_FACTOR_NORMAL && eg_value(ei.value) < VALUE_ZERO)))
328   {
329       ScaleFactor sf;
330
331       // Only the two bishops ?
332       if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
333           && pos.non_pawn_material(BLACK) == BishopValueMidgame)
334       {
335           // Check for KBP vs KB with only a single pawn that is almost
336           // certainly a draw or at least two pawns.
337           bool one_pawn = (pos.piece_count(WHITE, PAWN) + pos.piece_count(BLACK, PAWN) == 1);
338           sf = one_pawn ? ScaleFactor(8) : ScaleFactor(32);
339       }
340       else
341           // Endgame with opposite-colored bishops, but also other pieces. Still
342           // a bit drawish, but not as drawish as with only the two bishops.
343            sf = ScaleFactor(50);
344
345       if (factor[WHITE] == SCALE_FACTOR_NORMAL)
346           factor[WHITE] = sf;
347       if (factor[BLACK] == SCALE_FACTOR_NORMAL)
348           factor[BLACK] = sf;
349   }
350
351   // Interpolate between the middle game and the endgame score
352   return Sign[pos.side_to_move()] * scale_by_game_phase(ei.value, phase, factor);
353 }
354
355 } // namespace
356
357 /// init_eval() initializes various tables used by the evaluation function
358
359 void init_eval(int threads) {
360
361   assert(threads <= MAX_THREADS);
362
363   for (int i = 0; i < MAX_THREADS; i++)
364   {
365     if (i >= threads)
366     {
367         delete PawnTable[i];
368         delete MaterialTable[i];
369         PawnTable[i] = NULL;
370         MaterialTable[i] = NULL;
371         continue;
372     }
373     if (!PawnTable[i])
374         PawnTable[i] = new PawnInfoTable();
375     if (!MaterialTable[i])
376         MaterialTable[i] = new MaterialInfoTable();
377   }
378 }
379
380
381 /// quit_eval() releases heap-allocated memory at program termination
382
383 void quit_eval() {
384
385   for (int i = 0; i < MAX_THREADS; i++)
386   {
387       delete PawnTable[i];
388       delete MaterialTable[i];
389       PawnTable[i] = NULL;
390       MaterialTable[i] = NULL;
391   }
392 }
393
394
395 /// read_weights() reads evaluation weights from the corresponding UCI parameters
396
397 void read_weights(Color us) {
398
399   // King safety is asymmetrical. Our king danger level is weighted by
400   // "Cowardice" UCI parameter, instead the opponent one by "Aggressiveness".
401   const int kingDangerUs   = (us == WHITE ? KingDangerUs   : KingDangerThem);
402   const int kingDangerThem = (us == WHITE ? KingDangerThem : KingDangerUs);
403
404   Weights[Mobility]       = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightsInternal[Mobility]);
405   Weights[PawnStructure]  = weight_option("Pawn Structure (Middle Game)", "Pawn Structure (Endgame)", WeightsInternal[PawnStructure]);
406   Weights[PassedPawns]    = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightsInternal[PassedPawns]);
407   Weights[Space]          = weight_option("Space", "Space", WeightsInternal[Space]);
408   Weights[kingDangerUs]   = weight_option("Cowardice", "Cowardice", WeightsInternal[KingDangerUs]);
409   Weights[kingDangerThem] = weight_option("Aggressiveness", "Aggressiveness", WeightsInternal[KingDangerThem]);
410
411   // If running in analysis mode, make sure we use symmetrical king safety. We do this
412   // by replacing both Weights[kingDangerUs] and Weights[kingDangerThem] by their average.
413   if (get_option_value_bool("UCI_AnalyseMode"))
414       Weights[kingDangerUs] = Weights[kingDangerThem] = (Weights[kingDangerUs] + Weights[kingDangerThem]) / 2;
415
416   init_safety();
417 }
418
419
420 namespace {
421
422   // init_attack_tables() initializes king bitboards for both sides adding
423   // pawn attacks. To be done before other evaluations.
424
425   template<Color Us, bool HasPopCnt>
426   void init_attack_tables(const Position& pos, EvalInfo& ei) {
427
428     const Color Them = (Us == WHITE ? BLACK : WHITE);
429
430     Bitboard b = ei.attackedBy[Them][KING] = pos.attacks_from<KING>(pos.king_square(Them));
431     ei.kingZone[Us] = (b | (Us == WHITE ? b >> 8 : b << 8));
432     ei.attackedBy[Us][PAWN] = ei.pi->pawn_attacks(Us);
433     b &= ei.attackedBy[Us][PAWN];
434     if (b)
435         ei.kingAttackersCount[Us] = count_1s_max_15<HasPopCnt>(b) / 2;
436   }
437
438
439   // evaluate_outposts() evaluates bishop and knight outposts squares
440
441   template<PieceType Piece, Color Us>
442   void evaluate_outposts(const Position& pos, EvalInfo& ei, Square s) {
443
444     const Color Them = (Us == WHITE ? BLACK : WHITE);
445
446     assert (Piece == BISHOP || Piece == KNIGHT);
447
448     // Initial bonus based on square
449     Value bonus = OutpostBonus[Piece == BISHOP][relative_square(Us, s)];
450
451     // Increase bonus if supported by pawn, especially if the opponent has
452     // no minor piece which can exchange the outpost piece
453     if (bonus && bit_is_set(ei.attackedBy[Us][PAWN], s))
454     {
455         if (    pos.pieces(KNIGHT, Them) == EmptyBoardBB
456             && (SquaresByColorBB[square_color(s)] & pos.pieces(BISHOP, Them)) == EmptyBoardBB)
457             bonus += bonus + bonus / 2;
458         else
459             bonus += bonus / 2;
460     }
461     ei.value += Sign[Us] * make_score(bonus, bonus);
462   }
463
464
465   // evaluate_pieces<>() assigns bonuses and penalties to the pieces of a given color
466
467   template<PieceType Piece, Color Us, bool HasPopCnt>
468   void evaluate_pieces(const Position& pos, EvalInfo& ei, Bitboard no_mob_area) {
469
470     Bitboard b;
471     Square s, ksq;
472     int mob;
473     File f;
474
475     const Color Them = (Us == WHITE ? BLACK : WHITE);
476     const Square* ptr = pos.piece_list_begin(Us, Piece);
477
478     while ((s = *ptr++) != SQ_NONE)
479     {
480         // Find attacked squares, including x-ray attacks for bishops and rooks
481         if (Piece == KNIGHT || Piece == QUEEN)
482             b = pos.attacks_from<Piece>(s);
483         else if (Piece == BISHOP)
484             b = bishop_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(QUEEN, Us));
485         else if (Piece == ROOK)
486             b = rook_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(ROOK, QUEEN, Us));
487         else
488             assert(false);
489
490         // Update attack info
491         ei.attackedBy[Us][Piece] |= b;
492
493         // King attacks
494         if (b & ei.kingZone[Us])
495         {
496             ei.kingAttackersCount[Us]++;
497             ei.kingAttackersWeight[Us] += KingAttackWeights[Piece];
498             Bitboard bb = (b & ei.attackedBy[Them][KING]);
499             if (bb)
500                 ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
501         }
502
503         // Mobility
504         mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & no_mob_area)
505                               : count_1s<HasPopCnt>(b & no_mob_area));
506
507         ei.mobility += Sign[Us] * MobilityBonus[Piece][mob];
508
509         // Decrease score if we are attacked by an enemy pawn. Remaining part
510         // of threat evaluation must be done later when we have full attack info.
511         if (bit_is_set(ei.attackedBy[Them][PAWN], s))
512             ei.value -= Sign[Us] * ThreatedByPawnPenalty[Piece];
513
514         // Bishop and knight outposts squares
515         if ((Piece == BISHOP || Piece == KNIGHT) && pos.square_is_weak(s, Us))
516             evaluate_outposts<Piece, Us>(pos, ei, s);
517
518         // Queen or rook on 7th rank
519         if (  (Piece == ROOK || Piece == QUEEN)
520             && relative_rank(Us, s) == RANK_7
521             && relative_rank(Us, pos.king_square(Them)) == RANK_8)
522         {
523             ei.value += Sign[Us] * (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
524         }
525
526         // Special extra evaluation for rooks
527         if (Piece == ROOK)
528         {
529             // Open and half-open files
530             f = square_file(s);
531             if (ei.pi->file_is_half_open(Us, f))
532             {
533                 if (ei.pi->file_is_half_open(Them, f))
534                     ei.value += Sign[Us] * RookOpenFileBonus;
535                 else
536                     ei.value += Sign[Us] * RookHalfOpenFileBonus;
537             }
538
539             // Penalize rooks which are trapped inside a king. Penalize more if
540             // king has lost right to castle.
541             if (mob > 6 || ei.pi->file_is_half_open(Us, f))
542                 continue;
543
544             ksq = pos.king_square(Us);
545
546             if (    square_file(ksq) >= FILE_E
547                 &&  square_file(s) > square_file(ksq)
548                 && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
549             {
550                 // Is there a half-open file between the king and the edge of the board?
551                 if (!ei.pi->has_open_file_to_right(Us, square_file(ksq)))
552                     ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
553                                                                          : (TrappedRookPenalty - mob * 16), 0);
554             }
555             else if (    square_file(ksq) <= FILE_D
556                      &&  square_file(s) < square_file(ksq)
557                      && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
558             {
559                 // Is there a half-open file between the king and the edge of the board?
560                 if (!ei.pi->has_open_file_to_left(Us, square_file(ksq)))
561                     ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
562                                                                          : (TrappedRookPenalty - mob * 16), 0);
563             }
564         }
565     }
566   }
567
568
569   // evaluate_threats<>() assigns bonuses according to the type of attacking piece
570   // and the type of attacked one.
571
572   template<Color Us>
573   void evaluate_threats(const Position& pos, EvalInfo& ei) {
574
575     const Color Them = (Us == WHITE ? BLACK : WHITE);
576
577     Bitboard b;
578     Score bonus = SCORE_ZERO;
579
580     // Enemy pieces not defended by a pawn and under our attack
581     Bitboard weakEnemies =  pos.pieces_of_color(Them)
582                           & ~ei.attackedBy[Them][PAWN]
583                           & ei.attackedBy[Us][0];
584     if (!weakEnemies)
585         return;
586
587     // Add bonus according to type of attacked enemy pieces and to the
588     // type of attacking piece, from knights to queens. Kings are not
589     // considered because are already special handled in king evaluation.
590     for (PieceType pt1 = KNIGHT; pt1 < KING; pt1++)
591     {
592         b = ei.attackedBy[Us][pt1] & weakEnemies;
593         if (b)
594             for (PieceType pt2 = PAWN; pt2 < KING; pt2++)
595                 if (b & pos.pieces(pt2))
596                     bonus += ThreatBonus[pt1][pt2];
597     }
598     ei.value += Sign[Us] * bonus;
599   }
600
601
602   // evaluate_pieces_of_color<>() assigns bonuses and penalties to all the
603   // pieces of a given color.
604
605   template<Color Us, bool HasPopCnt>
606   void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei) {
607
608     const Color Them = (Us == WHITE ? BLACK : WHITE);
609
610     // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
611     const Bitboard no_mob_area = ~(ei.attackedBy[Them][PAWN] | pos.pieces_of_color(Us));
612
613     evaluate_pieces<KNIGHT, Us, HasPopCnt>(pos, ei, no_mob_area);
614     evaluate_pieces<BISHOP, Us, HasPopCnt>(pos, ei, no_mob_area);
615     evaluate_pieces<ROOK,   Us, HasPopCnt>(pos, ei, no_mob_area);
616     evaluate_pieces<QUEEN,  Us, HasPopCnt>(pos, ei, no_mob_area);
617
618     // Sum up all attacked squares
619     ei.attackedBy[Us][0] =   ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
620                            | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
621                            | ei.attackedBy[Us][QUEEN]  | ei.attackedBy[Us][KING];
622   }
623
624
625   // evaluate_king<>() assigns bonuses and penalties to a king of a given color
626
627   template<Color Us, bool HasPopCnt>
628   void evaluate_king(const Position& pos, EvalInfo& ei) {
629
630     const Color Them = (Us == WHITE ? BLACK : WHITE);
631
632     Bitboard undefended, b, b1, b2, safe;
633     bool sente;
634     int attackUnits;
635     const Square ksq = pos.king_square(Us);
636
637     // King shelter
638     ei.value += Sign[Us] * ei.pi->king_shelter(pos, Us, ksq);
639
640     // King safety. This is quite complicated, and is almost certainly far
641     // from optimally tuned.
642     if (   pos.piece_count(Them, QUEEN) >= 1
643         && ei.kingAttackersCount[Them]  >= 2
644         && pos.non_pawn_material(Them)  >= QueenValueMidgame + RookValueMidgame
645         && ei.kingAdjacentZoneAttacksCount[Them])
646     {
647         // Is it the attackers turn to move?
648         sente = (Them == pos.side_to_move());
649
650         // Find the attacked squares around the king which has no defenders
651         // apart from the king itself
652         undefended = ei.attacked_by(Them) & ei.attacked_by(Us, KING);
653         undefended &= ~(  ei.attacked_by(Us, PAWN)   | ei.attacked_by(Us, KNIGHT)
654                         | ei.attacked_by(Us, BISHOP) | ei.attacked_by(Us, ROOK)
655                         | ei.attacked_by(Us, QUEEN));
656
657         // Initialize the 'attackUnits' variable, which is used later on as an
658         // index to the KingDangerTable[] array. The initial value is based on
659         // the number and types of the enemy's attacking pieces, the number of
660         // attacked and undefended squares around our king, the square of the
661         // king, and the quality of the pawn shelter.
662         attackUnits =  Min(25, (ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2)
663                      + 3 * (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended))
664                      + InitKingDanger[relative_square(Us, ksq)]
665                      - mg_value(ei.pi->king_shelter(pos, Us, ksq)) / 32;
666
667         // Analyse enemy's safe queen contact checks. First find undefended
668         // squares around the king attacked by enemy queen...
669         b = undefended & ei.attacked_by(Them, QUEEN) & ~pos.pieces_of_color(Them);
670         if (b)
671         {
672             // ...then remove squares not supported by another enemy piece
673             b &= (  ei.attacked_by(Them, PAWN)   | ei.attacked_by(Them, KNIGHT)
674                   | ei.attacked_by(Them, BISHOP) | ei.attacked_by(Them, ROOK));
675             if (b)
676                 attackUnits += QueenContactCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
677         }
678
679         // Analyse enemy's safe distance checks for sliders and knights
680         safe = ~(pos.pieces_of_color(Them) | ei.attacked_by(Us));
681
682         b1 = pos.attacks_from<ROOK>(ksq) & safe;
683         b2 = pos.attacks_from<BISHOP>(ksq) & safe;
684
685         // Enemy queen safe checks
686         b = (b1 | b2) & ei.attacked_by(Them, QUEEN);
687         if (b)
688             attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b);
689
690         // Enemy rooks safe checks
691         b = b1 & ei.attacked_by(Them, ROOK);
692         if (b)
693             attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b);
694
695         // Enemy bishops safe checks
696         b = b2 & ei.attacked_by(Them, BISHOP);
697         if (b)
698             attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b);
699
700         // Enemy knights safe checks
701         b = pos.attacks_from<KNIGHT>(ksq) & ei.attacked_by(Them, KNIGHT) & safe;
702         if (b)
703             attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b);
704
705         // To index KingDangerTable[] attackUnits must be in [0, 99] range
706         attackUnits = Min(99, Max(0, attackUnits));
707
708         // Finally, extract the king danger score from the KingDangerTable[]
709         // array and subtract the score from evaluation. Set also ei.kingDanger[]
710         // value that will be used for pruning because this value can sometimes
711         // be very big, and so capturing a single attacking piece can therefore
712         // result in a score change far bigger than the value of the captured piece.
713         ei.value -= Sign[Us] * KingDangerTable[Us][attackUnits];
714         ei.kingDanger[Us] = mg_value(KingDangerTable[Us][attackUnits]);
715     }
716   }
717
718
719   // evaluate_passed_pawns<>() evaluates the passed pawns of the given color
720
721   template<Color Us>
722   void evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
723
724     const Color Them = (Us == WHITE ? BLACK : WHITE);
725
726     Bitboard squaresToQueen, defendedSquares, unsafeSquares, supportingPawns;
727     Bitboard b = ei.pi->passed_pawns(Us);
728
729     while (b)
730     {
731         Square s = pop_1st_bit(&b);
732
733         assert(pos.pawn_is_passed(Us, s));
734
735         int r = int(relative_rank(Us, s) - RANK_2);
736         int tr = r * (r - 1);
737
738         // Base bonus based on rank
739         Value mbonus = Value(20 * tr);
740         Value ebonus = Value(10 + r * r * 10);
741
742         if (tr)
743         {
744             Square blockSq = s + pawn_push(Us);
745
746             // Adjust bonus based on kings proximity
747             ebonus -= Value(square_distance(pos.king_square(Us), blockSq) * 3 * tr);
748             ebonus -= Value(square_distance(pos.king_square(Us), blockSq + pawn_push(Us)) * 1 * tr);
749             ebonus += Value(square_distance(pos.king_square(Them), blockSq) * 6 * tr);
750
751             // If the pawn is free to advance, increase bonus
752             if (pos.square_is_empty(blockSq))
753             {
754                 squaresToQueen = squares_in_front_of(Us, s);
755                 defendedSquares = squaresToQueen & ei.attacked_by(Us);
756
757                 // If there is an enemy rook or queen attacking the pawn from behind,
758                 // add all X-ray attacks by the rook or queen. Otherwise consider only
759                 // the squares in the pawn's path attacked or occupied by the enemy.
760                 if (   (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them))
761                     && (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<ROOK>(s)))
762                     unsafeSquares = squaresToQueen;
763                 else
764                     unsafeSquares = squaresToQueen & (ei.attacked_by(Them) | pos.pieces_of_color(Them));
765
766                 // If there aren't enemy attacks or pieces along the path to queen give
767                 // huge bonus. Even bigger if we protect the pawn's path.
768                 if (!unsafeSquares)
769                     ebonus += Value(tr * (squaresToQueen == defendedSquares ? 17 : 15));
770                 else
771                     // OK, there are enemy attacks or pieces (but not pawns). Are those
772                     // squares which are attacked by the enemy also attacked by us ?
773                     // If yes, big bonus (but smaller than when there are no enemy attacks),
774                     // if no, somewhat smaller bonus.
775                     ebonus += Value(tr * ((unsafeSquares & defendedSquares) == unsafeSquares ? 13 : 8));
776
777                 // At last, add a small bonus when there are no *friendly* pieces
778                 // in the pawn's path.
779                 if (!(squaresToQueen & pos.pieces_of_color(Us)))
780                     ebonus += Value(tr);
781             }
782         } // tr != 0
783
784         // Increase the bonus if the passed pawn is supported by a friendly pawn
785         // on the same rank and a bit smaller if it's on the previous rank.
786         supportingPawns = pos.pieces(PAWN, Us) & neighboring_files_bb(s);
787         if (supportingPawns & rank_bb(s))
788             ebonus += Value(r * 20);
789         else if (supportingPawns & rank_bb(s - pawn_push(Us)))
790             ebonus += Value(r * 12);
791
792         // Rook pawns are a special case: They are sometimes worse, and
793         // sometimes better than other passed pawns. It is difficult to find
794         // good rules for determining whether they are good or bad. For now,
795         // we try the following: Increase the value for rook pawns if the
796         // other side has no pieces apart from a knight, and decrease the
797         // value if the other side has a rook or queen.
798         if (square_file(s) == FILE_A || square_file(s) == FILE_H)
799         {
800             if (pos.non_pawn_material(Them) <= KnightValueMidgame)
801                 ebonus += ebonus / 4;
802             else if (pos.pieces(ROOK, QUEEN, Them))
803                 ebonus -= ebonus / 4;
804         }
805
806         // Add the scores for this pawn to the middle game and endgame eval
807         ei.value += Sign[Us] * apply_weight(make_score(mbonus, ebonus), Weights[PassedPawns]);
808
809     } // while
810   }
811
812
813   // evaluate_space() computes the space evaluation for a given side. The
814   // space evaluation is a simple bonus based on the number of safe squares
815   // available for minor pieces on the central four files on ranks 2--4. Safe
816   // squares one, two or three squares behind a friendly pawn are counted
817   // twice. Finally, the space bonus is scaled by a weight taken from the
818   // material hash table.
819   template<Color Us, bool HasPopCnt>
820   int evaluate_space(const Position& pos, EvalInfo& ei) {
821
822     const Color Them = (Us == WHITE ? BLACK : WHITE);
823
824     // Find the safe squares for our pieces inside the area defined by
825     // SpaceMask[us]. A square is unsafe if it is attacked by an enemy
826     // pawn, or if it is undefended and attacked by an enemy piece.
827     Bitboard safe =   SpaceMask[Us]
828                    & ~pos.pieces(PAWN, Us)
829                    & ~ei.attacked_by(Them, PAWN)
830                    & (ei.attacked_by(Us) | ~ei.attacked_by(Them));
831
832     // Find all squares which are at most three squares behind some friendly pawn
833     Bitboard behind = pos.pieces(PAWN, Us);
834     behind |= (Us == WHITE ? behind >>  8 : behind <<  8);
835     behind |= (Us == WHITE ? behind >> 16 : behind << 16);
836
837     return count_1s_max_15<HasPopCnt>(safe) + count_1s_max_15<HasPopCnt>(behind & safe);
838   }
839
840
841   // apply_weight() applies an evaluation weight to a value trying to prevent overflow
842
843   inline Score apply_weight(Score v, Score w) {
844       return make_score((int(mg_value(v)) * mg_value(w)) / 0x100, (int(eg_value(v)) * eg_value(w)) / 0x100);
845   }
846
847
848   // scale_by_game_phase() interpolates between a middle game and an endgame score,
849   // based on game phase. It also scales the return value by a ScaleFactor array.
850
851   Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]) {
852
853     assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
854     assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
855     assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
856
857     Value eg = eg_value(v);
858     ScaleFactor f = sf[eg > VALUE_ZERO ? WHITE : BLACK];
859     Value ev = Value((eg * int(f)) / SCALE_FACTOR_NORMAL);
860
861     int result = (mg_value(v) * int(ph) + ev * int(128 - ph)) / 128;
862     return Value(result & ~(GrainSize - 1));
863   }
864
865
866   // weight_option() computes the value of an evaluation weight, by combining
867   // two UCI-configurable weights (midgame and endgame) with an internal weight.
868
869   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
870
871     // Scale option value from 100 to 256
872     int mg = get_option_value_int(mgOpt) * 256 / 100;
873     int eg = get_option_value_int(egOpt) * 256 / 100;
874
875     return apply_weight(make_score(mg, eg), internalWeight);
876   }
877
878   // init_safety() initizes the king safety evaluation, based on UCI
879   // parameters. It is called from read_weights().
880
881   void init_safety() {
882
883     const Value MaxSlope = Value(30);
884     const Value Peak = Value(1280);
885     Value t[100];
886
887     // First setup the base table
888     for (int i = 0; i < 100; i++)
889     {
890         t[i] = Value(int(0.4 * i * i));
891
892         if (i > 0)
893             t[i] = Min(t[i], t[i - 1] + MaxSlope);
894
895         t[i] = Min(t[i], Peak);
896     }
897
898     // Then apply the weights and get the final KingDangerTable[] array
899     for (Color c = WHITE; c <= BLACK; c++)
900         for (int i = 0; i < 100; i++)
901             KingDangerTable[c][i] = apply_weight(make_score(t[i], 0), Weights[KingDangerUs + c]);
902   }
903 }