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