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