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