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