]> git.sesse.net Git - stockfish/blob - src/pawns.cpp
Maximize usage of transposition table in probcut
[stockfish] / src / pawns.cpp
1 /*
2   Stockfish, a UCI chess playing engine derived from Glaurung 2.1
3   Copyright (C) 2004-2008 Tord Romstad (Glaurung author)
4   Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad
5   Copyright (C) 2015-2020 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad
6
7   Stockfish is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   Stockfish is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <algorithm>
22 #include <cassert>
23
24 #include "bitboard.h"
25 #include "pawns.h"
26 #include "position.h"
27 #include "thread.h"
28
29 namespace {
30
31   #define V Value
32   #define S(mg, eg) make_score(mg, eg)
33
34   // Pawn penalties
35   constexpr Score Backward      = S( 9, 24);
36   constexpr Score Doubled       = S(11, 56);
37   constexpr Score Isolated      = S( 5, 15);
38   constexpr Score WeakLever     = S( 0, 56);
39   constexpr Score WeakUnopposed = S(13, 27);
40
41   // Bonus for blocked pawns at 5th or 6th rank
42   constexpr Score BlockedPawn[2] = { S(-11, -4), S(-3, 4) };
43
44   constexpr Score BlockedStorm[RANK_NB] = {
45     S(0, 0), S(0, 0), S(76, 78), S(-10, 15), S(-7, 10), S(-4, 6), S(-1, 2)
46   };
47
48   // Connected pawn bonus
49   constexpr int Connected[RANK_NB] = { 0, 7, 8, 12, 29, 48, 86 };
50
51   // Strength of pawn shelter for our king by [distance from edge][rank].
52   // RANK_1 = 0 is used for files where we have no pawn, or pawn is behind our king.
53   constexpr Value ShelterStrength[int(FILE_NB) / 2][RANK_NB] = {
54     { V( -6), V( 81), V( 93), V( 58), V( 39), V( 18), V(  25) },
55     { V(-43), V( 61), V( 35), V(-49), V(-29), V(-11), V( -63) },
56     { V(-10), V( 75), V( 23), V( -2), V( 32), V(  3), V( -45) },
57     { V(-39), V(-13), V(-29), V(-52), V(-48), V(-67), V(-166) }
58   };
59
60   // Danger of enemy pawns moving toward our king by [distance from edge][rank].
61   // RANK_1 = 0 is used for files where the enemy has no pawn, or their pawn
62   // is behind our king. Note that UnblockedStorm[0][1-2] accommodate opponent pawn
63   // on edge, likely blocked by our king.
64   constexpr Value UnblockedStorm[int(FILE_NB) / 2][RANK_NB] = {
65     { V( 85), V(-289), V(-166), V(97), V(50), V( 45), V( 50) },
66     { V( 46), V( -25), V( 122), V(45), V(37), V(-10), V( 20) },
67     { V( -6), V(  51), V( 168), V(34), V(-2), V(-22), V(-14) },
68     { V(-15), V( -11), V( 101), V( 4), V(11), V(-15), V(-29) }
69   };
70
71   #undef S
72   #undef V
73
74
75   /// evaluate() calculates a score for the static pawn structure of the given position.
76   /// We cannot use the location of pieces or king in this function, as the evaluation
77   /// of the pawn structure will be stored in a small cache for speed reasons, and will
78   /// be re-used even when the pieces have moved.
79
80   template<Color Us>
81   Score evaluate(const Position& pos, Pawns::Entry* e) {
82
83     constexpr Color     Them = ~Us;
84     constexpr Direction Up   = pawn_push(Us);
85
86     Bitboard neighbours, stoppers, support, phalanx, opposed;
87     Bitboard lever, leverPush, blocked;
88     Square s;
89     bool backward, passed, doubled;
90     Score score = SCORE_ZERO;
91     const Square* pl = pos.squares<PAWN>(Us);
92
93     Bitboard ourPawns   = pos.pieces(  Us, PAWN);
94     Bitboard theirPawns = pos.pieces(Them, PAWN);
95
96     Bitboard doubleAttackThem = pawn_double_attacks_bb<Them>(theirPawns);
97
98     e->passedPawns[Us] = 0;
99     e->kingSquares[Us] = SQ_NONE;
100     e->pawnAttacks[Us] = e->pawnAttacksSpan[Us] = pawn_attacks_bb<Us>(ourPawns);
101     e->blockedCount += popcount(shift<Up>(ourPawns) & (theirPawns | doubleAttackThem));
102
103     // Loop through all pawns of the current color and score each pawn
104     while ((s = *pl++) != SQ_NONE)
105     {
106         assert(pos.piece_on(s) == make_piece(Us, PAWN));
107
108         Rank r = relative_rank(Us, s);
109
110         // Flag the pawn
111         opposed    = theirPawns & forward_file_bb(Us, s);
112         blocked    = theirPawns & (s + Up);
113         stoppers   = theirPawns & passed_pawn_span(Us, s);
114         lever      = theirPawns & pawn_attacks_bb(Us, s);
115         leverPush  = theirPawns & pawn_attacks_bb(Us, s + Up);
116         doubled    = ourPawns   & (s - Up);
117         neighbours = ourPawns   & adjacent_files_bb(s);
118         phalanx    = neighbours & rank_bb(s);
119         support    = neighbours & rank_bb(s - Up);
120
121         // A pawn is backward when it is behind all pawns of the same color on
122         // the adjacent files and cannot safely advance.
123         backward =  !(neighbours & forward_ranks_bb(Them, s + Up))
124                   && (leverPush | blocked);
125
126         // Compute additional span if pawn is not backward nor blocked
127         if (!backward && !blocked)
128             e->pawnAttacksSpan[Us] |= pawn_attack_span(Us, s);
129
130         // A pawn is passed if one of the three following conditions is true:
131         // (a) there is no stoppers except some levers
132         // (b) the only stoppers are the leverPush, but we outnumber them
133         // (c) there is only one front stopper which can be levered.
134         //     (Refined in Evaluation::passed)
135         passed =   !(stoppers ^ lever)
136                 || (   !(stoppers ^ leverPush)
137                     && popcount(phalanx) >= popcount(leverPush))
138                 || (   stoppers == blocked && r >= RANK_5
139                     && (shift<Up>(support) & ~(theirPawns | doubleAttackThem)));
140
141         passed &= !(forward_file_bb(Us, s) & ourPawns);
142
143         // Passed pawns will be properly scored later in evaluation when we have
144         // full attack info.
145         if (passed)
146             e->passedPawns[Us] |= s;
147
148         // Score this pawn
149         if (support | phalanx)
150         {
151             int v =  Connected[r] * (2 + bool(phalanx) - bool(opposed))
152                    + 21 * popcount(support);
153
154             score += make_score(v, v * (r - 2) / 4);
155         }
156
157         else if (!neighbours)
158         {
159             if (     opposed
160                 &&  (ourPawns & forward_file_bb(Them, s))
161                 && !(theirPawns & adjacent_files_bb(s)))
162                 score -= Doubled;
163             else
164                 score -=  Isolated
165                         + WeakUnopposed * !opposed;
166         }
167
168         else if (backward)
169             score -=  Backward
170                     + WeakUnopposed * !opposed;
171
172         if (!support)
173             score -=  Doubled * doubled
174                     + WeakLever * more_than_one(lever);
175
176         if (blocked && r > RANK_4)
177             score += BlockedPawn[r-4];
178     }
179
180     return score;
181   }
182
183 } // namespace
184
185 namespace Pawns {
186
187
188 /// Pawns::probe() looks up the current position's pawns configuration in
189 /// the pawns hash table. It returns a pointer to the Entry if the position
190 /// is found. Otherwise a new Entry is computed and stored there, so we don't
191 /// have to recompute all when the same pawns configuration occurs again.
192
193 Entry* probe(const Position& pos) {
194
195   Key key = pos.pawn_key();
196   Entry* e = pos.this_thread()->pawnsTable[key];
197
198   if (e->key == key)
199       return e;
200
201   e->key = key;
202   e->blockedCount = 0;
203   e->scores[WHITE] = evaluate<WHITE>(pos, e);
204   e->scores[BLACK] = evaluate<BLACK>(pos, e);
205
206   return e;
207 }
208
209
210 /// Entry::evaluate_shelter() calculates the shelter bonus and the storm
211 /// penalty for a king, looking at the king file and the two closest files.
212
213 template<Color Us>
214 Score Entry::evaluate_shelter(const Position& pos, Square ksq) const {
215
216   constexpr Color Them = ~Us;
217
218   Bitboard b = pos.pieces(PAWN) & ~forward_ranks_bb(Them, ksq);
219   Bitboard ourPawns = b & pos.pieces(Us) & ~pawnAttacks[Them];
220   Bitboard theirPawns = b & pos.pieces(Them);
221
222   Score bonus = make_score(5, 5);
223
224   File center = Utility::clamp(file_of(ksq), FILE_B, FILE_G);
225   for (File f = File(center - 1); f <= File(center + 1); ++f)
226   {
227       b = ourPawns & file_bb(f);
228       int ourRank = b ? relative_rank(Us, frontmost_sq(Them, b)) : 0;
229
230       b = theirPawns & file_bb(f);
231       int theirRank = b ? relative_rank(Us, frontmost_sq(Them, b)) : 0;
232
233       int d = edge_distance(f);
234       bonus += make_score(ShelterStrength[d][ourRank], 0);
235
236       if (ourRank && (ourRank == theirRank - 1))
237           bonus -= BlockedStorm[theirRank];
238       else
239           bonus -= make_score(UnblockedStorm[d][theirRank], 0);
240   }
241
242   return bonus;
243 }
244
245
246 /// Entry::do_king_safety() calculates a bonus for king safety. It is called only
247 /// when king square changes, which is about 20% of total king_safety() calls.
248
249 template<Color Us>
250 Score Entry::do_king_safety(const Position& pos) {
251
252   Square ksq = pos.square<KING>(Us);
253   kingSquares[Us] = ksq;
254   castlingRights[Us] = pos.castling_rights(Us);
255   auto compare = [](Score a, Score b) { return mg_value(a) < mg_value(b); };
256
257   Score shelter = evaluate_shelter<Us>(pos, ksq);
258
259   // If we can castle use the bonus after castling if it is bigger
260
261   if (pos.can_castle(Us & KING_SIDE))
262       shelter = std::max(shelter, evaluate_shelter<Us>(pos, relative_square(Us, SQ_G1)), compare);
263
264   if (pos.can_castle(Us & QUEEN_SIDE))
265       shelter = std::max(shelter, evaluate_shelter<Us>(pos, relative_square(Us, SQ_C1)), compare);
266
267   // In endgame we like to bring our king near our closest pawn
268   Bitboard pawns = pos.pieces(Us, PAWN);
269   int minPawnDist = 6;
270
271   if (pawns & attacks_bb<KING>(ksq))
272       minPawnDist = 1;
273   else while (pawns)
274       minPawnDist = std::min(minPawnDist, distance(ksq, pop_lsb(&pawns)));
275
276   return shelter - make_score(0, 16 * minPawnDist);
277 }
278
279 // Explicit template instantiation
280 template Score Entry::do_king_safety<WHITE>(const Position& pos);
281 template Score Entry::do_king_safety<BLACK>(const Position& pos);
282
283 } // namespace Pawns