]> git.sesse.net Git - stockfish/blob - src/evaluate.cpp
Rearrange table layout in evaluate.cpp
[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-2009 Marco Costalba
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 "scale.h"
33 #include "thread.h"
34 #include "ucioption.h"
35
36
37 ////
38 //// Local definitions
39 ////
40
41 namespace {
42
43   const int Sign[2] = { 1, -1 };
44
45   // Evaluation grain size, must be a power of 2
46   const int GrainSize = 8;
47
48   // Evaluation weights, initialized from UCI options
49   Score WeightMobility, WeightPawnStructure;
50   Score WeightPassedPawns, WeightSpace;
51   Score WeightKingSafety[2];
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 WeightMobilityInternal      = make_score(248, 271);
60   const Score WeightPawnStructureInternal = make_score(233, 201);
61   const Score WeightPassedPawnsInternal   = make_score(252, 259);
62   const Score WeightSpaceInternal         = make_score( 46,   0);
63   const Score WeightKingSafetyInternal    = make_score(247,   0);
64   const Score WeightKingOppSafetyInternal = make_score(259,   0);
65
66   // Mobility and outposts bonus modified by Joona Kiiski
67   //
68   // Visually better to define tables constants
69   typedef Value V;
70   #define S(mg, eg) make_score(mg, eg)
71
72   CACHE_LINE_ALIGNMENT
73
74   // Knight mobility bonus in middle game and endgame, indexed by the number
75   // of attacked squares not occupied by friendly piecess.
76   const Score KnightMobilityBonus[16] = {
77     S(-38,-33), S(-25,-23), S(-12,-13), S( 0,-3),
78     S( 12,  7), S( 25, 17), S( 31, 22), S(38, 27), S(38, 27)
79   };
80
81   // Bishop 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 are also included.
84   const Score BishopMobilityBonus[16] = {
85     S(-25,-30), S(-11,-16), S( 3, -2), S(17, 12),
86     S( 31, 26), S( 45, 40), S(57, 52), S(65, 60),
87     S( 71, 65), S( 74, 69), S(76, 71), S(78, 73),
88     S( 79, 74), S( 80, 75), S(81, 76), S(81, 76)
89   };
90
91   // Rook mobility bonus in middle game and endgame, indexed by the number
92   // of attacked squares not occupied by friendly pieces. X-ray attacks through
93   // queens and rooks are also included.
94   const Score RookMobilityBonus[16] = {
95     S(-20,-36), S(-14,-19), S(-8, -3), S(-2, 13),
96     S(  4, 29), S( 10, 46), S(14, 62), S(19, 79),
97     S( 23, 95), S( 26,106), S(27,111), S(28,114),
98     S( 29,116), S( 30,117), S(31,118), S(32,118)
99   };
100
101   // Queen mobility bonus in middle game and endgame, indexed by the number
102   // of attacked squares not occupied by friendly pieces.
103   const Score QueenMobilityBonus[32] = {
104     S(-10,-18), S(-8,-13), S(-6, -7), S(-3, -2), S(-1,  3), S( 1,  8),
105     S(  3, 13), S( 5, 19), S( 8, 23), S(10, 27), S(12, 32), S(15, 34),
106     S( 16, 35), S(17, 35), S(18, 35), S(20, 35), S(20, 35), S(20, 35),
107     S( 20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35),
108     S( 20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35), S(20, 35),
109     S( 20, 35), S(20, 35)
110   };
111
112   // Pointers table to access mobility tables through piece type
113   const Score* MobilityBonus[8] = { 0, 0, KnightMobilityBonus, BishopMobilityBonus,
114                                    RookMobilityBonus, QueenMobilityBonus, 0, 0 };
115
116   // Outpost bonuses for knights and bishops, indexed by square (from white's
117   // point of view).
118   const Value KnightOutpostBonus[64] = {
119   //  A     B     C     D     E     F     G     H
120     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 1
121     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 2
122     V(0), V(0), V(4), V(8), V(8), V(4), V(0), V(0), // 3
123     V(0), V(4),V(17),V(26),V(26),V(17), V(4), V(0), // 4
124     V(0), V(8),V(26),V(35),V(35),V(26), V(8), V(0), // 5
125     V(0), V(4),V(17),V(17),V(17),V(17), V(4), V(0), // 6
126     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 7
127     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0)  // 8
128   };
129
130   const Value BishopOutpostBonus[64] = {
131   //  A     B     C     D     E     F     G     H
132     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 1
133     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 2
134     V(0), V(0), V(5), V(5), V(5), V(5), V(0), V(0), // 3
135     V(0), V(5),V(10),V(10),V(10),V(10), V(5), V(0), // 4
136     V(0),V(10),V(21),V(21),V(21),V(21),V(10), V(0), // 5
137     V(0), V(5), V(8), V(8), V(8), V(8), V(5), V(0), // 6
138     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0), // 7
139     V(0), V(0), V(0), V(0), V(0), V(0), V(0), V(0)  // 8
140   };
141
142   // ThreatBonus[][] contains bonus according to which piece type
143   // attacks which one.
144   #define Z make_score(0, 0)
145
146   const Score ThreatBonus[8][8] = {
147       { Z, Z, Z, Z, Z, Z, Z, Z }, // not used
148       { Z, S(18,37),       Z, S(37,47), S(55,97), S(55,97), Z, Z }, // KNIGHT attacks
149       { Z, S(18,37), S(37,47),       Z, S(55,97), S(55,97), Z, Z }, // BISHOP attacks
150       { Z, S( 9,27), S(27,47), S(27,47),       Z, S(37,47), Z, Z }, // ROOK attacks
151       { Z, S(27,37), S(27,37), S(27,37), S(27,37),       Z, Z, Z }, // QUEEN attacks
152       { Z, Z, Z, Z, Z, Z, Z, Z }, // not used
153       { Z, Z, Z, Z, Z, Z, Z, Z }, // not used
154       { Z, Z, Z, Z, Z, Z, Z, Z }  // not used
155   };
156
157   // ThreatedByPawnPenalty[] contains a penalty according to which piece
158   // type is attacked by an enemy pawn.
159   const Score ThreatedByPawnPenalty[8] = {
160     Z, Z, S(56, 70), S(56, 70), S(76, 99), S(86, 118), Z, Z
161   };
162
163   #undef Z
164   #undef S
165
166   // Bonus for unstoppable passed pawns
167   const Value UnstoppablePawnValue = Value(0x500);
168
169   // Rooks and queens on the 7th rank (modified by Joona Kiiski)
170   const Score RookOn7thBonus  = make_score(47, 98);
171   const Score QueenOn7thBonus = make_score(27, 54);
172
173   // Rooks on open files (modified by Joona Kiiski)
174   const Score RookOpenFileBonus = make_score(43, 43);
175   const Score RookHalfOpenFileBonus = make_score(19, 19);
176
177   // Penalty for rooks trapped inside a friendly king which has lost the
178   // right to castle.
179   const Value TrappedRookPenalty = Value(180);
180
181   // Penalty for a bishop on a7/h7 (a2/h2 for black) which is trapped by
182   // enemy pawns.
183   const Score TrappedBishopA7H7Penalty = make_score(300, 300);
184
185   // Bitboard masks for detecting trapped bishops on a7/h7 (a2/h2 for black)
186   const Bitboard MaskA7H7[2] = {
187     ((1ULL << SQ_A7) | (1ULL << SQ_H7)),
188     ((1ULL << SQ_A2) | (1ULL << SQ_H2))
189   };
190
191   // Penalty for a bishop on a1/h1 (a8/h8 for black) which is trapped by
192   // a friendly pawn on b2/g2 (b7/g7 for black). This can obviously only
193   // happen in Chess960 games.
194   const Score TrappedBishopA1H1Penalty = make_score(100, 100);
195
196   // Bitboard masks for detecting trapped bishops on a1/h1 (a8/h8 for black)
197   const Bitboard MaskA1H1[2] = {
198     ((1ULL << SQ_A1) | (1ULL << SQ_H1)),
199     ((1ULL << SQ_A8) | (1ULL << SQ_H8))
200   };
201
202   // The SpaceMask[color] contains the area of the board which is considered
203   // by the space evaluation. In the middle game, each side is given a bonus
204   // based on how many squares inside this area are safe and available for
205   // friendly minor pieces.
206   const Bitboard SpaceMask[2] = {
207     (1ULL<<SQ_C2) | (1ULL<<SQ_D2) | (1ULL<<SQ_E2) | (1ULL<<SQ_F2) |
208     (1ULL<<SQ_C3) | (1ULL<<SQ_D3) | (1ULL<<SQ_E3) | (1ULL<<SQ_F3) |
209     (1ULL<<SQ_C4) | (1ULL<<SQ_D4) | (1ULL<<SQ_E4) | (1ULL<<SQ_F4),
210     (1ULL<<SQ_C7) | (1ULL<<SQ_D7) | (1ULL<<SQ_E7) | (1ULL<<SQ_F7) |
211     (1ULL<<SQ_C6) | (1ULL<<SQ_D6) | (1ULL<<SQ_E6) | (1ULL<<SQ_F6) |
212     (1ULL<<SQ_C5) | (1ULL<<SQ_D5) | (1ULL<<SQ_E5) | (1ULL<<SQ_F5)
213   };
214
215   /// King safety constants and variables. The king safety scores are taken
216   /// from the array SafetyTable[]. Various little "meta-bonuses" measuring
217   /// the strength of the attack are added up into an integer, which is used
218   /// as an index to SafetyTable[].
219
220   // Attack weights for each piece type and table indexed on piece type
221   const int QueenAttackWeight  = 5;
222   const int RookAttackWeight   = 3;
223   const int BishopAttackWeight = 2;
224   const int KnightAttackWeight = 2;
225
226   const int AttackWeight[] = { 0, 0, KnightAttackWeight, BishopAttackWeight, RookAttackWeight, QueenAttackWeight };
227
228   // Bonuses for safe checks, initialized from UCI options
229   int QueenContactCheckBonus, DiscoveredCheckBonus;
230   int QueenCheckBonus, RookCheckBonus, BishopCheckBonus, KnightCheckBonus;
231
232   // Scan for queen contact mates?
233   const bool QueenContactMates = true;
234
235   // Bonus for having a mate threat, initialized from UCI options
236   int MateThreatBonus;
237
238   // InitKingDanger[] contains bonuses based on the position of the defending
239   // king.
240   const int InitKingDanger[64] = {
241      2,  0,  2,  5,  5,  2,  0,  2,
242      2,  2,  4,  8,  8,  4,  2,  2,
243      7, 10, 12, 12, 12, 12, 10,  7,
244     15, 15, 15, 15, 15, 15, 15, 15,
245     15, 15, 15, 15, 15, 15, 15, 15,
246     15, 15, 15, 15, 15, 15, 15, 15,
247     15, 15, 15, 15, 15, 15, 15, 15,
248     15, 15, 15, 15, 15, 15, 15, 15
249   };
250
251   // SafetyTable[] contains the actual king safety scores. It is initialized
252   // in init_safety().
253   Value SafetyTable[100];
254
255   // Pawn and material hash tables, indexed by the current thread id
256   PawnInfoTable* PawnTable[8] = {0, 0, 0, 0, 0, 0, 0, 0};
257   MaterialInfoTable* MaterialTable[8] = {0, 0, 0, 0, 0, 0, 0, 0};
258
259   // Sizes of pawn and material hash tables
260   const int PawnTableSize = 16384;
261   const int MaterialTableSize = 1024;
262
263   // Function prototypes
264   template<bool HasPopCnt>
265   Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID);
266
267   template<Color Us, bool HasPopCnt>
268   void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei);
269
270   template<Color Us, bool HasPopCnt>
271   void evaluate_king(const Position& pos, EvalInfo& ei);
272
273   template<Color Us>
274   void evaluate_threats(const Position& pos, EvalInfo& ei);
275
276   template<Color Us, bool HasPopCnt>
277   void evaluate_space(const Position& pos, EvalInfo& ei);
278
279   void evaluate_passed_pawns(const Position& pos, EvalInfo& ei);
280   void evaluate_trapped_bishop_a7h7(const Position& pos, Square s, Color us, EvalInfo& ei);
281   void evaluate_trapped_bishop_a1h1(const Position& pos, Square s, Color us, EvalInfo& ei);
282   inline Score apply_weight(Score v, Score weight);
283   Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]);
284   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight);
285   void init_safety();
286 }
287
288
289 ////
290 //// Functions
291 ////
292
293 /// evaluate() is the main evaluation function. It always computes two
294 /// values, an endgame score and a middle game score, and interpolates
295 /// between them based on the remaining material.
296 Value evaluate(const Position& pos, EvalInfo& ei, int threadID) {
297
298     return CpuHasPOPCNT ? do_evaluate<true>(pos, ei, threadID)
299                         : do_evaluate<false>(pos, ei, threadID);
300 }
301
302 namespace {
303
304 template<bool HasPopCnt>
305 Value do_evaluate(const Position& pos, EvalInfo& ei, int threadID) {
306
307   assert(pos.is_ok());
308   assert(threadID >= 0 && threadID < THREAD_MAX);
309   assert(!pos.is_check());
310
311   memset(&ei, 0, sizeof(EvalInfo));
312
313   // Initialize by reading the incrementally updated scores included in the
314   // position object (material + piece square tables)
315   ei.value = pos.value();
316
317   // Probe the material hash table
318   ei.mi = MaterialTable[threadID]->get_material_info(pos);
319   ei.value += ei.mi->material_value();
320
321   // If we have a specialized evaluation function for the current material
322   // configuration, call it and return
323   if (ei.mi->specialized_eval_exists())
324       return ei.mi->evaluate(pos);
325
326   // After get_material_info() call that modifies them
327   ScaleFactor factor[2];
328   factor[WHITE] = ei.mi->scale_factor(pos, WHITE);
329   factor[BLACK] = ei.mi->scale_factor(pos, BLACK);
330
331   // Probe the pawn hash table
332   ei.pi = PawnTable[threadID]->get_pawn_info(pos);
333   ei.value += apply_weight(ei.pi->value(), WeightPawnStructure);
334
335   // Initialize king attack bitboards and king attack zones for both sides
336   ei.attackedBy[WHITE][KING] = pos.attacks_from<KING>(pos.king_square(WHITE));
337   ei.attackedBy[BLACK][KING] = pos.attacks_from<KING>(pos.king_square(BLACK));
338   ei.kingZone[WHITE] = ei.attackedBy[BLACK][KING] | (ei.attackedBy[BLACK][KING] >> 8);
339   ei.kingZone[BLACK] = ei.attackedBy[WHITE][KING] | (ei.attackedBy[WHITE][KING] << 8);
340
341   // Initialize pawn attack bitboards for both sides
342   ei.attackedBy[WHITE][PAWN] = ei.pi->pawn_attacks(WHITE);
343   ei.attackedBy[BLACK][PAWN] = ei.pi->pawn_attacks(BLACK);
344   Bitboard b1 = ei.attackedBy[WHITE][PAWN] & ei.attackedBy[BLACK][KING];
345   Bitboard b2 = ei.attackedBy[BLACK][PAWN] & ei.attackedBy[WHITE][KING];
346   if (b1)
347       ei.kingAttackersCount[WHITE] = count_1s_max_15<HasPopCnt>(b1)/2;
348
349   if (b2)
350       ei.kingAttackersCount[BLACK] = count_1s_max_15<HasPopCnt>(b2)/2;
351
352   // Evaluate pieces
353   evaluate_pieces_of_color<WHITE, HasPopCnt>(pos, ei);
354   evaluate_pieces_of_color<BLACK, HasPopCnt>(pos, ei);
355
356   // Kings. Kings are evaluated after all other pieces for both sides,
357   // because we need complete attack information for all pieces when computing
358   // the king safety evaluation.
359   evaluate_king<WHITE, HasPopCnt>(pos, ei);
360   evaluate_king<BLACK, HasPopCnt>(pos, ei);
361
362   // Evaluate tactical threats, we need full attack info
363   evaluate_threats<WHITE>(pos, ei);
364   evaluate_threats<BLACK>(pos, ei);
365
366   // Evaluate passed pawns. We evaluate passed pawns for both sides at once,
367   // because we need to know which side promotes first in positions where
368   // both sides have an unstoppable passed pawn. To be called after all attacks
369   // are computed, included king.
370   if (ei.pi->passed_pawns())
371       evaluate_passed_pawns(pos, ei);
372
373   Phase phase = pos.game_phase();
374
375   // Middle-game specific evaluation terms
376   if (phase > PHASE_ENDGAME)
377   {
378     // Pawn storms in positions with opposite castling.
379     if (   square_file(pos.king_square(WHITE)) >= FILE_E
380         && square_file(pos.king_square(BLACK)) <= FILE_D)
381
382         ei.value += make_score(ei.pi->queenside_storm_value(WHITE) - ei.pi->kingside_storm_value(BLACK), 0);
383
384     else if (   square_file(pos.king_square(WHITE)) <= FILE_D
385              && square_file(pos.king_square(BLACK)) >= FILE_E)
386
387         ei.value += make_score(ei.pi->kingside_storm_value(WHITE) - ei.pi->queenside_storm_value(BLACK), 0);
388
389     // Evaluate space for both sides
390     if (ei.mi->space_weight() > 0)
391     {
392         evaluate_space<WHITE, HasPopCnt>(pos, ei);
393         evaluate_space<BLACK, HasPopCnt>(pos, ei);
394     }
395   }
396
397   // Mobility
398   ei.value += apply_weight(ei.mobility, WeightMobility);
399
400   // If we don't already have an unusual scale factor, check for opposite
401   // colored bishop endgames, and use a lower scale for those
402   if (   phase < PHASE_MIDGAME
403       && pos.opposite_colored_bishops()
404       && (   (factor[WHITE] == SCALE_FACTOR_NORMAL && eg_value(ei.value) > Value(0))
405           || (factor[BLACK] == SCALE_FACTOR_NORMAL && eg_value(ei.value) < Value(0))))
406   {
407       ScaleFactor sf;
408
409       // Only the two bishops ?
410       if (   pos.non_pawn_material(WHITE) == BishopValueMidgame
411           && pos.non_pawn_material(BLACK) == BishopValueMidgame)
412       {
413           // Check for KBP vs KB with only a single pawn that is almost
414           // certainly a draw or at least two pawns.
415           bool one_pawn = (pos.piece_count(WHITE, PAWN) + pos.piece_count(BLACK, PAWN) == 1);
416           sf = one_pawn ? ScaleFactor(8) : ScaleFactor(32);
417       }
418       else
419           // Endgame with opposite-colored bishops, but also other pieces. Still
420           // a bit drawish, but not as drawish as with only the two bishops.
421            sf = ScaleFactor(50);
422
423       if (factor[WHITE] == SCALE_FACTOR_NORMAL)
424           factor[WHITE] = sf;
425       if (factor[BLACK] == SCALE_FACTOR_NORMAL)
426           factor[BLACK] = sf;
427   }
428
429   // Interpolate between the middle game and the endgame score
430   Color stm = pos.side_to_move();
431
432   Value v = Sign[stm] * scale_by_game_phase(ei.value, phase, factor);
433
434   return (ei.mateThreat[stm] == MOVE_NONE ? v : 8 * QueenValueMidgame - v);
435 }
436
437 } // namespace
438
439 /// quick_evaluate() does a very approximate evaluation of the current position.
440 /// It currently considers only material and piece square table scores. Perhaps
441 /// we should add scores from the pawn and material hash tables?
442
443 Value quick_evaluate(const Position &pos) {
444
445   assert(pos.is_ok());
446
447   static const
448   ScaleFactor sf[2] = {SCALE_FACTOR_NORMAL, SCALE_FACTOR_NORMAL};
449
450   Phase ph = pos.game_phase();
451   Color stm = pos.side_to_move();
452
453   return Sign[stm] * scale_by_game_phase(pos.value(), ph, sf);
454 }
455
456
457 /// init_eval() initializes various tables used by the evaluation function
458
459 void init_eval(int threads) {
460
461   assert(threads <= THREAD_MAX);
462
463   for (int i = 0; i < THREAD_MAX; i++)
464   {
465     if (i >= threads)
466     {
467         delete PawnTable[i];
468         delete MaterialTable[i];
469         PawnTable[i] = NULL;
470         MaterialTable[i] = NULL;
471         continue;
472     }
473     if (!PawnTable[i])
474         PawnTable[i] = new PawnInfoTable(PawnTableSize);
475     if (!MaterialTable[i])
476         MaterialTable[i] = new MaterialInfoTable(MaterialTableSize);
477   }
478 }
479
480
481 /// quit_eval() releases heap-allocated memory at program termination
482
483 void quit_eval() {
484
485   for (int i = 0; i < THREAD_MAX; i++)
486   {
487       delete PawnTable[i];
488       delete MaterialTable[i];
489       PawnTable[i] = NULL;
490       MaterialTable[i] = NULL;
491   }
492 }
493
494
495 /// read_weights() reads evaluation weights from the corresponding UCI parameters
496
497 void read_weights(Color us) {
498
499   Color them = opposite_color(us);
500
501   WeightMobility         = weight_option("Mobility (Middle Game)", "Mobility (Endgame)", WeightMobilityInternal);
502   WeightPawnStructure    = weight_option("Pawn Structure (Middle Game)", "Pawn Structure (Endgame)", WeightPawnStructureInternal);
503   WeightPassedPawns      = weight_option("Passed Pawns (Middle Game)", "Passed Pawns (Endgame)", WeightPassedPawnsInternal);
504   WeightSpace            = weight_option("Space", "Space", WeightSpaceInternal);
505   WeightKingSafety[us]   = weight_option("Cowardice", "Cowardice", WeightKingSafetyInternal);
506   WeightKingSafety[them] = weight_option("Aggressiveness", "Aggressiveness", WeightKingOppSafetyInternal);
507
508   // If running in analysis mode, make sure we use symmetrical king safety. We do this
509   // by replacing both WeightKingSafety[us] and WeightKingSafety[them] by their average.
510   if (get_option_value_bool("UCI_AnalyseMode"))
511   {
512       WeightKingSafety[us] = (WeightKingSafety[us] + WeightKingSafety[them]) / 2;
513       WeightKingSafety[them] = WeightKingSafety[us];
514   }
515   init_safety();
516 }
517
518
519 namespace {
520
521   // evaluate_outposts() evaluates bishop and knight outposts squares
522
523   template<PieceType Piece, Color Us>
524   void evaluate_outposts(const Position& pos, EvalInfo& ei, Square s) {
525
526     const Color Them = (Us == WHITE ? BLACK : WHITE);
527
528     // Initial bonus based on square
529     Value bonus = (Piece == BISHOP ? BishopOutpostBonus[relative_square(Us, s)]
530                                    : KnightOutpostBonus[relative_square(Us, s)]);
531
532     // Increase bonus if supported by pawn, especially if the opponent has
533     // no minor piece which can exchange the outpost piece
534     if (bonus && bit_is_set(ei.attackedBy[Us][PAWN], s))
535     {
536         if (    pos.pieces(KNIGHT, Them) == EmptyBoardBB
537             && (SquaresByColorBB[square_color(s)] & pos.pieces(BISHOP, Them)) == EmptyBoardBB)
538             bonus += bonus + bonus / 2;
539         else
540             bonus += bonus / 2;
541     }
542     ei.value += Sign[Us] * make_score(bonus, bonus);
543   }
544
545
546   // evaluate_pieces<>() assigns bonuses and penalties to the pieces of a given color
547
548   template<PieceType Piece, Color Us, bool HasPopCnt>
549   void evaluate_pieces(const Position& pos, EvalInfo& ei, Bitboard no_mob_area) {
550
551     Bitboard b;
552     Square s, ksq;
553     int mob;
554     File f;
555
556     const Color Them = (Us == WHITE ? BLACK : WHITE);
557     const Square* ptr = pos.piece_list_begin(Us, Piece);
558
559     while ((s = *ptr++) != SQ_NONE)
560     {
561         // Find attacked squares, including x-ray attacks for bishops and rooks
562         if (Piece == KNIGHT || Piece == QUEEN)
563             b = pos.attacks_from<Piece>(s);
564         else if (Piece == BISHOP)
565             b = bishop_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(QUEEN, Us));
566         else if (Piece == ROOK)
567             b = rook_attacks_bb(s, pos.occupied_squares() & ~pos.pieces(ROOK, QUEEN, Us));
568         else
569             assert(false);
570
571         // Update attack info
572         ei.attackedBy[Us][Piece] |= b;
573
574         // King attacks
575         if (b & ei.kingZone[Us])
576         {
577             ei.kingAttackersCount[Us]++;
578             ei.kingAttackersWeight[Us] += AttackWeight[Piece];
579             Bitboard bb = (b & ei.attackedBy[Them][KING]);
580             if (bb)
581                 ei.kingAdjacentZoneAttacksCount[Us] += count_1s_max_15<HasPopCnt>(bb);
582         }
583
584         // Mobility
585         mob = (Piece != QUEEN ? count_1s_max_15<HasPopCnt>(b & no_mob_area)
586                               : count_1s<HasPopCnt>(b & no_mob_area));
587
588         ei.mobility += Sign[Us] * MobilityBonus[Piece][mob];
589
590         // Decrease score if we are attacked by an enemy pawn. Remaining part
591         // of threat evaluation must be done later when we have full attack info.
592         if (bit_is_set(ei.attackedBy[Them][PAWN], s))
593             ei.value -= Sign[Us] * ThreatedByPawnPenalty[Piece];
594
595         // Bishop and knight outposts squares
596         if ((Piece == BISHOP || Piece == KNIGHT) && pos.square_is_weak(s, Them))
597             evaluate_outposts<Piece, Us>(pos, ei, s);
598
599         // Special patterns: trapped bishops on a7/h7/a2/h2
600         // and trapped bishops on a1/h1/a8/h8 in Chess960.
601         if (Piece == BISHOP)
602         {
603             if (bit_is_set(MaskA7H7[Us], s))
604                 evaluate_trapped_bishop_a7h7(pos, s, Us, ei);
605
606             if (Chess960 && bit_is_set(MaskA1H1[Us], s))
607                 evaluate_trapped_bishop_a1h1(pos, s, Us, ei);
608         }
609
610         // Queen or rook on 7th rank
611         if (  (Piece == ROOK || Piece == QUEEN)
612             && relative_rank(Us, s) == RANK_7
613             && relative_rank(Us, pos.king_square(Them)) == RANK_8)
614         {
615             ei.value += Sign[Us] * (Piece == ROOK ? RookOn7thBonus : QueenOn7thBonus);
616         }
617
618         // Special extra evaluation for rooks
619         if (Piece == ROOK)
620         {
621             // Open and half-open files
622             f = square_file(s);
623             if (ei.pi->file_is_half_open(Us, f))
624             {
625                 if (ei.pi->file_is_half_open(Them, f))
626                     ei.value += Sign[Us] * RookOpenFileBonus;
627                 else
628                     ei.value += Sign[Us] * RookHalfOpenFileBonus;
629             }
630
631             // Penalize rooks which are trapped inside a king. Penalize more if
632             // king has lost right to castle.
633             if (mob > 6 || ei.pi->file_is_half_open(Us, f))
634                 continue;
635
636             ksq = pos.king_square(Us);
637
638             if (    square_file(ksq) >= FILE_E
639                 &&  square_file(s) > square_file(ksq)
640                 && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
641             {
642                 // Is there a half-open file between the king and the edge of the board?
643                 if (!ei.pi->has_open_file_to_right(Us, square_file(ksq)))
644                     ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
645                                                                          : (TrappedRookPenalty - mob * 16), 0);
646             }
647             else if (    square_file(ksq) <= FILE_D
648                      &&  square_file(s) < square_file(ksq)
649                      && (relative_rank(Us, ksq) == RANK_1 || square_rank(ksq) == square_rank(s)))
650             {
651                 // Is there a half-open file between the king and the edge of the board?
652                 if (!ei.pi->has_open_file_to_left(Us, square_file(ksq)))
653                     ei.value -= Sign[Us] * make_score(pos.can_castle(Us) ? (TrappedRookPenalty - mob * 16) / 2
654                                                                          : (TrappedRookPenalty - mob * 16), 0);
655             }
656         }
657     }
658   }
659
660
661   // evaluate_threats<>() assigns bonuses according to the type of attacking piece
662   // and the type of attacked one.
663
664   template<Color Us>
665   void evaluate_threats(const Position& pos, EvalInfo& ei) {
666
667     const Color Them = (Us == WHITE ? BLACK : WHITE);
668
669     Bitboard b;
670     Score bonus = make_score(0, 0);
671
672     // Enemy pieces not defended by a pawn and under our attack
673     Bitboard weakEnemies =  pos.pieces_of_color(Them)
674                           & ~ei.attackedBy[Them][PAWN]
675                           & ei.attackedBy[Us][0];
676     if (!weakEnemies)
677         return;
678
679     // Add bonus according to type of attacked enemy pieces and to the
680     // type of attacking piece, from knights to queens. Kings are not
681     // considered because are already special handled in king evaluation.
682     for (PieceType pt1 = KNIGHT; pt1 < KING; pt1++)
683     {
684         b = ei.attackedBy[Us][pt1] & weakEnemies;
685         if (b)
686             for (PieceType pt2 = PAWN; pt2 < KING; pt2++)
687                 if (b & pos.pieces(pt2))
688                     bonus += ThreatBonus[pt1][pt2];
689     }
690     ei.value += Sign[Us] * bonus;
691   }
692
693
694   // evaluate_pieces_of_color<>() assigns bonuses and penalties to all the
695   // pieces of a given color.
696
697   template<Color Us, bool HasPopCnt>
698   void evaluate_pieces_of_color(const Position& pos, EvalInfo& ei) {
699
700     const Color Them = (Us == WHITE ? BLACK : WHITE);
701
702     // Do not include in mobility squares protected by enemy pawns or occupied by our pieces
703     const Bitboard no_mob_area = ~(ei.attackedBy[Them][PAWN] | pos.pieces_of_color(Us));
704
705     evaluate_pieces<KNIGHT, Us, HasPopCnt>(pos, ei, no_mob_area);
706     evaluate_pieces<BISHOP, Us, HasPopCnt>(pos, ei, no_mob_area);
707     evaluate_pieces<ROOK,   Us, HasPopCnt>(pos, ei, no_mob_area);
708     evaluate_pieces<QUEEN,  Us, HasPopCnt>(pos, ei, no_mob_area);
709
710     // Sum up all attacked squares
711     ei.attackedBy[Us][0] =   ei.attackedBy[Us][PAWN]   | ei.attackedBy[Us][KNIGHT]
712                            | ei.attackedBy[Us][BISHOP] | ei.attackedBy[Us][ROOK]
713                            | ei.attackedBy[Us][QUEEN]  | ei.attackedBy[Us][KING];
714   }
715
716
717   // evaluate_king<>() assigns bonuses and penalties to a king of a given color
718
719   template<Color Us, bool HasPopCnt>
720   void evaluate_king(const Position& pos, EvalInfo& ei) {
721
722     const Color Them = (Us == WHITE ? BLACK : WHITE);
723     const Square s = pos.king_square(Us);
724     int shelter = 0;
725
726     // King shelter
727     if (relative_rank(Us, s) <= RANK_4)
728     {
729         shelter = ei.pi->get_king_shelter(pos, Us, s);
730         ei.value += Sign[Us] * make_score(shelter, 0);
731     }
732
733     // King safety. This is quite complicated, and is almost certainly far
734     // from optimally tuned.
735     if (   pos.piece_count(Them, QUEEN) >= 1
736         && ei.kingAttackersCount[Them] >= 2
737         && pos.non_pawn_material(Them) >= QueenValueMidgame + RookValueMidgame
738         && ei.kingAdjacentZoneAttacksCount[Them])
739     {
740       // Is it the attackers turn to move?
741       bool sente = (Them == pos.side_to_move());
742
743       // Find the attacked squares around the king which has no defenders
744       // apart from the king itself
745       Bitboard undefended =
746              ei.attacked_by(Them)       & ~ei.attacked_by(Us, PAWN)
747           & ~ei.attacked_by(Us, KNIGHT) & ~ei.attacked_by(Us, BISHOP)
748           & ~ei.attacked_by(Us, ROOK)   & ~ei.attacked_by(Us, QUEEN)
749           &  ei.attacked_by(Us, KING);
750
751       Bitboard occ = pos.occupied_squares(), b, b2;
752
753       // Initialize the 'attackUnits' variable, which is used later on as an
754       // index to the SafetyTable[] array.  The initial value is based on the
755       // number and types of the attacking pieces, the number of attacked and
756       // undefended squares around the king, the square of the king, and the
757       // quality of the pawn shelter.
758       int attackUnits =
759             Min((ei.kingAttackersCount[Them] * ei.kingAttackersWeight[Them]) / 2, 25)
760           + (ei.kingAdjacentZoneAttacksCount[Them] + count_1s_max_15<HasPopCnt>(undefended)) * 3
761           + InitKingDanger[relative_square(Us, s)] - (shelter >> 5);
762
763       // Analyse safe queen contact checks
764       b = undefended & ei.attacked_by(Them, QUEEN) & ~pos.pieces_of_color(Them);
765       if (b)
766       {
767         Bitboard attackedByOthers =
768               ei.attacked_by(Them, PAWN)   | ei.attacked_by(Them, KNIGHT)
769             | ei.attacked_by(Them, BISHOP) | ei.attacked_by(Them, ROOK);
770
771         b &= attackedByOthers;
772         if (b)
773         {
774           // The bitboard b now contains the squares available for safe queen
775           // contact checks.
776           int count = count_1s_max_15<HasPopCnt>(b);
777           attackUnits += QueenContactCheckBonus * count * (sente ? 2 : 1);
778
779           // Is there a mate threat?
780           if (QueenContactMates && !pos.is_check())
781           {
782             Bitboard escapeSquares =
783                 pos.attacks_from<KING>(s) & ~pos.pieces_of_color(Us) & ~attackedByOthers;
784
785             while (b)
786             {
787                 Square from, to = pop_1st_bit(&b);
788                 if (!(escapeSquares & ~queen_attacks_bb(to, occ & ClearMaskBB[s])))
789                 {
790                     // We have a mate, unless the queen is pinned or there
791                     // is an X-ray attack through the queen.
792                     for (int i = 0; i < pos.piece_count(Them, QUEEN); i++)
793                     {
794                         from = pos.piece_list(Them, QUEEN, i);
795                         if (    bit_is_set(pos.attacks_from<QUEEN>(from), to)
796                             && !bit_is_set(pos.pinned_pieces(Them), from)
797                             && !(rook_attacks_bb(to, occ & ClearMaskBB[from]) & pos.pieces(ROOK, QUEEN, Us))
798                             && !(bishop_attacks_bb(to, occ & ClearMaskBB[from]) & pos.pieces(BISHOP, QUEEN, Us)))
799
800                             ei.mateThreat[Them] = make_move(from, to);
801                     }
802                 }
803             }
804           }
805         }
806       }
807
808       // Analyse safe distance checks
809       if (QueenCheckBonus > 0 || RookCheckBonus > 0)
810       {
811           b = pos.attacks_from<ROOK>(s) & ~pos.pieces_of_color(Them) & ~ei.attacked_by(Us);
812
813           // Queen checks
814           b2 = b & ei.attacked_by(Them, QUEEN);
815           if (b2)
816               attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b2);
817
818           // Rook checks
819           b2 = b & ei.attacked_by(Them, ROOK);
820           if (b2)
821               attackUnits += RookCheckBonus * count_1s_max_15<HasPopCnt>(b2);
822       }
823       if (QueenCheckBonus > 0 || BishopCheckBonus > 0)
824       {
825           b = pos.attacks_from<BISHOP>(s) & ~pos.pieces_of_color(Them) & ~ei.attacked_by(Us);
826
827           // Queen checks
828           b2 = b & ei.attacked_by(Them, QUEEN);
829           if (b2)
830               attackUnits += QueenCheckBonus * count_1s_max_15<HasPopCnt>(b2);
831
832           // Bishop checks
833           b2 = b & ei.attacked_by(Them, BISHOP);
834           if (b2)
835               attackUnits += BishopCheckBonus * count_1s_max_15<HasPopCnt>(b2);
836       }
837       if (KnightCheckBonus > 0)
838       {
839           b = pos.attacks_from<KNIGHT>(s) & ~pos.pieces_of_color(Them) & ~ei.attacked_by(Us);
840
841           // Knight checks
842           b2 = b & ei.attacked_by(Them, KNIGHT);
843           if (b2)
844               attackUnits += KnightCheckBonus * count_1s_max_15<HasPopCnt>(b2);
845       }
846
847       // Analyse discovered checks (only for non-pawns right now, consider
848       // adding pawns later).
849       if (DiscoveredCheckBonus)
850       {
851         b = pos.discovered_check_candidates(Them) & ~pos.pieces(PAWN);
852         if (b)
853           attackUnits += DiscoveredCheckBonus * count_1s_max_15<HasPopCnt>(b) * (sente ? 2 : 1);
854       }
855
856       // Has a mate threat been found?  We don't do anything here if the
857       // side with the mating move is the side to move, because in that
858       // case the mating side will get a huge bonus at the end of the main
859       // evaluation function instead.
860       if (ei.mateThreat[Them] != MOVE_NONE)
861           attackUnits += MateThreatBonus;
862
863       // Ensure that attackUnits is between 0 and 99, in order to avoid array
864       // out of bounds errors:
865       if (attackUnits < 0)
866           attackUnits = 0;
867
868       if (attackUnits >= 100)
869           attackUnits = 99;
870
871       // Finally, extract the king safety score from the SafetyTable[] array.
872       // Add the score to the evaluation, and also to ei.futilityMargin.  The
873       // reason for adding the king safety score to the futility margin is
874       // that the king safety scores can sometimes be very big, and that
875       // capturing a single attacking piece can therefore result in a score
876       // change far bigger than the value of the captured piece.
877       Score v = apply_weight(make_score(SafetyTable[attackUnits], 0), WeightKingSafety[Us]);
878
879       ei.value -= Sign[Us] * v;
880
881       if (Us == pos.side_to_move())
882           ei.futilityMargin += mg_value(v);
883     }
884   }
885
886
887   // evaluate_passed_pawns() evaluates the passed pawns of the given color
888
889   template<Color Us>
890   void evaluate_passed_pawns_of_color(const Position& pos, int movesToGo[], Square pawnToGo[], EvalInfo& ei) {
891
892     const Color Them = (Us == WHITE ? BLACK : WHITE);
893
894     Bitboard b2, b3, b4;
895     Square ourKingSq = pos.king_square(Us);
896     Square theirKingSq = pos.king_square(Them);
897     Bitboard b = ei.pi->passed_pawns() & pos.pieces(PAWN, Us);
898
899     while (b)
900     {
901         Square s = pop_1st_bit(&b);
902
903         assert(pos.piece_on(s) == piece_of_color_and_type(Us, PAWN));
904         assert(pos.pawn_is_passed(Us, s));
905
906         int r = int(relative_rank(Us, s) - RANK_2);
907         int tr = Max(0, r * (r - 1));
908
909         // Base bonus based on rank
910         Value mbonus = Value(20 * tr);
911         Value ebonus = Value(10 + r * r * 10);
912
913         // Adjust bonus based on king proximity
914         if (tr)
915         {
916             Square blockSq = s + pawn_push(Us);
917
918             ebonus -= Value(square_distance(ourKingSq, blockSq) * 3 * tr);
919             ebonus -= Value(square_distance(ourKingSq, blockSq + pawn_push(Us)) * 1 * tr);
920             ebonus += Value(square_distance(theirKingSq, blockSq) * 6 * tr);
921
922             // If the pawn is free to advance, increase bonus
923             if (pos.square_is_empty(blockSq))
924             {
925                 // There are no enemy pawns in the pawn's path
926                 b2 = squares_in_front_of(Us, s);
927
928                 assert((b2 & pos.pieces(PAWN, Them)) == EmptyBoardBB);
929
930                 // Squares attacked by us
931                 b4 = b2 & ei.attacked_by(Us);
932
933                 // Squares attacked or occupied by enemy pieces
934                 b3 = b2 & (ei.attacked_by(Them) | pos.pieces_of_color(Them));
935
936                 // If there is an enemy rook or queen attacking the pawn from behind,
937                 // add all X-ray attacks by the rook or queen.
938                 if (   (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them))
939                     && (squares_behind(Us, s) & pos.pieces(ROOK, QUEEN, Them) & pos.attacks_from<QUEEN>(s)))
940                     b3 = b2;
941
942                 // Are any of the squares in the pawn's path attacked or occupied by the enemy?
943                 if (b3 == EmptyBoardBB)
944                     // No enemy attacks or pieces, huge bonus!
945                     // Even bigger if we protect the pawn's path
946                     ebonus += Value(tr * (b2 == b4 ? 17 : 15));
947                 else
948                     // OK, there are enemy attacks or pieces (but not pawns). Are those
949                     // squares which are attacked by the enemy also attacked by us ?
950                     // If yes, big bonus (but smaller than when there are no enemy attacks),
951                     // if no, somewhat smaller bonus.
952                     ebonus += Value(tr * ((b3 & b4) == b3 ? 13 : 8));
953
954                 // At last, add a small bonus when there are no *friendly* pieces
955                 // in the pawn's path.
956                 if ((b2 & pos.pieces_of_color(Us)) == EmptyBoardBB)
957                     ebonus += Value(tr);
958             }
959         } // tr != 0
960
961         // If the pawn is supported by a friendly pawn, increase bonus
962         b2 = pos.pieces(PAWN, Us) & neighboring_files_bb(s);
963         if (b2 & rank_bb(s))
964             ebonus += Value(r * 20);
965         else if (pos.attacks_from<PAWN>(s, Them) & b2)
966             ebonus += Value(r * 12);
967
968         // If the other side has only a king, check whether the pawn is
969         // unstoppable
970         if (pos.non_pawn_material(Them) == Value(0))
971         {
972             Square qsq;
973             int d;
974
975             qsq = relative_square(Us, make_square(square_file(s), RANK_8));
976             d =  square_distance(s, qsq)
977                - square_distance(theirKingSq, qsq)
978                + (Us != pos.side_to_move());
979
980             if (d < 0)
981             {
982                 int mtg = RANK_8 - relative_rank(Us, s);
983                 int blockerCount = count_1s_max_15(squares_in_front_of(Us,s) & pos.occupied_squares());
984                 mtg += blockerCount;
985                 d += blockerCount;
986                 if (d < 0 && (!movesToGo[Us] || movesToGo[Us] > mtg))
987                 {
988                     movesToGo[Us] = mtg;
989                     pawnToGo[Us] = s;
990                 }
991             }
992         }
993
994         // Rook pawns are a special case: They are sometimes worse, and
995         // sometimes better than other passed pawns. It is difficult to find
996         // good rules for determining whether they are good or bad. For now,
997         // we try the following: Increase the value for rook pawns if the
998         // other side has no pieces apart from a knight, and decrease the
999         // value if the other side has a rook or queen.
1000         if (square_file(s) == FILE_A || square_file(s) == FILE_H)
1001         {
1002             if (   pos.non_pawn_material(Them) <= KnightValueMidgame
1003                 && pos.piece_count(Them, KNIGHT) <= 1)
1004                 ebonus += ebonus / 4;
1005             else if (pos.pieces(ROOK, QUEEN, Them))
1006                 ebonus -= ebonus / 4;
1007         }
1008
1009         // Add the scores for this pawn to the middle game and endgame eval.
1010         ei.value += Sign[Us] * apply_weight(make_score(mbonus, ebonus), WeightPassedPawns);
1011
1012     } // while
1013   }
1014
1015
1016   // evaluate_passed_pawns() evaluates the passed pawns for both sides
1017
1018   void evaluate_passed_pawns(const Position& pos, EvalInfo& ei) {
1019
1020     int movesToGo[2] = {0, 0};
1021     Square pawnToGo[2] = {SQ_NONE, SQ_NONE};
1022
1023     // Evaluate pawns for each color
1024     evaluate_passed_pawns_of_color<WHITE>(pos, movesToGo, pawnToGo, ei);
1025     evaluate_passed_pawns_of_color<BLACK>(pos, movesToGo, pawnToGo, ei);
1026
1027     // Neither side has an unstoppable passed pawn?
1028     if (!(movesToGo[WHITE] | movesToGo[BLACK]))
1029         return;
1030
1031     // Does only one side have an unstoppable passed pawn?
1032     if (!movesToGo[WHITE] || !movesToGo[BLACK])
1033     {
1034         Color winnerSide = movesToGo[WHITE] ? WHITE : BLACK;
1035         ei.value += make_score(0, Sign[winnerSide] * (UnstoppablePawnValue - Value(0x40 * movesToGo[winnerSide])));
1036     }
1037     else
1038     {   // Both sides have unstoppable pawns! Try to find out who queens
1039         // first. We begin by transforming 'movesToGo' to the number of
1040         // plies until the pawn queens for both sides.
1041         movesToGo[WHITE] *= 2;
1042         movesToGo[BLACK] *= 2;
1043         movesToGo[pos.side_to_move()]--;
1044
1045         Color winnerSide = movesToGo[WHITE] < movesToGo[BLACK] ? WHITE : BLACK;
1046         Color loserSide = opposite_color(winnerSide);
1047
1048         // If one side queens at least three plies before the other, that side wins
1049         if (movesToGo[winnerSide] <= movesToGo[loserSide] - 3)
1050             ei.value += Sign[winnerSide] * make_score(0, UnstoppablePawnValue - Value(0x40 * (movesToGo[winnerSide]/2)));
1051
1052         // If one side queens one ply before the other and checks the king or attacks
1053         // the undefended opponent's queening square, that side wins. To avoid cases
1054         // where the opponent's king could move somewhere before first pawn queens we
1055         // consider only free paths to queen for both pawns.
1056         else if (   !(squares_in_front_of(WHITE, pawnToGo[WHITE]) & pos.occupied_squares())
1057                  && !(squares_in_front_of(BLACK, pawnToGo[BLACK]) & pos.occupied_squares()))
1058         {
1059             assert(movesToGo[loserSide] - movesToGo[winnerSide] == 1);
1060
1061             Square winnerQSq = relative_square(winnerSide, make_square(square_file(pawnToGo[winnerSide]), RANK_8));
1062             Square loserQSq = relative_square(loserSide, make_square(square_file(pawnToGo[loserSide]), RANK_8));
1063
1064             Bitboard b = pos.occupied_squares();
1065             clear_bit(&b, pawnToGo[winnerSide]);
1066             clear_bit(&b, pawnToGo[loserSide]);
1067             b = queen_attacks_bb(winnerQSq, b);
1068
1069             if (  (b & pos.pieces(KING, loserSide))
1070                 ||(bit_is_set(b, loserQSq) && !bit_is_set(ei.attacked_by(loserSide), loserQSq)))
1071                 ei.value += Sign[winnerSide] * make_score(0, UnstoppablePawnValue - Value(0x40 * (movesToGo[winnerSide]/2)));
1072         }
1073     }
1074   }
1075
1076
1077   // evaluate_trapped_bishop_a7h7() determines whether a bishop on a7/h7
1078   // (a2/h2 for black) is trapped by enemy pawns, and assigns a penalty
1079   // if it is.
1080
1081   void evaluate_trapped_bishop_a7h7(const Position& pos, Square s, Color us, EvalInfo &ei) {
1082
1083     assert(square_is_ok(s));
1084     assert(pos.piece_on(s) == piece_of_color_and_type(us, BISHOP));
1085
1086     Square b6 = relative_square(us, (square_file(s) == FILE_A) ? SQ_B6 : SQ_G6);
1087     Square b8 = relative_square(us, (square_file(s) == FILE_A) ? SQ_B8 : SQ_G8);
1088
1089     if (   pos.piece_on(b6) == piece_of_color_and_type(opposite_color(us), PAWN)
1090         && pos.see(s, b6) < 0
1091         && pos.see(s, b8) < 0)
1092     {
1093         ei.value -= Sign[us] * TrappedBishopA7H7Penalty;
1094     }
1095   }
1096
1097
1098   // evaluate_trapped_bishop_a1h1() determines whether a bishop on a1/h1
1099   // (a8/h8 for black) is trapped by a friendly pawn on b2/g2 (b7/g7 for
1100   // black), and assigns a penalty if it is. This pattern can obviously
1101   // only occur in Chess960 games.
1102
1103   void evaluate_trapped_bishop_a1h1(const Position& pos, Square s, Color us, EvalInfo& ei) {
1104
1105     Piece pawn = piece_of_color_and_type(us, PAWN);
1106     Square b2, b3, c3;
1107
1108     assert(Chess960);
1109     assert(square_is_ok(s));
1110     assert(pos.piece_on(s) == piece_of_color_and_type(us, BISHOP));
1111
1112     if (square_file(s) == FILE_A)
1113     {
1114         b2 = relative_square(us, SQ_B2);
1115         b3 = relative_square(us, SQ_B3);
1116         c3 = relative_square(us, SQ_C3);
1117     }
1118     else
1119     {
1120         b2 = relative_square(us, SQ_G2);
1121         b3 = relative_square(us, SQ_G3);
1122         c3 = relative_square(us, SQ_F3);
1123     }
1124
1125     if (pos.piece_on(b2) == pawn)
1126     {
1127         Score penalty;
1128
1129         if (!pos.square_is_empty(b3))
1130             penalty = 2 * TrappedBishopA1H1Penalty;
1131         else if (pos.piece_on(c3) == pawn)
1132             penalty = TrappedBishopA1H1Penalty;
1133         else
1134             penalty = TrappedBishopA1H1Penalty / 2;
1135
1136         ei.value -= Sign[us] * penalty;
1137     }
1138   }
1139
1140
1141   // evaluate_space() computes the space evaluation for a given side. The
1142   // space evaluation is a simple bonus based on the number of safe squares
1143   // available for minor pieces on the central four files on ranks 2--4. Safe
1144   // squares one, two or three squares behind a friendly pawn are counted
1145   // twice. Finally, the space bonus is scaled by a weight taken from the
1146   // material hash table.
1147   template<Color Us, bool HasPopCnt>
1148   void evaluate_space(const Position& pos, EvalInfo& ei) {
1149
1150     const Color Them = (Us == WHITE ? BLACK : WHITE);
1151
1152     // Find the safe squares for our pieces inside the area defined by
1153     // SpaceMask[us]. A square is unsafe if it is attacked by an enemy
1154     // pawn, or if it is undefended and attacked by an enemy piece.
1155
1156     Bitboard safeSquares =   SpaceMask[Us]
1157                           & ~pos.pieces(PAWN, Us)
1158                           & ~ei.attacked_by(Them, PAWN)
1159                           & ~(~ei.attacked_by(Us) & ei.attacked_by(Them));
1160
1161     // Find all squares which are at most three squares behind some friendly
1162     // pawn.
1163     Bitboard behindFriendlyPawns = pos.pieces(PAWN, Us);
1164     behindFriendlyPawns |= (Us == WHITE ? behindFriendlyPawns >>  8 : behindFriendlyPawns <<  8);
1165     behindFriendlyPawns |= (Us == WHITE ? behindFriendlyPawns >> 16 : behindFriendlyPawns << 16);
1166
1167     int space =  count_1s_max_15<HasPopCnt>(safeSquares)
1168                + count_1s_max_15<HasPopCnt>(behindFriendlyPawns & safeSquares);
1169
1170     ei.value += Sign[Us] * apply_weight(make_score(space * ei.mi->space_weight(), 0), WeightSpace);
1171   }
1172
1173
1174   // apply_weight() applies an evaluation weight to a value trying to prevent overflow
1175
1176   inline Score apply_weight(Score v, Score w) {
1177       return make_score((int(mg_value(v)) * mg_value(w)) / 0x100, (int(eg_value(v)) * eg_value(w)) / 0x100);
1178   }
1179
1180
1181   // scale_by_game_phase() interpolates between a middle game and an endgame
1182   // score, based on game phase.  It also scales the return value by a
1183   // ScaleFactor array.
1184
1185   Value scale_by_game_phase(const Score& v, Phase ph, const ScaleFactor sf[]) {
1186
1187     assert(mg_value(v) > -VALUE_INFINITE && mg_value(v) < VALUE_INFINITE);
1188     assert(eg_value(v) > -VALUE_INFINITE && eg_value(v) < VALUE_INFINITE);
1189     assert(ph >= PHASE_ENDGAME && ph <= PHASE_MIDGAME);
1190
1191     Value ev = apply_scale_factor(eg_value(v), sf[(eg_value(v) > Value(0) ? WHITE : BLACK)]);
1192
1193     int result = (mg_value(v) * ph + ev * (128 - ph)) / 128;
1194     return Value(result & ~(GrainSize - 1));
1195   }
1196
1197
1198   // weight_option() computes the value of an evaluation weight, by combining
1199   // two UCI-configurable weights (midgame and endgame) with an internal weight.
1200
1201   Score weight_option(const std::string& mgOpt, const std::string& egOpt, Score internalWeight) {
1202
1203     Score uciWeight = make_score(get_option_value_int(mgOpt), get_option_value_int(egOpt));
1204
1205     // Convert to integer to prevent overflow
1206     int mg = mg_value(uciWeight);
1207     int eg = eg_value(uciWeight);
1208
1209     mg = (mg * 0x100) / 100;
1210     eg = (eg * 0x100) / 100;
1211     mg = (mg * mg_value(internalWeight)) / 0x100;
1212     eg = (eg * eg_value(internalWeight)) / 0x100;
1213     return make_score(mg, eg);
1214   }
1215
1216   // init_safety() initizes the king safety evaluation, based on UCI
1217   // parameters.  It is called from read_weights().
1218
1219   void init_safety() {
1220
1221     QueenContactCheckBonus = get_option_value_int("Queen Contact Check Bonus");
1222     QueenCheckBonus        = get_option_value_int("Queen Check Bonus");
1223     RookCheckBonus         = get_option_value_int("Rook Check Bonus");
1224     BishopCheckBonus       = get_option_value_int("Bishop Check Bonus");
1225     KnightCheckBonus       = get_option_value_int("Knight Check Bonus");
1226     DiscoveredCheckBonus   = get_option_value_int("Discovered Check Bonus");
1227     MateThreatBonus        = get_option_value_int("Mate Threat Bonus");
1228
1229     int maxSlope = get_option_value_int("King Safety Max Slope");
1230     int peak     = get_option_value_int("King Safety Max Value") * 256 / 100;
1231     double a     = get_option_value_int("King Safety Coefficient") / 100.0;
1232     double b     = get_option_value_int("King Safety X Intercept");
1233     bool quad    = (get_option_value_string("King Safety Curve") == "Quadratic");
1234     bool linear  = (get_option_value_string("King Safety Curve") == "Linear");
1235
1236     for (int i = 0; i < 100; i++)
1237     {
1238         if (i < b)
1239             SafetyTable[i] = Value(0);
1240         else if (quad)
1241             SafetyTable[i] = Value((int)(a * (i - b) * (i - b)));
1242         else if (linear)
1243             SafetyTable[i] = Value((int)(100 * a * (i - b)));
1244     }
1245
1246     for (int i = 0; i < 100; i++)
1247     {
1248         if (SafetyTable[i+1] - SafetyTable[i] > maxSlope)
1249             for (int j = i + 1; j < 100; j++)
1250                 SafetyTable[j] = SafetyTable[j-1] + Value(maxSlope);
1251
1252         if (SafetyTable[i]  > Value(peak))
1253             SafetyTable[i] = Value(peak);
1254     }
1255   }
1256 }