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