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