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